api.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  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. maxCompartmentIDs int,
  461. baseAPIParameterValidator common.APIParameterValidator,
  462. formatter common.APIParameterLogFieldFormatter,
  463. geoIPData common.GeoIPData) (common.LogFields, error) {
  464. if len(request.PersonalCompartmentIDs) > maxCompartmentIDs {
  465. return nil, errors.Tracef("invalid compartment IDs length: %d", len(request.PersonalCompartmentIDs))
  466. }
  467. if request.Metrics == nil {
  468. return nil, errors.TraceNew("missing metrics")
  469. }
  470. logFields, err := request.Metrics.ValidateAndGetLogFields(
  471. baseAPIParameterValidator, formatter, geoIPData)
  472. if err != nil {
  473. return nil, errors.Trace(err)
  474. }
  475. // PersonalCompartmentIDs are user-generated and shared out-of-band;
  476. // values are not logged since they may link users.
  477. hasPersonalCompartmentIDs := len(request.PersonalCompartmentIDs) > 0
  478. logFields["has_personal_compartment_ids"] = hasPersonalCompartmentIDs
  479. return logFields, nil
  480. }
  481. // ValidateAndGetLogFields validates the ClientOfferRequest and returns
  482. // common.LogFields for logging.
  483. func (request *ClientOfferRequest) ValidateAndGetLogFields(
  484. maxCompartmentIDs int,
  485. lookupGeoIP LookupGeoIP,
  486. baseAPIParameterValidator common.APIParameterValidator,
  487. formatter common.APIParameterLogFieldFormatter,
  488. geoIPData common.GeoIPData) (common.LogFields, error) {
  489. if len(request.CommonCompartmentIDs) > maxCompartmentIDs {
  490. return nil, errors.Tracef("invalid compartment IDs length: %d", len(request.CommonCompartmentIDs))
  491. }
  492. if len(request.PersonalCompartmentIDs) > maxCompartmentIDs {
  493. return nil, errors.Tracef("invalid compartment IDs length: %d", len(request.PersonalCompartmentIDs))
  494. }
  495. // The client offer SDP may contain no ICE candidates.
  496. errorOnNoCandidates := false
  497. // Client offer SDP candidate addresses must match the country and ASN of
  498. // the client. Don't facilitate connections to arbitrary destinations.
  499. sdpMetrics, err := ValidateSDPAddresses(
  500. []byte(request.ClientOfferSDP.SDP), errorOnNoCandidates, lookupGeoIP, geoIPData)
  501. if err != nil {
  502. return nil, errors.Trace(err)
  503. }
  504. // The client's self-reported ICECandidateTypes are used instead of the
  505. // candidate types that can be derived from the SDP, since port mapping
  506. // types are edited into the SDP in a way that makes them
  507. // indistinguishable from host candidate types.
  508. if !request.ICECandidateTypes.IsValid() {
  509. return nil, errors.Tracef("invalid ICE candidate types: %v", request.ICECandidateTypes)
  510. }
  511. if request.Metrics == nil {
  512. return nil, errors.TraceNew("missing metrics")
  513. }
  514. logFields, err := request.Metrics.ValidateAndGetLogFields(
  515. baseAPIParameterValidator, formatter, geoIPData)
  516. if err != nil {
  517. return nil, errors.Trace(err)
  518. }
  519. if request.TrafficShapingParameters != nil {
  520. err := request.TrafficShapingParameters.Validate()
  521. if err != nil {
  522. return nil, errors.Trace(err)
  523. }
  524. }
  525. // CommonCompartmentIDs are generated and managed and are a form of
  526. // obfuscation secret, so are not logged. PersonalCompartmentIDs are
  527. // user-generated and shared out-of-band; values are not logged since
  528. // they may link users.
  529. hasCommonCompartmentIDs := len(request.CommonCompartmentIDs) > 0
  530. hasPersonalCompartmentIDs := len(request.PersonalCompartmentIDs) > 0
  531. logFields["has_common_compartment_ids"] = hasCommonCompartmentIDs
  532. logFields["has_personal_compartment_ids"] = hasPersonalCompartmentIDs
  533. logFields["ice_candidate_types"] = request.ICECandidateTypes
  534. logFields["has_IPv6"] = sdpMetrics.HasIPv6
  535. return logFields, nil
  536. }
  537. // Validate validates the that client has not specified excess traffic shaping
  538. // padding or decoy traffic.
  539. func (params *DataChannelTrafficShapingParameters) Validate() error {
  540. if params.MinPaddedMessages < 0 ||
  541. params.MinPaddedMessages > params.MaxPaddedMessages ||
  542. params.MaxPaddedMessages > maxPaddedMessages {
  543. return errors.TraceNew("invalid padded messages")
  544. }
  545. if params.MinPaddingSize < 0 ||
  546. params.MinPaddingSize > params.MaxPaddingSize ||
  547. params.MaxPaddingSize > maxPaddingSize {
  548. return errors.TraceNew("invalid padding size")
  549. }
  550. if params.MinDecoyMessages < 0 ||
  551. params.MinDecoyMessages > params.MaxDecoyMessages ||
  552. params.MaxDecoyMessages > maxDecoyMessages {
  553. return errors.TraceNew("invalid decoy messages")
  554. }
  555. if params.MinDecoySize < 0 ||
  556. params.MinDecoySize > params.MaxDecoySize ||
  557. params.MaxDecoySize > maxDecoySize {
  558. return errors.TraceNew("invalid decoy size")
  559. }
  560. return nil
  561. }
  562. // ValidateAndGetLogFields validates the ProxyAnswerRequest and returns
  563. // common.LogFields for logging.
  564. func (request *ProxyAnswerRequest) ValidateAndGetLogFields(
  565. lookupGeoIP LookupGeoIP,
  566. baseAPIParameterValidator common.APIParameterValidator,
  567. formatter common.APIParameterLogFieldFormatter,
  568. geoIPData common.GeoIPData) (common.LogFields, error) {
  569. // The proxy answer SDP must contain at least one ICE candidate.
  570. errorOnNoCandidates := true
  571. // Proxy answer SDP candidate addresses must match the country and ASN of
  572. // the proxy. Don't facilitate connections to arbitrary destinations.
  573. sdpMetrics, err := ValidateSDPAddresses(
  574. []byte(request.ProxyAnswerSDP.SDP), errorOnNoCandidates, lookupGeoIP, geoIPData)
  575. if err != nil {
  576. return nil, errors.Trace(err)
  577. }
  578. // The proxy's self-reported ICECandidateTypes are used instead of the
  579. // candidate types that can be derived from the SDP, since port mapping
  580. // types are edited into the SDP in a way that makes them
  581. // indistinguishable from host candidate types.
  582. if !request.ICECandidateTypes.IsValid() {
  583. return nil, errors.Tracef("invalid ICE candidate types: %v", request.ICECandidateTypes)
  584. }
  585. if request.SelectedProxyProtocolVersion != ProxyProtocolVersion1 {
  586. return nil, errors.Tracef("invalid select proxy protocol version: %v", request.SelectedProxyProtocolVersion)
  587. }
  588. logFields := formatter(geoIPData, common.APIParameters{})
  589. logFields["connection_id"] = request.ConnectionID
  590. logFields["ice_candidate_types"] = request.ICECandidateTypes
  591. logFields["has_IPv6"] = sdpMetrics.HasIPv6
  592. logFields["answer_error"] = request.AnswerError
  593. return logFields, nil
  594. }
  595. // ValidateAndGetLogFields validates the ClientRelayedPacketRequest and returns
  596. // common.LogFields for logging.
  597. func (request *ClientRelayedPacketRequest) ValidateAndGetLogFields(
  598. baseAPIParameterValidator common.APIParameterValidator,
  599. formatter common.APIParameterLogFieldFormatter,
  600. geoIPData common.GeoIPData) (common.LogFields, error) {
  601. logFields := formatter(geoIPData, common.APIParameters{})
  602. logFields["connection_id"] = request.ConnectionID
  603. return logFields, nil
  604. }
  605. // ValidateAndGetLogFields validates the BrokerServerReport and returns
  606. // common.LogFields for logging.
  607. func (request *BrokerServerReport) ValidateAndGetLogFields() (common.LogFields, error) {
  608. if !request.ProxyNATType.IsValid() {
  609. return nil, errors.Tracef("invalid proxy NAT type: %v", request.ProxyNATType)
  610. }
  611. if !request.ProxyPortMappingTypes.IsValid() {
  612. return nil, errors.Tracef("invalid proxy portmapping types: %v", request.ProxyPortMappingTypes)
  613. }
  614. if !request.ClientNATType.IsValid() {
  615. return nil, errors.Tracef("invalid client NAT type: %v", request.ClientNATType)
  616. }
  617. if !request.ClientPortMappingTypes.IsValid() {
  618. return nil, errors.Tracef("invalid client portmapping types: %v", request.ClientPortMappingTypes)
  619. }
  620. // Neither ClientIP nor ProxyIP is logged.
  621. logFields := common.LogFields{}
  622. logFields["proxy_id"] = request.ProxyID
  623. logFields["connection_id"] = request.ConnectionID
  624. logFields["matched_common_compartments"] = request.MatchedCommonCompartments
  625. logFields["matched_personal_compartments"] = request.MatchedPersonalCompartments
  626. logFields["proxy_nat_type"] = request.ProxyNATType
  627. logFields["proxy_port_mapping_types"] = request.ProxyPortMappingTypes
  628. logFields["client_nat_type"] = request.ClientNATType
  629. logFields["client_port_mapping_types"] = request.ClientPortMappingTypes
  630. return common.LogFields{}, nil
  631. }
  632. func MarshalProxyAnnounceRequest(request *ProxyAnnounceRequest) ([]byte, error) {
  633. payload, err := marshalRecord(request, recordTypeAPIProxyAnnounceRequest)
  634. return payload, errors.Trace(err)
  635. }
  636. func UnmarshalProxyAnnounceRequest(payload []byte) (*ProxyAnnounceRequest, error) {
  637. var request *ProxyAnnounceRequest
  638. err := unmarshalRecord(recordTypeAPIProxyAnnounceRequest, payload, &request)
  639. return request, errors.Trace(err)
  640. }
  641. func MarshalProxyAnnounceResponse(response *ProxyAnnounceResponse) ([]byte, error) {
  642. payload, err := marshalRecord(response, recordTypeAPIProxyAnnounceResponse)
  643. return payload, errors.Trace(err)
  644. }
  645. func UnmarshalProxyAnnounceResponse(payload []byte) (*ProxyAnnounceResponse, error) {
  646. var response *ProxyAnnounceResponse
  647. err := unmarshalRecord(recordTypeAPIProxyAnnounceResponse, payload, &response)
  648. return response, errors.Trace(err)
  649. }
  650. func MarshalProxyAnswerRequest(request *ProxyAnswerRequest) ([]byte, error) {
  651. payload, err := marshalRecord(request, recordTypeAPIProxyAnswerRequest)
  652. return payload, errors.Trace(err)
  653. }
  654. func UnmarshalProxyAnswerRequest(payload []byte) (*ProxyAnswerRequest, error) {
  655. var request *ProxyAnswerRequest
  656. err := unmarshalRecord(recordTypeAPIProxyAnswerRequest, payload, &request)
  657. return request, errors.Trace(err)
  658. }
  659. func MarshalProxyAnswerResponse(response *ProxyAnswerResponse) ([]byte, error) {
  660. payload, err := marshalRecord(response, recordTypeAPIProxyAnswerResponse)
  661. return payload, errors.Trace(err)
  662. }
  663. func UnmarshalProxyAnswerResponse(payload []byte) (*ProxyAnswerResponse, error) {
  664. var response *ProxyAnswerResponse
  665. err := unmarshalRecord(recordTypeAPIProxyAnswerResponse, payload, &response)
  666. return response, errors.Trace(err)
  667. }
  668. func MarshalClientOfferRequest(request *ClientOfferRequest) ([]byte, error) {
  669. payload, err := marshalRecord(request, recordTypeAPIClientOfferRequest)
  670. return payload, errors.Trace(err)
  671. }
  672. func UnmarshalClientOfferRequest(payload []byte) (*ClientOfferRequest, error) {
  673. var request *ClientOfferRequest
  674. err := unmarshalRecord(recordTypeAPIClientOfferRequest, payload, &request)
  675. return request, errors.Trace(err)
  676. }
  677. func MarshalClientOfferResponse(response *ClientOfferResponse) ([]byte, error) {
  678. payload, err := marshalRecord(response, recordTypeAPIClientOfferResponse)
  679. return payload, errors.Trace(err)
  680. }
  681. func UnmarshalClientOfferResponse(payload []byte) (*ClientOfferResponse, error) {
  682. var response *ClientOfferResponse
  683. err := unmarshalRecord(recordTypeAPIClientOfferResponse, payload, &response)
  684. return response, errors.Trace(err)
  685. }
  686. func MarshalClientRelayedPacketRequest(request *ClientRelayedPacketRequest) ([]byte, error) {
  687. payload, err := marshalRecord(request, recordTypeAPIClientRelayedPacketRequest)
  688. return payload, errors.Trace(err)
  689. }
  690. func UnmarshalClientRelayedPacketRequest(payload []byte) (*ClientRelayedPacketRequest, error) {
  691. var request *ClientRelayedPacketRequest
  692. err := unmarshalRecord(recordTypeAPIClientRelayedPacketRequest, payload, &request)
  693. return request, errors.Trace(err)
  694. }
  695. func MarshalClientRelayedPacketResponse(response *ClientRelayedPacketResponse) ([]byte, error) {
  696. payload, err := marshalRecord(response, recordTypeAPIClientRelayedPacketResponse)
  697. return payload, errors.Trace(err)
  698. }
  699. func UnmarshalClientRelayedPacketResponse(payload []byte) (*ClientRelayedPacketResponse, error) {
  700. var response *ClientRelayedPacketResponse
  701. err := unmarshalRecord(recordTypeAPIClientRelayedPacketResponse, payload, &response)
  702. return response, errors.Trace(err)
  703. }
  704. func MarshalBrokerServerReport(request *BrokerServerReport) ([]byte, error) {
  705. payload, err := marshalRecord(request, recordTypeAPIBrokerServerReport)
  706. return payload, errors.Trace(err)
  707. }
  708. func UnmarshalBrokerServerReport(payload []byte) (*BrokerServerReport, error) {
  709. var request *BrokerServerReport
  710. err := unmarshalRecord(recordTypeAPIBrokerServerReport, payload, &request)
  711. return request, errors.Trace(err)
  712. }