api.go 32 KB

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