api.go 33 KB

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