api.go 34 KB

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