api.go 37 KB

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