api.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. /*
  2. * Copyright (c) 2023, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package inproxy
  20. import (
  21. "crypto/rand"
  22. "crypto/subtle"
  23. "encoding/base64"
  24. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  25. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  26. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  27. )
  28. const (
  29. // ProxyProtocolVersion1 represents protocol version 1.
  30. ProxyProtocolVersion1 = int32(1)
  31. // MinimumProxyProtocolVersion is the minimum supported version number.
  32. MinimumProxyProtocolVersion = ProxyProtocolVersion1
  33. MaxCompartmentIDs = 10
  34. )
  35. // proxyProtocolVersion is the current protocol version number.
  36. // proxyProtocolVersion is variable, to enable overriding the value in tests.
  37. // This value should not be overridden outside of test cases.
  38. var proxyProtocolVersion = ProxyProtocolVersion1
  39. // ID is a unique identifier used to identify inproxy connections and actors.
  40. type ID [32]byte
  41. // MakeID generates a new ID using crypto/rand.
  42. func MakeID() (ID, error) {
  43. var id ID
  44. for {
  45. _, err := rand.Read(id[:])
  46. if err != nil {
  47. return id, errors.Trace(err)
  48. }
  49. if !id.Zero() {
  50. return id, nil
  51. }
  52. }
  53. }
  54. // IDFromString returns an ID given its string encoding.
  55. func IDFromString(s string) (ID, error) {
  56. var id ID
  57. return id, errors.Trace(fromBase64String(s, id[:]))
  58. }
  59. func fromBase64String(s string, b []byte) error {
  60. value, err := base64.RawStdEncoding.DecodeString(s)
  61. if err != nil {
  62. return errors.Trace(err)
  63. }
  64. if len(value) != len(b) {
  65. return errors.TraceNew("invalid length")
  66. }
  67. copy(b, value)
  68. return nil
  69. }
  70. // IDsFromStrings returns a list of IDs given a list of string encodings.
  71. func IDsFromStrings(strs []string) ([]ID, error) {
  72. var ids []ID
  73. for _, str := range strs {
  74. id, err := IDFromString(str)
  75. if err != nil {
  76. return nil, errors.Trace(err)
  77. }
  78. ids = append(ids, id)
  79. }
  80. return ids, nil
  81. }
  82. // MarshalText emits IDs as base64.
  83. func (id ID) MarshalText() ([]byte, error) {
  84. return []byte(id.String()), nil
  85. }
  86. // String emits IDs as base64.
  87. func (id ID) String() string {
  88. return base64.RawStdEncoding.EncodeToString([]byte(id[:]))
  89. }
  90. // Equal indicates whether two IDs are equal. It uses a constant time
  91. // comparison.
  92. func (id ID) Equal(x ID) bool {
  93. return subtle.ConstantTimeCompare(id[:], x[:]) == 1
  94. }
  95. // Zero indicates whether the ID is the zero value.
  96. func (id ID) Zero() bool {
  97. var zero ID
  98. return id.Equal(zero)
  99. }
  100. // HaveCommonIDs indicates whether two lists of IDs have a common entry.
  101. func HaveCommonIDs(a, b []ID) bool {
  102. for _, x := range a {
  103. for _, y := range b {
  104. // Each comparison is constant time, but the number of comparisons
  105. // varies and might leak the size of a list.
  106. if x.Equal(y) {
  107. return true
  108. }
  109. }
  110. }
  111. return false
  112. }
  113. // NetworkType is the type of a network, such as WiFi or Mobile. This enum is
  114. // used for compact API message encoding.
  115. type NetworkType int32
  116. const (
  117. NetworkTypeUnknown NetworkType = iota
  118. NetworkTypeWiFi
  119. NetworkTypeMobile
  120. )
  121. // NetworkProtocol is an Internet protocol, such as TCP or UDP. This enum is
  122. // used for compact API message encoding.
  123. type NetworkProtocol int32
  124. const (
  125. NetworkProtocolTCP NetworkProtocol = iota
  126. NetworkProtocolUDP
  127. )
  128. // NetworkProtocolFromString converts a "net" package network protocol string
  129. // value to a NetworkProtocol.
  130. func NetworkProtocolFromString(networkProtocol string) (NetworkProtocol, error) {
  131. switch networkProtocol {
  132. case "tcp":
  133. return NetworkProtocolTCP, nil
  134. case "udp":
  135. return NetworkProtocolUDP, nil
  136. }
  137. var p NetworkProtocol
  138. return p, errors.Tracef("unknown network protocol: %s", networkProtocol)
  139. }
  140. // String converts a NetworkProtocol to a "net" package network protocol string.
  141. func (p NetworkProtocol) String() string {
  142. switch p {
  143. case NetworkProtocolTCP:
  144. return "tcp"
  145. case NetworkProtocolUDP:
  146. return "udp"
  147. }
  148. // This case will cause net dials to fail.
  149. return ""
  150. }
  151. // IsStream indicates if the NetworkProtocol is stream-oriented (e.g., TCP)
  152. // and not packet-oriented (e.g., UDP).
  153. func (p NetworkProtocol) IsStream() bool {
  154. switch p {
  155. case NetworkProtocolTCP:
  156. return true
  157. case NetworkProtocolUDP:
  158. return false
  159. }
  160. return false
  161. }
  162. // ProxyMetrics are network topolology and resource metrics provided by a
  163. // proxy to a broker. The broker uses this information when matching proxies
  164. // and clients.
  165. type ProxyMetrics struct {
  166. BaseAPIParameters protocol.PackedAPIParameters `cbor:"1,keyasint,omitempty"`
  167. ProxyProtocolVersion int32 `cbor:"2,keyasint,omitempty"`
  168. NATType NATType `cbor:"3,keyasint,omitempty"`
  169. PortMappingTypes PortMappingTypes `cbor:"4,keyasint,omitempty"`
  170. MaxClients int32 `cbor:"6,keyasint,omitempty"`
  171. ConnectingClients int32 `cbor:"7,keyasint,omitempty"`
  172. ConnectedClients int32 `cbor:"8,keyasint,omitempty"`
  173. LimitUpstreamBytesPerSecond int64 `cbor:"9,keyasint,omitempty"`
  174. LimitDownstreamBytesPerSecond int64 `cbor:"10,keyasint,omitempty"`
  175. PeakUpstreamBytesPerSecond int64 `cbor:"11,keyasint,omitempty"`
  176. PeakDownstreamBytesPerSecond int64 `cbor:"12,keyasint,omitempty"`
  177. }
  178. // ClientMetrics are network topolology metrics provided by a client to a
  179. // broker. The broker uses this information when matching proxies and
  180. // clients.
  181. type ClientMetrics struct {
  182. BaseAPIParameters protocol.PackedAPIParameters `cbor:"1,keyasint,omitempty"`
  183. ProxyProtocolVersion int32 `cbor:"2,keyasint,omitempty"`
  184. NATType NATType `cbor:"3,keyasint,omitempty"`
  185. PortMappingTypes PortMappingTypes `cbor:"4,keyasint,omitempty"`
  186. }
  187. // ProxyAnnounceRequest is an API request sent from a proxy to a broker,
  188. // announcing that it is available for a client connection. Proxies send one
  189. // ProxyAnnounceRequest for each available client connection. The broker will
  190. // match the proxy with a client and return WebRTC connection information
  191. // in the response.
  192. //
  193. // PersonalCompartmentIDs limits the clients to those that supply one of the
  194. // specified compartment IDs; personal compartment IDs are distributed from
  195. // proxy operators to client users out-of-band and provide optional access
  196. // control.
  197. //
  198. // When CheckTactics is set, the broker will check for new tactics or indicate
  199. // that the proxy's cached tactics TTL may be extended. Tactics information
  200. // is returned in the response TacticsPayload. To minimize broker processing
  201. // overhead, proxies with multiple workers should designate just one worker
  202. // to set CheckTactics.
  203. //
  204. // The proxy's session public key is an implicit and cryptographically
  205. // verified proxy ID.
  206. type ProxyAnnounceRequest struct {
  207. PersonalCompartmentIDs []ID `cbor:"1,keyasint,omitempty"`
  208. Metrics *ProxyMetrics `cbor:"2,keyasint,omitempty"`
  209. CheckTactics bool `cbor:"3,keyasint,omitempty"`
  210. }
  211. // WebRTCSessionDescription is compatible with pion/webrtc.SessionDescription
  212. // and facilitates the PSIPHON_ENABLE_INPROXY build tag exclusion of pion
  213. // dependencies.
  214. type WebRTCSessionDescription struct {
  215. Type int `cbor:"1,keyasint,omitempty"`
  216. SDP string `cbor:"2,keyasint,omitempty"`
  217. }
  218. // TODO: send ProxyAnnounceRequest/ClientOfferRequest.Metrics only with the
  219. // first request in a session and cache.
  220. // ProxyAnnounceResponse returns the connection information for a matched
  221. // client. To establish a WebRTC connection, the proxy uses the client's
  222. // offer SDP to create its own answer SDP and send that to the broker in a
  223. // subsequent ProxyAnswerRequest. The ConnectionID is a unique identifier for
  224. // this single connection and must be relayed back in the ProxyAnswerRequest.
  225. //
  226. // ClientRootObfuscationSecret is generated (or replayed) by the client and
  227. // sent to the proxy and used to drive obfuscation operations.
  228. //
  229. // DestinationAddress is the dial address for the Psiphon server the proxy is
  230. // to relay client traffic with. The broker validates that the dial address
  231. // corresponds to a valid Psiphon server.
  232. //
  233. // MustUpgrade is an optional flag that is set by the broker, based on the
  234. // submitted ProxyProtocolVersion, when the proxy app must be upgraded in
  235. // order to function properly. Potential must-upgrade scenarios include
  236. // changes to the personal pairing broker rendezvous algorithm, where no
  237. // protocol backwards compatibility accommodations can ensure a rendezvous
  238. // and match. When MustUpgrade is set, NoMatch is implied.
  239. type ProxyAnnounceResponse struct {
  240. TacticsPayload []byte `cbor:"2,keyasint,omitempty"`
  241. Limited bool `cbor:"3,keyasint,omitempty"`
  242. NoMatch bool `cbor:"4,keyasint,omitempty"`
  243. MustUpgrade bool `cbor:"13,keyasint,omitempty"`
  244. ConnectionID ID `cbor:"5,keyasint,omitempty"`
  245. ClientProxyProtocolVersion int32 `cbor:"6,keyasint,omitempty"`
  246. ClientOfferSDP WebRTCSessionDescription `cbor:"7,keyasint,omitempty"`
  247. ClientRootObfuscationSecret ObfuscationSecret `cbor:"8,keyasint,omitempty"`
  248. DoDTLSRandomization bool `cbor:"9,keyasint,omitempty"`
  249. TrafficShapingParameters *DataChannelTrafficShapingParameters `cbor:"10,keyasint,omitempty"`
  250. NetworkProtocol NetworkProtocol `cbor:"11,keyasint,omitempty"`
  251. DestinationAddress string `cbor:"12,keyasint,omitempty"`
  252. }
  253. // ClientOfferRequest is an API request sent from a client to a broker,
  254. // requesting a proxy connection. The client sends its WebRTC offer SDP with
  255. // this request.
  256. //
  257. // Clients specify known compartment IDs and are matched with proxies in those
  258. // compartments. CommonCompartmentIDs are comparment IDs managed by Psiphon
  259. // and revealed through tactics or bundled with server lists.
  260. // PersonalCompartmentIDs are compartment IDs shared privately between users,
  261. // out-of-band.
  262. //
  263. // ClientRootObfuscationSecret is generated (or replayed) by the client and
  264. // sent to the proxy and used to drive obfuscation operations.
  265. //
  266. // To specify the Psiphon server it wishes to proxy to, the client sends the
  267. // full, digitally signed Psiphon server entry to the broker and also the
  268. // specific dial address that it has selected for that server. The broker
  269. // validates the server entry signature, the server in-proxy capability, and
  270. // that the dial address corresponds to the network protocol, IP address or
  271. // domain, and destination port for a valid Psiphon tunnel protocol run by
  272. // the specified server entry.
  273. type ClientOfferRequest struct {
  274. Metrics *ClientMetrics `cbor:"1,keyasint,omitempty"`
  275. CommonCompartmentIDs []ID `cbor:"2,keyasint,omitempty"`
  276. PersonalCompartmentIDs []ID `cbor:"3,keyasint,omitempty"`
  277. ClientOfferSDP WebRTCSessionDescription `cbor:"4,keyasint,omitempty"`
  278. ICECandidateTypes ICECandidateTypes `cbor:"5,keyasint,omitempty"`
  279. ClientRootObfuscationSecret ObfuscationSecret `cbor:"6,keyasint,omitempty"`
  280. DoDTLSRandomization bool `cbor:"7,keyasint,omitempty"`
  281. TrafficShapingParameters *DataChannelTrafficShapingParameters `cbor:"8,keyasint,omitempty"`
  282. PackedDestinationServerEntry []byte `cbor:"9,keyasint,omitempty"`
  283. NetworkProtocol NetworkProtocol `cbor:"10,keyasint,omitempty"`
  284. DestinationAddress string `cbor:"11,keyasint,omitempty"`
  285. }
  286. // DataChannelTrafficShapingParameters specifies a data channel traffic
  287. // shaping configuration, including random padding and decoy messages.
  288. // Clients determine their own traffic shaping configuration, and generate
  289. // and send a configuration for the peer proxy to use.
  290. type DataChannelTrafficShapingParameters struct {
  291. MinPaddedMessages int `cbor:"1,keyasint,omitempty"`
  292. MaxPaddedMessages int `cbor:"2,keyasint,omitempty"`
  293. MinPaddingSize int `cbor:"3,keyasint,omitempty"`
  294. MaxPaddingSize int `cbor:"4,keyasint,omitempty"`
  295. MinDecoyMessages int `cbor:"5,keyasint,omitempty"`
  296. MaxDecoyMessages int `cbor:"6,keyasint,omitempty"`
  297. MinDecoySize int `cbor:"7,keyasint,omitempty"`
  298. MaxDecoySize int `cbor:"8,keyasint,omitempty"`
  299. DecoyMessageProbability float64 `cbor:"9,keyasint,omitempty"`
  300. }
  301. // ClientOfferResponse returns the connecting information for a matched proxy.
  302. // The proxy's WebRTC SDP is an answer to the offer sent in
  303. // ClientOfferRequest and is used to begin dialing the WebRTC connection.
  304. //
  305. // Once the client completes its connection to the Psiphon server, it must
  306. // relay a BrokerServerReport to the server on behalf of the broker. This
  307. // relay is conducted within a secure session. First, the client sends
  308. // RelayPacketToServer to the server. Then the client relays any responses to
  309. // the broker using ClientRelayedPacketRequests and continues to relay using
  310. // ClientRelayedPacketRequests until complete. ConnectionID identifies this
  311. // connection and its relayed BrokerServerReport.
  312. //
  313. // MustUpgrade is an optional flag that is set by the broker, based on the
  314. // submitted ProxyProtocolVersion, when the client app must be upgraded in
  315. // order to function properly. Potential must-upgrade scenarios include
  316. // changes to the personal pairing broker rendezvous algorithm, where no
  317. // protocol backwards compatibility accommodations can ensure a rendezvous
  318. // and match. When MustUpgrade is set, NoMatch is implied.
  319. type ClientOfferResponse struct {
  320. Limited bool `cbor:"1,keyasint,omitempty"`
  321. NoMatch bool `cbor:"2,keyasint,omitempty"`
  322. MustUpgrade bool `cbor:"7,keyasint,omitempty"`
  323. ConnectionID ID `cbor:"3,keyasint,omitempty"`
  324. SelectedProxyProtocolVersion int32 `cbor:"4,keyasint,omitempty"`
  325. ProxyAnswerSDP WebRTCSessionDescription `cbor:"5,keyasint,omitempty"`
  326. RelayPacketToServer []byte `cbor:"6,keyasint,omitempty"`
  327. }
  328. // TODO: Encode SDPs using CBOR without field names, simliar to packed metrics?
  329. // ProxyAnswerRequest is an API request sent from a proxy to a broker,
  330. // following ProxyAnnounceResponse, with the WebRTC answer SDP corresponding
  331. // to the client offer SDP received in ProxyAnnounceResponse. ConnectionID
  332. // identifies the connection begun in ProxyAnnounceResponse.
  333. //
  334. // If the proxy was unable to establish an answer SDP or failed for some other
  335. // reason, it should still send ProxyAnswerRequest with AnswerError
  336. // populated; the broker will signal the client to abort this connection.
  337. type ProxyAnswerRequest struct {
  338. ConnectionID ID `cbor:"1,keyasint,omitempty"`
  339. SelectedProxyProtocolVersion int32 `cbor:"2,keyasint,omitempty"`
  340. ProxyAnswerSDP WebRTCSessionDescription `cbor:"3,keyasint,omitempty"`
  341. ICECandidateTypes ICECandidateTypes `cbor:"4,keyasint,omitempty"`
  342. AnswerError string `cbor:"5,keyasint,omitempty"`
  343. }
  344. // ProxyAnswerResponse is the acknowledgement for a ProxyAnswerRequest.
  345. type ProxyAnswerResponse struct {
  346. }
  347. // ClientRelayedPacketRequest is an API request sent from a client to a
  348. // broker, relaying a secure session packet from the Psiphon server to the
  349. // broker. This relay is a continuation of the broker/server exchange begun
  350. // with ClientOfferResponse.RelayPacketToServer. PacketFromServer is the next
  351. // packet from the server.
  352. //
  353. // When a broker attempts to use an existing session which has expired on the
  354. // server, the packet from the server may contain a signed reset session
  355. // token, which is used to automatically reset and start establishing a new
  356. // session before relaying the payload.
  357. type ClientRelayedPacketRequest struct {
  358. ConnectionID ID `cbor:"1,keyasint,omitempty"`
  359. PacketFromServer []byte `cbor:"2,keyasint,omitempty"`
  360. }
  361. // ClientRelayedPacketResponse returns the next packet from the broker to the
  362. // server. When PacketToServer is empty, the broker/server exchange is done
  363. // and the client stops relaying packets.
  364. type ClientRelayedPacketResponse struct {
  365. PacketToServer []byte `cbor:"1,keyasint,omitempty"`
  366. }
  367. // BrokerServerReport is a one-way API call sent from a broker to a
  368. // Psiphon server. This delivers, to the server, information that neither the
  369. // client nor the proxy is trusted to report. ProxyID is the proxy ID to be
  370. // logged with server_tunnel to attribute traffic to a specific proxy.
  371. // ClientIP is the original client IP as seen by the broker; this is the IP
  372. // value to be used in GeoIP-related operations including traffic rules,
  373. // tactics, and OSL progress. ProxyIP is the proxy IP as seen by the broker;
  374. // this value should match the Psiphon's server observed client IP.
  375. // Additional fields are metrics to be logged with server_tunnel.
  376. //
  377. // Using a one-way message here means that, once a broker/server session is
  378. // established, the entire relay can be encasulated in a single additional
  379. // field sent in the Psiphon API handshake. This minimizes observable and
  380. // potentially fingerprintable traffic flows as the client does not need to
  381. // relay any further session packets before starting the tunnel. The
  382. // trade-off is that the broker doesn't get an indication from the server
  383. // that the message was accepted or rejects and cannot directly, in real time
  384. // log any tunnel error associated with the server rejecting the message, or
  385. // log that the relay was completed successfully. These events can be logged
  386. // on the server and logs reconciled using the in-proxy Connection ID.
  387. type BrokerServerReport struct {
  388. ProxyID ID `cbor:"1,keyasint,omitempty"`
  389. ConnectionID ID `cbor:"2,keyasint,omitempty"`
  390. MatchedCommonCompartments bool `cbor:"3,keyasint,omitempty"`
  391. MatchedPersonalCompartments bool `cbor:"4,keyasint,omitempty"`
  392. ClientNATType NATType `cbor:"7,keyasint,omitempty"`
  393. ClientPortMappingTypes PortMappingTypes `cbor:"8,keyasint,omitempty"`
  394. ClientIP string `cbor:"9,keyasint,omitempty"`
  395. ProxyIP string `cbor:"10,keyasint,omitempty"`
  396. ProxyMetrics *ProxyMetrics `cbor:"11,keyasint,omitempty"`
  397. // These legacy fields are now sent in ProxyMetrics.
  398. ProxyNATType NATType `cbor:"5,keyasint,omitempty"`
  399. ProxyPortMappingTypes PortMappingTypes `cbor:"6,keyasint,omitempty"`
  400. }
  401. // GetNetworkType extracts the network_type from base API metrics and returns
  402. // a corresponding NetworkType. This is the one base metric that is used in
  403. // the broker logic, and not simply logged.
  404. func GetNetworkType(packedBaseParams protocol.PackedAPIParameters) NetworkType {
  405. baseNetworkType, ok := packedBaseParams.GetNetworkType()
  406. if !ok {
  407. return NetworkTypeUnknown
  408. }
  409. switch baseNetworkType {
  410. case "WIFI":
  411. return NetworkTypeWiFi
  412. case "MOBILE":
  413. return NetworkTypeMobile
  414. }
  415. return NetworkTypeUnknown
  416. }
  417. // Sanity check values.
  418. const (
  419. maxICECandidateTypes = 10
  420. maxPortMappingTypes = 10
  421. maxPaddedMessages = 100
  422. maxPaddingSize = 16384
  423. maxDecoyMessages = 100
  424. maxDecoySize = 16384
  425. )
  426. // ValidateAndGetParametersAndLogFields validates the ProxyMetrics and returns
  427. // Psiphon API parameters for processing and common.LogFields for logging.
  428. func (metrics *ProxyMetrics) ValidateAndGetParametersAndLogFields(
  429. baseAPIParameterValidator common.APIParameterValidator,
  430. formatter common.APIParameterLogFieldFormatter,
  431. logFieldPrefix string,
  432. geoIPData common.GeoIPData) (common.APIParameters, common.LogFields, error) {
  433. if metrics.BaseAPIParameters == nil {
  434. return nil, nil, errors.TraceNew("missing base API parameters")
  435. }
  436. baseParams, err := protocol.DecodePackedAPIParameters(metrics.BaseAPIParameters)
  437. if err != nil {
  438. return nil, nil, errors.Trace(err)
  439. }
  440. err = baseAPIParameterValidator(baseParams)
  441. if err != nil {
  442. return nil, nil, errors.Trace(err)
  443. }
  444. if metrics.ProxyProtocolVersion < 0 || metrics.ProxyProtocolVersion > proxyProtocolVersion {
  445. return nil, nil, errors.Tracef("invalid proxy protocol version: %v", metrics.ProxyProtocolVersion)
  446. }
  447. if !metrics.NATType.IsValid() {
  448. return nil, nil, errors.Tracef("invalid NAT type: %v", metrics.NATType)
  449. }
  450. if len(metrics.PortMappingTypes) > maxPortMappingTypes {
  451. return nil, nil, errors.Tracef("invalid portmapping types length: %d", len(metrics.PortMappingTypes))
  452. }
  453. if !metrics.PortMappingTypes.IsValid() {
  454. return nil, nil, errors.Tracef("invalid portmapping types: %v", metrics.PortMappingTypes)
  455. }
  456. logFields := formatter(logFieldPrefix, geoIPData, baseParams)
  457. logFields[logFieldPrefix+"proxy_protocol_version"] = metrics.ProxyProtocolVersion
  458. logFields[logFieldPrefix+"nat_type"] = metrics.NATType
  459. logFields[logFieldPrefix+"port_mapping_types"] = metrics.PortMappingTypes
  460. logFields[logFieldPrefix+"max_clients"] = metrics.MaxClients
  461. logFields[logFieldPrefix+"connecting_clients"] = metrics.ConnectingClients
  462. logFields[logFieldPrefix+"connected_clients"] = metrics.ConnectedClients
  463. logFields[logFieldPrefix+"limit_upstream_bytes_per_second"] = metrics.LimitUpstreamBytesPerSecond
  464. logFields[logFieldPrefix+"limit_downstream_bytes_per_second"] = metrics.LimitDownstreamBytesPerSecond
  465. logFields[logFieldPrefix+"peak_upstream_bytes_per_second"] = metrics.PeakUpstreamBytesPerSecond
  466. logFields[logFieldPrefix+"peak_downstream_bytes_per_second"] = metrics.PeakDownstreamBytesPerSecond
  467. return baseParams, logFields, nil
  468. }
  469. // ValidateAndGetLogFields validates the ClientMetrics and returns
  470. // common.LogFields for logging.
  471. func (metrics *ClientMetrics) ValidateAndGetLogFields(
  472. baseAPIParameterValidator common.APIParameterValidator,
  473. formatter common.APIParameterLogFieldFormatter,
  474. geoIPData common.GeoIPData) (common.LogFields, error) {
  475. if metrics.BaseAPIParameters == nil {
  476. return nil, errors.TraceNew("missing base API parameters")
  477. }
  478. baseParams, err := protocol.DecodePackedAPIParameters(metrics.BaseAPIParameters)
  479. if err != nil {
  480. return nil, errors.Trace(err)
  481. }
  482. err = baseAPIParameterValidator(baseParams)
  483. if err != nil {
  484. return nil, errors.Trace(err)
  485. }
  486. if metrics.ProxyProtocolVersion < 0 || metrics.ProxyProtocolVersion > proxyProtocolVersion {
  487. return nil, errors.Tracef("invalid proxy protocol version: %v", metrics.ProxyProtocolVersion)
  488. }
  489. if !metrics.NATType.IsValid() {
  490. return nil, errors.Tracef("invalid NAT type: %v", metrics.NATType)
  491. }
  492. if len(metrics.PortMappingTypes) > maxPortMappingTypes {
  493. return nil, errors.Tracef("invalid portmapping types length: %d", len(metrics.PortMappingTypes))
  494. }
  495. if !metrics.PortMappingTypes.IsValid() {
  496. return nil, errors.Tracef("invalid portmapping types: %v", metrics.PortMappingTypes)
  497. }
  498. logFields := formatter("", geoIPData, baseParams)
  499. logFields["proxy_protocol_version"] = metrics.ProxyProtocolVersion
  500. logFields["nat_type"] = metrics.NATType
  501. logFields["port_mapping_types"] = metrics.PortMappingTypes
  502. return logFields, nil
  503. }
  504. // ValidateAndGetParametersAndLogFields validates the ProxyAnnounceRequest and
  505. // returns Psiphon API parameters for processing and common.LogFields for
  506. // logging.
  507. func (request *ProxyAnnounceRequest) ValidateAndGetParametersAndLogFields(
  508. maxCompartmentIDs int,
  509. baseAPIParameterValidator common.APIParameterValidator,
  510. formatter common.APIParameterLogFieldFormatter,
  511. geoIPData common.GeoIPData) (common.APIParameters, common.LogFields, error) {
  512. // A proxy may specify at most 1 personal compartment ID. This is
  513. // currently a limitation of the multi-queue implementation; see comment
  514. // in announcementMultiQueue.enqueue.
  515. if len(request.PersonalCompartmentIDs) > 1 {
  516. return nil, nil, errors.Tracef(
  517. "invalid compartment IDs length: %d", len(request.PersonalCompartmentIDs))
  518. }
  519. if request.Metrics == nil {
  520. return nil, nil, errors.TraceNew("missing metrics")
  521. }
  522. apiParams, logFields, err := request.Metrics.ValidateAndGetParametersAndLogFields(
  523. baseAPIParameterValidator, formatter, "", geoIPData)
  524. if err != nil {
  525. return nil, nil, errors.Trace(err)
  526. }
  527. // PersonalCompartmentIDs are user-generated and shared out-of-band;
  528. // values are not logged since they may link users.
  529. hasPersonalCompartmentIDs := len(request.PersonalCompartmentIDs) > 0
  530. logFields["has_personal_compartment_ids"] = hasPersonalCompartmentIDs
  531. return apiParams, logFields, nil
  532. }
  533. // ValidateAndGetLogFields validates the ClientOfferRequest and returns
  534. // common.LogFields for logging.
  535. func (request *ClientOfferRequest) ValidateAndGetLogFields(
  536. maxCompartmentIDs int,
  537. lookupGeoIP LookupGeoIP,
  538. baseAPIParameterValidator common.APIParameterValidator,
  539. formatter common.APIParameterLogFieldFormatter,
  540. geoIPData common.GeoIPData) ([]byte, common.LogFields, error) {
  541. if len(request.CommonCompartmentIDs) > maxCompartmentIDs {
  542. return nil, nil, errors.Tracef(
  543. "invalid compartment IDs length: %d", len(request.CommonCompartmentIDs))
  544. }
  545. if len(request.PersonalCompartmentIDs) > maxCompartmentIDs {
  546. return nil, nil, errors.Tracef(
  547. "invalid compartment IDs length: %d", len(request.PersonalCompartmentIDs))
  548. }
  549. if len(request.CommonCompartmentIDs) > 0 && len(request.PersonalCompartmentIDs) > 0 {
  550. return nil, nil, errors.TraceNew("multiple compartment ID types")
  551. }
  552. // The client offer SDP may contain no ICE candidates.
  553. errorOnNoCandidates := false
  554. // The client offer SDP may include RFC 1918/4193 private IP addresses in
  555. // personal pairing mode. filterSDPAddresses should not filter out
  556. // private IP addresses based on the broker's local interfaces; this
  557. // filtering occurs on the proxy that receives the SDP.
  558. allowPrivateIPAddressCandidates :=
  559. len(request.PersonalCompartmentIDs) > 0 &&
  560. len(request.CommonCompartmentIDs) == 0
  561. filterPrivateIPAddressCandidates := false
  562. // Client offer SDP candidate addresses must match the country and ASN of
  563. // the client. Don't facilitate connections to arbitrary destinations.
  564. filteredSDP, sdpMetrics, err := filterSDPAddresses(
  565. []byte(request.ClientOfferSDP.SDP),
  566. errorOnNoCandidates,
  567. lookupGeoIP,
  568. geoIPData,
  569. allowPrivateIPAddressCandidates,
  570. filterPrivateIPAddressCandidates)
  571. if err != nil {
  572. return nil, nil, errors.Trace(err)
  573. }
  574. // The client's self-reported ICECandidateTypes are used instead of the
  575. // candidate types that can be derived from the SDP, since port mapping
  576. // types are edited into the SDP in a way that makes them
  577. // indistinguishable from host candidate types.
  578. if !request.ICECandidateTypes.IsValid() {
  579. return nil, nil, errors.Tracef(
  580. "invalid ICE candidate types: %v", request.ICECandidateTypes)
  581. }
  582. if request.Metrics == nil {
  583. return nil, nil, errors.TraceNew("missing metrics")
  584. }
  585. logFields, err := request.Metrics.ValidateAndGetLogFields(
  586. baseAPIParameterValidator, formatter, geoIPData)
  587. if err != nil {
  588. return nil, nil, errors.Trace(err)
  589. }
  590. if request.TrafficShapingParameters != nil {
  591. err := request.TrafficShapingParameters.Validate()
  592. if err != nil {
  593. return nil, nil, errors.Trace(err)
  594. }
  595. }
  596. // CommonCompartmentIDs are generated and managed and are a form of
  597. // obfuscation secret, so are not logged. PersonalCompartmentIDs are
  598. // user-generated and shared out-of-band; values are not logged since
  599. // they may link users.
  600. hasCommonCompartmentIDs := len(request.CommonCompartmentIDs) > 0
  601. hasPersonalCompartmentIDs := len(request.PersonalCompartmentIDs) > 0
  602. logFields["has_common_compartment_ids"] = hasCommonCompartmentIDs
  603. logFields["has_personal_compartment_ids"] = hasPersonalCompartmentIDs
  604. logFields["ice_candidate_types"] = request.ICECandidateTypes
  605. logFields["has_IPv6"] = sdpMetrics.hasIPv6
  606. logFields["has_private_IP"] = sdpMetrics.hasPrivateIP
  607. logFields["filtered_ice_candidates"] = sdpMetrics.filteredICECandidates
  608. return filteredSDP, logFields, nil
  609. }
  610. // Validate validates the that client has not specified excess traffic shaping
  611. // padding or decoy traffic.
  612. func (params *DataChannelTrafficShapingParameters) Validate() error {
  613. if params.MinPaddedMessages < 0 ||
  614. params.MinPaddedMessages > params.MaxPaddedMessages ||
  615. params.MaxPaddedMessages > maxPaddedMessages {
  616. return errors.TraceNew("invalid padded messages")
  617. }
  618. if params.MinPaddingSize < 0 ||
  619. params.MinPaddingSize > params.MaxPaddingSize ||
  620. params.MaxPaddingSize > maxPaddingSize {
  621. return errors.TraceNew("invalid padding size")
  622. }
  623. if params.MinDecoyMessages < 0 ||
  624. params.MinDecoyMessages > params.MaxDecoyMessages ||
  625. params.MaxDecoyMessages > maxDecoyMessages {
  626. return errors.TraceNew("invalid decoy messages")
  627. }
  628. if params.MinDecoySize < 0 ||
  629. params.MinDecoySize > params.MaxDecoySize ||
  630. params.MaxDecoySize > maxDecoySize {
  631. return errors.TraceNew("invalid decoy size")
  632. }
  633. return nil
  634. }
  635. // ValidateAndGetLogFields validates the ProxyAnswerRequest and returns
  636. // common.LogFields for logging.
  637. func (request *ProxyAnswerRequest) ValidateAndGetLogFields(
  638. lookupGeoIP LookupGeoIP,
  639. baseAPIParameterValidator common.APIParameterValidator,
  640. formatter common.APIParameterLogFieldFormatter,
  641. geoIPData common.GeoIPData,
  642. proxyAnnouncementHasPersonalCompartmentIDs bool) ([]byte, common.LogFields, error) {
  643. // The proxy answer SDP must contain at least one ICE candidate.
  644. errorOnNoCandidates := true
  645. // The proxy answer SDP may include RFC 1918/4193 private IP addresses in
  646. // personal pairing mode. filterSDPAddresses should not filter out
  647. // private IP addresses based on the broker's local interfaces; this
  648. // filtering occurs on the client that receives the SDP.
  649. allowPrivateIPAddressCandidates := proxyAnnouncementHasPersonalCompartmentIDs
  650. filterPrivateIPAddressCandidates := false
  651. // Proxy answer SDP candidate addresses must match the country and ASN of
  652. // the proxy. Don't facilitate connections to arbitrary destinations.
  653. filteredSDP, sdpMetrics, err := filterSDPAddresses(
  654. []byte(request.ProxyAnswerSDP.SDP),
  655. errorOnNoCandidates,
  656. lookupGeoIP,
  657. geoIPData,
  658. allowPrivateIPAddressCandidates,
  659. filterPrivateIPAddressCandidates)
  660. if err != nil {
  661. return nil, nil, errors.Trace(err)
  662. }
  663. // The proxy's self-reported ICECandidateTypes are used instead of the
  664. // candidate types that can be derived from the SDP, since port mapping
  665. // types are edited into the SDP in a way that makes them
  666. // indistinguishable from host candidate types.
  667. if !request.ICECandidateTypes.IsValid() {
  668. return nil, nil, errors.Tracef(
  669. "invalid ICE candidate types: %v", request.ICECandidateTypes)
  670. }
  671. if request.SelectedProxyProtocolVersion != ProxyProtocolVersion1 {
  672. return nil, nil, errors.Tracef(
  673. "invalid select proxy protocol version: %v", request.SelectedProxyProtocolVersion)
  674. }
  675. logFields := formatter("", geoIPData, common.APIParameters{})
  676. logFields["connection_id"] = request.ConnectionID
  677. logFields["ice_candidate_types"] = request.ICECandidateTypes
  678. logFields["has_IPv6"] = sdpMetrics.hasIPv6
  679. logFields["has_private_IP"] = sdpMetrics.hasPrivateIP
  680. logFields["filtered_ice_candidates"] = sdpMetrics.filteredICECandidates
  681. logFields["answer_error"] = request.AnswerError
  682. return filteredSDP, logFields, nil
  683. }
  684. // ValidateAndGetLogFields validates the ClientRelayedPacketRequest and returns
  685. // common.LogFields for logging.
  686. func (request *ClientRelayedPacketRequest) ValidateAndGetLogFields(
  687. baseAPIParameterValidator common.APIParameterValidator,
  688. formatter common.APIParameterLogFieldFormatter,
  689. geoIPData common.GeoIPData) (common.LogFields, error) {
  690. logFields := formatter("", geoIPData, common.APIParameters{})
  691. logFields["connection_id"] = request.ConnectionID
  692. return logFields, nil
  693. }
  694. // ValidateAndGetLogFields validates the BrokerServerReport and returns
  695. // common.LogFields for logging.
  696. func (report *BrokerServerReport) ValidateAndGetLogFields(
  697. baseAPIParameterValidator common.APIParameterValidator,
  698. formatter common.APIParameterLogFieldFormatter,
  699. proxyMetricsPrefix string) (common.LogFields, error) {
  700. // Neither ClientIP nor ProxyIP is logged.
  701. if !report.ClientNATType.IsValid() {
  702. return nil, errors.Tracef("invalid client NAT type: %v", report.ClientNATType)
  703. }
  704. if !report.ClientPortMappingTypes.IsValid() {
  705. return nil, errors.Tracef("invalid client portmapping types: %v", report.ClientPortMappingTypes)
  706. }
  707. var logFields common.LogFields
  708. if report.ProxyMetrics == nil {
  709. // Backwards compatibility for reports without ProxyMetrics.
  710. if !report.ProxyNATType.IsValid() {
  711. return nil, errors.Tracef("invalid proxy NAT type: %v", report.ProxyNATType)
  712. }
  713. if !report.ProxyPortMappingTypes.IsValid() {
  714. return nil, errors.Tracef("invalid proxy portmapping types: %v", report.ProxyPortMappingTypes)
  715. }
  716. logFields = common.LogFields{}
  717. logFields["inproxy_proxy_nat_type"] = report.ProxyNATType
  718. logFields["inproxy_proxy_port_mapping_types"] = report.ProxyPortMappingTypes
  719. } else {
  720. var err error
  721. _, logFields, err = report.ProxyMetrics.ValidateAndGetParametersAndLogFields(
  722. baseAPIParameterValidator,
  723. formatter,
  724. proxyMetricsPrefix,
  725. common.GeoIPData{}) // Proxy GeoIP data is added by the caller.
  726. if err != nil {
  727. return nil, errors.Trace(err)
  728. }
  729. }
  730. logFields["inproxy_proxy_id"] = report.ProxyID
  731. logFields["inproxy_connection_id"] = report.ConnectionID
  732. logFields["inproxy_matched_common_compartments"] = report.MatchedCommonCompartments
  733. logFields["inproxy_matched_personal_compartments"] = report.MatchedPersonalCompartments
  734. logFields["inproxy_client_nat_type"] = report.ClientNATType
  735. logFields["inproxy_client_port_mapping_types"] = report.ClientPortMappingTypes
  736. // TODO:
  737. // - log IPv4 vs. IPv6 information
  738. // - relay and log broker transport stats, such as meek HTTP version
  739. return logFields, nil
  740. }
  741. func MarshalProxyAnnounceRequest(request *ProxyAnnounceRequest) ([]byte, error) {
  742. payload, err := marshalRecord(request, recordTypeAPIProxyAnnounceRequest)
  743. return payload, errors.Trace(err)
  744. }
  745. func UnmarshalProxyAnnounceRequest(payload []byte) (*ProxyAnnounceRequest, error) {
  746. var request *ProxyAnnounceRequest
  747. err := unmarshalRecord(recordTypeAPIProxyAnnounceRequest, payload, &request)
  748. return request, errors.Trace(err)
  749. }
  750. func MarshalProxyAnnounceResponse(response *ProxyAnnounceResponse) ([]byte, error) {
  751. payload, err := marshalRecord(response, recordTypeAPIProxyAnnounceResponse)
  752. return payload, errors.Trace(err)
  753. }
  754. func UnmarshalProxyAnnounceResponse(payload []byte) (*ProxyAnnounceResponse, error) {
  755. var response *ProxyAnnounceResponse
  756. err := unmarshalRecord(recordTypeAPIProxyAnnounceResponse, payload, &response)
  757. return response, errors.Trace(err)
  758. }
  759. func MarshalProxyAnswerRequest(request *ProxyAnswerRequest) ([]byte, error) {
  760. payload, err := marshalRecord(request, recordTypeAPIProxyAnswerRequest)
  761. return payload, errors.Trace(err)
  762. }
  763. func UnmarshalProxyAnswerRequest(payload []byte) (*ProxyAnswerRequest, error) {
  764. var request *ProxyAnswerRequest
  765. err := unmarshalRecord(recordTypeAPIProxyAnswerRequest, payload, &request)
  766. return request, errors.Trace(err)
  767. }
  768. func MarshalProxyAnswerResponse(response *ProxyAnswerResponse) ([]byte, error) {
  769. payload, err := marshalRecord(response, recordTypeAPIProxyAnswerResponse)
  770. return payload, errors.Trace(err)
  771. }
  772. func UnmarshalProxyAnswerResponse(payload []byte) (*ProxyAnswerResponse, error) {
  773. var response *ProxyAnswerResponse
  774. err := unmarshalRecord(recordTypeAPIProxyAnswerResponse, payload, &response)
  775. return response, errors.Trace(err)
  776. }
  777. func MarshalClientOfferRequest(request *ClientOfferRequest) ([]byte, error) {
  778. payload, err := marshalRecord(request, recordTypeAPIClientOfferRequest)
  779. return payload, errors.Trace(err)
  780. }
  781. func UnmarshalClientOfferRequest(payload []byte) (*ClientOfferRequest, error) {
  782. var request *ClientOfferRequest
  783. err := unmarshalRecord(recordTypeAPIClientOfferRequest, payload, &request)
  784. return request, errors.Trace(err)
  785. }
  786. func MarshalClientOfferResponse(response *ClientOfferResponse) ([]byte, error) {
  787. payload, err := marshalRecord(response, recordTypeAPIClientOfferResponse)
  788. return payload, errors.Trace(err)
  789. }
  790. func UnmarshalClientOfferResponse(payload []byte) (*ClientOfferResponse, error) {
  791. var response *ClientOfferResponse
  792. err := unmarshalRecord(recordTypeAPIClientOfferResponse, payload, &response)
  793. return response, errors.Trace(err)
  794. }
  795. func MarshalClientRelayedPacketRequest(request *ClientRelayedPacketRequest) ([]byte, error) {
  796. payload, err := marshalRecord(request, recordTypeAPIClientRelayedPacketRequest)
  797. return payload, errors.Trace(err)
  798. }
  799. func UnmarshalClientRelayedPacketRequest(payload []byte) (*ClientRelayedPacketRequest, error) {
  800. var request *ClientRelayedPacketRequest
  801. err := unmarshalRecord(recordTypeAPIClientRelayedPacketRequest, payload, &request)
  802. return request, errors.Trace(err)
  803. }
  804. func MarshalClientRelayedPacketResponse(response *ClientRelayedPacketResponse) ([]byte, error) {
  805. payload, err := marshalRecord(response, recordTypeAPIClientRelayedPacketResponse)
  806. return payload, errors.Trace(err)
  807. }
  808. func UnmarshalClientRelayedPacketResponse(payload []byte) (*ClientRelayedPacketResponse, error) {
  809. var response *ClientRelayedPacketResponse
  810. err := unmarshalRecord(recordTypeAPIClientRelayedPacketResponse, payload, &response)
  811. return response, errors.Trace(err)
  812. }
  813. func MarshalBrokerServerReport(request *BrokerServerReport) ([]byte, error) {
  814. payload, err := marshalRecord(request, recordTypeAPIBrokerServerReport)
  815. return payload, errors.Trace(err)
  816. }
  817. func UnmarshalBrokerServerReport(payload []byte) (*BrokerServerReport, error) {
  818. var request *BrokerServerReport
  819. err := unmarshalRecord(recordTypeAPIBrokerServerReport, payload, &request)
  820. return request, errors.Trace(err)
  821. }