api.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  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 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. // The proxy's session public key is an implicit and cryptographically
  199. // verified proxy ID.
  200. type ProxyAnnounceRequest struct {
  201. PersonalCompartmentIDs []ID `cbor:"1,keyasint,omitempty"`
  202. Metrics *ProxyMetrics `cbor:"2,keyasint,omitempty"`
  203. }
  204. // WebRTCSessionDescription is compatible with pion/webrtc.SessionDescription
  205. // and facilitates the PSIPHON_ENABLE_INPROXY build tag exclusion of pion
  206. // dependencies.
  207. type WebRTCSessionDescription struct {
  208. Type int `cbor:"1,keyasint,omitempty"`
  209. SDP string `cbor:"2,keyasint,omitempty"`
  210. }
  211. // TODO: send ProxyAnnounceRequest/ClientOfferRequest.Metrics only with the
  212. // first request in a session and cache.
  213. // ProxyAnnounceResponse returns the connection information for a matched
  214. // client. To establish a WebRTC connection, the proxy uses the client's
  215. // offer SDP to create its own answer SDP and send that to the broker in a
  216. // subsequent ProxyAnswerRequest. The ConnectionID is a unique identifier for
  217. // this single connection and must be relayed back in the ProxyAnswerRequest.
  218. //
  219. // ClientRootObfuscationSecret is generated (or replayed) by the client and
  220. // sent to the proxy and used to drive obfuscation operations.
  221. //
  222. // DestinationAddress is the dial address for the Psiphon server the proxy is
  223. // to relay client traffic with. The broker validates that the dial address
  224. // corresponds to a valid Psiphon server.
  225. //
  226. // MustUpgrade is an optional flag that is set by the broker, based on the
  227. // submitted ProxyProtocolVersion, when the proxy app must be upgraded in
  228. // order to function properly. Potential must-upgrade scenarios include
  229. // changes to the personal pairing broker rendezvous algorithm, where no
  230. // protocol backwards compatibility accommodations can ensure a rendezvous
  231. // and match. When MustUpgrade is set, NoMatch is implied.
  232. type ProxyAnnounceResponse struct {
  233. TacticsPayload []byte `cbor:"2,keyasint,omitempty"`
  234. Limited bool `cbor:"3,keyasint,omitempty"`
  235. NoMatch bool `cbor:"4,keyasint,omitempty"`
  236. MustUpgrade bool `cbor:"13,keyasint,omitempty"`
  237. ConnectionID ID `cbor:"5,keyasint,omitempty"`
  238. ClientProxyProtocolVersion int32 `cbor:"6,keyasint,omitempty"`
  239. ClientOfferSDP WebRTCSessionDescription `cbor:"7,keyasint,omitempty"`
  240. ClientRootObfuscationSecret ObfuscationSecret `cbor:"8,keyasint,omitempty"`
  241. DoDTLSRandomization bool `cbor:"9,keyasint,omitempty"`
  242. TrafficShapingParameters *DataChannelTrafficShapingParameters `cbor:"10,keyasint,omitempty"`
  243. NetworkProtocol NetworkProtocol `cbor:"11,keyasint,omitempty"`
  244. DestinationAddress string `cbor:"12,keyasint,omitempty"`
  245. }
  246. // ClientOfferRequest is an API request sent from a client to a broker,
  247. // requesting a proxy connection. The client sends its WebRTC offer SDP with
  248. // this request.
  249. //
  250. // Clients specify known compartment IDs and are matched with proxies in those
  251. // compartments. CommonCompartmentIDs are comparment IDs managed by Psiphon
  252. // and revealed through tactics or bundled with server lists.
  253. // PersonalCompartmentIDs are compartment IDs shared privately between users,
  254. // out-of-band.
  255. //
  256. // ClientRootObfuscationSecret is generated (or replayed) by the client and
  257. // sent to the proxy and used to drive obfuscation operations.
  258. //
  259. // To specify the Psiphon server it wishes to proxy to, the client sends the
  260. // full, digitally signed Psiphon server entry to the broker and also the
  261. // specific dial address that it has selected for that server. The broker
  262. // validates the server entry signature, the server in-proxy capability, and
  263. // that the dial address corresponds to the network protocol, IP address or
  264. // domain, and destination port for a valid Psiphon tunnel protocol run by
  265. // the specified server entry.
  266. type ClientOfferRequest struct {
  267. Metrics *ClientMetrics `cbor:"1,keyasint,omitempty"`
  268. CommonCompartmentIDs []ID `cbor:"2,keyasint,omitempty"`
  269. PersonalCompartmentIDs []ID `cbor:"3,keyasint,omitempty"`
  270. ClientOfferSDP WebRTCSessionDescription `cbor:"4,keyasint,omitempty"`
  271. ICECandidateTypes ICECandidateTypes `cbor:"5,keyasint,omitempty"`
  272. ClientRootObfuscationSecret ObfuscationSecret `cbor:"6,keyasint,omitempty"`
  273. DoDTLSRandomization bool `cbor:"7,keyasint,omitempty"`
  274. TrafficShapingParameters *DataChannelTrafficShapingParameters `cbor:"8,keyasint,omitempty"`
  275. PackedDestinationServerEntry []byte `cbor:"9,keyasint,omitempty"`
  276. NetworkProtocol NetworkProtocol `cbor:"10,keyasint,omitempty"`
  277. DestinationAddress string `cbor:"11,keyasint,omitempty"`
  278. }
  279. // DataChannelTrafficShapingParameters specifies a data channel traffic
  280. // shaping configuration, including random padding and decoy messages.
  281. // Clients determine their own traffic shaping configuration, and generate
  282. // and send a configuration for the peer proxy to use.
  283. type DataChannelTrafficShapingParameters struct {
  284. MinPaddedMessages int `cbor:"1,keyasint,omitempty"`
  285. MaxPaddedMessages int `cbor:"2,keyasint,omitempty"`
  286. MinPaddingSize int `cbor:"3,keyasint,omitempty"`
  287. MaxPaddingSize int `cbor:"4,keyasint,omitempty"`
  288. MinDecoyMessages int `cbor:"5,keyasint,omitempty"`
  289. MaxDecoyMessages int `cbor:"6,keyasint,omitempty"`
  290. MinDecoySize int `cbor:"7,keyasint,omitempty"`
  291. MaxDecoySize int `cbor:"8,keyasint,omitempty"`
  292. DecoyMessageProbability float64 `cbor:"9,keyasint,omitempty"`
  293. }
  294. // ClientOfferResponse returns the connecting information for a matched proxy.
  295. // The proxy's WebRTC SDP is an answer to the offer sent in
  296. // ClientOfferRequest and is used to begin dialing the WebRTC connection.
  297. //
  298. // Once the client completes its connection to the Psiphon server, it must
  299. // relay a BrokerServerReport to the server on behalf of the broker. This
  300. // relay is conducted within a secure session. First, the client sends
  301. // RelayPacketToServer to the server. Then the client relays any responses to
  302. // the broker using ClientRelayedPacketRequests and continues to relay using
  303. // ClientRelayedPacketRequests until complete. ConnectionID identifies this
  304. // connection and its relayed BrokerServerReport.
  305. //
  306. // MustUpgrade is an optional flag that is set by the broker, based on the
  307. // submitted ProxyProtocolVersion, when the client app must be upgraded in
  308. // order to function properly. Potential must-upgrade scenarios include
  309. // changes to the personal pairing broker rendezvous algorithm, where no
  310. // protocol backwards compatibility accommodations can ensure a rendezvous
  311. // and match. When MustUpgrade is set, NoMatch is implied.
  312. type ClientOfferResponse struct {
  313. Limited bool `cbor:"1,keyasint,omitempty"`
  314. NoMatch bool `cbor:"2,keyasint,omitempty"`
  315. MustUpgrade bool `cbor:"7,keyasint,omitempty"`
  316. ConnectionID ID `cbor:"3,keyasint,omitempty"`
  317. SelectedProxyProtocolVersion int32 `cbor:"4,keyasint,omitempty"`
  318. ProxyAnswerSDP WebRTCSessionDescription `cbor:"5,keyasint,omitempty"`
  319. RelayPacketToServer []byte `cbor:"6,keyasint,omitempty"`
  320. }
  321. // TODO: Encode SDPs using CBOR without field names, simliar to packed metrics?
  322. // ProxyAnswerRequest is an API request sent from a proxy to a broker,
  323. // following ProxyAnnounceResponse, with the WebRTC answer SDP corresponding
  324. // to the client offer SDP received in ProxyAnnounceResponse. ConnectionID
  325. // identifies the connection begun in ProxyAnnounceResponse.
  326. //
  327. // If the proxy was unable to establish an answer SDP or failed for some other
  328. // reason, it should still send ProxyAnswerRequest with AnswerError
  329. // populated; the broker will signal the client to abort this connection.
  330. type ProxyAnswerRequest struct {
  331. ConnectionID ID `cbor:"1,keyasint,omitempty"`
  332. SelectedProxyProtocolVersion int32 `cbor:"2,keyasint,omitempty"`
  333. ProxyAnswerSDP WebRTCSessionDescription `cbor:"3,keyasint,omitempty"`
  334. ICECandidateTypes ICECandidateTypes `cbor:"4,keyasint,omitempty"`
  335. AnswerError string `cbor:"5,keyasint,omitempty"`
  336. }
  337. // ProxyAnswerResponse is the acknowledgement for a ProxyAnswerRequest.
  338. type ProxyAnswerResponse struct {
  339. }
  340. // ClientRelayedPacketRequest is an API request sent from a client to a
  341. // broker, relaying a secure session packet from the Psiphon server to the
  342. // broker. This relay is a continuation of the broker/server exchange begun
  343. // with ClientOfferResponse.RelayPacketToServer. PacketFromServer is the next
  344. // packet from the server.
  345. //
  346. // When a broker attempts to use an existing session which has expired on the
  347. // server, the packet from the server may contain a signed reset session
  348. // token, which is used to automatically reset and start establishing a new
  349. // session before relaying the payload.
  350. type ClientRelayedPacketRequest struct {
  351. ConnectionID ID `cbor:"1,keyasint,omitempty"`
  352. PacketFromServer []byte `cbor:"2,keyasint,omitempty"`
  353. }
  354. // ClientRelayedPacketResponse returns the next packet from the broker to the
  355. // server. When PacketToServer is empty, the broker/server exchange is done
  356. // and the client stops relaying packets.
  357. type ClientRelayedPacketResponse struct {
  358. PacketToServer []byte `cbor:"1,keyasint,omitempty"`
  359. }
  360. // BrokerServerReport is a one-way API call sent from a broker to a
  361. // Psiphon server. This delivers, to the server, information that neither the
  362. // client nor the proxy is trusted to report. ProxyID is the proxy ID to be
  363. // logged with server_tunnel to attribute traffic to a specific proxy.
  364. // ClientIP is the original client IP as seen by the broker; this is the IP
  365. // value to be used in GeoIP-related operations including traffic rules,
  366. // tactics, and OSL progress. ProxyIP is the proxy IP as seen by the broker;
  367. // this value should match the Psiphon's server observed client IP.
  368. // Additional fields are metrics to be logged with server_tunnel.
  369. //
  370. // Using a one-way message here means that, once a broker/server session is
  371. // established, the entire relay can be encasulated in a single additional
  372. // field sent in the Psiphon API handshake. This minimizes observable and
  373. // potentially fingerprintable traffic flows as the client does not need to
  374. // relay any further session packets before starting the tunnel. The
  375. // trade-off is that the broker doesn't get an indication from the server
  376. // that the message was accepted or rejects and cannot directly, in real time
  377. // log any tunnel error associated with the server rejecting the message, or
  378. // log that the relay was completed successfully. These events can be logged
  379. // on the server and logs reconciled using the in-proxy Connection ID.
  380. type BrokerServerReport struct {
  381. ProxyID ID `cbor:"1,keyasint,omitempty"`
  382. ConnectionID ID `cbor:"2,keyasint,omitempty"`
  383. MatchedCommonCompartments bool `cbor:"3,keyasint,omitempty"`
  384. MatchedPersonalCompartments bool `cbor:"4,keyasint,omitempty"`
  385. ProxyNATType NATType `cbor:"5,keyasint,omitempty"`
  386. ProxyPortMappingTypes PortMappingTypes `cbor:"6,keyasint,omitempty"`
  387. ClientNATType NATType `cbor:"7,keyasint,omitempty"`
  388. ClientPortMappingTypes PortMappingTypes `cbor:"8,keyasint,omitempty"`
  389. ClientIP string `cbor:"9,keyasint,omitempty"`
  390. ProxyIP string `cbor:"10,keyasint,omitempty"`
  391. }
  392. // GetNetworkType extracts the network_type from base API metrics and returns
  393. // a corresponding NetworkType. This is the one base metric that is used in
  394. // the broker logic, and not simply logged.
  395. func GetNetworkType(packedBaseParams protocol.PackedAPIParameters) NetworkType {
  396. baseNetworkType, ok := packedBaseParams.GetNetworkType()
  397. if !ok {
  398. return NetworkTypeUnknown
  399. }
  400. switch baseNetworkType {
  401. case "WIFI":
  402. return NetworkTypeWiFi
  403. case "MOBILE":
  404. return NetworkTypeMobile
  405. }
  406. return NetworkTypeUnknown
  407. }
  408. // Sanity check values.
  409. const (
  410. maxICECandidateTypes = 10
  411. maxPortMappingTypes = 10
  412. maxPaddedMessages = 100
  413. maxPaddingSize = 16384
  414. maxDecoyMessages = 100
  415. maxDecoySize = 16384
  416. )
  417. // ValidateAndGetParametersAndLogFields validates the ProxyMetrics and returns
  418. // Psiphon API parameters for processing and common.LogFields for logging.
  419. func (metrics *ProxyMetrics) ValidateAndGetParametersAndLogFields(
  420. baseAPIParameterValidator common.APIParameterValidator,
  421. formatter common.APIParameterLogFieldFormatter,
  422. geoIPData common.GeoIPData) (common.APIParameters, common.LogFields, error) {
  423. if metrics.BaseAPIParameters == nil {
  424. return nil, nil, errors.TraceNew("missing base API parameters")
  425. }
  426. baseParams, err := protocol.DecodePackedAPIParameters(metrics.BaseAPIParameters)
  427. if err != nil {
  428. return nil, nil, errors.Trace(err)
  429. }
  430. err = baseAPIParameterValidator(baseParams)
  431. if err != nil {
  432. return nil, nil, errors.Trace(err)
  433. }
  434. if metrics.ProxyProtocolVersion < 0 || metrics.ProxyProtocolVersion > proxyProtocolVersion {
  435. return nil, nil, errors.Tracef("invalid proxy protocol version: %v", metrics.ProxyProtocolVersion)
  436. }
  437. if !metrics.NATType.IsValid() {
  438. return nil, nil, errors.Tracef("invalid NAT type: %v", metrics.NATType)
  439. }
  440. if len(metrics.PortMappingTypes) > maxPortMappingTypes {
  441. return nil, nil, errors.Tracef("invalid portmapping types length: %d", len(metrics.PortMappingTypes))
  442. }
  443. if !metrics.PortMappingTypes.IsValid() {
  444. return nil, nil, errors.Tracef("invalid portmapping types: %v", metrics.PortMappingTypes)
  445. }
  446. logFields := formatter(geoIPData, baseParams)
  447. logFields["proxy_protocol_version"] = metrics.ProxyProtocolVersion
  448. logFields["nat_type"] = metrics.NATType
  449. logFields["port_mapping_types"] = metrics.PortMappingTypes
  450. logFields["max_clients"] = metrics.MaxClients
  451. logFields["connecting_clients"] = metrics.ConnectingClients
  452. logFields["connected_clients"] = metrics.ConnectedClients
  453. logFields["limit_upstream_bytes_per_second"] = metrics.LimitUpstreamBytesPerSecond
  454. logFields["limit_downstream_bytes_per_second"] = metrics.LimitDownstreamBytesPerSecond
  455. logFields["peak_upstream_bytes_per_second"] = metrics.PeakUpstreamBytesPerSecond
  456. logFields["peak_downstream_bytes_per_second"] = metrics.PeakDownstreamBytesPerSecond
  457. return baseParams, logFields, nil
  458. }
  459. // ValidateAndGetLogFields validates the ClientMetrics and returns
  460. // common.LogFields for logging.
  461. func (metrics *ClientMetrics) ValidateAndGetLogFields(
  462. baseAPIParameterValidator common.APIParameterValidator,
  463. formatter common.APIParameterLogFieldFormatter,
  464. geoIPData common.GeoIPData) (common.LogFields, error) {
  465. if metrics.BaseAPIParameters == nil {
  466. return nil, errors.TraceNew("missing base API parameters")
  467. }
  468. baseParams, err := protocol.DecodePackedAPIParameters(metrics.BaseAPIParameters)
  469. if err != nil {
  470. return nil, errors.Trace(err)
  471. }
  472. err = baseAPIParameterValidator(baseParams)
  473. if err != nil {
  474. return nil, errors.Trace(err)
  475. }
  476. if metrics.ProxyProtocolVersion < 0 || metrics.ProxyProtocolVersion > proxyProtocolVersion {
  477. return nil, errors.Tracef("invalid proxy protocol version: %v", metrics.ProxyProtocolVersion)
  478. }
  479. if !metrics.NATType.IsValid() {
  480. return nil, errors.Tracef("invalid NAT type: %v", metrics.NATType)
  481. }
  482. if len(metrics.PortMappingTypes) > maxPortMappingTypes {
  483. return nil, errors.Tracef("invalid portmapping types length: %d", len(metrics.PortMappingTypes))
  484. }
  485. if !metrics.PortMappingTypes.IsValid() {
  486. return nil, errors.Tracef("invalid portmapping types: %v", metrics.PortMappingTypes)
  487. }
  488. logFields := formatter(geoIPData, baseParams)
  489. logFields["proxy_protocol_version"] = metrics.ProxyProtocolVersion
  490. logFields["nat_type"] = metrics.NATType
  491. logFields["port_mapping_types"] = metrics.PortMappingTypes
  492. return logFields, nil
  493. }
  494. // ValidateAndGetParametersAndLogFields validates the ProxyAnnounceRequest and
  495. // returns Psiphon API parameters for processing and common.LogFields for
  496. // logging.
  497. func (request *ProxyAnnounceRequest) ValidateAndGetParametersAndLogFields(
  498. maxCompartmentIDs int,
  499. baseAPIParameterValidator common.APIParameterValidator,
  500. formatter common.APIParameterLogFieldFormatter,
  501. geoIPData common.GeoIPData) (common.APIParameters, common.LogFields, error) {
  502. // A proxy may specify at most 1 personal compartment ID. This is
  503. // currently a limitation of the multi-queue implementation; see comment
  504. // in announcementMultiQueue.enqueue.
  505. if len(request.PersonalCompartmentIDs) > 1 {
  506. return nil, nil, errors.Tracef(
  507. "invalid compartment IDs length: %d", len(request.PersonalCompartmentIDs))
  508. }
  509. if request.Metrics == nil {
  510. return nil, nil, errors.TraceNew("missing metrics")
  511. }
  512. apiParams, logFields, err := request.Metrics.ValidateAndGetParametersAndLogFields(
  513. baseAPIParameterValidator, formatter, geoIPData)
  514. if err != nil {
  515. return nil, nil, errors.Trace(err)
  516. }
  517. // PersonalCompartmentIDs are user-generated and shared out-of-band;
  518. // values are not logged since they may link users.
  519. hasPersonalCompartmentIDs := len(request.PersonalCompartmentIDs) > 0
  520. logFields["has_personal_compartment_ids"] = hasPersonalCompartmentIDs
  521. return apiParams, logFields, nil
  522. }
  523. // ValidateAndGetLogFields validates the ClientOfferRequest and returns
  524. // common.LogFields for logging.
  525. func (request *ClientOfferRequest) ValidateAndGetLogFields(
  526. maxCompartmentIDs int,
  527. lookupGeoIP LookupGeoIP,
  528. baseAPIParameterValidator common.APIParameterValidator,
  529. formatter common.APIParameterLogFieldFormatter,
  530. geoIPData common.GeoIPData) ([]byte, common.LogFields, error) {
  531. if len(request.CommonCompartmentIDs) > maxCompartmentIDs {
  532. return nil, nil, errors.Tracef(
  533. "invalid compartment IDs length: %d", len(request.CommonCompartmentIDs))
  534. }
  535. if len(request.PersonalCompartmentIDs) > maxCompartmentIDs {
  536. return nil, nil, errors.Tracef(
  537. "invalid compartment IDs length: %d", len(request.PersonalCompartmentIDs))
  538. }
  539. if len(request.CommonCompartmentIDs) > 0 && len(request.PersonalCompartmentIDs) > 0 {
  540. return nil, nil, errors.TraceNew("multiple compartment ID types")
  541. }
  542. // The client offer SDP may contain no ICE candidates.
  543. errorOnNoCandidates := false
  544. // The client offer SDP may include RFC 1918/4193 private IP addresses in
  545. // personal pairing mode. filterSDPAddresses should not filter out
  546. // private IP addresses based on the broker's local interfaces; this
  547. // filtering occurs on the proxy that receives the SDP.
  548. allowPrivateIPAddressCandidates :=
  549. len(request.PersonalCompartmentIDs) > 0 &&
  550. len(request.CommonCompartmentIDs) == 0
  551. filterPrivateIPAddressCandidates := false
  552. // Client offer SDP candidate addresses must match the country and ASN of
  553. // the client. Don't facilitate connections to arbitrary destinations.
  554. filteredSDP, sdpMetrics, err := filterSDPAddresses(
  555. []byte(request.ClientOfferSDP.SDP),
  556. errorOnNoCandidates,
  557. lookupGeoIP,
  558. geoIPData,
  559. allowPrivateIPAddressCandidates,
  560. filterPrivateIPAddressCandidates)
  561. if err != nil {
  562. return nil, nil, errors.Trace(err)
  563. }
  564. // The client's self-reported ICECandidateTypes are used instead of the
  565. // candidate types that can be derived from the SDP, since port mapping
  566. // types are edited into the SDP in a way that makes them
  567. // indistinguishable from host candidate types.
  568. if !request.ICECandidateTypes.IsValid() {
  569. return nil, nil, errors.Tracef(
  570. "invalid ICE candidate types: %v", request.ICECandidateTypes)
  571. }
  572. if request.Metrics == nil {
  573. return nil, nil, errors.TraceNew("missing metrics")
  574. }
  575. logFields, err := request.Metrics.ValidateAndGetLogFields(
  576. baseAPIParameterValidator, formatter, geoIPData)
  577. if err != nil {
  578. return nil, nil, errors.Trace(err)
  579. }
  580. if request.TrafficShapingParameters != nil {
  581. err := request.TrafficShapingParameters.Validate()
  582. if err != nil {
  583. return nil, nil, errors.Trace(err)
  584. }
  585. }
  586. // CommonCompartmentIDs are generated and managed and are a form of
  587. // obfuscation secret, so are not logged. PersonalCompartmentIDs are
  588. // user-generated and shared out-of-band; values are not logged since
  589. // they may link users.
  590. hasCommonCompartmentIDs := len(request.CommonCompartmentIDs) > 0
  591. hasPersonalCompartmentIDs := len(request.PersonalCompartmentIDs) > 0
  592. logFields["has_common_compartment_ids"] = hasCommonCompartmentIDs
  593. logFields["has_personal_compartment_ids"] = hasPersonalCompartmentIDs
  594. logFields["ice_candidate_types"] = request.ICECandidateTypes
  595. logFields["has_IPv6"] = sdpMetrics.hasIPv6
  596. logFields["has_private_IP"] = sdpMetrics.hasPrivateIP
  597. logFields["filtered_ice_candidates"] = sdpMetrics.filteredICECandidates
  598. return filteredSDP, logFields, nil
  599. }
  600. // Validate validates the that client has not specified excess traffic shaping
  601. // padding or decoy traffic.
  602. func (params *DataChannelTrafficShapingParameters) Validate() error {
  603. if params.MinPaddedMessages < 0 ||
  604. params.MinPaddedMessages > params.MaxPaddedMessages ||
  605. params.MaxPaddedMessages > maxPaddedMessages {
  606. return errors.TraceNew("invalid padded messages")
  607. }
  608. if params.MinPaddingSize < 0 ||
  609. params.MinPaddingSize > params.MaxPaddingSize ||
  610. params.MaxPaddingSize > maxPaddingSize {
  611. return errors.TraceNew("invalid padding size")
  612. }
  613. if params.MinDecoyMessages < 0 ||
  614. params.MinDecoyMessages > params.MaxDecoyMessages ||
  615. params.MaxDecoyMessages > maxDecoyMessages {
  616. return errors.TraceNew("invalid decoy messages")
  617. }
  618. if params.MinDecoySize < 0 ||
  619. params.MinDecoySize > params.MaxDecoySize ||
  620. params.MaxDecoySize > maxDecoySize {
  621. return errors.TraceNew("invalid decoy size")
  622. }
  623. return nil
  624. }
  625. // ValidateAndGetLogFields validates the ProxyAnswerRequest and returns
  626. // common.LogFields for logging.
  627. func (request *ProxyAnswerRequest) ValidateAndGetLogFields(
  628. lookupGeoIP LookupGeoIP,
  629. baseAPIParameterValidator common.APIParameterValidator,
  630. formatter common.APIParameterLogFieldFormatter,
  631. geoIPData common.GeoIPData,
  632. proxyAnnouncementHasPersonalCompartmentIDs bool) ([]byte, common.LogFields, error) {
  633. // The proxy answer SDP must contain at least one ICE candidate.
  634. errorOnNoCandidates := true
  635. // The proxy answer SDP may include RFC 1918/4193 private IP addresses in
  636. // personal pairing mode. filterSDPAddresses should not filter out
  637. // private IP addresses based on the broker's local interfaces; this
  638. // filtering occurs on the client that receives the SDP.
  639. allowPrivateIPAddressCandidates := proxyAnnouncementHasPersonalCompartmentIDs
  640. filterPrivateIPAddressCandidates := false
  641. // Proxy answer SDP candidate addresses must match the country and ASN of
  642. // the proxy. Don't facilitate connections to arbitrary destinations.
  643. filteredSDP, sdpMetrics, err := filterSDPAddresses(
  644. []byte(request.ProxyAnswerSDP.SDP),
  645. errorOnNoCandidates,
  646. lookupGeoIP,
  647. geoIPData,
  648. allowPrivateIPAddressCandidates,
  649. filterPrivateIPAddressCandidates)
  650. if err != nil {
  651. return nil, nil, errors.Trace(err)
  652. }
  653. // The proxy's self-reported ICECandidateTypes are used instead of the
  654. // candidate types that can be derived from the SDP, since port mapping
  655. // types are edited into the SDP in a way that makes them
  656. // indistinguishable from host candidate types.
  657. if !request.ICECandidateTypes.IsValid() {
  658. return nil, nil, errors.Tracef(
  659. "invalid ICE candidate types: %v", request.ICECandidateTypes)
  660. }
  661. if request.SelectedProxyProtocolVersion != ProxyProtocolVersion1 {
  662. return nil, nil, errors.Tracef(
  663. "invalid select proxy protocol version: %v", request.SelectedProxyProtocolVersion)
  664. }
  665. logFields := formatter(geoIPData, common.APIParameters{})
  666. logFields["connection_id"] = request.ConnectionID
  667. logFields["ice_candidate_types"] = request.ICECandidateTypes
  668. logFields["has_IPv6"] = sdpMetrics.hasIPv6
  669. logFields["has_private_IP"] = sdpMetrics.hasPrivateIP
  670. logFields["filtered_ice_candidates"] = sdpMetrics.filteredICECandidates
  671. logFields["answer_error"] = request.AnswerError
  672. return filteredSDP, logFields, nil
  673. }
  674. // ValidateAndGetLogFields validates the ClientRelayedPacketRequest and returns
  675. // common.LogFields for logging.
  676. func (request *ClientRelayedPacketRequest) ValidateAndGetLogFields(
  677. baseAPIParameterValidator common.APIParameterValidator,
  678. formatter common.APIParameterLogFieldFormatter,
  679. geoIPData common.GeoIPData) (common.LogFields, error) {
  680. logFields := formatter(geoIPData, common.APIParameters{})
  681. logFields["connection_id"] = request.ConnectionID
  682. return logFields, nil
  683. }
  684. // ValidateAndGetLogFields validates the BrokerServerReport and returns
  685. // common.LogFields for logging.
  686. func (request *BrokerServerReport) ValidateAndGetLogFields() (common.LogFields, error) {
  687. if !request.ProxyNATType.IsValid() {
  688. return nil, errors.Tracef("invalid proxy NAT type: %v", request.ProxyNATType)
  689. }
  690. if !request.ProxyPortMappingTypes.IsValid() {
  691. return nil, errors.Tracef("invalid proxy portmapping types: %v", request.ProxyPortMappingTypes)
  692. }
  693. if !request.ClientNATType.IsValid() {
  694. return nil, errors.Tracef("invalid client NAT type: %v", request.ClientNATType)
  695. }
  696. if !request.ClientPortMappingTypes.IsValid() {
  697. return nil, errors.Tracef("invalid client portmapping types: %v", request.ClientPortMappingTypes)
  698. }
  699. // Neither ClientIP nor ProxyIP is logged.
  700. logFields := common.LogFields{}
  701. logFields["proxy_id"] = request.ProxyID
  702. logFields["connection_id"] = request.ConnectionID
  703. logFields["matched_common_compartments"] = request.MatchedCommonCompartments
  704. logFields["matched_personal_compartments"] = request.MatchedPersonalCompartments
  705. logFields["proxy_nat_type"] = request.ProxyNATType
  706. logFields["proxy_port_mapping_types"] = request.ProxyPortMappingTypes
  707. logFields["client_nat_type"] = request.ClientNATType
  708. logFields["client_port_mapping_types"] = request.ClientPortMappingTypes
  709. return common.LogFields{}, nil
  710. }
  711. func MarshalProxyAnnounceRequest(request *ProxyAnnounceRequest) ([]byte, error) {
  712. payload, err := marshalRecord(request, recordTypeAPIProxyAnnounceRequest)
  713. return payload, errors.Trace(err)
  714. }
  715. func UnmarshalProxyAnnounceRequest(payload []byte) (*ProxyAnnounceRequest, error) {
  716. var request *ProxyAnnounceRequest
  717. err := unmarshalRecord(recordTypeAPIProxyAnnounceRequest, payload, &request)
  718. return request, errors.Trace(err)
  719. }
  720. func MarshalProxyAnnounceResponse(response *ProxyAnnounceResponse) ([]byte, error) {
  721. payload, err := marshalRecord(response, recordTypeAPIProxyAnnounceResponse)
  722. return payload, errors.Trace(err)
  723. }
  724. func UnmarshalProxyAnnounceResponse(payload []byte) (*ProxyAnnounceResponse, error) {
  725. var response *ProxyAnnounceResponse
  726. err := unmarshalRecord(recordTypeAPIProxyAnnounceResponse, payload, &response)
  727. return response, errors.Trace(err)
  728. }
  729. func MarshalProxyAnswerRequest(request *ProxyAnswerRequest) ([]byte, error) {
  730. payload, err := marshalRecord(request, recordTypeAPIProxyAnswerRequest)
  731. return payload, errors.Trace(err)
  732. }
  733. func UnmarshalProxyAnswerRequest(payload []byte) (*ProxyAnswerRequest, error) {
  734. var request *ProxyAnswerRequest
  735. err := unmarshalRecord(recordTypeAPIProxyAnswerRequest, payload, &request)
  736. return request, errors.Trace(err)
  737. }
  738. func MarshalProxyAnswerResponse(response *ProxyAnswerResponse) ([]byte, error) {
  739. payload, err := marshalRecord(response, recordTypeAPIProxyAnswerResponse)
  740. return payload, errors.Trace(err)
  741. }
  742. func UnmarshalProxyAnswerResponse(payload []byte) (*ProxyAnswerResponse, error) {
  743. var response *ProxyAnswerResponse
  744. err := unmarshalRecord(recordTypeAPIProxyAnswerResponse, payload, &response)
  745. return response, errors.Trace(err)
  746. }
  747. func MarshalClientOfferRequest(request *ClientOfferRequest) ([]byte, error) {
  748. payload, err := marshalRecord(request, recordTypeAPIClientOfferRequest)
  749. return payload, errors.Trace(err)
  750. }
  751. func UnmarshalClientOfferRequest(payload []byte) (*ClientOfferRequest, error) {
  752. var request *ClientOfferRequest
  753. err := unmarshalRecord(recordTypeAPIClientOfferRequest, payload, &request)
  754. return request, errors.Trace(err)
  755. }
  756. func MarshalClientOfferResponse(response *ClientOfferResponse) ([]byte, error) {
  757. payload, err := marshalRecord(response, recordTypeAPIClientOfferResponse)
  758. return payload, errors.Trace(err)
  759. }
  760. func UnmarshalClientOfferResponse(payload []byte) (*ClientOfferResponse, error) {
  761. var response *ClientOfferResponse
  762. err := unmarshalRecord(recordTypeAPIClientOfferResponse, payload, &response)
  763. return response, errors.Trace(err)
  764. }
  765. func MarshalClientRelayedPacketRequest(request *ClientRelayedPacketRequest) ([]byte, error) {
  766. payload, err := marshalRecord(request, recordTypeAPIClientRelayedPacketRequest)
  767. return payload, errors.Trace(err)
  768. }
  769. func UnmarshalClientRelayedPacketRequest(payload []byte) (*ClientRelayedPacketRequest, error) {
  770. var request *ClientRelayedPacketRequest
  771. err := unmarshalRecord(recordTypeAPIClientRelayedPacketRequest, payload, &request)
  772. return request, errors.Trace(err)
  773. }
  774. func MarshalClientRelayedPacketResponse(response *ClientRelayedPacketResponse) ([]byte, error) {
  775. payload, err := marshalRecord(response, recordTypeAPIClientRelayedPacketResponse)
  776. return payload, errors.Trace(err)
  777. }
  778. func UnmarshalClientRelayedPacketResponse(payload []byte) (*ClientRelayedPacketResponse, error) {
  779. var response *ClientRelayedPacketResponse
  780. err := unmarshalRecord(recordTypeAPIClientRelayedPacketResponse, payload, &response)
  781. return response, errors.Trace(err)
  782. }
  783. func MarshalBrokerServerReport(request *BrokerServerReport) ([]byte, error) {
  784. payload, err := marshalRecord(request, recordTypeAPIBrokerServerReport)
  785. return payload, errors.Trace(err)
  786. }
  787. func UnmarshalBrokerServerReport(payload []byte) (*BrokerServerReport, error) {
  788. var request *BrokerServerReport
  789. err := unmarshalRecord(recordTypeAPIBrokerServerReport, payload, &request)
  790. return request, errors.Trace(err)
  791. }