api.go 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  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. "encoding/binary"
  25. "math"
  26. "strconv"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  30. )
  31. const (
  32. // ProtocolVersion1 represents protocol version 1, the initial in-proxy
  33. // protocol version number.
  34. ProtocolVersion1 = int32(1)
  35. // ProtocolVersion2 represents protocol version 2, which adds support for
  36. // proxying over WebRTC media streams.
  37. ProtocolVersion2 = int32(2)
  38. // LatestProtocolVersion is the current, default protocol version number.
  39. LatestProtocolVersion = ProtocolVersion2
  40. // MinimumProxyProtocolVersion is the minimum required protocol version
  41. // number for proxies.
  42. MinimumProxyProtocolVersion = ProtocolVersion1
  43. // MinimumClientProtocolVersion is the minimum supported protocol version
  44. // number for clients.
  45. MinimumClientProtocolVersion = ProtocolVersion1
  46. MaxCompartmentIDs = 10
  47. )
  48. // minimumProxyProtocolVersion and minimumClientProtocolVersion are variable
  49. // to enable overriding the values in tests. These value should not be
  50. // overridden outside of test cases.
  51. var (
  52. minimumProxyProtocolVersion = MinimumProxyProtocolVersion
  53. minimumClientProtocolVersion = MinimumClientProtocolVersion
  54. )
  55. // negotiateProtocolVersion selects the in-proxy protocol version for a new
  56. // proxy/client match, based on the client's and proxy's reported protocol
  57. // versions, and the client's selected protocol options. Returns false if no
  58. // protocol version selection is possible.
  59. //
  60. // The broker performs the negotiation on behalf of the proxy and client. Both
  61. // the proxy and client initially specify the latest protocol version they
  62. // support. The client specifies the protocol options to use, based on
  63. // tactics and replay.
  64. //
  65. // negotiateProtocolVersion is used by the matcher when searching for
  66. // potential matches; for this reason, the failure case is expected and
  67. // returns a simple boolean intead of formating an error message.
  68. //
  69. // Existing, legacy proxies have the equivalent of an "if
  70. // announceResponse.SelectedProtocolVersion != ProtocolVersion1" check, so
  71. // the SelectedProtocolVersion must be downgraded in that case, if a match is
  72. // possible.
  73. func negotiateProtocolVersion(
  74. proxyProtocolVersion int32,
  75. clientProtocolVersion int32,
  76. useMediaStreams bool) (int32, bool) {
  77. // When not using WebRTC media streams, introduced in ProtocolVersion2,
  78. // potentially downgrade if either the proxy or client supports only
  79. // ProtocolVersion1.
  80. if (proxyProtocolVersion == ProtocolVersion1 ||
  81. clientProtocolVersion == ProtocolVersion1) &&
  82. !useMediaStreams {
  83. return ProtocolVersion1, true
  84. }
  85. // Select the client's protocol version.
  86. if proxyProtocolVersion >= clientProtocolVersion {
  87. return clientProtocolVersion, true
  88. }
  89. // No selection is possible. This includes the case where the proxy
  90. // supports up to ProtocolVersion1 and the client has specified media
  91. // streams.
  92. return 0, false
  93. }
  94. // ID is a unique identifier used to identify inproxy connections and actors.
  95. type ID [32]byte
  96. // MakeID generates a new ID using crypto/rand.
  97. func MakeID() (ID, error) {
  98. var id ID
  99. for {
  100. _, err := rand.Read(id[:])
  101. if err != nil {
  102. return id, errors.Trace(err)
  103. }
  104. if !id.Zero() {
  105. return id, nil
  106. }
  107. }
  108. }
  109. // IDFromString returns an ID given its string encoding.
  110. func IDFromString(s string) (ID, error) {
  111. var id ID
  112. return id, errors.Trace(fromBase64String(s, id[:]))
  113. }
  114. func fromBase64String(s string, b []byte) error {
  115. value, err := base64.RawStdEncoding.DecodeString(s)
  116. if err != nil {
  117. return errors.Trace(err)
  118. }
  119. if len(value) != len(b) {
  120. return errors.TraceNew("invalid length")
  121. }
  122. copy(b, value)
  123. return nil
  124. }
  125. // IDsFromStrings returns a list of IDs given a list of string encodings.
  126. func IDsFromStrings(strs []string) ([]ID, error) {
  127. var ids []ID
  128. for _, str := range strs {
  129. id, err := IDFromString(str)
  130. if err != nil {
  131. return nil, errors.Trace(err)
  132. }
  133. ids = append(ids, id)
  134. }
  135. return ids, nil
  136. }
  137. // MarshalText emits IDs as base64.
  138. func (id ID) MarshalText() ([]byte, error) {
  139. return []byte(id.String()), nil
  140. }
  141. // String emits IDs as base64.
  142. func (id ID) String() string {
  143. return base64.RawStdEncoding.EncodeToString([]byte(id[:]))
  144. }
  145. // Equal indicates whether two IDs are equal. It uses a constant time
  146. // comparison.
  147. func (id ID) Equal(x ID) bool {
  148. return subtle.ConstantTimeCompare(id[:], x[:]) == 1
  149. }
  150. // Zero indicates whether the ID is the zero value.
  151. func (id ID) Zero() bool {
  152. var zero ID
  153. return id.Equal(zero)
  154. }
  155. // HaveCommonIDs indicates whether two lists of IDs have a common entry.
  156. func HaveCommonIDs(a, b []ID) bool {
  157. for _, x := range a {
  158. for _, y := range b {
  159. // Each comparison is constant time, but the number of comparisons
  160. // varies and might leak the size of a list.
  161. if x.Equal(y) {
  162. return true
  163. }
  164. }
  165. }
  166. return false
  167. }
  168. // NetworkType is the type of a network, such as WiFi or Mobile. This enum is
  169. // used for compact API message encoding.
  170. type NetworkType int32
  171. const (
  172. NetworkTypeUnknown NetworkType = iota
  173. NetworkTypeWiFi
  174. NetworkTypeMobile
  175. NetworkTypeWired
  176. NetworkTypeVPN
  177. )
  178. // NetworkProtocol is an Internet protocol, such as TCP or UDP. This enum is
  179. // used for compact API message encoding.
  180. type NetworkProtocol int32
  181. const (
  182. NetworkProtocolTCP NetworkProtocol = iota
  183. NetworkProtocolUDP
  184. )
  185. // NetworkProtocolFromString converts a "net" package network protocol string
  186. // value to a NetworkProtocol.
  187. func NetworkProtocolFromString(networkProtocol string) (NetworkProtocol, error) {
  188. switch networkProtocol {
  189. case "tcp":
  190. return NetworkProtocolTCP, nil
  191. case "udp":
  192. return NetworkProtocolUDP, nil
  193. }
  194. var p NetworkProtocol
  195. return p, errors.Tracef("unknown network protocol: %s", networkProtocol)
  196. }
  197. // String converts a NetworkProtocol to a "net" package network protocol string.
  198. func (p NetworkProtocol) String() string {
  199. switch p {
  200. case NetworkProtocolTCP:
  201. return "tcp"
  202. case NetworkProtocolUDP:
  203. return "udp"
  204. }
  205. // This case will cause net dials to fail.
  206. return ""
  207. }
  208. // IsStream indicates if the NetworkProtocol is stream-oriented (e.g., TCP)
  209. // and not packet-oriented (e.g., UDP).
  210. func (p NetworkProtocol) IsStream() bool {
  211. switch p {
  212. case NetworkProtocolTCP:
  213. return true
  214. case NetworkProtocolUDP:
  215. return false
  216. }
  217. return false
  218. }
  219. // ProxyMetrics are network topolology and resource metrics provided by a
  220. // proxy to a broker. The broker uses this information when matching proxies
  221. // and clients.
  222. type ProxyMetrics struct {
  223. BaseAPIParameters protocol.PackedAPIParameters `cbor:"1,keyasint,omitempty"`
  224. ProtocolVersion int32 `cbor:"2,keyasint,omitempty"`
  225. NATType NATType `cbor:"3,keyasint,omitempty"`
  226. PortMappingTypes PortMappingTypes `cbor:"4,keyasint,omitempty"`
  227. MaxClients int32 `cbor:"6,keyasint,omitempty"`
  228. ConnectingClients int32 `cbor:"7,keyasint,omitempty"`
  229. ConnectedClients int32 `cbor:"8,keyasint,omitempty"`
  230. LimitUpstreamBytesPerSecond int64 `cbor:"9,keyasint,omitempty"`
  231. LimitDownstreamBytesPerSecond int64 `cbor:"10,keyasint,omitempty"`
  232. PeakUpstreamBytesPerSecond int64 `cbor:"11,keyasint,omitempty"`
  233. PeakDownstreamBytesPerSecond int64 `cbor:"12,keyasint,omitempty"`
  234. }
  235. // ClientMetrics are network topolology metrics provided by a client to a
  236. // broker. The broker uses this information when matching proxies and
  237. // clients.
  238. type ClientMetrics struct {
  239. BaseAPIParameters protocol.PackedAPIParameters `cbor:"1,keyasint,omitempty"`
  240. ProtocolVersion int32 `cbor:"2,keyasint,omitempty"`
  241. NATType NATType `cbor:"3,keyasint,omitempty"`
  242. PortMappingTypes PortMappingTypes `cbor:"4,keyasint,omitempty"`
  243. }
  244. // ProxyAnnounceRequest is an API request sent from a proxy to a broker,
  245. // announcing that it is available for a client connection. Proxies send one
  246. // ProxyAnnounceRequest for each available client connection. The broker will
  247. // match the proxy with a client and return WebRTC connection information
  248. // in the response.
  249. //
  250. // PersonalCompartmentIDs limits the clients to those that supply one of the
  251. // specified compartment IDs; personal compartment IDs are distributed from
  252. // proxy operators to client users out-of-band and provide optional access
  253. // control.
  254. //
  255. // When CheckTactics is set, the broker will check for new tactics or indicate
  256. // that the proxy's cached tactics TTL may be extended. Tactics information
  257. // is returned in the response TacticsPayload. To minimize broker processing
  258. // overhead, proxies with multiple workers should designate just one worker
  259. // to set CheckTactics.
  260. //
  261. // The proxy's session public key is an implicit and cryptographically
  262. // verified proxy ID.
  263. type ProxyAnnounceRequest struct {
  264. PersonalCompartmentIDs []ID `cbor:"1,keyasint,omitempty"`
  265. Metrics *ProxyMetrics `cbor:"2,keyasint,omitempty"`
  266. CheckTactics bool `cbor:"3,keyasint,omitempty"`
  267. }
  268. // WebRTCSessionDescription is compatible with pion/webrtc.SessionDescription
  269. // and facilitates the PSIPHON_ENABLE_INPROXY build tag exclusion of pion
  270. // dependencies.
  271. type WebRTCSessionDescription struct {
  272. Type int `cbor:"1,keyasint,omitempty"`
  273. SDP string `cbor:"2,keyasint,omitempty"`
  274. }
  275. // TODO: send ProxyAnnounceRequest/ClientOfferRequest.Metrics only with the
  276. // first request in a session and cache.
  277. // ProxyAnnounceResponse returns the connection information for a matched
  278. // client. To establish a WebRTC connection, the proxy uses the client's
  279. // offer SDP to create its own answer SDP and send that to the broker in a
  280. // subsequent ProxyAnswerRequest. The ConnectionID is a unique identifier for
  281. // this single connection and must be relayed back in the ProxyAnswerRequest.
  282. //
  283. // ClientRootObfuscationSecret is generated (or replayed) by the client and
  284. // sent to the proxy and used to drive obfuscation operations.
  285. //
  286. // DestinationAddress is the dial address for the Psiphon server the proxy is
  287. // to relay client traffic with. The broker validates that the dial address
  288. // corresponds to a valid Psiphon server.
  289. //
  290. // MustUpgrade is an optional flag that is set by the broker, based on the
  291. // submitted ProtocolVersion, when the proxy app must be upgraded in order to
  292. // function properly. Potential must-upgrade scenarios include changes to the
  293. // personal pairing broker rendezvous algorithm, where no protocol backwards
  294. // compatibility accommodations can ensure a rendezvous and match. When
  295. // MustUpgrade is set, NoMatch is implied.
  296. type ProxyAnnounceResponse struct {
  297. TacticsPayload []byte `cbor:"2,keyasint,omitempty"`
  298. Limited bool `cbor:"3,keyasint,omitempty"`
  299. NoMatch bool `cbor:"4,keyasint,omitempty"`
  300. MustUpgrade bool `cbor:"13,keyasint,omitempty"`
  301. ConnectionID ID `cbor:"5,keyasint,omitempty"`
  302. SelectedProtocolVersion int32 `cbor:"6,keyasint,omitempty"`
  303. ClientOfferSDP WebRTCSessionDescription `cbor:"7,keyasint,omitempty"`
  304. ClientRootObfuscationSecret ObfuscationSecret `cbor:"8,keyasint,omitempty"`
  305. DoDTLSRandomization bool `cbor:"9,keyasint,omitempty"`
  306. UseMediaStreams bool `cbor:"14,keyasint,omitempty"`
  307. TrafficShapingParameters *TrafficShapingParameters `cbor:"10,keyasint,omitempty"`
  308. NetworkProtocol NetworkProtocol `cbor:"11,keyasint,omitempty"`
  309. DestinationAddress string `cbor:"12,keyasint,omitempty"`
  310. }
  311. // ClientOfferRequest is an API request sent from a client to a broker,
  312. // requesting a proxy connection. The client sends its WebRTC offer SDP with
  313. // this request.
  314. //
  315. // Clients specify known compartment IDs and are matched with proxies in those
  316. // compartments. CommonCompartmentIDs are comparment IDs managed by Psiphon
  317. // and revealed through tactics or bundled with server lists.
  318. // PersonalCompartmentIDs are compartment IDs shared privately between users,
  319. // out-of-band.
  320. //
  321. // ClientRootObfuscationSecret is generated (or replayed) by the client and
  322. // sent to the proxy and used to drive obfuscation operations.
  323. //
  324. // To specify the Psiphon server it wishes to proxy to, the client sends the
  325. // full, digitally signed Psiphon server entry to the broker and also the
  326. // specific dial address that it has selected for that server. The broker
  327. // validates the server entry signature, the server in-proxy capability, and
  328. // that the dial address corresponds to the network protocol, IP address or
  329. // domain, and destination port for a valid Psiphon tunnel protocol run by
  330. // the specified server entry.
  331. type ClientOfferRequest struct {
  332. Metrics *ClientMetrics `cbor:"1,keyasint,omitempty"`
  333. CommonCompartmentIDs []ID `cbor:"2,keyasint,omitempty"`
  334. PersonalCompartmentIDs []ID `cbor:"3,keyasint,omitempty"`
  335. ClientOfferSDP WebRTCSessionDescription `cbor:"4,keyasint,omitempty"`
  336. ICECandidateTypes ICECandidateTypes `cbor:"5,keyasint,omitempty"`
  337. ClientRootObfuscationSecret ObfuscationSecret `cbor:"6,keyasint,omitempty"`
  338. DoDTLSRandomization bool `cbor:"7,keyasint,omitempty"`
  339. UseMediaStreams bool `cbor:"12,keyasint,omitempty"`
  340. TrafficShapingParameters *TrafficShapingParameters `cbor:"8,keyasint,omitempty"`
  341. PackedDestinationServerEntry []byte `cbor:"9,keyasint,omitempty"`
  342. NetworkProtocol NetworkProtocol `cbor:"10,keyasint,omitempty"`
  343. DestinationAddress string `cbor:"11,keyasint,omitempty"`
  344. }
  345. // TrafficShapingParameters specifies data channel or media stream traffic
  346. // shaping configuration, including random padding and decoy messages (or
  347. // packets). Clients determine their own traffic shaping configuration, and
  348. // generate and send a configuration for the peer proxy to use.
  349. type TrafficShapingParameters struct {
  350. MinPaddedMessages int `cbor:"1,keyasint,omitempty"`
  351. MaxPaddedMessages int `cbor:"2,keyasint,omitempty"`
  352. MinPaddingSize int `cbor:"3,keyasint,omitempty"`
  353. MaxPaddingSize int `cbor:"4,keyasint,omitempty"`
  354. MinDecoyMessages int `cbor:"5,keyasint,omitempty"`
  355. MaxDecoyMessages int `cbor:"6,keyasint,omitempty"`
  356. MinDecoySize int `cbor:"7,keyasint,omitempty"`
  357. MaxDecoySize int `cbor:"8,keyasint,omitempty"`
  358. DecoyMessageProbability float64 `cbor:"9,keyasint,omitempty"`
  359. }
  360. // ClientOfferResponse returns the connecting information for a matched proxy.
  361. // The proxy's WebRTC SDP is an answer to the offer sent in
  362. // ClientOfferRequest and is used to begin dialing the WebRTC connection.
  363. //
  364. // Once the client completes its connection to the Psiphon server, it must
  365. // relay a BrokerServerReport to the server on behalf of the broker. This
  366. // relay is conducted within a secure session. First, the client sends
  367. // RelayPacketToServer to the server. Then the client relays any responses to
  368. // the broker using ClientRelayedPacketRequests and continues to relay using
  369. // ClientRelayedPacketRequests until complete. ConnectionID identifies this
  370. // connection and its relayed BrokerServerReport.
  371. //
  372. // MustUpgrade is an optional flag that is set by the broker, based on the
  373. // submitted ProtocolVersion, when the client app must be upgraded in order
  374. // to function properly. Potential must-upgrade scenarios include changes to
  375. // the personal pairing broker rendezvous algorithm, where no protocol
  376. // backwards compatibility accommodations can ensure a rendezvous and match.
  377. // When MustUpgrade is set, NoMatch is implied.
  378. type ClientOfferResponse struct {
  379. Limited bool `cbor:"1,keyasint,omitempty"`
  380. NoMatch bool `cbor:"2,keyasint,omitempty"`
  381. MustUpgrade bool `cbor:"7,keyasint,omitempty"`
  382. ConnectionID ID `cbor:"3,keyasint,omitempty"`
  383. SelectedProtocolVersion int32 `cbor:"4,keyasint,omitempty"`
  384. ProxyAnswerSDP WebRTCSessionDescription `cbor:"5,keyasint,omitempty"`
  385. RelayPacketToServer []byte `cbor:"6,keyasint,omitempty"`
  386. }
  387. // TODO: Encode SDPs using CBOR without field names, simliar to packed metrics?
  388. // ProxyAnswerRequest is an API request sent from a proxy to a broker,
  389. // following ProxyAnnounceResponse, with the WebRTC answer SDP corresponding
  390. // to the client offer SDP received in ProxyAnnounceResponse. ConnectionID
  391. // identifies the connection begun in ProxyAnnounceResponse.
  392. //
  393. // If the proxy was unable to establish an answer SDP or failed for some other
  394. // reason, it should still send ProxyAnswerRequest with AnswerError
  395. // populated; the broker will signal the client to abort this connection.
  396. type ProxyAnswerRequest struct {
  397. ConnectionID ID `cbor:"1,keyasint,omitempty"`
  398. ProxyAnswerSDP WebRTCSessionDescription `cbor:"3,keyasint,omitempty"`
  399. ICECandidateTypes ICECandidateTypes `cbor:"4,keyasint,omitempty"`
  400. AnswerError string `cbor:"5,keyasint,omitempty"`
  401. // These fields are no longer used.
  402. //
  403. // SelectedProtocolVersion int32 `cbor:"2,keyasint,omitempty"`
  404. }
  405. // ProxyAnswerResponse is the acknowledgement for a ProxyAnswerRequest.
  406. type ProxyAnswerResponse struct {
  407. }
  408. // ClientRelayedPacketRequest is an API request sent from a client to a
  409. // broker, relaying a secure session packet from the Psiphon server to the
  410. // broker. This relay is a continuation of the broker/server exchange begun
  411. // with ClientOfferResponse.RelayPacketToServer. PacketFromServer is the next
  412. // packet from the server.
  413. //
  414. // When a broker attempts to use an existing session which has expired on the
  415. // server, the packet from the server may contain a signed reset session
  416. // token, which is used to automatically reset and start establishing a new
  417. // session before relaying the payload.
  418. type ClientRelayedPacketRequest struct {
  419. ConnectionID ID `cbor:"1,keyasint,omitempty"`
  420. PacketFromServer []byte `cbor:"2,keyasint,omitempty"`
  421. }
  422. // ClientRelayedPacketResponse returns the next packet from the broker to the
  423. // server. When PacketToServer is empty, the broker/server exchange is done
  424. // and the client stops relaying packets.
  425. type ClientRelayedPacketResponse struct {
  426. PacketToServer []byte `cbor:"1,keyasint,omitempty"`
  427. }
  428. // BrokerServerReport is a one-way API call sent from a broker to a
  429. // Psiphon server. This delivers, to the server, information that neither the
  430. // client nor the proxy is trusted to report. ProxyID is the proxy ID to be
  431. // logged with server_tunnel to attribute traffic to a specific proxy.
  432. // ClientIP is the original client IP as seen by the broker; this is the IP
  433. // value to be used in GeoIP-related operations including traffic rules,
  434. // tactics, and OSL progress. ProxyIP is the proxy IP as seen by the broker;
  435. // this value should match the Psiphon's server observed client IP.
  436. // Additional fields are metrics to be logged with server_tunnel.
  437. //
  438. // Using a one-way message here means that, once a broker/server session is
  439. // established, the entire relay can be encasulated in a single additional
  440. // field sent in the Psiphon API handshake. This minimizes observable and
  441. // potentially fingerprintable traffic flows as the client does not need to
  442. // relay any further session packets before starting the tunnel. The
  443. // trade-off is that the broker doesn't get an indication from the server
  444. // that the message was accepted or rejects and cannot directly, in real time
  445. // log any tunnel error associated with the server rejecting the message, or
  446. // log that the relay was completed successfully. These events can be logged
  447. // on the server and logs reconciled using the in-proxy Connection ID.
  448. type BrokerServerReport struct {
  449. ProxyID ID `cbor:"1,keyasint,omitempty"`
  450. ConnectionID ID `cbor:"2,keyasint,omitempty"`
  451. MatchedCommonCompartments bool `cbor:"3,keyasint,omitempty"`
  452. MatchedPersonalCompartments bool `cbor:"4,keyasint,omitempty"`
  453. ClientNATType NATType `cbor:"7,keyasint,omitempty"`
  454. ClientPortMappingTypes PortMappingTypes `cbor:"8,keyasint,omitempty"`
  455. ClientIP string `cbor:"9,keyasint,omitempty"`
  456. ProxyIP string `cbor:"10,keyasint,omitempty"`
  457. ProxyMetrics *ProxyMetrics `cbor:"11,keyasint,omitempty"`
  458. ProxyIsPriority bool `cbor:"12,keyasint,omitempty"`
  459. // These legacy fields are now sent in ProxyMetrics.
  460. ProxyNATType NATType `cbor:"5,keyasint,omitempty"`
  461. ProxyPortMappingTypes PortMappingTypes `cbor:"6,keyasint,omitempty"`
  462. }
  463. // ClientDSLRequest is a client DSL request that the broker relays to the DSL
  464. // backend. The broker's role is to provide a blocking resistant initial
  465. // hop; DSL requests are not direct components of the in-proxy protocol.
  466. type ClientDSLRequest struct {
  467. RequestPayload []byte `cbor:"1,keyasint,omitempty"`
  468. }
  469. // ClientDSLResponse is a DSL response relayed back to the client.
  470. type ClientDSLResponse struct {
  471. ResponsePayload []byte `cbor:"1,keyasint,omitempty"`
  472. }
  473. // ProxyQualityKey is the key that proxy quality is indexed on a proxy ID and
  474. // a proxy ASN. Quality is tracked at a fine-grained level, with the proxy ID
  475. // representing, typically, an individual device, and the proxy ASN
  476. // representing the network the device used at the time a quality tunnel was
  477. // reported.
  478. type ProxyQualityKey [36]byte
  479. // MakeProxyQualityKey creates a ProxyQualityKey using the given proxy ID and
  480. // proxy ASN. In the key, the proxy ID remains encoded as-is, and the ASN is
  481. // encoded in the 4-byte representation (see RFC6793).
  482. func MakeProxyQualityKey(proxyID ID, proxyASN string) ProxyQualityKey {
  483. var key ProxyQualityKey
  484. copy(key[0:32], proxyID[:])
  485. ASN, err := strconv.ParseInt(proxyASN, 10, 0)
  486. if err != nil || ASN < 0 || ASN > math.MaxUint32 {
  487. // In cases including failed or misconfigured GeoIP lookups -- with
  488. // values such as server.GEOIP_UNKNOWN_VALUE or invalid AS numbers --
  489. // fall back to a reserved AS number (see RFC5398). This is, effectively, a less
  490. // fine-grained key.
  491. //
  492. // Note that GeoIP lookups are performed server-side and a proxy
  493. // itself cannot force this downgrade (to obtain false quality
  494. // classification across different networks).
  495. ASN = 65536
  496. }
  497. binary.BigEndian.PutUint32(key[32:36], uint32(ASN))
  498. return key
  499. }
  500. // ProxyQualityASNCounts is tunnel quality data, a map from client ASNs to
  501. // counts of quality tunnels that a proxy relayed for those client ASNs.
  502. type ProxyQualityASNCounts map[string]int
  503. // ProxyQualityRequestCounts is ProxyQualityASNCounts for a set of proxies.
  504. type ProxyQualityRequestCounts map[ProxyQualityKey]ProxyQualityASNCounts
  505. // ServerProxyQualityRequest is an API request sent from a server to a broker,
  506. // reporting a set of proxy IDs/ASNs that have relayed quality tunnels -- as
  507. // determined by bytes transferred and duration thresholds -- for clients in
  508. // the given ASNs. This quality data is used, by brokers, to prioritize
  509. // well-performing proxies, and to match clients with proxies that worked
  510. // successfully for the client's ASN.
  511. //
  512. // QualityCounts is a map from proxy ID/ASN to ASN quality tunnel counts.
  513. //
  514. // DialParameters specifies additional parameters to log with proxy quality
  515. // broker events, including any relevant server broker dial parameters.
  516. // Unlike clients and proxies, servers do not send BaseAPIParameters to
  517. // brokers.
  518. type ServerProxyQualityRequest struct {
  519. QualityCounts ProxyQualityRequestCounts `cbor:"1,keyasint,omitempty"`
  520. DialParameters protocol.PackedAPIParameters `cbor:"2,keyasint,omitempty"`
  521. }
  522. // ServerProxyQualityResponse is the acknowledgement for a
  523. // ServerProxyQualityRequest.
  524. type ServerProxyQualityResponse struct {
  525. }
  526. // GetNetworkType extracts the network_type from base API metrics and returns
  527. // a corresponding NetworkType. This is the one base metric that is used in
  528. // the broker logic, and not simply logged.
  529. func GetNetworkType(packedBaseParams protocol.PackedAPIParameters) NetworkType {
  530. baseNetworkType, ok := packedBaseParams.GetNetworkType()
  531. if !ok {
  532. return NetworkTypeUnknown
  533. }
  534. switch baseNetworkType {
  535. case "WIFI":
  536. return NetworkTypeWiFi
  537. case "MOBILE":
  538. return NetworkTypeMobile
  539. case "WIRED":
  540. return NetworkTypeWired
  541. case "VPN":
  542. return NetworkTypeVPN
  543. }
  544. return NetworkTypeUnknown
  545. }
  546. // Sanity check values.
  547. const (
  548. maxICECandidateTypes = 10
  549. maxPortMappingTypes = 10
  550. maxPaddedMessages = 100
  551. maxPaddingSize = 16384
  552. maxDecoyMessages = 100
  553. maxDecoySize = 16384
  554. maxQualityCounts = 10000
  555. )
  556. // ValidateAndGetParametersAndLogFields validates the ProxyMetrics and returns
  557. // Psiphon API parameters for processing and common.LogFields for logging.
  558. func (metrics *ProxyMetrics) ValidateAndGetParametersAndLogFields(
  559. baseAPIParameterValidator common.APIParameterValidator,
  560. formatter common.APIParameterLogFieldFormatter,
  561. logFieldPrefix string,
  562. geoIPData common.GeoIPData) (common.APIParameters, common.LogFields, error) {
  563. if metrics.BaseAPIParameters == nil {
  564. return nil, nil, errors.TraceNew("missing base API parameters")
  565. }
  566. baseParams, err := protocol.DecodePackedAPIParameters(metrics.BaseAPIParameters)
  567. if err != nil {
  568. return nil, nil, errors.Trace(err)
  569. }
  570. err = baseAPIParameterValidator(baseParams)
  571. if err != nil {
  572. return nil, nil, errors.Trace(err)
  573. }
  574. if metrics.ProtocolVersion < ProtocolVersion1 || metrics.ProtocolVersion > LatestProtocolVersion {
  575. return nil, nil, errors.Tracef("invalid protocol version: %v", metrics.ProtocolVersion)
  576. }
  577. if !metrics.NATType.IsValid() {
  578. return nil, nil, errors.Tracef("invalid NAT type: %v", metrics.NATType)
  579. }
  580. if len(metrics.PortMappingTypes) > maxPortMappingTypes {
  581. return nil, nil, errors.Tracef("invalid portmapping types length: %d", len(metrics.PortMappingTypes))
  582. }
  583. if !metrics.PortMappingTypes.IsValid() {
  584. return nil, nil, errors.Tracef("invalid portmapping types: %v", metrics.PortMappingTypes)
  585. }
  586. logFields := formatter(logFieldPrefix, geoIPData, baseParams)
  587. logFields[logFieldPrefix+"protocol_version"] = metrics.ProtocolVersion
  588. logFields[logFieldPrefix+"nat_type"] = metrics.NATType
  589. logFields[logFieldPrefix+"port_mapping_types"] = metrics.PortMappingTypes
  590. logFields[logFieldPrefix+"max_clients"] = metrics.MaxClients
  591. logFields[logFieldPrefix+"connecting_clients"] = metrics.ConnectingClients
  592. logFields[logFieldPrefix+"connected_clients"] = metrics.ConnectedClients
  593. logFields[logFieldPrefix+"limit_upstream_bytes_per_second"] = metrics.LimitUpstreamBytesPerSecond
  594. logFields[logFieldPrefix+"limit_downstream_bytes_per_second"] = metrics.LimitDownstreamBytesPerSecond
  595. logFields[logFieldPrefix+"peak_upstream_bytes_per_second"] = metrics.PeakUpstreamBytesPerSecond
  596. logFields[logFieldPrefix+"peak_downstream_bytes_per_second"] = metrics.PeakDownstreamBytesPerSecond
  597. return baseParams, logFields, nil
  598. }
  599. // ValidateAndGetLogFields validates the ClientMetrics and returns
  600. // common.LogFields for logging.
  601. func (metrics *ClientMetrics) ValidateAndGetLogFields(
  602. baseAPIParameterValidator common.APIParameterValidator,
  603. formatter common.APIParameterLogFieldFormatter,
  604. geoIPData common.GeoIPData) (common.LogFields, error) {
  605. if metrics.BaseAPIParameters == nil {
  606. return nil, errors.TraceNew("missing base API parameters")
  607. }
  608. baseParams, err := protocol.DecodePackedAPIParameters(metrics.BaseAPIParameters)
  609. if err != nil {
  610. return nil, errors.Trace(err)
  611. }
  612. err = baseAPIParameterValidator(baseParams)
  613. if err != nil {
  614. return nil, errors.Trace(err)
  615. }
  616. if metrics.ProtocolVersion < ProtocolVersion1 || metrics.ProtocolVersion > LatestProtocolVersion {
  617. return nil, errors.Tracef("invalid protocol version: %v", metrics.ProtocolVersion)
  618. }
  619. if !metrics.NATType.IsValid() {
  620. return nil, errors.Tracef("invalid NAT type: %v", metrics.NATType)
  621. }
  622. if len(metrics.PortMappingTypes) > maxPortMappingTypes {
  623. return nil, errors.Tracef("invalid portmapping types length: %d", len(metrics.PortMappingTypes))
  624. }
  625. if !metrics.PortMappingTypes.IsValid() {
  626. return nil, errors.Tracef("invalid portmapping types: %v", metrics.PortMappingTypes)
  627. }
  628. logFields := formatter("", geoIPData, baseParams)
  629. logFields["protocol_version"] = metrics.ProtocolVersion
  630. logFields["nat_type"] = metrics.NATType
  631. logFields["port_mapping_types"] = metrics.PortMappingTypes
  632. return logFields, nil
  633. }
  634. // ValidateAndGetParametersAndLogFields validates the ProxyAnnounceRequest and
  635. // returns Psiphon API parameters for processing and common.LogFields for
  636. // logging.
  637. func (request *ProxyAnnounceRequest) ValidateAndGetParametersAndLogFields(
  638. maxCompartmentIDs int,
  639. baseAPIParameterValidator common.APIParameterValidator,
  640. formatter common.APIParameterLogFieldFormatter,
  641. geoIPData common.GeoIPData) (common.APIParameters, common.LogFields, error) {
  642. // A proxy may specify at most 1 personal compartment ID. This is
  643. // currently a limitation of the multi-queue implementation; see comment
  644. // in announcementMultiQueue.enqueue.
  645. if len(request.PersonalCompartmentIDs) > 1 {
  646. return nil, nil, errors.Tracef(
  647. "invalid compartment IDs length: %d", len(request.PersonalCompartmentIDs))
  648. }
  649. if request.Metrics == nil {
  650. return nil, nil, errors.TraceNew("missing metrics")
  651. }
  652. apiParams, logFields, err := request.Metrics.ValidateAndGetParametersAndLogFields(
  653. baseAPIParameterValidator, formatter, "", geoIPData)
  654. if err != nil {
  655. return nil, nil, errors.Trace(err)
  656. }
  657. // PersonalCompartmentIDs are user-generated and shared out-of-band;
  658. // values are not logged since they may link users.
  659. hasPersonalCompartmentIDs := len(request.PersonalCompartmentIDs) > 0
  660. logFields["has_personal_compartment_ids"] = hasPersonalCompartmentIDs
  661. return apiParams, logFields, nil
  662. }
  663. // ValidateAndGetLogFields validates the ClientOfferRequest and returns
  664. // common.LogFields for logging.
  665. func (request *ClientOfferRequest) ValidateAndGetLogFields(
  666. maxCompartmentIDs int,
  667. lookupGeoIP LookupGeoIP,
  668. baseAPIParameterValidator common.APIParameterValidator,
  669. formatter common.APIParameterLogFieldFormatter,
  670. geoIPData common.GeoIPData) ([]byte, common.LogFields, error) {
  671. // UseMediaStreams requires at least ProtocolVersion2.
  672. if request.UseMediaStreams &&
  673. request.Metrics.ProtocolVersion < ProtocolVersion2 {
  674. return nil, nil, errors.Tracef(
  675. "invalid protocol version: %d", request.Metrics.ProtocolVersion)
  676. }
  677. if len(request.CommonCompartmentIDs) > maxCompartmentIDs {
  678. return nil, nil, errors.Tracef(
  679. "invalid compartment IDs length: %d", len(request.CommonCompartmentIDs))
  680. }
  681. if len(request.PersonalCompartmentIDs) > maxCompartmentIDs {
  682. return nil, nil, errors.Tracef(
  683. "invalid compartment IDs length: %d", len(request.PersonalCompartmentIDs))
  684. }
  685. if len(request.CommonCompartmentIDs) > 0 && len(request.PersonalCompartmentIDs) > 0 {
  686. return nil, nil, errors.TraceNew("multiple compartment ID types")
  687. }
  688. // The client offer SDP may contain no ICE candidates.
  689. errorOnNoCandidates := false
  690. // The client offer SDP may include RFC 1918/4193 private IP addresses in
  691. // personal pairing mode. filterSDPAddresses should not filter out
  692. // private IP addresses based on the broker's local interfaces; this
  693. // filtering occurs on the proxy that receives the SDP.
  694. allowPrivateIPAddressCandidates :=
  695. len(request.PersonalCompartmentIDs) > 0 &&
  696. len(request.CommonCompartmentIDs) == 0
  697. filterPrivateIPAddressCandidates := false
  698. // Client offer SDP candidate addresses must match the country and ASN of
  699. // the client. Don't facilitate connections to arbitrary destinations.
  700. filteredSDP, sdpMetrics, err := filterSDPAddresses(
  701. []byte(request.ClientOfferSDP.SDP),
  702. errorOnNoCandidates,
  703. lookupGeoIP,
  704. geoIPData,
  705. allowPrivateIPAddressCandidates,
  706. filterPrivateIPAddressCandidates)
  707. if err != nil {
  708. return nil, nil, errors.Trace(err)
  709. }
  710. // The client's self-reported ICECandidateTypes are used instead of the
  711. // candidate types that can be derived from the SDP, since port mapping
  712. // types are edited into the SDP in a way that makes them
  713. // indistinguishable from host candidate types.
  714. if !request.ICECandidateTypes.IsValid() {
  715. return nil, nil, errors.Tracef(
  716. "invalid ICE candidate types: %v", request.ICECandidateTypes)
  717. }
  718. if request.Metrics == nil {
  719. return nil, nil, errors.TraceNew("missing metrics")
  720. }
  721. logFields, err := request.Metrics.ValidateAndGetLogFields(
  722. baseAPIParameterValidator, formatter, geoIPData)
  723. if err != nil {
  724. return nil, nil, errors.Trace(err)
  725. }
  726. if request.TrafficShapingParameters != nil {
  727. err := request.TrafficShapingParameters.Validate()
  728. if err != nil {
  729. return nil, nil, errors.Trace(err)
  730. }
  731. }
  732. // CommonCompartmentIDs are generated and managed and are a form of
  733. // obfuscation secret, so are not logged. PersonalCompartmentIDs are
  734. // user-generated and shared out-of-band; values are not logged since
  735. // they may link users.
  736. hasCommonCompartmentIDs := len(request.CommonCompartmentIDs) > 0
  737. hasPersonalCompartmentIDs := len(request.PersonalCompartmentIDs) > 0
  738. logFields["has_common_compartment_ids"] = hasCommonCompartmentIDs
  739. logFields["has_personal_compartment_ids"] = hasPersonalCompartmentIDs
  740. logFields["ice_candidate_types"] = request.ICECandidateTypes
  741. logFields["has_IPv6"] = sdpMetrics.hasIPv6
  742. logFields["has_private_IP"] = sdpMetrics.hasPrivateIP
  743. logFields["filtered_ice_candidates"] = sdpMetrics.filteredICECandidates
  744. logFields["use_media_streams"] = request.UseMediaStreams
  745. return filteredSDP, logFields, nil
  746. }
  747. // Validate validates the that client has not specified excess traffic shaping
  748. // padding or decoy traffic.
  749. func (params *TrafficShapingParameters) Validate() error {
  750. if params.MinPaddedMessages < 0 ||
  751. params.MinPaddedMessages > params.MaxPaddedMessages ||
  752. params.MaxPaddedMessages > maxPaddedMessages {
  753. return errors.TraceNew("invalid padded messages")
  754. }
  755. if params.MinPaddingSize < 0 ||
  756. params.MinPaddingSize > params.MaxPaddingSize ||
  757. params.MaxPaddingSize > maxPaddingSize {
  758. return errors.TraceNew("invalid padding size")
  759. }
  760. if params.MinDecoyMessages < 0 ||
  761. params.MinDecoyMessages > params.MaxDecoyMessages ||
  762. params.MaxDecoyMessages > maxDecoyMessages {
  763. return errors.TraceNew("invalid decoy messages")
  764. }
  765. if params.MinDecoySize < 0 ||
  766. params.MinDecoySize > params.MaxDecoySize ||
  767. params.MaxDecoySize > maxDecoySize {
  768. return errors.TraceNew("invalid decoy size")
  769. }
  770. return nil
  771. }
  772. // ValidateAndGetLogFields validates the ProxyAnswerRequest and returns
  773. // common.LogFields for logging.
  774. func (request *ProxyAnswerRequest) ValidateAndGetLogFields(
  775. lookupGeoIP LookupGeoIP,
  776. baseAPIParameterValidator common.APIParameterValidator,
  777. formatter common.APIParameterLogFieldFormatter,
  778. geoIPData common.GeoIPData,
  779. proxyAnnouncementHasPersonalCompartmentIDs bool) ([]byte, common.LogFields, error) {
  780. // The proxy answer SDP must contain at least one ICE candidate.
  781. errorOnNoCandidates := true
  782. // The proxy answer SDP may include RFC 1918/4193 private IP addresses in
  783. // personal pairing mode. filterSDPAddresses should not filter out
  784. // private IP addresses based on the broker's local interfaces; this
  785. // filtering occurs on the client that receives the SDP.
  786. allowPrivateIPAddressCandidates := proxyAnnouncementHasPersonalCompartmentIDs
  787. filterPrivateIPAddressCandidates := false
  788. // Proxy answer SDP candidate addresses must match the country and ASN of
  789. // the proxy. Don't facilitate connections to arbitrary destinations.
  790. filteredSDP, sdpMetrics, err := filterSDPAddresses(
  791. []byte(request.ProxyAnswerSDP.SDP),
  792. errorOnNoCandidates,
  793. lookupGeoIP,
  794. geoIPData,
  795. allowPrivateIPAddressCandidates,
  796. filterPrivateIPAddressCandidates)
  797. if err != nil {
  798. return nil, nil, errors.Trace(err)
  799. }
  800. // The proxy's self-reported ICECandidateTypes are used instead of the
  801. // candidate types that can be derived from the SDP, since port mapping
  802. // types are edited into the SDP in a way that makes them
  803. // indistinguishable from host candidate types.
  804. if !request.ICECandidateTypes.IsValid() {
  805. return nil, nil, errors.Tracef(
  806. "invalid ICE candidate types: %v", request.ICECandidateTypes)
  807. }
  808. logFields := formatter("", geoIPData, common.APIParameters{})
  809. logFields["connection_id"] = request.ConnectionID
  810. logFields["ice_candidate_types"] = request.ICECandidateTypes
  811. logFields["has_IPv6"] = sdpMetrics.hasIPv6
  812. logFields["has_private_IP"] = sdpMetrics.hasPrivateIP
  813. logFields["filtered_ice_candidates"] = sdpMetrics.filteredICECandidates
  814. logFields["answer_error"] = request.AnswerError
  815. return filteredSDP, logFields, nil
  816. }
  817. // ValidateAndGetLogFields validates the ClientRelayedPacketRequest and returns
  818. // common.LogFields for logging.
  819. func (request *ClientRelayedPacketRequest) ValidateAndGetLogFields(
  820. baseAPIParameterValidator common.APIParameterValidator,
  821. formatter common.APIParameterLogFieldFormatter,
  822. geoIPData common.GeoIPData) (common.LogFields, error) {
  823. logFields := formatter("", geoIPData, common.APIParameters{})
  824. logFields["connection_id"] = request.ConnectionID
  825. return logFields, nil
  826. }
  827. // ValidateAndGetLogFields validates the BrokerServerReport and returns
  828. // common.LogFields for logging.
  829. func (report *BrokerServerReport) ValidateAndGetLogFields(
  830. baseAPIParameterValidator common.APIParameterValidator,
  831. formatter common.APIParameterLogFieldFormatter,
  832. proxyMetricsPrefix string) (common.LogFields, error) {
  833. // Neither ClientIP nor ProxyIP is logged.
  834. if !report.ClientNATType.IsValid() {
  835. return nil, errors.Tracef("invalid client NAT type: %v", report.ClientNATType)
  836. }
  837. if !report.ClientPortMappingTypes.IsValid() {
  838. return nil, errors.Tracef("invalid client portmapping types: %v", report.ClientPortMappingTypes)
  839. }
  840. var logFields common.LogFields
  841. if report.ProxyMetrics == nil {
  842. // Backwards compatibility for reports without ProxyMetrics.
  843. if !report.ProxyNATType.IsValid() {
  844. return nil, errors.Tracef("invalid proxy NAT type: %v", report.ProxyNATType)
  845. }
  846. if !report.ProxyPortMappingTypes.IsValid() {
  847. return nil, errors.Tracef("invalid proxy portmapping types: %v", report.ProxyPortMappingTypes)
  848. }
  849. logFields = common.LogFields{}
  850. logFields["inproxy_proxy_nat_type"] = report.ProxyNATType
  851. logFields["inproxy_proxy_port_mapping_types"] = report.ProxyPortMappingTypes
  852. } else {
  853. var err error
  854. _, logFields, err = report.ProxyMetrics.ValidateAndGetParametersAndLogFields(
  855. baseAPIParameterValidator,
  856. formatter,
  857. proxyMetricsPrefix,
  858. common.GeoIPData{}) // Proxy GeoIP data is added by the caller.
  859. if err != nil {
  860. return nil, errors.Trace(err)
  861. }
  862. }
  863. logFields["inproxy_proxy_id"] = report.ProxyID
  864. logFields["inproxy_connection_id"] = report.ConnectionID
  865. logFields["inproxy_matched_common_compartments"] = report.MatchedCommonCompartments
  866. logFields["inproxy_matched_personal_compartments"] = report.MatchedPersonalCompartments
  867. logFields["inproxy_client_nat_type"] = report.ClientNATType
  868. logFields["inproxy_client_port_mapping_types"] = report.ClientPortMappingTypes
  869. logFields["inproxy_proxy_is_priority"] = report.ProxyIsPriority
  870. // TODO:
  871. // - log IPv4 vs. IPv6 information
  872. // - relay and log broker transport stats, such as meek HTTP version
  873. return logFields, nil
  874. }
  875. // ValidateAndGetLogFields validates the ServerProxyQualityRequest and returns
  876. // common.LogFields for logging.
  877. func (request *ServerProxyQualityRequest) ValidateAndGetLogFields() (common.LogFields, error) {
  878. if len(request.QualityCounts) > maxQualityCounts {
  879. return nil, errors.Tracef("invalid quality count length: %d", len(request.QualityCounts))
  880. }
  881. // Currently, there is no custom validator or formatter for
  882. // DialParameters, as there is for the BaseAPIParameters sent by clients
  883. // and proxies:
  884. //
  885. // - The DialParameters inputs, used only to annotate logs, are from a
  886. // trusted Psiphon server.
  887. //
  888. // - Psiphon servers do not send fields required by the existing
  889. // BaseAPIParameters validators, such as sponsor ID.
  890. //
  891. // - No formatter transforms, such as "0"/"1" to bool, are currently
  892. // expected; and server.getRequestLogFields is inefficient when a
  893. // couple of log fields are expected; for an example for any future
  894. // special case formatter, see
  895. // server.getInproxyBrokerServerReportParameterLogFieldFormatter.
  896. dialParams, err := protocol.DecodePackedAPIParameters(request.DialParameters)
  897. if err != nil {
  898. return nil, errors.Trace(err)
  899. }
  900. logFields := common.LogFields(dialParams)
  901. return logFields, nil
  902. }
  903. func MarshalProxyAnnounceRequest(request *ProxyAnnounceRequest) ([]byte, error) {
  904. payload, err := marshalRecord(request, recordTypeAPIProxyAnnounceRequest)
  905. return payload, errors.Trace(err)
  906. }
  907. func UnmarshalProxyAnnounceRequest(payload []byte) (*ProxyAnnounceRequest, error) {
  908. var request *ProxyAnnounceRequest
  909. err := unmarshalRecord(recordTypeAPIProxyAnnounceRequest, payload, &request)
  910. return request, errors.Trace(err)
  911. }
  912. func MarshalProxyAnnounceResponse(response *ProxyAnnounceResponse) ([]byte, error) {
  913. payload, err := marshalRecord(response, recordTypeAPIProxyAnnounceResponse)
  914. return payload, errors.Trace(err)
  915. }
  916. func UnmarshalProxyAnnounceResponse(payload []byte) (*ProxyAnnounceResponse, error) {
  917. var response *ProxyAnnounceResponse
  918. err := unmarshalRecord(recordTypeAPIProxyAnnounceResponse, payload, &response)
  919. return response, errors.Trace(err)
  920. }
  921. func MarshalProxyAnswerRequest(request *ProxyAnswerRequest) ([]byte, error) {
  922. payload, err := marshalRecord(request, recordTypeAPIProxyAnswerRequest)
  923. return payload, errors.Trace(err)
  924. }
  925. func UnmarshalProxyAnswerRequest(payload []byte) (*ProxyAnswerRequest, error) {
  926. var request *ProxyAnswerRequest
  927. err := unmarshalRecord(recordTypeAPIProxyAnswerRequest, payload, &request)
  928. return request, errors.Trace(err)
  929. }
  930. func MarshalProxyAnswerResponse(response *ProxyAnswerResponse) ([]byte, error) {
  931. payload, err := marshalRecord(response, recordTypeAPIProxyAnswerResponse)
  932. return payload, errors.Trace(err)
  933. }
  934. func UnmarshalProxyAnswerResponse(payload []byte) (*ProxyAnswerResponse, error) {
  935. var response *ProxyAnswerResponse
  936. err := unmarshalRecord(recordTypeAPIProxyAnswerResponse, payload, &response)
  937. return response, errors.Trace(err)
  938. }
  939. func MarshalClientOfferRequest(request *ClientOfferRequest) ([]byte, error) {
  940. payload, err := marshalRecord(request, recordTypeAPIClientOfferRequest)
  941. return payload, errors.Trace(err)
  942. }
  943. func UnmarshalClientOfferRequest(payload []byte) (*ClientOfferRequest, error) {
  944. var request *ClientOfferRequest
  945. err := unmarshalRecord(recordTypeAPIClientOfferRequest, payload, &request)
  946. return request, errors.Trace(err)
  947. }
  948. func MarshalClientOfferResponse(response *ClientOfferResponse) ([]byte, error) {
  949. payload, err := marshalRecord(response, recordTypeAPIClientOfferResponse)
  950. return payload, errors.Trace(err)
  951. }
  952. func UnmarshalClientOfferResponse(payload []byte) (*ClientOfferResponse, error) {
  953. var response *ClientOfferResponse
  954. err := unmarshalRecord(recordTypeAPIClientOfferResponse, payload, &response)
  955. return response, errors.Trace(err)
  956. }
  957. func MarshalClientRelayedPacketRequest(request *ClientRelayedPacketRequest) ([]byte, error) {
  958. payload, err := marshalRecord(request, recordTypeAPIClientRelayedPacketRequest)
  959. return payload, errors.Trace(err)
  960. }
  961. func UnmarshalClientRelayedPacketRequest(payload []byte) (*ClientRelayedPacketRequest, error) {
  962. var request *ClientRelayedPacketRequest
  963. err := unmarshalRecord(recordTypeAPIClientRelayedPacketRequest, payload, &request)
  964. return request, errors.Trace(err)
  965. }
  966. func MarshalClientRelayedPacketResponse(response *ClientRelayedPacketResponse) ([]byte, error) {
  967. payload, err := marshalRecord(response, recordTypeAPIClientRelayedPacketResponse)
  968. return payload, errors.Trace(err)
  969. }
  970. func UnmarshalClientRelayedPacketResponse(payload []byte) (*ClientRelayedPacketResponse, error) {
  971. var response *ClientRelayedPacketResponse
  972. err := unmarshalRecord(recordTypeAPIClientRelayedPacketResponse, payload, &response)
  973. return response, errors.Trace(err)
  974. }
  975. func MarshalBrokerServerReport(request *BrokerServerReport) ([]byte, error) {
  976. payload, err := marshalRecord(request, recordTypeAPIBrokerServerReport)
  977. return payload, errors.Trace(err)
  978. }
  979. func UnmarshalBrokerServerReport(payload []byte) (*BrokerServerReport, error) {
  980. var request *BrokerServerReport
  981. err := unmarshalRecord(recordTypeAPIBrokerServerReport, payload, &request)
  982. return request, errors.Trace(err)
  983. }
  984. func MarshalServerProxyQualityRequest(request *ServerProxyQualityRequest) ([]byte, error) {
  985. payload, err := marshalRecord(request, recordTypeAPIServerProxyQualityRequest)
  986. return payload, errors.Trace(err)
  987. }
  988. func UnmarshalServerProxyQualityRequest(payload []byte) (*ServerProxyQualityRequest, error) {
  989. var request *ServerProxyQualityRequest
  990. err := unmarshalRecord(recordTypeAPIServerProxyQualityRequest, payload, &request)
  991. return request, errors.Trace(err)
  992. }
  993. func MarshalServerProxyQualityResponse(response *ServerProxyQualityResponse) ([]byte, error) {
  994. payload, err := marshalRecord(response, recordTypeAPIServerProxyQualityResponse)
  995. return payload, errors.Trace(err)
  996. }
  997. func UnmarshalServerProxyQualityResponse(payload []byte) (*ServerProxyQualityResponse, error) {
  998. var response *ServerProxyQualityResponse
  999. err := unmarshalRecord(recordTypeAPIServerProxyQualityResponse, payload, &response)
  1000. return response, errors.Trace(err)
  1001. }
  1002. func MarshalClientDSLRequest(request *ClientDSLRequest) ([]byte, error) {
  1003. payload, err := marshalRecord(request, recordTypeAPIClientDSLRequest)
  1004. return payload, errors.Trace(err)
  1005. }
  1006. func UnmarshalClientDSLRequest(payload []byte) (*ClientDSLRequest, error) {
  1007. var request *ClientDSLRequest
  1008. err := unmarshalRecord(recordTypeAPIClientDSLRequest, payload, &request)
  1009. return request, errors.Trace(err)
  1010. }
  1011. func MarshalClientDSLResponse(response *ClientDSLResponse) ([]byte, error) {
  1012. payload, err := marshalRecord(response, recordTypeAPIClientDSLResponse)
  1013. return payload, errors.Trace(err)
  1014. }
  1015. func UnmarshalClientDSLResponse(payload []byte) (*ClientDSLResponse, error) {
  1016. var response *ClientDSLResponse
  1017. err := unmarshalRecord(recordTypeAPIClientDSLResponse, payload, &response)
  1018. return response, errors.Trace(err)
  1019. }