api.go 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  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. // ProxyQualityKey is the key that proxy quality is indexed on a proxy ID and
  464. // a proxy ASN. Quality is tracked at a fine-grained level, with the proxy ID
  465. // representing, typically, an individual device, and the proxy ASN
  466. // representing the network the device used at the time a quality tunnel was
  467. // reported.
  468. type ProxyQualityKey [36]byte
  469. // MakeProxyQualityKey creates a ProxyQualityKey using the given proxy ID and
  470. // proxy ASN. In the key, the proxy ID remains encoded as-is, and the ASN is
  471. // encoded in the 4-byte representation (see RFC6793).
  472. func MakeProxyQualityKey(proxyID ID, proxyASN string) ProxyQualityKey {
  473. var key ProxyQualityKey
  474. copy(key[0:32], proxyID[:])
  475. ASN, err := strconv.ParseInt(proxyASN, 10, 0)
  476. if err != nil || ASN < 0 || ASN > math.MaxUint32 {
  477. // In cases including failed or misconfigured GeoIP lookups -- with
  478. // values such as server.GEOIP_UNKNOWN_VALUE or invalid AS numbers --
  479. // fall back to a reserved AS number (see RFC5398). This is, effectively, a less
  480. // fine-grained key.
  481. //
  482. // Note that GeoIP lookups are performed server-side and a proxy
  483. // itself cannot force this downgrade (to obtain false quality
  484. // classification across different networks).
  485. ASN = 65536
  486. }
  487. binary.BigEndian.PutUint32(key[32:36], uint32(ASN))
  488. return key
  489. }
  490. // ProxyQualityASNCounts is tunnel quality data, a map from client ASNs to
  491. // counts of quality tunnels that a proxy relayed for those client ASNs.
  492. type ProxyQualityASNCounts map[string]int
  493. // ProxyQualityRequestCounts is ProxyQualityASNCounts for a set of proxies.
  494. type ProxyQualityRequestCounts map[ProxyQualityKey]ProxyQualityASNCounts
  495. // ServerProxyQualityRequest is an API request sent from a server to a broker,
  496. // reporting a set of proxy IDs/ASNs that have relayed quality tunnels -- as
  497. // determined by bytes transferred and duration thresholds -- for clients in
  498. // the given ASNs. This quality data is used, by brokers, to prioritize
  499. // well-performing proxies, and to match clients with proxies that worked
  500. // successfully for the client's ASN.
  501. //
  502. // QualityCounts is a map from proxy ID/ASN to ASN quality tunnel counts.
  503. //
  504. // DialParameters specifies additional parameters to log with proxy quality
  505. // broker events, including any relevant server broker dial parameters.
  506. // Unlike clients and proxies, servers do not send BaseAPIParameters to
  507. // brokers.
  508. type ServerProxyQualityRequest struct {
  509. QualityCounts ProxyQualityRequestCounts `cbor:"1,keyasint,omitempty"`
  510. DialParameters protocol.PackedAPIParameters `cbor:"2,keyasint,omitempty"`
  511. }
  512. // ServerProxyQualityResponse is the acknowledgement for a
  513. // ServerProxyQualityRequest.
  514. type ServerProxyQualityResponse struct {
  515. }
  516. // GetNetworkType extracts the network_type from base API metrics and returns
  517. // a corresponding NetworkType. This is the one base metric that is used in
  518. // the broker logic, and not simply logged.
  519. func GetNetworkType(packedBaseParams protocol.PackedAPIParameters) NetworkType {
  520. baseNetworkType, ok := packedBaseParams.GetNetworkType()
  521. if !ok {
  522. return NetworkTypeUnknown
  523. }
  524. switch baseNetworkType {
  525. case "WIFI":
  526. return NetworkTypeWiFi
  527. case "MOBILE":
  528. return NetworkTypeMobile
  529. case "WIRED":
  530. return NetworkTypeWired
  531. case "VPN":
  532. return NetworkTypeVPN
  533. }
  534. return NetworkTypeUnknown
  535. }
  536. // Sanity check values.
  537. const (
  538. maxICECandidateTypes = 10
  539. maxPortMappingTypes = 10
  540. maxPaddedMessages = 100
  541. maxPaddingSize = 16384
  542. maxDecoyMessages = 100
  543. maxDecoySize = 16384
  544. maxQualityCounts = 10000
  545. )
  546. // ValidateAndGetParametersAndLogFields validates the ProxyMetrics and returns
  547. // Psiphon API parameters for processing and common.LogFields for logging.
  548. func (metrics *ProxyMetrics) ValidateAndGetParametersAndLogFields(
  549. baseAPIParameterValidator common.APIParameterValidator,
  550. formatter common.APIParameterLogFieldFormatter,
  551. logFieldPrefix string,
  552. geoIPData common.GeoIPData) (common.APIParameters, common.LogFields, error) {
  553. if metrics.BaseAPIParameters == nil {
  554. return nil, nil, errors.TraceNew("missing base API parameters")
  555. }
  556. baseParams, err := protocol.DecodePackedAPIParameters(metrics.BaseAPIParameters)
  557. if err != nil {
  558. return nil, nil, errors.Trace(err)
  559. }
  560. err = baseAPIParameterValidator(baseParams)
  561. if err != nil {
  562. return nil, nil, errors.Trace(err)
  563. }
  564. if metrics.ProtocolVersion < ProtocolVersion1 || metrics.ProtocolVersion > LatestProtocolVersion {
  565. return nil, nil, errors.Tracef("invalid protocol version: %v", metrics.ProtocolVersion)
  566. }
  567. if !metrics.NATType.IsValid() {
  568. return nil, nil, errors.Tracef("invalid NAT type: %v", metrics.NATType)
  569. }
  570. if len(metrics.PortMappingTypes) > maxPortMappingTypes {
  571. return nil, nil, errors.Tracef("invalid portmapping types length: %d", len(metrics.PortMappingTypes))
  572. }
  573. if !metrics.PortMappingTypes.IsValid() {
  574. return nil, nil, errors.Tracef("invalid portmapping types: %v", metrics.PortMappingTypes)
  575. }
  576. logFields := formatter(logFieldPrefix, geoIPData, baseParams)
  577. logFields[logFieldPrefix+"protocol_version"] = metrics.ProtocolVersion
  578. logFields[logFieldPrefix+"nat_type"] = metrics.NATType
  579. logFields[logFieldPrefix+"port_mapping_types"] = metrics.PortMappingTypes
  580. logFields[logFieldPrefix+"max_clients"] = metrics.MaxClients
  581. logFields[logFieldPrefix+"connecting_clients"] = metrics.ConnectingClients
  582. logFields[logFieldPrefix+"connected_clients"] = metrics.ConnectedClients
  583. logFields[logFieldPrefix+"limit_upstream_bytes_per_second"] = metrics.LimitUpstreamBytesPerSecond
  584. logFields[logFieldPrefix+"limit_downstream_bytes_per_second"] = metrics.LimitDownstreamBytesPerSecond
  585. logFields[logFieldPrefix+"peak_upstream_bytes_per_second"] = metrics.PeakUpstreamBytesPerSecond
  586. logFields[logFieldPrefix+"peak_downstream_bytes_per_second"] = metrics.PeakDownstreamBytesPerSecond
  587. return baseParams, logFields, nil
  588. }
  589. // ValidateAndGetLogFields validates the ClientMetrics and returns
  590. // common.LogFields for logging.
  591. func (metrics *ClientMetrics) ValidateAndGetLogFields(
  592. baseAPIParameterValidator common.APIParameterValidator,
  593. formatter common.APIParameterLogFieldFormatter,
  594. geoIPData common.GeoIPData) (common.LogFields, error) {
  595. if metrics.BaseAPIParameters == nil {
  596. return nil, errors.TraceNew("missing base API parameters")
  597. }
  598. baseParams, err := protocol.DecodePackedAPIParameters(metrics.BaseAPIParameters)
  599. if err != nil {
  600. return nil, errors.Trace(err)
  601. }
  602. err = baseAPIParameterValidator(baseParams)
  603. if err != nil {
  604. return nil, errors.Trace(err)
  605. }
  606. if metrics.ProtocolVersion < ProtocolVersion1 || metrics.ProtocolVersion > LatestProtocolVersion {
  607. return nil, errors.Tracef("invalid protocol version: %v", metrics.ProtocolVersion)
  608. }
  609. if !metrics.NATType.IsValid() {
  610. return nil, errors.Tracef("invalid NAT type: %v", metrics.NATType)
  611. }
  612. if len(metrics.PortMappingTypes) > maxPortMappingTypes {
  613. return nil, errors.Tracef("invalid portmapping types length: %d", len(metrics.PortMappingTypes))
  614. }
  615. if !metrics.PortMappingTypes.IsValid() {
  616. return nil, errors.Tracef("invalid portmapping types: %v", metrics.PortMappingTypes)
  617. }
  618. logFields := formatter("", geoIPData, baseParams)
  619. logFields["protocol_version"] = metrics.ProtocolVersion
  620. logFields["nat_type"] = metrics.NATType
  621. logFields["port_mapping_types"] = metrics.PortMappingTypes
  622. return logFields, nil
  623. }
  624. // ValidateAndGetParametersAndLogFields validates the ProxyAnnounceRequest and
  625. // returns Psiphon API parameters for processing and common.LogFields for
  626. // logging.
  627. func (request *ProxyAnnounceRequest) ValidateAndGetParametersAndLogFields(
  628. maxCompartmentIDs int,
  629. baseAPIParameterValidator common.APIParameterValidator,
  630. formatter common.APIParameterLogFieldFormatter,
  631. geoIPData common.GeoIPData) (common.APIParameters, common.LogFields, error) {
  632. // A proxy may specify at most 1 personal compartment ID. This is
  633. // currently a limitation of the multi-queue implementation; see comment
  634. // in announcementMultiQueue.enqueue.
  635. if len(request.PersonalCompartmentIDs) > 1 {
  636. return nil, nil, errors.Tracef(
  637. "invalid compartment IDs length: %d", len(request.PersonalCompartmentIDs))
  638. }
  639. if request.Metrics == nil {
  640. return nil, nil, errors.TraceNew("missing metrics")
  641. }
  642. apiParams, logFields, err := request.Metrics.ValidateAndGetParametersAndLogFields(
  643. baseAPIParameterValidator, formatter, "", geoIPData)
  644. if err != nil {
  645. return nil, nil, errors.Trace(err)
  646. }
  647. // PersonalCompartmentIDs are user-generated and shared out-of-band;
  648. // values are not logged since they may link users.
  649. hasPersonalCompartmentIDs := len(request.PersonalCompartmentIDs) > 0
  650. logFields["has_personal_compartment_ids"] = hasPersonalCompartmentIDs
  651. return apiParams, logFields, nil
  652. }
  653. // ValidateAndGetLogFields validates the ClientOfferRequest and returns
  654. // common.LogFields for logging.
  655. func (request *ClientOfferRequest) ValidateAndGetLogFields(
  656. maxCompartmentIDs int,
  657. lookupGeoIP LookupGeoIP,
  658. baseAPIParameterValidator common.APIParameterValidator,
  659. formatter common.APIParameterLogFieldFormatter,
  660. geoIPData common.GeoIPData) ([]byte, common.LogFields, error) {
  661. // UseMediaStreams requires at least ProtocolVersion2.
  662. if request.UseMediaStreams &&
  663. request.Metrics.ProtocolVersion < ProtocolVersion2 {
  664. return nil, nil, errors.Tracef(
  665. "invalid protocol version: %d", request.Metrics.ProtocolVersion)
  666. }
  667. if len(request.CommonCompartmentIDs) > maxCompartmentIDs {
  668. return nil, nil, errors.Tracef(
  669. "invalid compartment IDs length: %d", len(request.CommonCompartmentIDs))
  670. }
  671. if len(request.PersonalCompartmentIDs) > maxCompartmentIDs {
  672. return nil, nil, errors.Tracef(
  673. "invalid compartment IDs length: %d", len(request.PersonalCompartmentIDs))
  674. }
  675. if len(request.CommonCompartmentIDs) > 0 && len(request.PersonalCompartmentIDs) > 0 {
  676. return nil, nil, errors.TraceNew("multiple compartment ID types")
  677. }
  678. // The client offer SDP may contain no ICE candidates.
  679. errorOnNoCandidates := false
  680. // The client offer SDP may include RFC 1918/4193 private IP addresses in
  681. // personal pairing mode. filterSDPAddresses should not filter out
  682. // private IP addresses based on the broker's local interfaces; this
  683. // filtering occurs on the proxy that receives the SDP.
  684. allowPrivateIPAddressCandidates :=
  685. len(request.PersonalCompartmentIDs) > 0 &&
  686. len(request.CommonCompartmentIDs) == 0
  687. filterPrivateIPAddressCandidates := false
  688. // Client offer SDP candidate addresses must match the country and ASN of
  689. // the client. Don't facilitate connections to arbitrary destinations.
  690. filteredSDP, sdpMetrics, err := filterSDPAddresses(
  691. []byte(request.ClientOfferSDP.SDP),
  692. errorOnNoCandidates,
  693. lookupGeoIP,
  694. geoIPData,
  695. allowPrivateIPAddressCandidates,
  696. filterPrivateIPAddressCandidates)
  697. if err != nil {
  698. return nil, nil, errors.Trace(err)
  699. }
  700. // The client's self-reported ICECandidateTypes are used instead of the
  701. // candidate types that can be derived from the SDP, since port mapping
  702. // types are edited into the SDP in a way that makes them
  703. // indistinguishable from host candidate types.
  704. if !request.ICECandidateTypes.IsValid() {
  705. return nil, nil, errors.Tracef(
  706. "invalid ICE candidate types: %v", request.ICECandidateTypes)
  707. }
  708. if request.Metrics == nil {
  709. return nil, nil, errors.TraceNew("missing metrics")
  710. }
  711. logFields, err := request.Metrics.ValidateAndGetLogFields(
  712. baseAPIParameterValidator, formatter, geoIPData)
  713. if err != nil {
  714. return nil, nil, errors.Trace(err)
  715. }
  716. if request.TrafficShapingParameters != nil {
  717. err := request.TrafficShapingParameters.Validate()
  718. if err != nil {
  719. return nil, nil, errors.Trace(err)
  720. }
  721. }
  722. // CommonCompartmentIDs are generated and managed and are a form of
  723. // obfuscation secret, so are not logged. PersonalCompartmentIDs are
  724. // user-generated and shared out-of-band; values are not logged since
  725. // they may link users.
  726. hasCommonCompartmentIDs := len(request.CommonCompartmentIDs) > 0
  727. hasPersonalCompartmentIDs := len(request.PersonalCompartmentIDs) > 0
  728. logFields["has_common_compartment_ids"] = hasCommonCompartmentIDs
  729. logFields["has_personal_compartment_ids"] = hasPersonalCompartmentIDs
  730. logFields["ice_candidate_types"] = request.ICECandidateTypes
  731. logFields["has_IPv6"] = sdpMetrics.hasIPv6
  732. logFields["has_private_IP"] = sdpMetrics.hasPrivateIP
  733. logFields["filtered_ice_candidates"] = sdpMetrics.filteredICECandidates
  734. logFields["use_media_streams"] = request.UseMediaStreams
  735. return filteredSDP, logFields, nil
  736. }
  737. // Validate validates the that client has not specified excess traffic shaping
  738. // padding or decoy traffic.
  739. func (params *TrafficShapingParameters) Validate() error {
  740. if params.MinPaddedMessages < 0 ||
  741. params.MinPaddedMessages > params.MaxPaddedMessages ||
  742. params.MaxPaddedMessages > maxPaddedMessages {
  743. return errors.TraceNew("invalid padded messages")
  744. }
  745. if params.MinPaddingSize < 0 ||
  746. params.MinPaddingSize > params.MaxPaddingSize ||
  747. params.MaxPaddingSize > maxPaddingSize {
  748. return errors.TraceNew("invalid padding size")
  749. }
  750. if params.MinDecoyMessages < 0 ||
  751. params.MinDecoyMessages > params.MaxDecoyMessages ||
  752. params.MaxDecoyMessages > maxDecoyMessages {
  753. return errors.TraceNew("invalid decoy messages")
  754. }
  755. if params.MinDecoySize < 0 ||
  756. params.MinDecoySize > params.MaxDecoySize ||
  757. params.MaxDecoySize > maxDecoySize {
  758. return errors.TraceNew("invalid decoy size")
  759. }
  760. return nil
  761. }
  762. // ValidateAndGetLogFields validates the ProxyAnswerRequest and returns
  763. // common.LogFields for logging.
  764. func (request *ProxyAnswerRequest) ValidateAndGetLogFields(
  765. lookupGeoIP LookupGeoIP,
  766. baseAPIParameterValidator common.APIParameterValidator,
  767. formatter common.APIParameterLogFieldFormatter,
  768. geoIPData common.GeoIPData,
  769. proxyAnnouncementHasPersonalCompartmentIDs bool) ([]byte, common.LogFields, error) {
  770. // The proxy answer SDP must contain at least one ICE candidate.
  771. errorOnNoCandidates := true
  772. // The proxy answer SDP may include RFC 1918/4193 private IP addresses in
  773. // personal pairing mode. filterSDPAddresses should not filter out
  774. // private IP addresses based on the broker's local interfaces; this
  775. // filtering occurs on the client that receives the SDP.
  776. allowPrivateIPAddressCandidates := proxyAnnouncementHasPersonalCompartmentIDs
  777. filterPrivateIPAddressCandidates := false
  778. // Proxy answer SDP candidate addresses must match the country and ASN of
  779. // the proxy. Don't facilitate connections to arbitrary destinations.
  780. filteredSDP, sdpMetrics, err := filterSDPAddresses(
  781. []byte(request.ProxyAnswerSDP.SDP),
  782. errorOnNoCandidates,
  783. lookupGeoIP,
  784. geoIPData,
  785. allowPrivateIPAddressCandidates,
  786. filterPrivateIPAddressCandidates)
  787. if err != nil {
  788. return nil, nil, errors.Trace(err)
  789. }
  790. // The proxy's self-reported ICECandidateTypes are used instead of the
  791. // candidate types that can be derived from the SDP, since port mapping
  792. // types are edited into the SDP in a way that makes them
  793. // indistinguishable from host candidate types.
  794. if !request.ICECandidateTypes.IsValid() {
  795. return nil, nil, errors.Tracef(
  796. "invalid ICE candidate types: %v", request.ICECandidateTypes)
  797. }
  798. logFields := formatter("", geoIPData, common.APIParameters{})
  799. logFields["connection_id"] = request.ConnectionID
  800. logFields["ice_candidate_types"] = request.ICECandidateTypes
  801. logFields["has_IPv6"] = sdpMetrics.hasIPv6
  802. logFields["has_private_IP"] = sdpMetrics.hasPrivateIP
  803. logFields["filtered_ice_candidates"] = sdpMetrics.filteredICECandidates
  804. logFields["answer_error"] = request.AnswerError
  805. return filteredSDP, logFields, nil
  806. }
  807. // ValidateAndGetLogFields validates the ClientRelayedPacketRequest and returns
  808. // common.LogFields for logging.
  809. func (request *ClientRelayedPacketRequest) ValidateAndGetLogFields(
  810. baseAPIParameterValidator common.APIParameterValidator,
  811. formatter common.APIParameterLogFieldFormatter,
  812. geoIPData common.GeoIPData) (common.LogFields, error) {
  813. logFields := formatter("", geoIPData, common.APIParameters{})
  814. logFields["connection_id"] = request.ConnectionID
  815. return logFields, nil
  816. }
  817. // ValidateAndGetLogFields validates the BrokerServerReport and returns
  818. // common.LogFields for logging.
  819. func (report *BrokerServerReport) ValidateAndGetLogFields(
  820. baseAPIParameterValidator common.APIParameterValidator,
  821. formatter common.APIParameterLogFieldFormatter,
  822. proxyMetricsPrefix string) (common.LogFields, error) {
  823. // Neither ClientIP nor ProxyIP is logged.
  824. if !report.ClientNATType.IsValid() {
  825. return nil, errors.Tracef("invalid client NAT type: %v", report.ClientNATType)
  826. }
  827. if !report.ClientPortMappingTypes.IsValid() {
  828. return nil, errors.Tracef("invalid client portmapping types: %v", report.ClientPortMappingTypes)
  829. }
  830. var logFields common.LogFields
  831. if report.ProxyMetrics == nil {
  832. // Backwards compatibility for reports without ProxyMetrics.
  833. if !report.ProxyNATType.IsValid() {
  834. return nil, errors.Tracef("invalid proxy NAT type: %v", report.ProxyNATType)
  835. }
  836. if !report.ProxyPortMappingTypes.IsValid() {
  837. return nil, errors.Tracef("invalid proxy portmapping types: %v", report.ProxyPortMappingTypes)
  838. }
  839. logFields = common.LogFields{}
  840. logFields["inproxy_proxy_nat_type"] = report.ProxyNATType
  841. logFields["inproxy_proxy_port_mapping_types"] = report.ProxyPortMappingTypes
  842. } else {
  843. var err error
  844. _, logFields, err = report.ProxyMetrics.ValidateAndGetParametersAndLogFields(
  845. baseAPIParameterValidator,
  846. formatter,
  847. proxyMetricsPrefix,
  848. common.GeoIPData{}) // Proxy GeoIP data is added by the caller.
  849. if err != nil {
  850. return nil, errors.Trace(err)
  851. }
  852. }
  853. logFields["inproxy_proxy_id"] = report.ProxyID
  854. logFields["inproxy_connection_id"] = report.ConnectionID
  855. logFields["inproxy_matched_common_compartments"] = report.MatchedCommonCompartments
  856. logFields["inproxy_matched_personal_compartments"] = report.MatchedPersonalCompartments
  857. logFields["inproxy_client_nat_type"] = report.ClientNATType
  858. logFields["inproxy_client_port_mapping_types"] = report.ClientPortMappingTypes
  859. logFields["inproxy_proxy_is_priority"] = report.ProxyIsPriority
  860. // TODO:
  861. // - log IPv4 vs. IPv6 information
  862. // - relay and log broker transport stats, such as meek HTTP version
  863. return logFields, nil
  864. }
  865. // ValidateAndGetLogFields validates the ServerProxyQualityRequest and returns
  866. // common.LogFields for logging.
  867. func (request *ServerProxyQualityRequest) ValidateAndGetLogFields() (common.LogFields, error) {
  868. if len(request.QualityCounts) > maxQualityCounts {
  869. return nil, errors.Tracef("invalid quality count length: %d", len(request.QualityCounts))
  870. }
  871. // Currently, there is no custom validator or formatter for
  872. // DialParameters, as there is for the BaseAPIParameters sent by clients
  873. // and proxies:
  874. //
  875. // - The DialParameters inputs, used only to annotate logs, are from a
  876. // trusted Psiphon server.
  877. //
  878. // - Psiphon servers do not send fields required by the existing
  879. // BaseAPIParameters validators, such as sponsor ID.
  880. //
  881. // - No formatter transforms, such as "0"/"1" to bool, are currently
  882. // expected; and server.getRequestLogFields is inefficient when a
  883. // couple of log fields are expected; for an example for any future
  884. // special case formatter, see
  885. // server.getInproxyBrokerServerReportParameterLogFieldFormatter.
  886. dialParams, err := protocol.DecodePackedAPIParameters(request.DialParameters)
  887. if err != nil {
  888. return nil, errors.Trace(err)
  889. }
  890. logFields := common.LogFields(dialParams)
  891. return logFields, nil
  892. }
  893. func MarshalProxyAnnounceRequest(request *ProxyAnnounceRequest) ([]byte, error) {
  894. payload, err := marshalRecord(request, recordTypeAPIProxyAnnounceRequest)
  895. return payload, errors.Trace(err)
  896. }
  897. func UnmarshalProxyAnnounceRequest(payload []byte) (*ProxyAnnounceRequest, error) {
  898. var request *ProxyAnnounceRequest
  899. err := unmarshalRecord(recordTypeAPIProxyAnnounceRequest, payload, &request)
  900. return request, errors.Trace(err)
  901. }
  902. func MarshalProxyAnnounceResponse(response *ProxyAnnounceResponse) ([]byte, error) {
  903. payload, err := marshalRecord(response, recordTypeAPIProxyAnnounceResponse)
  904. return payload, errors.Trace(err)
  905. }
  906. func UnmarshalProxyAnnounceResponse(payload []byte) (*ProxyAnnounceResponse, error) {
  907. var response *ProxyAnnounceResponse
  908. err := unmarshalRecord(recordTypeAPIProxyAnnounceResponse, payload, &response)
  909. return response, errors.Trace(err)
  910. }
  911. func MarshalProxyAnswerRequest(request *ProxyAnswerRequest) ([]byte, error) {
  912. payload, err := marshalRecord(request, recordTypeAPIProxyAnswerRequest)
  913. return payload, errors.Trace(err)
  914. }
  915. func UnmarshalProxyAnswerRequest(payload []byte) (*ProxyAnswerRequest, error) {
  916. var request *ProxyAnswerRequest
  917. err := unmarshalRecord(recordTypeAPIProxyAnswerRequest, payload, &request)
  918. return request, errors.Trace(err)
  919. }
  920. func MarshalProxyAnswerResponse(response *ProxyAnswerResponse) ([]byte, error) {
  921. payload, err := marshalRecord(response, recordTypeAPIProxyAnswerResponse)
  922. return payload, errors.Trace(err)
  923. }
  924. func UnmarshalProxyAnswerResponse(payload []byte) (*ProxyAnswerResponse, error) {
  925. var response *ProxyAnswerResponse
  926. err := unmarshalRecord(recordTypeAPIProxyAnswerResponse, payload, &response)
  927. return response, errors.Trace(err)
  928. }
  929. func MarshalClientOfferRequest(request *ClientOfferRequest) ([]byte, error) {
  930. payload, err := marshalRecord(request, recordTypeAPIClientOfferRequest)
  931. return payload, errors.Trace(err)
  932. }
  933. func UnmarshalClientOfferRequest(payload []byte) (*ClientOfferRequest, error) {
  934. var request *ClientOfferRequest
  935. err := unmarshalRecord(recordTypeAPIClientOfferRequest, payload, &request)
  936. return request, errors.Trace(err)
  937. }
  938. func MarshalClientOfferResponse(response *ClientOfferResponse) ([]byte, error) {
  939. payload, err := marshalRecord(response, recordTypeAPIClientOfferResponse)
  940. return payload, errors.Trace(err)
  941. }
  942. func UnmarshalClientOfferResponse(payload []byte) (*ClientOfferResponse, error) {
  943. var response *ClientOfferResponse
  944. err := unmarshalRecord(recordTypeAPIClientOfferResponse, payload, &response)
  945. return response, errors.Trace(err)
  946. }
  947. func MarshalClientRelayedPacketRequest(request *ClientRelayedPacketRequest) ([]byte, error) {
  948. payload, err := marshalRecord(request, recordTypeAPIClientRelayedPacketRequest)
  949. return payload, errors.Trace(err)
  950. }
  951. func UnmarshalClientRelayedPacketRequest(payload []byte) (*ClientRelayedPacketRequest, error) {
  952. var request *ClientRelayedPacketRequest
  953. err := unmarshalRecord(recordTypeAPIClientRelayedPacketRequest, payload, &request)
  954. return request, errors.Trace(err)
  955. }
  956. func MarshalClientRelayedPacketResponse(response *ClientRelayedPacketResponse) ([]byte, error) {
  957. payload, err := marshalRecord(response, recordTypeAPIClientRelayedPacketResponse)
  958. return payload, errors.Trace(err)
  959. }
  960. func UnmarshalClientRelayedPacketResponse(payload []byte) (*ClientRelayedPacketResponse, error) {
  961. var response *ClientRelayedPacketResponse
  962. err := unmarshalRecord(recordTypeAPIClientRelayedPacketResponse, payload, &response)
  963. return response, errors.Trace(err)
  964. }
  965. func MarshalBrokerServerReport(request *BrokerServerReport) ([]byte, error) {
  966. payload, err := marshalRecord(request, recordTypeAPIBrokerServerReport)
  967. return payload, errors.Trace(err)
  968. }
  969. func UnmarshalBrokerServerReport(payload []byte) (*BrokerServerReport, error) {
  970. var request *BrokerServerReport
  971. err := unmarshalRecord(recordTypeAPIBrokerServerReport, payload, &request)
  972. return request, errors.Trace(err)
  973. }
  974. func MarshalServerProxyQualityRequest(request *ServerProxyQualityRequest) ([]byte, error) {
  975. payload, err := marshalRecord(request, recordTypeAPIServerProxyQualityRequest)
  976. return payload, errors.Trace(err)
  977. }
  978. func UnmarshalServerProxyQualityRequest(payload []byte) (*ServerProxyQualityRequest, error) {
  979. var request *ServerProxyQualityRequest
  980. err := unmarshalRecord(recordTypeAPIServerProxyQualityRequest, payload, &request)
  981. return request, errors.Trace(err)
  982. }
  983. func MarshalServerProxyQualityResponse(response *ServerProxyQualityResponse) ([]byte, error) {
  984. payload, err := marshalRecord(response, recordTypeAPIServerProxyQualityResponse)
  985. return payload, errors.Trace(err)
  986. }
  987. func UnmarshalServerProxyQualityResponse(payload []byte) (*ServerProxyQualityResponse, error) {
  988. var response *ServerProxyQualityResponse
  989. err := unmarshalRecord(recordTypeAPIServerProxyQualityResponse, payload, &response)
  990. return response, errors.Trace(err)
  991. }