api.go 40 KB

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