broker.go 55 KB

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