broker.go 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513
  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. "context"
  22. std_errors "errors"
  23. "net"
  24. "strconv"
  25. "sync"
  26. "sync/atomic"
  27. "time"
  28. "github.com/Psiphon-Labs/consistent"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  32. "github.com/cespare/xxhash"
  33. lrucache "github.com/cognusion/go-cache-lru"
  34. "github.com/fxamacker/cbor/v2"
  35. )
  36. const (
  37. // BrokerMaxRequestBodySize is the maximum request size, that should be
  38. // enforced by the provided broker transport.
  39. BrokerMaxRequestBodySize = 65536
  40. // BrokerEndPointName is the standard name for referencing an endpoint
  41. // that services broker requests.
  42. BrokerEndPointName = "inproxy-broker"
  43. brokerProxyAnnounceTimeout = 2 * time.Minute
  44. brokerClientOfferTimeout = 10 * time.Second
  45. brokerPendingServerReportsTTL = 60 * time.Second
  46. brokerPendingServerReportsMaxSize = 100000
  47. brokerMetricName = "inproxy_broker"
  48. )
  49. // LookupGeoIP is a callback for providing GeoIP lookup service.
  50. type LookupGeoIP func(IP string) common.GeoIPData
  51. // ExtendTransportTimeout is a callback that extends the timeout for a
  52. // server-side broker transport handler, facilitating request-specific
  53. // timeouts including long-polling for proxy announcements.
  54. type ExtendTransportTimeout func(timeout time.Duration)
  55. // GetTactics is a callback which returns the appropriate tactics for the
  56. // specified client/proxy GeoIP data and API parameters.
  57. type GetTactics func(common.GeoIPData, common.APIParameters) ([]byte, string, error)
  58. // Broker is the in-proxy broker component, which matches clients and proxies
  59. // and provides WebRTC signaling functionalty.
  60. //
  61. // Both clients and proxies send requests to the broker to obtain matches and
  62. // exchange WebRTC SDPs. Broker does not implement a transport or obfuscation
  63. // layer; instead that is provided by the HandleSessionPacket caller. A
  64. // typical implementation would provide a domain fronted web server which
  65. // runs a Broker and calls Broker.HandleSessionPacket to handle web requests
  66. // encapsulating secure session packets.
  67. type Broker struct {
  68. config *BrokerConfig
  69. initiatorSessions *InitiatorSessions
  70. responderSessions *ResponderSessions
  71. matcher *Matcher
  72. pendingServerReports *lrucache.Cache
  73. commonCompartmentsMutex sync.Mutex
  74. commonCompartments *consistent.Consistent
  75. proxyAnnounceTimeout int64
  76. clientOfferTimeout int64
  77. pendingServerReportsTTL int64
  78. maxCompartmentIDs int64
  79. }
  80. // BrokerConfig specifies the configuration for a Broker.
  81. type BrokerConfig struct {
  82. // Logger is used to log events.
  83. Logger common.Logger
  84. // CommonCompartmentIDs is a list of common compartment IDs to apply to
  85. // proxies that announce without personal compartment ID. Common
  86. // compartment IDs are managed by Psiphon and distributed to clients via
  87. // tactics or embedded in OSLs. Clients must supply a valid compartment
  88. // ID to match with a proxy.
  89. //
  90. // A BrokerConfig must supply at least one compartment ID, or
  91. // SetCompartmentIDs must be called with at least one compartment ID
  92. // before calling Start.
  93. //
  94. // When only one, single common compartment ID is configured, it can serve
  95. // as an (obfuscation) secret that clients must obtain, via tactics, to
  96. // enable in-proxy participation.
  97. CommonCompartmentIDs []ID
  98. // AllowProxy is a callback which can indicate whether a proxy with the
  99. // given GeoIP data is allowed to match with common compartment ID
  100. // clients. Proxies with personal compartment IDs are always allowed.
  101. AllowProxy func(common.GeoIPData) bool
  102. // AllowClient is a callback which can indicate whether a client with the
  103. // given GeoIP data is allowed to match with common compartment ID
  104. // proxies. Clients are always allowed to match based on personal
  105. // compartment ID.
  106. AllowClient func(common.GeoIPData) bool
  107. // AllowDomainFrontedDestinations is a callback which can indicate whether
  108. // a client with the given GeoIP data is allowed to specify a proxied
  109. // destination for a domain fronted protocol. When false, only direct
  110. // address destinations are allowed.
  111. //
  112. // While tactics may may be set to instruct clients to use only direct
  113. // server tunnel protocols, with IP address destinations, this callback
  114. // adds server-side enforcement.
  115. AllowDomainFrontedDestinations func(common.GeoIPData) bool
  116. // LookupGeoIP provides GeoIP lookup service.
  117. LookupGeoIP LookupGeoIP
  118. // APIParameterValidator is a callback that validates base API metrics.
  119. APIParameterValidator common.APIParameterValidator
  120. // APIParameterValidator is a callback that formats base API metrics.
  121. APIParameterLogFieldFormatter common.APIParameterLogFieldFormatter
  122. // GetTactics provides a tactics lookup service.
  123. GetTactics GetTactics
  124. // IsValidServerEntryTag is a callback which checks if the specified
  125. // server entry tag is on the list of valid and active Psiphon server
  126. // entry tags.
  127. IsValidServerEntryTag func(serverEntryTag string) bool
  128. // PrivateKey is the broker's secure session long term private key.
  129. PrivateKey SessionPrivateKey
  130. // ObfuscationRootSecret broker's secure session long term obfuscation key.
  131. ObfuscationRootSecret ObfuscationSecret
  132. // ServerEntrySignaturePublicKey is the key used to verify Psiphon server
  133. // entry signatures.
  134. ServerEntrySignaturePublicKey string
  135. // These timeout parameters may be used to override defaults.
  136. ProxyAnnounceTimeout time.Duration
  137. ClientOfferTimeout time.Duration
  138. PendingServerReportsTTL time.Duration
  139. // Announcement queue limit configuration.
  140. MatcherAnnouncementLimitEntryCount int
  141. MatcherAnnouncementRateLimitQuantity int
  142. MatcherAnnouncementRateLimitInterval time.Duration
  143. MatcherAnnouncementNonlimitedProxyIDs []ID
  144. // Offer queue limit configuration.
  145. MatcherOfferLimitEntryCount int
  146. MatcherOfferRateLimitQuantity int
  147. MatcherOfferRateLimitInterval time.Duration
  148. // MaxCompartmentIDs specifies the maximum number of compartment IDs that
  149. // can be included, per list, in one request. If 0, the value
  150. // MaxCompartmentIDs is used.
  151. MaxCompartmentIDs int
  152. }
  153. // NewBroker initializes a new Broker.
  154. func NewBroker(config *BrokerConfig) (*Broker, error) {
  155. // initiatorSessions are secure sessions initiated by the broker and used
  156. // to send BrokerServerReports to servers. The servers will be
  157. // configured to establish sessions only with brokers with specified
  158. // public keys.
  159. initiatorSessions := NewInitiatorSessions(config.PrivateKey)
  160. // responderSessions are secure sessions initiated by clients and proxies
  161. // and used to send requests to the broker. Clients and proxies are
  162. // configured to establish sessions only with specified broker public keys.
  163. responderSessions, err := NewResponderSessions(
  164. config.PrivateKey, config.ObfuscationRootSecret)
  165. if err != nil {
  166. return nil, errors.Trace(err)
  167. }
  168. b := &Broker{
  169. config: config,
  170. initiatorSessions: initiatorSessions,
  171. responderSessions: responderSessions,
  172. matcher: NewMatcher(&MatcherConfig{
  173. Logger: config.Logger,
  174. AnnouncementLimitEntryCount: config.MatcherAnnouncementLimitEntryCount,
  175. AnnouncementRateLimitQuantity: config.MatcherAnnouncementRateLimitQuantity,
  176. AnnouncementRateLimitInterval: config.MatcherAnnouncementRateLimitInterval,
  177. AnnouncementNonlimitedProxyIDs: config.MatcherAnnouncementNonlimitedProxyIDs,
  178. OfferLimitEntryCount: config.MatcherOfferLimitEntryCount,
  179. OfferRateLimitQuantity: config.MatcherOfferRateLimitQuantity,
  180. OfferRateLimitInterval: config.MatcherOfferRateLimitInterval,
  181. }),
  182. proxyAnnounceTimeout: int64(config.ProxyAnnounceTimeout),
  183. clientOfferTimeout: int64(config.ClientOfferTimeout),
  184. pendingServerReportsTTL: int64(config.PendingServerReportsTTL),
  185. maxCompartmentIDs: int64(common.ValueOrDefault(config.MaxCompartmentIDs, MaxCompartmentIDs)),
  186. }
  187. b.pendingServerReports = lrucache.NewWithLRU(
  188. common.ValueOrDefault(config.PendingServerReportsTTL, brokerPendingServerReportsTTL),
  189. 1*time.Minute,
  190. brokerPendingServerReportsMaxSize)
  191. if len(config.CommonCompartmentIDs) > 0 {
  192. err = b.initializeCommonCompartmentIDHashing(config.CommonCompartmentIDs)
  193. if err != nil {
  194. return nil, errors.Trace(err)
  195. }
  196. }
  197. return b, nil
  198. }
  199. func (b *Broker) Start() error {
  200. if !b.isCommonCompartmentIDHashingInitialized() {
  201. return errors.TraceNew("missing common compartment IDs")
  202. }
  203. return errors.Trace(b.matcher.Start())
  204. }
  205. func (b *Broker) Stop() {
  206. b.matcher.Stop()
  207. }
  208. // SetCommonCompartmentIDs sets a new list of common compartment IDs,
  209. // replacing the previous configuration.
  210. func (b *Broker) SetCommonCompartmentIDs(commonCompartmentIDs []ID) error {
  211. // TODO: initializeCommonCompartmentIDHashing is called regardless whether
  212. // commonCompartmentIDs changes the previous configuration. To avoid the
  213. // overhead of consistent hashing initialization in
  214. // initializeCommonCompartmentIDHashing, add a mechanism to first quickly
  215. // check for changes?
  216. return errors.Trace(b.initializeCommonCompartmentIDHashing(commonCompartmentIDs))
  217. }
  218. // SetTimeouts sets new timeout values, replacing the previous configuration.
  219. // New timeout values do not apply to currently active announcement or offer
  220. // requests.
  221. func (b *Broker) SetTimeouts(
  222. proxyAnnounceTimeout time.Duration,
  223. clientOfferTimeout time.Duration,
  224. pendingServerReportsTTL time.Duration) {
  225. atomic.StoreInt64(&b.proxyAnnounceTimeout, int64(proxyAnnounceTimeout))
  226. atomic.StoreInt64(&b.clientOfferTimeout, int64(clientOfferTimeout))
  227. atomic.StoreInt64(&b.pendingServerReportsTTL, int64(pendingServerReportsTTL))
  228. }
  229. // SetLimits sets new queue limit values, replacing the previous
  230. // configuration. New limits are only partially applied to existing queue
  231. // states; see Matcher.SetLimits.
  232. func (b *Broker) SetLimits(
  233. matcherAnnouncementLimitEntryCount int,
  234. matcherAnnouncementRateLimitQuantity int,
  235. matcherAnnouncementRateLimitInterval time.Duration,
  236. matcherAnnouncementNonlimitedProxyIDs []ID,
  237. matcherOfferLimitEntryCount int,
  238. matcherOfferRateLimitQuantity int,
  239. matcherOfferRateLimitInterval time.Duration,
  240. maxCompartmentIDs int) {
  241. b.matcher.SetLimits(
  242. matcherAnnouncementLimitEntryCount,
  243. matcherAnnouncementRateLimitQuantity,
  244. matcherAnnouncementRateLimitInterval,
  245. matcherAnnouncementNonlimitedProxyIDs,
  246. matcherOfferLimitEntryCount,
  247. matcherOfferRateLimitQuantity,
  248. matcherOfferRateLimitInterval)
  249. atomic.StoreInt64(
  250. &b.maxCompartmentIDs,
  251. int64(common.ValueOrDefault(maxCompartmentIDs, MaxCompartmentIDs)))
  252. }
  253. // HandleSessionPacket handles a session packet from a client or proxy and
  254. // provides a response packet. The packet is part of a secure session and may
  255. // be a session handshake message, an expired session reset token, or a
  256. // session-wrapped request payload. Request payloads are routed to API
  257. // request endpoints.
  258. //
  259. // The caller is expected to provide a transport obfuscation layer, such as
  260. // domain fronted HTTPs. The session has an obfuscation layer that ensures
  261. // that packets are fully random, randomly padded, and cannot be replayed.
  262. // This makes session packets suitable to embed as plaintext in some
  263. // transports.
  264. //
  265. // The caller is responsible for rate limiting and enforcing timeouts and
  266. // maximum payload size checks.
  267. //
  268. // Secure sessions support multiplexing concurrent requests, as long as the
  269. // provided transport, for example HTTP/2, supports this as well.
  270. //
  271. // The input ctx should be canceled if the client/proxy disconnects from the
  272. // transport while HandleSessionPacket is running, since long-polling proxy
  273. // announcement requests will otherwise remain blocked until eventual
  274. // timeout; net/http does this.
  275. //
  276. // When HandleSessionPacket returns an error, the transport provider should
  277. // apply anti-probing mechanisms, as the client/proxy may be a prober or
  278. // scanner.
  279. func (b *Broker) HandleSessionPacket(
  280. ctx context.Context,
  281. extendTransportTimeout ExtendTransportTimeout,
  282. transportLogFields common.LogFields,
  283. brokerClientIP string,
  284. geoIPData common.GeoIPData,
  285. inPacket []byte) ([]byte, error) {
  286. // handleUnwrappedRequest handles requests after session unwrapping.
  287. // responderSessions.HandlePacket handles both session establishment and
  288. // request unwrapping, and invokes handleUnwrappedRequest once a session
  289. // is established and a valid request unwrapped.
  290. handleUnwrappedRequest := func(initiatorID ID, unwrappedRequestPayload []byte) ([]byte, error) {
  291. recordType, err := peekRecordPreambleType(unwrappedRequestPayload)
  292. if err != nil {
  293. return nil, errors.Trace(err)
  294. }
  295. var responsePayload []byte
  296. switch recordType {
  297. case recordTypeAPIProxyAnnounceRequest:
  298. responsePayload, err = b.handleProxyAnnounce(
  299. ctx,
  300. extendTransportTimeout,
  301. transportLogFields,
  302. brokerClientIP,
  303. geoIPData,
  304. initiatorID,
  305. unwrappedRequestPayload)
  306. if err != nil {
  307. return nil, errors.Trace(err)
  308. }
  309. case recordTypeAPIProxyAnswerRequest:
  310. responsePayload, err = b.handleProxyAnswer(
  311. ctx,
  312. extendTransportTimeout,
  313. transportLogFields,
  314. brokerClientIP,
  315. geoIPData,
  316. initiatorID,
  317. unwrappedRequestPayload)
  318. if err != nil {
  319. return nil, errors.Trace(err)
  320. }
  321. case recordTypeAPIClientOfferRequest:
  322. responsePayload, err = b.handleClientOffer(
  323. ctx,
  324. extendTransportTimeout,
  325. transportLogFields,
  326. brokerClientIP,
  327. geoIPData,
  328. initiatorID,
  329. unwrappedRequestPayload)
  330. if err != nil {
  331. return nil, errors.Trace(err)
  332. }
  333. case recordTypeAPIClientRelayedPacketRequest:
  334. responsePayload, err = b.handleClientRelayedPacket(
  335. ctx,
  336. extendTransportTimeout,
  337. transportLogFields,
  338. geoIPData,
  339. initiatorID,
  340. unwrappedRequestPayload)
  341. if err != nil {
  342. return nil, errors.Trace(err)
  343. }
  344. default:
  345. return nil, errors.Tracef("unexpected API record type %v", recordType)
  346. }
  347. return responsePayload, nil
  348. }
  349. // HandlePacket returns both a packet and an error in the expired session
  350. // reset token case. Log the error here, clear it, and return the
  351. // packetto be relayed back to the broker client.
  352. outPacket, err := b.responderSessions.HandlePacket(
  353. inPacket, handleUnwrappedRequest)
  354. if err != nil {
  355. if outPacket == nil {
  356. return nil, errors.Trace(err)
  357. }
  358. b.config.Logger.WithTraceFields(common.LogFields{"error": err}).Warning(
  359. "HandlePacket returned packet and error")
  360. }
  361. return outPacket, nil
  362. }
  363. // handleProxyAnnounce receives a proxy announcement, awaits a matching
  364. // client, and returns the client offer in the response. handleProxyAnnounce
  365. // has a long timeout so this request can idle until a matching client
  366. // arrives.
  367. func (b *Broker) handleProxyAnnounce(
  368. ctx context.Context,
  369. extendTransportTimeout ExtendTransportTimeout,
  370. transportLogFields common.LogFields,
  371. proxyIP string,
  372. geoIPData common.GeoIPData,
  373. initiatorID ID,
  374. requestPayload []byte) (retResponse []byte, retErr error) {
  375. startTime := time.Now()
  376. var logFields common.LogFields
  377. var newTacticsTag string
  378. var clientOffer *MatchOffer
  379. var matchMetrics *MatchMetrics
  380. var timedOut bool
  381. var limitedErr error
  382. // As a future enhancement, a broker could initiate its own test
  383. // connection to the proxy to verify its effectiveness, including
  384. // simulating a symmetric NAT client.
  385. // Each announcement represents availability for a single client matching.
  386. // Proxies with multiple client availability will send multiple requests.
  387. //
  388. // The announcement request and response could be extended to allow the
  389. // proxy to specify availability for multiple clients in the request, and
  390. // multiple client offers returned in the response.
  391. //
  392. // If, as we expect, proxies run on home ISPs have limited upstream
  393. // bandwidth, they will support only a couple of concurrent clients, and
  394. // the simple single-client-announcment model may be sufficient. Also, if
  395. // the transport is HTTP/2, multiple requests can be multiplexed over a
  396. // single connection (and session) in any case.
  397. // The proxy ID is an implicit parameter: it's the proxy's session public
  398. // key. As part of the session handshake, the proxy has proven that it
  399. // has the corresponding private key. Proxy IDs are logged to attribute
  400. // traffic to a specific proxy.
  401. proxyID := initiatorID
  402. // Generate a connection ID. This ID is used to associate proxy
  403. // announcments, client offers, and proxy answers, as well as associating
  404. // Psiphon tunnels with in-proxy pairings.
  405. connectionID, err := MakeID()
  406. if err != nil {
  407. return nil, errors.Trace(err)
  408. }
  409. // Always log the outcome.
  410. defer func() {
  411. if logFields == nil {
  412. logFields = b.config.APIParameterLogFieldFormatter(geoIPData, nil)
  413. }
  414. logFields["broker_event"] = "proxy-announce"
  415. logFields["proxy_id"] = proxyID
  416. logFields["elapsed_time"] = time.Since(startTime) / time.Millisecond
  417. logFields["connection_id"] = connectionID
  418. if newTacticsTag != "" {
  419. logFields["new_tactics_tag"] = newTacticsTag
  420. }
  421. if clientOffer != nil {
  422. // Log the target Psiphon server ID (diagnostic ID). The presence
  423. // of this field indicates that a match was made.
  424. logFields["destination_server_id"] = clientOffer.DestinationServerID
  425. }
  426. if timedOut {
  427. logFields["timed_out"] = true
  428. }
  429. if retErr != nil {
  430. logFields["error"] = retErr.Error()
  431. } else if limitedErr != nil {
  432. logFields["error"] = limitedErr.Error()
  433. }
  434. logFields.Add(transportLogFields)
  435. logFields.Add(matchMetrics.GetMetrics())
  436. b.config.Logger.LogMetric(brokerMetricName, logFields)
  437. }()
  438. announceRequest, err := UnmarshalProxyAnnounceRequest(requestPayload)
  439. if err != nil {
  440. return nil, errors.Trace(err)
  441. }
  442. var apiParams common.APIParameters
  443. apiParams, logFields, err = announceRequest.ValidateAndGetParametersAndLogFields(
  444. int(atomic.LoadInt64(&b.maxCompartmentIDs)),
  445. b.config.APIParameterValidator,
  446. b.config.APIParameterLogFieldFormatter,
  447. geoIPData)
  448. if err != nil {
  449. return nil, errors.Trace(err)
  450. }
  451. // Return MustUpgrade when the proxy's protocol version is less than the
  452. // minimum required.
  453. if announceRequest.Metrics.ProxyProtocolVersion < MinimumProxyProtocolVersion {
  454. responsePayload, err := MarshalProxyAnnounceResponse(
  455. &ProxyAnnounceResponse{
  456. NoMatch: true,
  457. MustUpgrade: true,
  458. })
  459. if err != nil {
  460. return nil, errors.Trace(err)
  461. }
  462. return responsePayload, nil
  463. }
  464. // Fetch new tactics for the proxy, if required, using the tactics tag
  465. // that should be included with the API parameters. A tacticsPayload may
  466. // be returned when there are no new tactics, and this is relayed back to
  467. // the proxy, after matching, so that it can extend the TTL for its
  468. // existing, cached tactics. In the case where tactics have changed,
  469. // don't enqueue the proxy announcement and return no-match so that the
  470. // proxy can store and apply the new tactics before announcing again.
  471. var tacticsPayload []byte
  472. tacticsPayload, newTacticsTag, err = b.config.GetTactics(geoIPData, apiParams)
  473. if err != nil {
  474. return nil, errors.Trace(err)
  475. }
  476. if tacticsPayload != nil && newTacticsTag != "" {
  477. responsePayload, err := MarshalProxyAnnounceResponse(
  478. &ProxyAnnounceResponse{
  479. TacticsPayload: tacticsPayload,
  480. NoMatch: true,
  481. })
  482. if err != nil {
  483. return nil, errors.Trace(err)
  484. }
  485. return responsePayload, nil
  486. }
  487. // AllowProxy may be used to disallow proxies from certain geolocations,
  488. // such as censored locations, from announcing. Proxies with personal
  489. // compartment IDs are always allowed, as they will be used only by
  490. // clients specifically configured to use them.
  491. if len(announceRequest.PersonalCompartmentIDs) == 0 &&
  492. !b.config.AllowProxy(geoIPData) {
  493. return nil, errors.TraceNew("proxy disallowed")
  494. }
  495. // Assign this proxy to a common compartment ID, unless it has specified a
  496. // dedicated, personal compartment ID. Assignment uses consistent hashing
  497. // keyed with the proxy ID, in an effort to keep proxies consistently
  498. // assigned to the same compartment.
  499. var commonCompartmentIDs []ID
  500. if len(announceRequest.PersonalCompartmentIDs) == 0 {
  501. compartmentID, err := b.selectCommonCompartmentID(proxyID)
  502. if err != nil {
  503. return nil, errors.Trace(err)
  504. }
  505. commonCompartmentIDs = []ID{compartmentID}
  506. }
  507. // Await client offer.
  508. timeout := common.ValueOrDefault(
  509. time.Duration(atomic.LoadInt64(&b.proxyAnnounceTimeout)),
  510. brokerProxyAnnounceTimeout)
  511. announceCtx, cancelFunc := context.WithTimeout(ctx, timeout)
  512. defer cancelFunc()
  513. extendTransportTimeout(timeout)
  514. // Note that matcher.Announce assumes a monotonically increasing
  515. // announceCtx.Deadline input for each successive call.
  516. clientOffer, matchMetrics, err = b.matcher.Announce(
  517. announceCtx,
  518. proxyIP,
  519. &MatchAnnouncement{
  520. Properties: MatchProperties{
  521. CommonCompartmentIDs: commonCompartmentIDs,
  522. PersonalCompartmentIDs: announceRequest.PersonalCompartmentIDs,
  523. GeoIPData: geoIPData,
  524. NetworkType: GetNetworkType(announceRequest.Metrics.BaseAPIParameters),
  525. NATType: announceRequest.Metrics.NATType,
  526. PortMappingTypes: announceRequest.Metrics.PortMappingTypes,
  527. },
  528. ProxyID: initiatorID,
  529. ConnectionID: connectionID,
  530. ProxyProtocolVersion: announceRequest.Metrics.ProxyProtocolVersion,
  531. })
  532. if err != nil {
  533. var limitError *MatcherLimitError
  534. limited := std_errors.As(err, &limitError)
  535. timeout := announceCtx.Err() == context.DeadlineExceeded
  536. if !limited && !timeout {
  537. return nil, errors.Trace(err)
  538. }
  539. // A no-match response is sent in the case of a timeout awaiting a
  540. // match. The faster-failing rate or entry limiting case also results
  541. // in a response, rather than an error return from handleProxyAnnounce,
  542. // so that the proxy doesn't receive a 404 and flag its BrokerClient as
  543. // having failed.
  544. //
  545. // When the timeout and limit case coincide, limit takes precedence in
  546. // the response.
  547. if timeout && !limited {
  548. // Note: the respective proxy and broker timeouts,
  549. // InproxyBrokerProxyAnnounceTimeout and
  550. // InproxyProxyAnnounceRequestTimeout in tactics, should be
  551. // configured so that the broker will timeout first and have an
  552. // opportunity to send this response before the proxy times out.
  553. timedOut = true
  554. } else {
  555. // Record the specific limit error in the proxy-announce broker event.
  556. limitedErr = err
  557. }
  558. responsePayload, err := MarshalProxyAnnounceResponse(
  559. &ProxyAnnounceResponse{
  560. TacticsPayload: tacticsPayload,
  561. Limited: limited,
  562. NoMatch: timeout && !limited,
  563. })
  564. if err != nil {
  565. return nil, errors.Trace(err)
  566. }
  567. return responsePayload, nil
  568. }
  569. // Respond with the client offer. The proxy will follow up with an answer
  570. // request, which is relayed to the client, and then the WebRTC dial begins.
  571. // Limitation: as part of the client's tunnel establishment horse race, a
  572. // client may abort an in-proxy dial at any point. If the overall dial is
  573. // past the SDP exchange and aborted during the WebRTC connection
  574. // establishment, the client may leave the proxy's Proxy.proxyOneClient
  575. // dangling until timeout. Consider adding a signal from the client to
  576. // the proxy, relayed by the broker, that a dial is aborted.
  577. responsePayload, err := MarshalProxyAnnounceResponse(
  578. &ProxyAnnounceResponse{
  579. TacticsPayload: tacticsPayload,
  580. ConnectionID: connectionID,
  581. ClientProxyProtocolVersion: clientOffer.ClientProxyProtocolVersion,
  582. ClientOfferSDP: clientOffer.ClientOfferSDP,
  583. ClientRootObfuscationSecret: clientOffer.ClientRootObfuscationSecret,
  584. DoDTLSRandomization: clientOffer.DoDTLSRandomization,
  585. TrafficShapingParameters: clientOffer.TrafficShapingParameters,
  586. NetworkProtocol: clientOffer.NetworkProtocol,
  587. DestinationAddress: clientOffer.DestinationAddress,
  588. })
  589. if err != nil {
  590. return nil, errors.Trace(err)
  591. }
  592. return responsePayload, nil
  593. }
  594. // handleClientOffer receives a client offer, awaits a matching client, and
  595. // returns the proxy answer. handleClientOffer has a shorter timeout than
  596. // handleProxyAnnounce since the client has supplied an SDP with STUN hole
  597. // punches which will expire; and, in general, the client is trying to
  598. // connect immediately and is also trying other candidates.
  599. func (b *Broker) handleClientOffer(
  600. ctx context.Context,
  601. extendTransportTimeout ExtendTransportTimeout,
  602. transportLogFields common.LogFields,
  603. clientIP string,
  604. geoIPData common.GeoIPData,
  605. initiatorID ID,
  606. requestPayload []byte) (retResponse []byte, retErr error) {
  607. // As a future enhancement, consider having proxies send offer SDPs with
  608. // announcements and clients long poll to await a match and then provide
  609. // an answer. This order of operations would make sense if client demand
  610. // is high and proxy supply is lower.
  611. //
  612. // Also see comment in Proxy.proxyOneClient for other alternative
  613. // approaches.
  614. // The client's session public key is ephemeral and is not logged.
  615. startTime := time.Now()
  616. var logFields common.LogFields
  617. var serverParams *serverParams
  618. var clientMatchOffer *MatchOffer
  619. var proxyMatchAnnouncement *MatchAnnouncement
  620. var proxyAnswer *MatchAnswer
  621. var matchMetrics *MatchMetrics
  622. var timedOut bool
  623. var limitedErr error
  624. // Always log the outcome.
  625. defer func() {
  626. if logFields == nil {
  627. logFields = b.config.APIParameterLogFieldFormatter(geoIPData, nil)
  628. }
  629. logFields["broker_event"] = "client-offer"
  630. if serverParams != nil {
  631. logFields["destination_server_id"] = serverParams.serverID
  632. }
  633. logFields["elapsed_time"] = time.Since(startTime) / time.Millisecond
  634. if proxyAnswer != nil {
  635. // The presence of these fields indicate that a match was made,
  636. // the proxy delivered an answer, and the client was still
  637. // waiting for it.
  638. logFields["connection_id"] = proxyAnswer.ConnectionID
  639. logFields["client_nat_type"] = clientMatchOffer.Properties.NATType
  640. logFields["client_port_mapping_types"] = clientMatchOffer.Properties.PortMappingTypes
  641. logFields["proxy_nat_type"] = proxyMatchAnnouncement.Properties.NATType
  642. logFields["proxy_port_mapping_types"] = proxyMatchAnnouncement.Properties.PortMappingTypes
  643. logFields["preferred_nat_match"] =
  644. clientMatchOffer.Properties.IsPreferredNATMatch(&proxyMatchAnnouncement.Properties)
  645. // TODO: also log proxy ice_candidate_types and has_IPv6; for the
  646. // client, these values are added by ValidateAndGetLogFields.
  647. }
  648. if timedOut {
  649. logFields["timed_out"] = true
  650. }
  651. if retErr != nil {
  652. logFields["error"] = retErr.Error()
  653. } else if limitedErr != nil {
  654. logFields["error"] = limitedErr.Error()
  655. }
  656. logFields.Add(transportLogFields)
  657. logFields.Add(matchMetrics.GetMetrics())
  658. b.config.Logger.LogMetric(brokerMetricName, logFields)
  659. }()
  660. offerRequest, err := UnmarshalClientOfferRequest(requestPayload)
  661. if err != nil {
  662. return nil, errors.Trace(err)
  663. }
  664. // The filtered SDP is the request SDP with any invalid (bogon, unexpected
  665. // GeoIP) ICE candidates filtered out. In some cases, clients cannot
  666. // avoid submitting invalid candidates (see comment in
  667. // processSDPAddresses), so all invalid candidates are removed and the
  668. // remaining SDP is used. Filtered candidate information is logged in
  669. // logFields.
  670. //
  671. // In personal pairing mode, RFC 1918/4193 private IP addresses are
  672. // permitted in exchanged SDPs and not filtered out.
  673. var filteredSDP []byte
  674. filteredSDP, logFields, err = offerRequest.ValidateAndGetLogFields(
  675. int(atomic.LoadInt64(&b.maxCompartmentIDs)),
  676. b.config.LookupGeoIP,
  677. b.config.APIParameterValidator,
  678. b.config.APIParameterLogFieldFormatter,
  679. geoIPData)
  680. if err != nil {
  681. return nil, errors.Trace(err)
  682. }
  683. offerSDP := offerRequest.ClientOfferSDP
  684. offerSDP.SDP = string(filteredSDP)
  685. // AllowClient may be used to disallow clients from certain geolocations
  686. // from offering. Clients are always allowed to match proxies with shared
  687. // personal compartment IDs.
  688. commonCompartmentIDs := offerRequest.CommonCompartmentIDs
  689. if !b.config.AllowClient(geoIPData) {
  690. if len(offerRequest.PersonalCompartmentIDs) == 0 {
  691. return nil, errors.TraceNew("client disallowed")
  692. }
  693. // Only match personal compartment IDs.
  694. commonCompartmentIDs = nil
  695. }
  696. // Validate that the proxy destination specified by the client is a valid
  697. // dial address for a signed Psiphon server entry. This ensures a client
  698. // can't misuse a proxy to connect to arbitrary destinations.
  699. serverParams, err = b.validateDestination(
  700. geoIPData,
  701. offerRequest.PackedDestinationServerEntry,
  702. offerRequest.NetworkProtocol,
  703. offerRequest.DestinationAddress)
  704. if err != nil {
  705. return nil, errors.Trace(err)
  706. }
  707. // Return MustUpgrade when the client's protocol version is less than the
  708. // minimum required.
  709. if offerRequest.Metrics.ProxyProtocolVersion < MinimumProxyProtocolVersion {
  710. responsePayload, err := MarshalClientOfferResponse(
  711. &ClientOfferResponse{
  712. NoMatch: true,
  713. MustUpgrade: true,
  714. })
  715. if err != nil {
  716. return nil, errors.Trace(err)
  717. }
  718. return responsePayload, nil
  719. }
  720. // Enqueue the client offer and await a proxy matching and subsequent
  721. // proxy answer.
  722. timeout := common.ValueOrDefault(
  723. time.Duration(atomic.LoadInt64(&b.clientOfferTimeout)),
  724. brokerClientOfferTimeout)
  725. offerCtx, cancelFunc := context.WithTimeout(ctx, timeout)
  726. defer cancelFunc()
  727. extendTransportTimeout(timeout)
  728. clientMatchOffer = &MatchOffer{
  729. Properties: MatchProperties{
  730. CommonCompartmentIDs: commonCompartmentIDs,
  731. PersonalCompartmentIDs: offerRequest.PersonalCompartmentIDs,
  732. GeoIPData: geoIPData,
  733. NetworkType: GetNetworkType(offerRequest.Metrics.BaseAPIParameters),
  734. NATType: offerRequest.Metrics.NATType,
  735. PortMappingTypes: offerRequest.Metrics.PortMappingTypes,
  736. },
  737. ClientProxyProtocolVersion: offerRequest.Metrics.ProxyProtocolVersion,
  738. ClientOfferSDP: offerSDP,
  739. ClientRootObfuscationSecret: offerRequest.ClientRootObfuscationSecret,
  740. DoDTLSRandomization: offerRequest.DoDTLSRandomization,
  741. TrafficShapingParameters: offerRequest.TrafficShapingParameters,
  742. NetworkProtocol: offerRequest.NetworkProtocol,
  743. DestinationAddress: offerRequest.DestinationAddress,
  744. DestinationServerID: serverParams.serverID,
  745. }
  746. proxyAnswer, proxyMatchAnnouncement, matchMetrics, err = b.matcher.Offer(
  747. offerCtx,
  748. clientIP,
  749. clientMatchOffer)
  750. if err != nil {
  751. var limitError *MatcherLimitError
  752. limited := std_errors.As(err, &limitError)
  753. timeout := offerCtx.Err() == context.DeadlineExceeded
  754. if !limited && !timeout {
  755. return nil, errors.Trace(err)
  756. }
  757. // A no-match response is sent in the case of a timeout awaiting a
  758. // match. The faster-failing rate or entry limiting case also results
  759. // in a response, rather than an error return from handleClientOffer,
  760. // so that the client doesn't receive a 404 and flag its BrokerClient
  761. // as having failed.
  762. //
  763. // When the timeout and limit case coincide, limit takes precedence in
  764. // the response.
  765. if timeout && !limited {
  766. // Note: the respective client and broker timeouts,
  767. // InproxyBrokerClientOfferTimeout and
  768. // InproxyClientOfferRequestTimeout in tactics, should be configured
  769. // so that the broker will timeout first and have an opportunity to
  770. // send this response before the client times out.
  771. timedOut = true
  772. } else {
  773. // Record the specific limit error in the client-offer broker event.
  774. limitedErr = err
  775. }
  776. responsePayload, err := MarshalClientOfferResponse(
  777. &ClientOfferResponse{
  778. Limited: limited,
  779. NoMatch: timeout && !limited,
  780. })
  781. if err != nil {
  782. return nil, errors.Trace(err)
  783. }
  784. return responsePayload, nil
  785. }
  786. // Log the type of compartment matching that occurred. As
  787. // PersonalCompartmentIDs are user-generated and shared, actual matching
  788. // values are not logged as they may link users.
  789. // TODO: log matching common compartment IDs?
  790. matchedCommonCompartments := HaveCommonIDs(
  791. proxyMatchAnnouncement.Properties.CommonCompartmentIDs,
  792. clientMatchOffer.Properties.CommonCompartmentIDs)
  793. matchedPersonalCompartments := HaveCommonIDs(
  794. proxyMatchAnnouncement.Properties.PersonalCompartmentIDs,
  795. clientMatchOffer.Properties.PersonalCompartmentIDs)
  796. // Initiate a BrokerServerReport, which sends important information
  797. // about the connection, including the original client IP, plus other
  798. // values to be logged with server_tunne, to the server. The report is
  799. // sent through a secure session established between the broker and the
  800. // server, relayed by the client.
  801. //
  802. // The first relay message will be embedded in the Psiphon handshake. The
  803. // broker may already have an established session with the server. In
  804. // this case, only only that initial message is required. The
  805. // BrokerServerReport is a one-way message, which avoids extra untunneled
  806. // client/broker traffic.
  807. //
  808. // Limitations, due to the one-way message:
  809. // - the broker can't actively clean up pendingServerReports as
  810. // tunnels are established and must rely on cache expiry.
  811. // - the broker doesn't learn that the server accepted the report, and
  812. // so cannot log a final connection status or signal the proxy to
  813. // disconnect the client in any misuse cases.
  814. //
  815. // As a future enhancement, consider adding a _tunneled_ client relay
  816. // of a server response acknowledging the broker report.
  817. relayPacket, err := b.initiateRelayedServerReport(
  818. serverParams,
  819. proxyAnswer.ConnectionID,
  820. &BrokerServerReport{
  821. ProxyID: proxyAnswer.ProxyID,
  822. ConnectionID: proxyAnswer.ConnectionID,
  823. MatchedCommonCompartments: matchedCommonCompartments,
  824. MatchedPersonalCompartments: matchedPersonalCompartments,
  825. ProxyNATType: proxyMatchAnnouncement.Properties.NATType,
  826. ProxyPortMappingTypes: proxyMatchAnnouncement.Properties.PortMappingTypes,
  827. ClientNATType: clientMatchOffer.Properties.NATType,
  828. ClientPortMappingTypes: clientMatchOffer.Properties.PortMappingTypes,
  829. ClientIP: clientIP,
  830. ProxyIP: proxyAnswer.ProxyIP,
  831. })
  832. if err != nil {
  833. return nil, errors.Trace(err)
  834. }
  835. // Respond with the proxy answer and initial broker/server session packet.
  836. responsePayload, err := MarshalClientOfferResponse(
  837. &ClientOfferResponse{
  838. ConnectionID: proxyAnswer.ConnectionID,
  839. SelectedProxyProtocolVersion: proxyAnswer.SelectedProxyProtocolVersion,
  840. ProxyAnswerSDP: proxyAnswer.ProxyAnswerSDP,
  841. RelayPacketToServer: relayPacket,
  842. })
  843. if err != nil {
  844. return nil, errors.Trace(err)
  845. }
  846. return responsePayload, nil
  847. }
  848. // handleProxyAnswer receives a proxy answer and delivers it to the waiting
  849. // client.
  850. func (b *Broker) handleProxyAnswer(
  851. ctx context.Context,
  852. extendTransportTimeout ExtendTransportTimeout,
  853. transportLogFields common.LogFields,
  854. proxyIP string,
  855. geoIPData common.GeoIPData,
  856. initiatorID ID,
  857. requestPayload []byte) (retResponse []byte, retErr error) {
  858. startTime := time.Now()
  859. var logFields common.LogFields
  860. var proxyAnswer *MatchAnswer
  861. var answerError string
  862. // The proxy ID is an implicit parameter: it's the proxy's session public
  863. // key.
  864. proxyID := initiatorID
  865. // Always log the outcome.
  866. defer func() {
  867. if logFields == nil {
  868. logFields = b.config.APIParameterLogFieldFormatter(geoIPData, nil)
  869. }
  870. logFields["broker_event"] = "proxy-answer"
  871. logFields["proxy_id"] = proxyID
  872. logFields["elapsed_time"] = time.Since(startTime) / time.Millisecond
  873. if proxyAnswer != nil {
  874. logFields["connection_id"] = proxyAnswer.ConnectionID
  875. }
  876. if answerError != "" {
  877. // This is a proxy-reported error that occurred while creating the answer.
  878. logFields["answer_error"] = answerError
  879. }
  880. if retErr != nil {
  881. logFields["error"] = retErr.Error()
  882. }
  883. logFields.Add(transportLogFields)
  884. b.config.Logger.LogMetric(brokerMetricName, logFields)
  885. }()
  886. answerRequest, err := UnmarshalProxyAnswerRequest(requestPayload)
  887. if err != nil {
  888. return nil, errors.Trace(err)
  889. }
  890. // The filtered SDP is the request SDP with any invalid (bogon, unexpected
  891. // GeoIP) ICE candidates filtered out. In some cases, proxies cannot
  892. // avoid submitting invalid candidates (see comment in
  893. // processSDPAddresses), so all invalid candidates are removed and the
  894. // remaining SDP is used. Filtered candidate information is logged in
  895. // logFields.
  896. //
  897. // In personal pairing mode, RFC 1918/4193 private IP addresses are
  898. // permitted in exchanged SDPs and not filtered out.
  899. hasPersonalCompartmentIDs, err := b.matcher.AnnouncementHasPersonalCompartmentIDs(
  900. initiatorID, answerRequest.ConnectionID)
  901. if err != nil {
  902. return nil, errors.Trace(err)
  903. }
  904. var filteredSDP []byte
  905. filteredSDP, logFields, err = answerRequest.ValidateAndGetLogFields(
  906. b.config.LookupGeoIP,
  907. b.config.APIParameterValidator,
  908. b.config.APIParameterLogFieldFormatter,
  909. geoIPData,
  910. hasPersonalCompartmentIDs)
  911. if err != nil {
  912. return nil, errors.Trace(err)
  913. }
  914. answerSDP := answerRequest.ProxyAnswerSDP
  915. answerSDP.SDP = string(filteredSDP)
  916. if answerRequest.AnswerError != "" {
  917. // The proxy failed to create an answer.
  918. answerError = answerRequest.AnswerError
  919. b.matcher.AnswerError(initiatorID, answerRequest.ConnectionID)
  920. } else {
  921. // Deliver the answer to the client.
  922. // Note that neither ProxyID nor ProxyIP is returned to the client.
  923. // These fields are used internally in the matcher.
  924. proxyAnswer = &MatchAnswer{
  925. ProxyIP: proxyIP,
  926. ProxyID: initiatorID,
  927. ConnectionID: answerRequest.ConnectionID,
  928. SelectedProxyProtocolVersion: answerRequest.SelectedProxyProtocolVersion,
  929. ProxyAnswerSDP: answerSDP,
  930. }
  931. err = b.matcher.Answer(proxyAnswer)
  932. if err != nil {
  933. return nil, errors.Trace(err)
  934. }
  935. }
  936. // There is no data in this response, it's simply an acknowledgement that
  937. // the answer was received. Upon receiving the response, the proxy should
  938. // begin the WebRTC dial operation.
  939. responsePayload, err := MarshalProxyAnswerResponse(
  940. &ProxyAnswerResponse{})
  941. if err != nil {
  942. return nil, errors.Trace(err)
  943. }
  944. return responsePayload, nil
  945. }
  946. // handleClientRelayedPacket facilitates broker/server sessions. The initial
  947. // packet from the broker is sent to the client in the ClientOfferResponse.
  948. // The client sends that to the server in the Psiphon handshake. If the
  949. // session was already established, the relay ends there. Otherwise, the
  950. // client receives any packet sent back by the server and that server packet
  951. // is then delivered to the broker in a ClientRelayedPacketRequest. If the
  952. // session needs to be [re-]negotiated, there are additional
  953. // ClientRelayedPacket round trips until the session is established and the
  954. // BrokerServerReport is securely exchanged between the broker and server.
  955. func (b *Broker) handleClientRelayedPacket(
  956. ctx context.Context,
  957. extendTransportTimeout ExtendTransportTimeout,
  958. transportLogFields common.LogFields,
  959. geoIPData common.GeoIPData,
  960. initiatorID ID,
  961. requestPayload []byte) (retResponse []byte, retErr error) {
  962. startTime := time.Now()
  963. var logFields common.LogFields
  964. var relayedPacketRequest *ClientRelayedPacketRequest
  965. var serverID string
  966. // Always log the outcome.
  967. defer func() {
  968. if logFields == nil {
  969. logFields = b.config.APIParameterLogFieldFormatter(geoIPData, nil)
  970. }
  971. logFields["broker_event"] = "client-relayed-packet"
  972. logFields["elapsed_time"] = time.Since(startTime) / time.Millisecond
  973. if relayedPacketRequest != nil {
  974. logFields["connection_id"] = relayedPacketRequest.ConnectionID
  975. }
  976. if serverID != "" {
  977. logFields["destination_server_id"] = serverID
  978. }
  979. if retErr != nil {
  980. logFields["error"] = retErr.Error()
  981. }
  982. logFields.Add(transportLogFields)
  983. b.config.Logger.LogMetric(brokerMetricName, logFields)
  984. }()
  985. relayedPacketRequest, err := UnmarshalClientRelayedPacketRequest(requestPayload)
  986. if err != nil {
  987. return nil, errors.Trace(err)
  988. }
  989. logFields, err = relayedPacketRequest.ValidateAndGetLogFields(
  990. b.config.APIParameterValidator,
  991. b.config.APIParameterLogFieldFormatter,
  992. geoIPData)
  993. if err != nil {
  994. return nil, errors.Trace(err)
  995. }
  996. // The relay state is associated with the connection ID.
  997. strConnectionID := string(relayedPacketRequest.ConnectionID[:])
  998. entry, ok := b.pendingServerReports.Get(strConnectionID)
  999. if !ok {
  1000. // The relay state is not found; it may have been evicted from the
  1001. // cache. The client will receive a generic error in this case and
  1002. // should stop relaying. Assuming the server is configured to require
  1003. // a BrokerServerReport, the tunnel will be terminated, so the
  1004. // client should also abandon the dial.
  1005. return nil, errors.TraceNew("no pending report")
  1006. }
  1007. pendingServerReport := entry.(*pendingServerReport)
  1008. serverID = pendingServerReport.serverID
  1009. // When the broker tried to use an existing session that was expired on the
  1010. // server, the server will respond here with a signed session reset token. The
  1011. // broker resets the session and starts to establish a new session.
  1012. //
  1013. // The non-waiting session establishment mode is used for broker/server
  1014. // sessions: if multiple clients concurrently try to relay new sessions,
  1015. // all establishments will happen in parallel without forcing any clients
  1016. // to wait for one client to lead the establishment. The last established
  1017. // session will be retained for reuse.
  1018. //
  1019. // If there is an error, the relayed packet is invalid. Drop the packet
  1020. // and return an error to be logged. Do _not_ reset the session,
  1021. // otherwise a malicious client could interrupt a valid broker/server
  1022. // session with a malformed packet.
  1023. // Next is given a nil ctx since we're not waiting for any other client to
  1024. // establish the session.
  1025. out, _, err := pendingServerReport.roundTrip.Next(
  1026. nil, relayedPacketRequest.PacketFromServer)
  1027. if err != nil {
  1028. return nil, errors.Trace(err)
  1029. }
  1030. if out == nil {
  1031. // The BrokerServerReport is a one-way message, As a result, the relay
  1032. // never ends with broker receiving a response; it's either
  1033. // (re)handshaking or sending the one-way report.
  1034. return nil, errors.TraceNew("unexpected nil packet")
  1035. }
  1036. // Return the next broker packet for the client to relay to the server.
  1037. // When it receives a nil PacketToServer, the client will stop relaying.
  1038. responsePayload, err := MarshalClientRelayedPacketResponse(
  1039. &ClientRelayedPacketResponse{
  1040. PacketToServer: out,
  1041. })
  1042. if err != nil {
  1043. return nil, errors.Trace(err)
  1044. }
  1045. return responsePayload, nil
  1046. }
  1047. type pendingServerReport struct {
  1048. serverID string
  1049. serverReport *BrokerServerReport
  1050. roundTrip *InitiatorRoundTrip
  1051. }
  1052. func (b *Broker) initiateRelayedServerReport(
  1053. serverParams *serverParams,
  1054. connectionID ID,
  1055. serverReport *BrokerServerReport) ([]byte, error) {
  1056. reportPayload, err := MarshalBrokerServerReport(serverReport)
  1057. if err != nil {
  1058. return nil, errors.Trace(err)
  1059. }
  1060. // Force a new, concurrent session establishment with the server even if
  1061. // another handshake is already in progess, relayed by some other client.
  1062. // This ensures clients don't block waiting for other client relays
  1063. // through other tunnels. The last established session will be retained
  1064. // for reuse.
  1065. waitToShareSession := false
  1066. roundTrip, err := b.initiatorSessions.NewRoundTrip(
  1067. serverParams.sessionPublicKey,
  1068. serverParams.sessionRootObfuscationSecret,
  1069. waitToShareSession,
  1070. reportPayload)
  1071. if err != nil {
  1072. return nil, errors.Trace(err)
  1073. }
  1074. relayPacket, _, err := roundTrip.Next(nil, nil)
  1075. if err != nil {
  1076. return nil, errors.Trace(err)
  1077. }
  1078. strConnectionID := string(connectionID[:])
  1079. b.pendingServerReports.Set(
  1080. strConnectionID,
  1081. &pendingServerReport{
  1082. serverID: serverParams.serverID,
  1083. serverReport: serverReport,
  1084. roundTrip: roundTrip,
  1085. },
  1086. time.Duration(atomic.LoadInt64(&b.pendingServerReportsTTL)))
  1087. return relayPacket, nil
  1088. }
  1089. type serverParams struct {
  1090. serverID string
  1091. sessionPublicKey SessionPublicKey
  1092. sessionRootObfuscationSecret ObfuscationSecret
  1093. }
  1094. // validateDestination checks that the client's specified proxy dial
  1095. // destination is valid destination address for a tunnel protocol in the
  1096. // specified signed and valid Psiphon server entry.
  1097. func (b *Broker) validateDestination(
  1098. geoIPData common.GeoIPData,
  1099. packedDestinationServerEntry []byte,
  1100. networkProtocol NetworkProtocol,
  1101. destinationAddress string) (*serverParams, error) {
  1102. var packedServerEntry protocol.PackedServerEntryFields
  1103. err := cbor.Unmarshal(packedDestinationServerEntry, &packedServerEntry)
  1104. if err != nil {
  1105. return nil, errors.Trace(err)
  1106. }
  1107. serverEntryFields, err := protocol.DecodePackedServerEntryFields(packedServerEntry)
  1108. if err != nil {
  1109. return nil, errors.Trace(err)
  1110. }
  1111. // Strip any unsigned fields, which could be forged by the client. In
  1112. // particular, this includes the server entry tag, which, in some cases,
  1113. // is locally populated by a client for its own reference.
  1114. serverEntryFields.RemoveUnsignedFields()
  1115. // Check that the server entry is signed by Psiphon. Otherwise a client
  1116. // could manufacture a server entry corresponding to an arbitrary dial
  1117. // destination.
  1118. err = serverEntryFields.VerifySignature(
  1119. b.config.ServerEntrySignaturePublicKey)
  1120. if err != nil {
  1121. return nil, errors.Trace(err)
  1122. }
  1123. // The server entry tag must be set and signed by Psiphon, as local,
  1124. // client derived tags are unsigned and untrusted.
  1125. serverEntryTag := serverEntryFields.GetTag()
  1126. if serverEntryTag == "" {
  1127. return nil, errors.TraceNew("missing server entry tag")
  1128. }
  1129. // Check that the server entry tag is on a list of active and valid
  1130. // Psiphon server entry tags. This ensures that an obsolete entry for a
  1131. // pruned server cannot by misused by a client to proxy to what's no
  1132. // longer a Psiphon server.
  1133. if !b.config.IsValidServerEntryTag(serverEntryTag) {
  1134. return nil, errors.TraceNew("invalid server entry tag")
  1135. }
  1136. serverID := serverEntryFields.GetDiagnosticID()
  1137. serverEntry, err := serverEntryFields.GetServerEntry()
  1138. if err != nil {
  1139. return nil, errors.Trace(err)
  1140. }
  1141. // Validate the dial host (IP or domain) and port matches a tunnel
  1142. // protocol offered by the server entry.
  1143. destHost, destPort, err := net.SplitHostPort(destinationAddress)
  1144. if err != nil {
  1145. return nil, errors.Trace(err)
  1146. }
  1147. destPortNum, err := strconv.Atoi(destPort)
  1148. if err != nil {
  1149. return nil, errors.Trace(err)
  1150. }
  1151. // For domain fronted cases, since we can't verify the Host header, access
  1152. // is strictly to limited to targeted clients. Clients should use tactics
  1153. // to avoid disallowed domain dial address cases, but here the broker
  1154. // enforces it.
  1155. //
  1156. // TODO: this issue could be further mitigated with a server
  1157. // acknowledgement of the broker's report, with no acknowledgement
  1158. // followed by signaling the proxy to terminate client connection.
  1159. // This assumes that any domain dial is for domain fronting.
  1160. isDomain := net.ParseIP(destHost) == nil
  1161. if isDomain && !b.config.AllowDomainFrontedDestinations(geoIPData) {
  1162. return nil, errors.TraceNew("domain fronted destinations disallowed")
  1163. }
  1164. // The server entry must include an in-proxy tunnel protocol capability
  1165. // and corresponding dial port number. In-proxy capacity may be set for
  1166. // only a subset of all Psiphon servers, to limited the number of servers
  1167. // a proxy can observe and enumerate. Well-behaved clients will not send
  1168. // any server entries lacking this capability, but here the broker
  1169. // enforces it.
  1170. if !serverEntry.IsValidInproxyDialAddress(networkProtocol.String(), destHost, destPortNum) {
  1171. return nil, errors.TraceNew("invalid destination address")
  1172. }
  1173. // Extract and return the key material to be used for the secure session
  1174. // and BrokerServer exchange between the broker and the Psiphon server
  1175. // corresponding to this server entry.
  1176. params := &serverParams{
  1177. serverID: serverID,
  1178. }
  1179. params.sessionPublicKey, err = SessionPublicKeyFromString(
  1180. serverEntry.InproxySessionPublicKey)
  1181. if err != nil {
  1182. return nil, errors.Trace(err)
  1183. }
  1184. params.sessionRootObfuscationSecret, err = ObfuscationSecretFromString(
  1185. serverEntry.InproxySessionRootObfuscationSecret)
  1186. if err != nil {
  1187. return nil, errors.Trace(err)
  1188. }
  1189. return params, nil
  1190. }
  1191. func (b *Broker) isCommonCompartmentIDHashingInitialized() bool {
  1192. b.commonCompartmentsMutex.Lock()
  1193. defer b.commonCompartmentsMutex.Unlock()
  1194. return b.commonCompartments != nil
  1195. }
  1196. func (b *Broker) initializeCommonCompartmentIDHashing(
  1197. commonCompartmentIDs []ID) error {
  1198. b.commonCompartmentsMutex.Lock()
  1199. defer b.commonCompartmentsMutex.Unlock()
  1200. // At least one common compartment ID is required. At a minimum, one ID
  1201. // will be used and distributed to clients via tactics, limiting matching
  1202. // to those clients targeted to receive that tactic parameters.
  1203. if len(commonCompartmentIDs) == 0 {
  1204. return errors.TraceNew("missing common compartment IDs")
  1205. }
  1206. // The consistent package doesn't allow duplicate members.
  1207. checkDup := make(map[ID]bool, len(commonCompartmentIDs))
  1208. for _, compartmentID := range commonCompartmentIDs {
  1209. if checkDup[compartmentID] {
  1210. return errors.TraceNew("duplicate common compartment IDs")
  1211. }
  1212. checkDup[compartmentID] = true
  1213. }
  1214. // Proxies without personal compartment IDs are randomly assigned to the
  1215. // set of common, Psiphon-specified, compartment IDs. These common
  1216. // compartment IDs are then distributed to targeted clients through
  1217. // tactics or embedded in OSLs, to limit access to proxies.
  1218. //
  1219. // Use consistent hashing in an effort to keep a consistent assignment of
  1220. // proxies (as specified by proxy ID, which covers all announcements for
  1221. // a single proxy). This is more of a concern for long-lived, permanent
  1222. // proxies that are not behind any NAT.
  1223. //
  1224. // Even with consistent hashing, a subset of proxies will still change
  1225. // assignment when CommonCompartmentIDs changes.
  1226. consistentMembers := make([]consistent.Member, len(commonCompartmentIDs))
  1227. for i, compartmentID := range commonCompartmentIDs {
  1228. consistentMembers[i] = consistentMember(compartmentID.String())
  1229. }
  1230. b.commonCompartments = consistent.New(
  1231. consistentMembers,
  1232. consistent.Config{
  1233. PartitionCount: len(consistentMembers),
  1234. ReplicationFactor: 1,
  1235. Load: 1,
  1236. Hasher: xxhasher{},
  1237. })
  1238. return nil
  1239. }
  1240. // xxhasher wraps github.com/cespare/xxhash.Sum64 in the interface expected by
  1241. // github.com/buraksezer/consistent. xxhash is a high quality hash function
  1242. // used in github.com/buraksezer/consistent examples.
  1243. type xxhasher struct{}
  1244. func (h xxhasher) Sum64(data []byte) uint64 {
  1245. return xxhash.Sum64(data)
  1246. }
  1247. // consistentMember wraps the string type with the interface expected by
  1248. // github.com/buraksezer/consistent.
  1249. type consistentMember string
  1250. func (m consistentMember) String() string {
  1251. return string(m)
  1252. }
  1253. func (b *Broker) selectCommonCompartmentID(proxyID ID) (ID, error) {
  1254. b.commonCompartmentsMutex.Lock()
  1255. defer b.commonCompartmentsMutex.Unlock()
  1256. compartmentID, err := IDFromString(
  1257. b.commonCompartments.LocateKey(proxyID[:]).String())
  1258. if err != nil {
  1259. return compartmentID, errors.Trace(err)
  1260. }
  1261. return compartmentID, nil
  1262. }