api.go 36 KB

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