api.go 34 KB

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