broker.go 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651
  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 in-proxy protocol
  108. // version, GeoIPData, and APIParameters should be prioritized in the
  109. // matcher queue. Priority proxy announcements match ahead of other proxy
  110. // announcements, regardless of announcement age/deadline. Priority
  111. // status takes precedence over preferred NAT matching. Prioritization
  112. // applies only to common compartment IDs and not personal pairing mode.
  113. PrioritizeProxy func(int, 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 isPriority bool
  414. var newTacticsTag string
  415. var clientOffer *MatchOffer
  416. var matchMetrics *MatchMetrics
  417. var timedOut bool
  418. var limitedErr error
  419. // As a future enhancement, a broker could initiate its own test
  420. // connection to the proxy to verify its effectiveness, including
  421. // simulating a symmetric NAT client.
  422. // Each announcement represents availability for a single client matching.
  423. // Proxies with multiple client availability will send multiple requests.
  424. //
  425. // The announcement request and response could be extended to allow the
  426. // proxy to specify availability for multiple clients in the request, and
  427. // multiple client offers returned in the response.
  428. //
  429. // If, as we expect, proxies run on home ISPs have limited upstream
  430. // bandwidth, they will support only a couple of concurrent clients, and
  431. // the simple single-client-announcment model may be sufficient. Also, if
  432. // the transport is HTTP/2, multiple requests can be multiplexed over a
  433. // single connection (and session) in any case.
  434. // The proxy ID is an implicit parameter: it's the proxy's session public
  435. // key. As part of the session handshake, the proxy has proven that it
  436. // has the corresponding private key. Proxy IDs are logged to attribute
  437. // traffic to a specific proxy.
  438. proxyID := initiatorID
  439. // Generate a connection ID. This ID is used to associate proxy
  440. // announcments, client offers, and proxy answers, as well as associating
  441. // Psiphon tunnels with in-proxy pairings.
  442. connectionID, err := MakeID()
  443. if err != nil {
  444. return nil, errors.Trace(err)
  445. }
  446. // Always log the outcome.
  447. defer func() {
  448. if logFields == nil {
  449. logFields = b.config.APIParameterLogFieldFormatter("", geoIPData, nil)
  450. }
  451. logFields["broker_event"] = "proxy-announce"
  452. logFields["broker_id"] = b.brokerID
  453. logFields["proxy_id"] = proxyID
  454. logFields["is_priority"] = isPriority
  455. logFields["elapsed_time"] = time.Since(startTime) / time.Millisecond
  456. logFields["connection_id"] = connectionID
  457. if newTacticsTag != "" {
  458. logFields["new_tactics_tag"] = newTacticsTag
  459. }
  460. if clientOffer != nil {
  461. // Log the target Psiphon server ID (diagnostic ID). The presence
  462. // of this field indicates that a match was made.
  463. logFields["destination_server_id"] = clientOffer.DestinationServerID
  464. logFields["use_media_streams"] = clientOffer.UseMediaStreams
  465. }
  466. if timedOut {
  467. logFields["timed_out"] = true
  468. }
  469. if retErr != nil {
  470. logFields["error"] = retErr.Error()
  471. } else if limitedErr != nil {
  472. logFields["error"] = limitedErr.Error()
  473. }
  474. logFields.Add(transportLogFields)
  475. logFields.Add(matchMetrics.GetMetrics())
  476. b.config.Logger.LogMetric(brokerMetricName, logFields)
  477. }()
  478. announceRequest, err := UnmarshalProxyAnnounceRequest(requestPayload)
  479. if err != nil {
  480. return nil, errors.Trace(err)
  481. }
  482. var apiParams common.APIParameters
  483. apiParams, logFields, err = announceRequest.ValidateAndGetParametersAndLogFields(
  484. int(atomic.LoadInt64(&b.maxCompartmentIDs)),
  485. b.config.APIParameterValidator,
  486. b.config.APIParameterLogFieldFormatter,
  487. geoIPData)
  488. if err != nil {
  489. return nil, errors.Trace(err)
  490. }
  491. hasPersonalCompartmentIDs := len(announceRequest.PersonalCompartmentIDs) > 0
  492. // Return MustUpgrade when the proxy's protocol version is less than the
  493. // minimum required.
  494. if announceRequest.Metrics.ProtocolVersion < minimumProxyProtocolVersion {
  495. responsePayload, err := MarshalProxyAnnounceResponse(
  496. &ProxyAnnounceResponse{
  497. NoMatch: true,
  498. MustUpgrade: true,
  499. })
  500. if err != nil {
  501. return nil, errors.Trace(err)
  502. }
  503. return responsePayload, nil
  504. }
  505. // Fetch new tactics for the proxy, if required, using the tactics tag
  506. // that should be included with the API parameters. A tacticsPayload may
  507. // be returned when there are no new tactics, and this is relayed back to
  508. // the proxy, after matching, so that it can extend the TTL for its
  509. // existing, cached tactics. In the case where tactics have changed,
  510. // don't enqueue the proxy announcement and return no-match so that the
  511. // proxy can store and apply the new tactics before announcing again.
  512. var tacticsPayload []byte
  513. if announceRequest.CheckTactics {
  514. tacticsPayload, newTacticsTag, err =
  515. b.config.GetTacticsPayload(geoIPData, apiParams)
  516. if err != nil {
  517. return nil, errors.Trace(err)
  518. }
  519. if tacticsPayload != nil && newTacticsTag != "" {
  520. responsePayload, err := MarshalProxyAnnounceResponse(
  521. &ProxyAnnounceResponse{
  522. TacticsPayload: tacticsPayload,
  523. NoMatch: true,
  524. })
  525. if err != nil {
  526. return nil, errors.Trace(err)
  527. }
  528. return responsePayload, nil
  529. }
  530. }
  531. // AllowProxy may be used to disallow proxies from certain geolocations,
  532. // such as censored locations, from announcing. Proxies with personal
  533. // compartment IDs are always allowed, as they will be used only by
  534. // clients specifically configured to use them.
  535. if !hasPersonalCompartmentIDs &&
  536. !b.config.AllowProxy(geoIPData) {
  537. return nil, errors.TraceNew("proxy disallowed")
  538. }
  539. // Assign this proxy to a common compartment ID, unless it has specified a
  540. // dedicated, personal compartment ID. Assignment uses consistent hashing
  541. // keyed with the proxy ID, in an effort to keep proxies consistently
  542. // assigned to the same compartment.
  543. var commonCompartmentIDs []ID
  544. if !hasPersonalCompartmentIDs {
  545. compartmentID, err := b.selectCommonCompartmentID(proxyID)
  546. if err != nil {
  547. return nil, errors.Trace(err)
  548. }
  549. commonCompartmentIDs = []ID{compartmentID}
  550. }
  551. // In the common compartment ID case, invoke the callback to check if the
  552. // announcement should be prioritized.
  553. if b.config.PrioritizeProxy != nil && !hasPersonalCompartmentIDs {
  554. // Limitation: Of the two return values from
  555. // ValidateAndGetParametersAndLogFields, apiParams and logFields,
  556. // only logFields contains fields such as max_clients
  557. // and *_bytes_per_second, and so these cannot be part of any
  558. // filtering performed by the PrioritizeProxy callback.
  559. //
  560. // TODO: include the additional fields in logFields. Since the
  561. // logFields return value is the output of server.getRequestLogFields
  562. // processing, it's not safe to use it directly. In addition,
  563. // filtering by fields such as max_clients and *_bytes_per_second
  564. // calls for range filtering, which is not yet supported in the
  565. // psiphon/server.MeekServer PrioritizeProxy provider.
  566. isPriority = b.config.PrioritizeProxy(
  567. int(announceRequest.Metrics.ProtocolVersion), geoIPData, apiParams)
  568. }
  569. // Await client offer.
  570. timeout := common.ValueOrDefault(
  571. time.Duration(atomic.LoadInt64(&b.proxyAnnounceTimeout)),
  572. brokerProxyAnnounceTimeout)
  573. // Adjust the timeout to respect any shorter maximum request timeouts for
  574. // the fronting provider.
  575. timeout = b.adjustRequestTimeout(logFields, timeout)
  576. announceCtx, cancelFunc := context.WithTimeout(ctx, timeout)
  577. defer cancelFunc()
  578. extendTransportTimeout(timeout)
  579. // Note that matcher.Announce assumes a monotonically increasing
  580. // announceCtx.Deadline input for each successive call.
  581. clientOffer, matchMetrics, err = b.matcher.Announce(
  582. announceCtx,
  583. proxyIP,
  584. &MatchAnnouncement{
  585. Properties: MatchProperties{
  586. IsPriority: isPriority,
  587. ProtocolVersion: announceRequest.Metrics.ProtocolVersion,
  588. CommonCompartmentIDs: commonCompartmentIDs,
  589. PersonalCompartmentIDs: announceRequest.PersonalCompartmentIDs,
  590. GeoIPData: geoIPData,
  591. NetworkType: GetNetworkType(announceRequest.Metrics.BaseAPIParameters),
  592. NATType: announceRequest.Metrics.NATType,
  593. PortMappingTypes: announceRequest.Metrics.PortMappingTypes,
  594. },
  595. ProxyID: initiatorID,
  596. ProxyMetrics: announceRequest.Metrics,
  597. ConnectionID: connectionID,
  598. })
  599. if err != nil {
  600. var limitError *MatcherLimitError
  601. limited := std_errors.As(err, &limitError)
  602. timeout := announceCtx.Err() == context.DeadlineExceeded
  603. if !limited && !timeout {
  604. return nil, errors.Trace(err)
  605. }
  606. // A no-match response is sent in the case of a timeout awaiting a
  607. // match. The faster-failing rate or entry limiting case also results
  608. // in a response, rather than an error return from handleProxyAnnounce,
  609. // so that the proxy doesn't receive a 404 and flag its BrokerClient as
  610. // having failed.
  611. //
  612. // When the timeout and limit case coincide, limit takes precedence in
  613. // the response.
  614. if timeout && !limited {
  615. // Note: the respective proxy and broker timeouts,
  616. // InproxyBrokerProxyAnnounceTimeout and
  617. // InproxyProxyAnnounceRequestTimeout in tactics, should be
  618. // configured so that the broker will timeout first and have an
  619. // opportunity to send this response before the proxy times out.
  620. timedOut = true
  621. } else {
  622. // Record the specific limit error in the proxy-announce broker event.
  623. limitedErr = err
  624. }
  625. responsePayload, err := MarshalProxyAnnounceResponse(
  626. &ProxyAnnounceResponse{
  627. TacticsPayload: tacticsPayload,
  628. Limited: limited,
  629. NoMatch: timeout && !limited,
  630. })
  631. if err != nil {
  632. return nil, errors.Trace(err)
  633. }
  634. return responsePayload, nil
  635. }
  636. // Select the protocol version. The matcher has already checked
  637. // negotiateProtocolVersion, so failure is not expected.
  638. negotiatedProtocolVersion, ok := negotiateProtocolVersion(
  639. announceRequest.Metrics.ProtocolVersion,
  640. clientOffer.Properties.ProtocolVersion,
  641. clientOffer.UseMediaStreams)
  642. if !ok {
  643. return nil, errors.TraceNew("unexpected negotiateProtocolVersion failure")
  644. }
  645. // Respond with the client offer. The proxy will follow up with an answer
  646. // request, which is relayed to the client, and then the WebRTC dial begins.
  647. // Limitation: as part of the client's tunnel establishment horse race, a
  648. // client may abort an in-proxy dial at any point. If the overall dial is
  649. // past the SDP exchange and aborted during the WebRTC connection
  650. // establishment, the client may leave the proxy's Proxy.proxyOneClient
  651. // dangling until timeout. Consider adding a signal from the client to
  652. // the proxy, relayed by the broker, that a dial is aborted.
  653. responsePayload, err := MarshalProxyAnnounceResponse(
  654. &ProxyAnnounceResponse{
  655. TacticsPayload: tacticsPayload,
  656. ConnectionID: connectionID,
  657. SelectedProtocolVersion: negotiatedProtocolVersion,
  658. ClientOfferSDP: clientOffer.ClientOfferSDP,
  659. ClientRootObfuscationSecret: clientOffer.ClientRootObfuscationSecret,
  660. DoDTLSRandomization: clientOffer.DoDTLSRandomization,
  661. UseMediaStreams: clientOffer.UseMediaStreams,
  662. TrafficShapingParameters: clientOffer.TrafficShapingParameters,
  663. NetworkProtocol: clientOffer.NetworkProtocol,
  664. DestinationAddress: clientOffer.DestinationAddress,
  665. })
  666. if err != nil {
  667. return nil, errors.Trace(err)
  668. }
  669. return responsePayload, nil
  670. }
  671. // handleClientOffer receives a client offer, awaits a matching client, and
  672. // returns the proxy answer. handleClientOffer has a shorter timeout than
  673. // handleProxyAnnounce since the client has supplied an SDP with STUN hole
  674. // punches which will expire; and, in general, the client is trying to
  675. // connect immediately and is also trying other candidates.
  676. func (b *Broker) handleClientOffer(
  677. ctx context.Context,
  678. extendTransportTimeout ExtendTransportTimeout,
  679. transportLogFields common.LogFields,
  680. clientIP string,
  681. geoIPData common.GeoIPData,
  682. initiatorID ID,
  683. requestPayload []byte) (retResponse []byte, retErr error) {
  684. // As a future enhancement, consider having proxies send offer SDPs with
  685. // announcements and clients long poll to await a match and then provide
  686. // an answer. This order of operations would make sense if client demand
  687. // is high and proxy supply is lower.
  688. //
  689. // Also see comment in Proxy.proxyOneClient for other alternative
  690. // approaches.
  691. // The client's session public key is ephemeral and is not logged.
  692. startTime := time.Now()
  693. var logFields common.LogFields
  694. var serverParams *serverParams
  695. var clientMatchOffer *MatchOffer
  696. var proxyMatchAnnouncement *MatchAnnouncement
  697. var proxyAnswer *MatchAnswer
  698. var matchMetrics *MatchMetrics
  699. var timedOut bool
  700. var limitedErr error
  701. // Always log the outcome.
  702. defer func() {
  703. if logFields == nil {
  704. logFields = b.config.APIParameterLogFieldFormatter("", geoIPData, nil)
  705. }
  706. logFields["broker_event"] = "client-offer"
  707. logFields["broker_id"] = b.brokerID
  708. if serverParams != nil {
  709. logFields["destination_server_id"] = serverParams.serverID
  710. }
  711. logFields["elapsed_time"] = time.Since(startTime) / time.Millisecond
  712. if proxyAnswer != nil {
  713. // The presence of these fields indicate that a match was made,
  714. // the proxy delivered an answer, and the client was still
  715. // waiting for it.
  716. logFields["connection_id"] = proxyAnswer.ConnectionID
  717. logFields["client_nat_type"] = clientMatchOffer.Properties.NATType
  718. logFields["client_port_mapping_types"] = clientMatchOffer.Properties.PortMappingTypes
  719. logFields["proxy_nat_type"] = proxyMatchAnnouncement.Properties.NATType
  720. logFields["proxy_port_mapping_types"] = proxyMatchAnnouncement.Properties.PortMappingTypes
  721. logFields["preferred_nat_match"] =
  722. clientMatchOffer.Properties.IsPreferredNATMatch(&proxyMatchAnnouncement.Properties)
  723. // TODO: also log proxy ice_candidate_types and has_IPv6; for the
  724. // client, these values are added by ValidateAndGetLogFields.
  725. }
  726. if timedOut {
  727. logFields["timed_out"] = true
  728. }
  729. if retErr != nil {
  730. logFields["error"] = retErr.Error()
  731. } else if limitedErr != nil {
  732. logFields["error"] = limitedErr.Error()
  733. }
  734. logFields.Add(transportLogFields)
  735. logFields.Add(matchMetrics.GetMetrics())
  736. b.config.Logger.LogMetric(brokerMetricName, logFields)
  737. }()
  738. offerRequest, err := UnmarshalClientOfferRequest(requestPayload)
  739. if err != nil {
  740. return nil, errors.Trace(err)
  741. }
  742. // The filtered SDP is the request SDP with any invalid (bogon, unexpected
  743. // GeoIP) ICE candidates filtered out. In some cases, clients cannot
  744. // avoid submitting invalid candidates (see comment in
  745. // processSDPAddresses), so all invalid candidates are removed and the
  746. // remaining SDP is used. Filtered candidate information is logged in
  747. // logFields.
  748. //
  749. // In personal pairing mode, RFC 1918/4193 private IP addresses are
  750. // permitted in exchanged SDPs and not filtered out.
  751. var filteredSDP []byte
  752. filteredSDP, logFields, err = offerRequest.ValidateAndGetLogFields(
  753. int(atomic.LoadInt64(&b.maxCompartmentIDs)),
  754. b.config.LookupGeoIP,
  755. b.config.APIParameterValidator,
  756. b.config.APIParameterLogFieldFormatter,
  757. geoIPData)
  758. if err != nil {
  759. return nil, errors.Trace(err)
  760. }
  761. hasPersonalCompartmentIDs := len(offerRequest.PersonalCompartmentIDs) > 0
  762. offerSDP := offerRequest.ClientOfferSDP
  763. offerSDP.SDP = string(filteredSDP)
  764. // AllowClient may be used to disallow clients from certain geolocations
  765. // from offering. Clients are always allowed to match proxies with shared
  766. // personal compartment IDs.
  767. if !hasPersonalCompartmentIDs &&
  768. !b.config.AllowClient(geoIPData) {
  769. return nil, errors.TraceNew("client disallowed")
  770. }
  771. // Validate that the proxy destination specified by the client is a valid
  772. // dial address for a signed Psiphon server entry. This ensures a client
  773. // can't misuse a proxy to connect to arbitrary destinations.
  774. serverParams, err = b.validateDestination(
  775. geoIPData,
  776. offerRequest.PackedDestinationServerEntry,
  777. offerRequest.NetworkProtocol,
  778. offerRequest.DestinationAddress)
  779. if err != nil {
  780. return nil, errors.Trace(err)
  781. }
  782. // Return MustUpgrade when the client's protocol version is less than the
  783. // minimum required.
  784. if offerRequest.Metrics.ProtocolVersion < minimumClientProtocolVersion {
  785. responsePayload, err := MarshalClientOfferResponse(
  786. &ClientOfferResponse{
  787. NoMatch: true,
  788. MustUpgrade: true,
  789. })
  790. if err != nil {
  791. return nil, errors.Trace(err)
  792. }
  793. return responsePayload, nil
  794. }
  795. // Enqueue the client offer and await a proxy matching and subsequent
  796. // proxy answer.
  797. // The Client Offer timeout may be configured with a shorter value in
  798. // personal pairing mode, to facilitate a faster no-match result and
  799. // resulting broker rotation.
  800. var timeout time.Duration
  801. if hasPersonalCompartmentIDs {
  802. timeout = time.Duration(atomic.LoadInt64(&b.clientOfferPersonalTimeout))
  803. } else {
  804. timeout = time.Duration(atomic.LoadInt64(&b.clientOfferTimeout))
  805. }
  806. timeout = common.ValueOrDefault(timeout, brokerClientOfferTimeout)
  807. // Adjust the timeout to respect any shorter maximum request timeouts for
  808. // the fronting provider.
  809. timeout = b.adjustRequestTimeout(logFields, timeout)
  810. offerCtx, cancelFunc := context.WithTimeout(ctx, timeout)
  811. defer cancelFunc()
  812. extendTransportTimeout(timeout)
  813. clientMatchOffer = &MatchOffer{
  814. Properties: MatchProperties{
  815. ProtocolVersion: offerRequest.Metrics.ProtocolVersion,
  816. CommonCompartmentIDs: offerRequest.CommonCompartmentIDs,
  817. PersonalCompartmentIDs: offerRequest.PersonalCompartmentIDs,
  818. GeoIPData: geoIPData,
  819. NetworkType: GetNetworkType(offerRequest.Metrics.BaseAPIParameters),
  820. NATType: offerRequest.Metrics.NATType,
  821. PortMappingTypes: offerRequest.Metrics.PortMappingTypes,
  822. },
  823. ClientOfferSDP: offerSDP,
  824. ClientRootObfuscationSecret: offerRequest.ClientRootObfuscationSecret,
  825. DoDTLSRandomization: offerRequest.DoDTLSRandomization,
  826. UseMediaStreams: offerRequest.UseMediaStreams,
  827. TrafficShapingParameters: offerRequest.TrafficShapingParameters,
  828. NetworkProtocol: offerRequest.NetworkProtocol,
  829. DestinationAddress: offerRequest.DestinationAddress,
  830. DestinationServerID: serverParams.serverID,
  831. }
  832. proxyAnswer, proxyMatchAnnouncement, matchMetrics, err = b.matcher.Offer(
  833. offerCtx,
  834. clientIP,
  835. clientMatchOffer)
  836. if err != nil {
  837. var limitError *MatcherLimitError
  838. limited := std_errors.As(err, &limitError)
  839. timeout := offerCtx.Err() == context.DeadlineExceeded
  840. if !limited && !timeout {
  841. return nil, errors.Trace(err)
  842. }
  843. // A no-match response is sent in the case of a timeout awaiting a
  844. // match. The faster-failing rate or entry limiting case also results
  845. // in a response, rather than an error return from handleClientOffer,
  846. // so that the client doesn't receive a 404 and flag its BrokerClient
  847. // as having failed.
  848. //
  849. // When the timeout and limit case coincide, limit takes precedence in
  850. // the response.
  851. if timeout && !limited {
  852. // Note: the respective client and broker timeouts,
  853. // InproxyBrokerClientOfferTimeout and
  854. // InproxyClientOfferRequestTimeout in tactics, should be configured
  855. // so that the broker will timeout first and have an opportunity to
  856. // send this response before the client times out.
  857. timedOut = true
  858. } else {
  859. // Record the specific limit error in the client-offer broker event.
  860. limitedErr = err
  861. }
  862. responsePayload, err := MarshalClientOfferResponse(
  863. &ClientOfferResponse{
  864. Limited: limited,
  865. NoMatch: timeout && !limited,
  866. })
  867. if err != nil {
  868. return nil, errors.Trace(err)
  869. }
  870. return responsePayload, nil
  871. }
  872. // Log the type of compartment matching that occurred. As
  873. // PersonalCompartmentIDs are user-generated and shared, actual matching
  874. // values are not logged as they may link users.
  875. // TODO: log matching common compartment IDs?
  876. matchedCommonCompartments := HaveCommonIDs(
  877. proxyMatchAnnouncement.Properties.CommonCompartmentIDs,
  878. clientMatchOffer.Properties.CommonCompartmentIDs)
  879. matchedPersonalCompartments := HaveCommonIDs(
  880. proxyMatchAnnouncement.Properties.PersonalCompartmentIDs,
  881. clientMatchOffer.Properties.PersonalCompartmentIDs)
  882. // Initiate a BrokerServerReport, which sends important information
  883. // about the connection, including the original client IP, plus other
  884. // values to be logged with server_tunne, to the server. The report is
  885. // sent through a secure session established between the broker and the
  886. // server, relayed by the client.
  887. //
  888. // The first relay message will be embedded in the Psiphon handshake. The
  889. // broker may already have an established session with the server. In
  890. // this case, only only that initial message is required. The
  891. // BrokerServerReport is a one-way message, which avoids extra untunneled
  892. // client/broker traffic.
  893. //
  894. // Limitations, due to the one-way message:
  895. // - the broker can't actively clean up pendingServerReports as
  896. // tunnels are established and must rely on cache expiry.
  897. // - the broker doesn't learn that the server accepted the report, and
  898. // so cannot log a final connection status or signal the proxy to
  899. // disconnect the client in any misuse cases.
  900. //
  901. // As a future enhancement, consider adding a _tunneled_ client relay
  902. // of a server response acknowledging the broker report.
  903. relayPacket, err := b.initiateRelayedServerReport(
  904. serverParams,
  905. proxyAnswer.ConnectionID,
  906. &BrokerServerReport{
  907. ProxyID: proxyAnswer.ProxyID,
  908. ConnectionID: proxyAnswer.ConnectionID,
  909. MatchedCommonCompartments: matchedCommonCompartments,
  910. MatchedPersonalCompartments: matchedPersonalCompartments,
  911. ClientNATType: clientMatchOffer.Properties.NATType,
  912. ClientPortMappingTypes: clientMatchOffer.Properties.PortMappingTypes,
  913. ClientIP: clientIP,
  914. ProxyIP: proxyAnswer.ProxyIP,
  915. ProxyMetrics: proxyMatchAnnouncement.ProxyMetrics,
  916. // ProxyMetrics includes proxy NAT and port mapping types.
  917. })
  918. if err != nil {
  919. return nil, errors.Trace(err)
  920. }
  921. // Select the protocol version. The matcher has already checked
  922. // negotiateProtocolVersion, so failure is not expected.
  923. negotiatedProtocolVersion, ok := negotiateProtocolVersion(
  924. proxyMatchAnnouncement.Properties.ProtocolVersion,
  925. offerRequest.Metrics.ProtocolVersion,
  926. offerRequest.UseMediaStreams)
  927. if !ok {
  928. return nil, errors.TraceNew("unexpected negotiateProtocolVersion failure")
  929. }
  930. // Respond with the proxy answer and initial broker/server session packet.
  931. responsePayload, err := MarshalClientOfferResponse(
  932. &ClientOfferResponse{
  933. ConnectionID: proxyAnswer.ConnectionID,
  934. SelectedProtocolVersion: negotiatedProtocolVersion,
  935. ProxyAnswerSDP: proxyAnswer.ProxyAnswerSDP,
  936. RelayPacketToServer: relayPacket,
  937. })
  938. if err != nil {
  939. return nil, errors.Trace(err)
  940. }
  941. return responsePayload, nil
  942. }
  943. // handleProxyAnswer receives a proxy answer and delivers it to the waiting
  944. // client.
  945. func (b *Broker) handleProxyAnswer(
  946. ctx context.Context,
  947. extendTransportTimeout ExtendTransportTimeout,
  948. transportLogFields common.LogFields,
  949. proxyIP string,
  950. geoIPData common.GeoIPData,
  951. initiatorID ID,
  952. requestPayload []byte) (retResponse []byte, retErr error) {
  953. startTime := time.Now()
  954. var logFields common.LogFields
  955. var proxyAnswer *MatchAnswer
  956. var answerError string
  957. // The proxy ID is an implicit parameter: it's the proxy's session public
  958. // key.
  959. proxyID := initiatorID
  960. // Always log the outcome.
  961. defer func() {
  962. if logFields == nil {
  963. logFields = b.config.APIParameterLogFieldFormatter("", geoIPData, nil)
  964. }
  965. logFields["broker_event"] = "proxy-answer"
  966. logFields["broker_id"] = b.brokerID
  967. logFields["proxy_id"] = proxyID
  968. logFields["elapsed_time"] = time.Since(startTime) / time.Millisecond
  969. if proxyAnswer != nil {
  970. logFields["connection_id"] = proxyAnswer.ConnectionID
  971. }
  972. if answerError != "" {
  973. // This is a proxy-reported error that occurred while creating the answer.
  974. logFields["answer_error"] = answerError
  975. }
  976. if retErr != nil {
  977. logFields["error"] = retErr.Error()
  978. }
  979. logFields.Add(transportLogFields)
  980. b.config.Logger.LogMetric(brokerMetricName, logFields)
  981. }()
  982. answerRequest, err := UnmarshalProxyAnswerRequest(requestPayload)
  983. if err != nil {
  984. return nil, errors.Trace(err)
  985. }
  986. // The filtered SDP is the request SDP with any invalid (bogon, unexpected
  987. // GeoIP) ICE candidates filtered out. In some cases, proxies cannot
  988. // avoid submitting invalid candidates (see comment in
  989. // processSDPAddresses), so all invalid candidates are removed and the
  990. // remaining SDP is used. Filtered candidate information is logged in
  991. // logFields.
  992. //
  993. // In personal pairing mode, RFC 1918/4193 private IP addresses are
  994. // permitted in exchanged SDPs and not filtered out.
  995. hasPersonalCompartmentIDs, err := b.matcher.AnnouncementHasPersonalCompartmentIDs(
  996. initiatorID, answerRequest.ConnectionID)
  997. if err != nil {
  998. return nil, errors.Trace(err)
  999. }
  1000. var filteredSDP []byte
  1001. filteredSDP, logFields, err = answerRequest.ValidateAndGetLogFields(
  1002. b.config.LookupGeoIP,
  1003. b.config.APIParameterValidator,
  1004. b.config.APIParameterLogFieldFormatter,
  1005. geoIPData,
  1006. hasPersonalCompartmentIDs)
  1007. if err != nil {
  1008. return nil, errors.Trace(err)
  1009. }
  1010. answerSDP := answerRequest.ProxyAnswerSDP
  1011. answerSDP.SDP = string(filteredSDP)
  1012. if answerRequest.AnswerError != "" {
  1013. // The proxy failed to create an answer.
  1014. answerError = answerRequest.AnswerError
  1015. b.matcher.AnswerError(initiatorID, answerRequest.ConnectionID)
  1016. } else {
  1017. // Deliver the answer to the client.
  1018. // Note that neither ProxyID nor ProxyIP is returned to the client.
  1019. // These fields are used internally in the matcher.
  1020. proxyAnswer = &MatchAnswer{
  1021. ProxyIP: proxyIP,
  1022. ProxyID: initiatorID,
  1023. ConnectionID: answerRequest.ConnectionID,
  1024. ProxyAnswerSDP: answerSDP,
  1025. }
  1026. err = b.matcher.Answer(proxyAnswer)
  1027. if err != nil {
  1028. return nil, errors.Trace(err)
  1029. }
  1030. }
  1031. // There is no data in this response, it's simply an acknowledgement that
  1032. // the answer was received. Upon receiving the response, the proxy should
  1033. // begin the WebRTC dial operation.
  1034. responsePayload, err := MarshalProxyAnswerResponse(
  1035. &ProxyAnswerResponse{})
  1036. if err != nil {
  1037. return nil, errors.Trace(err)
  1038. }
  1039. return responsePayload, nil
  1040. }
  1041. // handleClientRelayedPacket facilitates broker/server sessions. The initial
  1042. // packet from the broker is sent to the client in the ClientOfferResponse.
  1043. // The client sends that to the server in the Psiphon handshake. If the
  1044. // session was already established, the relay ends there. Otherwise, the
  1045. // client receives any packet sent back by the server and that server packet
  1046. // is then delivered to the broker in a ClientRelayedPacketRequest. If the
  1047. // session needs to be [re-]negotiated, there are additional
  1048. // ClientRelayedPacket round trips until the session is established and the
  1049. // BrokerServerReport is securely exchanged between the broker and server.
  1050. func (b *Broker) handleClientRelayedPacket(
  1051. ctx context.Context,
  1052. extendTransportTimeout ExtendTransportTimeout,
  1053. transportLogFields common.LogFields,
  1054. geoIPData common.GeoIPData,
  1055. initiatorID ID,
  1056. requestPayload []byte) (retResponse []byte, retErr error) {
  1057. startTime := time.Now()
  1058. var logFields common.LogFields
  1059. var relayedPacketRequest *ClientRelayedPacketRequest
  1060. var serverID string
  1061. // Always log the outcome.
  1062. defer func() {
  1063. if logFields == nil {
  1064. logFields = b.config.APIParameterLogFieldFormatter("", geoIPData, nil)
  1065. }
  1066. logFields["broker_event"] = "client-relayed-packet"
  1067. logFields["broker_id"] = b.brokerID
  1068. logFields["elapsed_time"] = time.Since(startTime) / time.Millisecond
  1069. if relayedPacketRequest != nil {
  1070. logFields["connection_id"] = relayedPacketRequest.ConnectionID
  1071. }
  1072. if serverID != "" {
  1073. logFields["destination_server_id"] = serverID
  1074. }
  1075. if retErr != nil {
  1076. logFields["error"] = retErr.Error()
  1077. }
  1078. logFields.Add(transportLogFields)
  1079. b.config.Logger.LogMetric(brokerMetricName, logFields)
  1080. }()
  1081. relayedPacketRequest, err := UnmarshalClientRelayedPacketRequest(requestPayload)
  1082. if err != nil {
  1083. return nil, errors.Trace(err)
  1084. }
  1085. logFields, err = relayedPacketRequest.ValidateAndGetLogFields(
  1086. b.config.APIParameterValidator,
  1087. b.config.APIParameterLogFieldFormatter,
  1088. geoIPData)
  1089. if err != nil {
  1090. return nil, errors.Trace(err)
  1091. }
  1092. // The relay state is associated with the connection ID.
  1093. strConnectionID := string(relayedPacketRequest.ConnectionID[:])
  1094. entry, ok := b.pendingServerReports.Get(strConnectionID)
  1095. if !ok {
  1096. // The relay state is not found; it may have been evicted from the
  1097. // cache. The client will receive a generic error in this case and
  1098. // should stop relaying. Assuming the server is configured to require
  1099. // a BrokerServerReport, the tunnel will be terminated, so the
  1100. // client should also abandon the dial.
  1101. return nil, errors.TraceNew("no pending report")
  1102. }
  1103. pendingServerReport := entry.(*pendingServerReport)
  1104. serverID = pendingServerReport.serverID
  1105. // When the broker tried to use an existing session that was expired on the
  1106. // server, the server will respond here with a signed session reset token. The
  1107. // broker resets the session and starts to establish a new session.
  1108. //
  1109. // The non-waiting session establishment mode is used for broker/server
  1110. // sessions: if multiple clients concurrently try to relay new sessions,
  1111. // all establishments will happen in parallel without forcing any clients
  1112. // to wait for one client to lead the establishment. The last established
  1113. // session will be retained for reuse.
  1114. //
  1115. // If there is an error, the relayed packet is invalid. Drop the packet
  1116. // and return an error to be logged. Do _not_ reset the session,
  1117. // otherwise a malicious client could interrupt a valid broker/server
  1118. // session with a malformed packet.
  1119. // Next is given a nil ctx since we're not waiting for any other client to
  1120. // establish the session.
  1121. out, _, err := pendingServerReport.roundTrip.Next(
  1122. nil, relayedPacketRequest.PacketFromServer)
  1123. if err != nil {
  1124. return nil, errors.Trace(err)
  1125. }
  1126. if out == nil {
  1127. // The BrokerServerReport is a one-way message, As a result, the relay
  1128. // never ends with broker receiving a response; it's either
  1129. // (re)handshaking or sending the one-way report.
  1130. return nil, errors.TraceNew("unexpected nil packet")
  1131. }
  1132. // Return the next broker packet for the client to relay to the server.
  1133. // When it receives a nil PacketToServer, the client will stop relaying.
  1134. responsePayload, err := MarshalClientRelayedPacketResponse(
  1135. &ClientRelayedPacketResponse{
  1136. PacketToServer: out,
  1137. })
  1138. if err != nil {
  1139. return nil, errors.Trace(err)
  1140. }
  1141. return responsePayload, nil
  1142. }
  1143. func (b *Broker) adjustRequestTimeout(
  1144. logFields common.LogFields, timeout time.Duration) time.Duration {
  1145. // Adjust long-polling request timeouts to respect any maximum request
  1146. // timeout supported by the provider fronting the request.
  1147. //
  1148. // Limitation: the client is trusted to provide the correct fronting
  1149. // provider ID.
  1150. maxRequestTimeouts, ok := b.maxRequestTimeouts.Load().(map[string]time.Duration)
  1151. if !ok || maxRequestTimeouts == nil {
  1152. return timeout
  1153. }
  1154. frontingProviderID, ok := logFields["fronting_provider_id"].(string)
  1155. if !ok {
  1156. return timeout
  1157. }
  1158. maxRequestTimeout, ok := maxRequestTimeouts[frontingProviderID]
  1159. if !ok || maxRequestTimeout <= 0 || timeout <= maxRequestTimeout {
  1160. return timeout
  1161. }
  1162. return maxRequestTimeout
  1163. }
  1164. type pendingServerReport struct {
  1165. serverID string
  1166. serverReport *BrokerServerReport
  1167. roundTrip *InitiatorRoundTrip
  1168. }
  1169. func (b *Broker) initiateRelayedServerReport(
  1170. serverParams *serverParams,
  1171. connectionID ID,
  1172. serverReport *BrokerServerReport) ([]byte, error) {
  1173. reportPayload, err := MarshalBrokerServerReport(serverReport)
  1174. if err != nil {
  1175. return nil, errors.Trace(err)
  1176. }
  1177. // Force a new, concurrent session establishment with the server even if
  1178. // another handshake is already in progess, relayed by some other client.
  1179. // This ensures clients don't block waiting for other client relays
  1180. // through other tunnels. The last established session will be retained
  1181. // for reuse.
  1182. waitToShareSession := false
  1183. roundTrip, err := b.initiatorSessions.NewRoundTrip(
  1184. serverParams.sessionPublicKey,
  1185. serverParams.sessionRootObfuscationSecret,
  1186. waitToShareSession,
  1187. reportPayload)
  1188. if err != nil {
  1189. return nil, errors.Trace(err)
  1190. }
  1191. relayPacket, _, err := roundTrip.Next(nil, nil)
  1192. if err != nil {
  1193. return nil, errors.Trace(err)
  1194. }
  1195. strConnectionID := string(connectionID[:])
  1196. b.pendingServerReports.Set(
  1197. strConnectionID,
  1198. &pendingServerReport{
  1199. serverID: serverParams.serverID,
  1200. serverReport: serverReport,
  1201. roundTrip: roundTrip,
  1202. },
  1203. time.Duration(atomic.LoadInt64(&b.pendingServerReportsTTL)))
  1204. return relayPacket, nil
  1205. }
  1206. type serverParams struct {
  1207. serverID string
  1208. sessionPublicKey SessionPublicKey
  1209. sessionRootObfuscationSecret ObfuscationSecret
  1210. }
  1211. // validateDestination checks that the client's specified proxy dial
  1212. // destination is valid destination address for a tunnel protocol in the
  1213. // specified signed and valid Psiphon server entry.
  1214. func (b *Broker) validateDestination(
  1215. geoIPData common.GeoIPData,
  1216. packedDestinationServerEntry []byte,
  1217. networkProtocol NetworkProtocol,
  1218. destinationAddress string) (*serverParams, error) {
  1219. var packedServerEntry protocol.PackedServerEntryFields
  1220. err := cbor.Unmarshal(packedDestinationServerEntry, &packedServerEntry)
  1221. if err != nil {
  1222. return nil, errors.Trace(err)
  1223. }
  1224. serverEntryFields, err := protocol.DecodePackedServerEntryFields(packedServerEntry)
  1225. if err != nil {
  1226. return nil, errors.Trace(err)
  1227. }
  1228. // Strip any unsigned fields, which could be forged by the client. In
  1229. // particular, this includes the server entry tag, which, in some cases,
  1230. // is locally populated by a client for its own reference.
  1231. serverEntryFields.RemoveUnsignedFields()
  1232. // Check that the server entry is signed by Psiphon. Otherwise a client
  1233. // could manufacture a server entry corresponding to an arbitrary dial
  1234. // destination.
  1235. err = serverEntryFields.VerifySignature(
  1236. b.config.ServerEntrySignaturePublicKey)
  1237. if err != nil {
  1238. return nil, errors.Trace(err)
  1239. }
  1240. // The server entry tag must be set and signed by Psiphon, as local,
  1241. // client derived tags are unsigned and untrusted.
  1242. serverEntryTag := serverEntryFields.GetTag()
  1243. if serverEntryTag == "" {
  1244. return nil, errors.TraceNew("missing server entry tag")
  1245. }
  1246. // Check that the server entry tag is on a list of active and valid
  1247. // Psiphon server entry tags. This ensures that an obsolete entry for a
  1248. // pruned server cannot by misused by a client to proxy to what's no
  1249. // longer a Psiphon server.
  1250. if !b.config.IsValidServerEntryTag(serverEntryTag) {
  1251. return nil, errors.TraceNew("invalid server entry tag")
  1252. }
  1253. serverID := serverEntryFields.GetDiagnosticID()
  1254. serverEntry, err := serverEntryFields.GetServerEntry()
  1255. if err != nil {
  1256. return nil, errors.Trace(err)
  1257. }
  1258. // Validate the dial host (IP or domain) and port matches a tunnel
  1259. // protocol offered by the server entry.
  1260. destHost, destPort, err := net.SplitHostPort(destinationAddress)
  1261. if err != nil {
  1262. return nil, errors.Trace(err)
  1263. }
  1264. destPortNum, err := strconv.Atoi(destPort)
  1265. if err != nil {
  1266. return nil, errors.Trace(err)
  1267. }
  1268. // For domain fronted cases, since we can't verify the Host header, access
  1269. // is strictly to limited to targeted clients. Clients should use tactics
  1270. // to avoid disallowed domain dial address cases, but here the broker
  1271. // enforces it.
  1272. //
  1273. // TODO: this issue could be further mitigated with a server
  1274. // acknowledgement of the broker's report, with no acknowledgement
  1275. // followed by signaling the proxy to terminate client connection.
  1276. // This assumes that any domain dial is for domain fronting.
  1277. isDomain := net.ParseIP(destHost) == nil
  1278. if isDomain && !b.config.AllowDomainFrontedDestinations(geoIPData) {
  1279. return nil, errors.TraceNew("domain fronted destinations disallowed")
  1280. }
  1281. // The server entry must include an in-proxy tunnel protocol capability
  1282. // and corresponding dial port number. In-proxy capacity may be set for
  1283. // only a subset of all Psiphon servers, to limited the number of servers
  1284. // a proxy can observe and enumerate. Well-behaved clients will not send
  1285. // any server entries lacking this capability, but here the broker
  1286. // enforces it.
  1287. if !serverEntry.IsValidInproxyDialAddress(networkProtocol.String(), destHost, destPortNum) {
  1288. return nil, errors.TraceNew("invalid destination address")
  1289. }
  1290. // Extract and return the key material to be used for the secure session
  1291. // and BrokerServer exchange between the broker and the Psiphon server
  1292. // corresponding to this server entry.
  1293. params := &serverParams{
  1294. serverID: serverID,
  1295. }
  1296. params.sessionPublicKey, err = SessionPublicKeyFromString(
  1297. serverEntry.InproxySessionPublicKey)
  1298. if err != nil {
  1299. return nil, errors.Trace(err)
  1300. }
  1301. params.sessionRootObfuscationSecret, err = ObfuscationSecretFromString(
  1302. serverEntry.InproxySessionRootObfuscationSecret)
  1303. if err != nil {
  1304. return nil, errors.Trace(err)
  1305. }
  1306. return params, nil
  1307. }
  1308. func (b *Broker) isCommonCompartmentIDHashingInitialized() bool {
  1309. b.commonCompartmentsMutex.Lock()
  1310. defer b.commonCompartmentsMutex.Unlock()
  1311. return b.commonCompartments != nil
  1312. }
  1313. func (b *Broker) initializeCommonCompartmentIDHashing(
  1314. commonCompartmentIDs []ID) error {
  1315. b.commonCompartmentsMutex.Lock()
  1316. defer b.commonCompartmentsMutex.Unlock()
  1317. // At least one common compartment ID is required. At a minimum, one ID
  1318. // will be used and distributed to clients via tactics, limiting matching
  1319. // to those clients targeted to receive that tactic parameters.
  1320. if len(commonCompartmentIDs) == 0 {
  1321. return errors.TraceNew("missing common compartment IDs")
  1322. }
  1323. // The consistent package doesn't allow duplicate members.
  1324. checkDup := make(map[ID]bool, len(commonCompartmentIDs))
  1325. for _, compartmentID := range commonCompartmentIDs {
  1326. if checkDup[compartmentID] {
  1327. return errors.TraceNew("duplicate common compartment IDs")
  1328. }
  1329. checkDup[compartmentID] = true
  1330. }
  1331. // Proxies without personal compartment IDs are randomly assigned to the
  1332. // set of common, Psiphon-specified, compartment IDs. These common
  1333. // compartment IDs are then distributed to targeted clients through
  1334. // tactics or embedded in OSLs, to limit access to proxies.
  1335. //
  1336. // Use consistent hashing in an effort to keep a consistent assignment of
  1337. // proxies (as specified by proxy ID, which covers all announcements for
  1338. // a single proxy). This is more of a concern for long-lived, permanent
  1339. // proxies that are not behind any NAT.
  1340. //
  1341. // Even with consistent hashing, a subset of proxies will still change
  1342. // assignment when CommonCompartmentIDs changes.
  1343. consistentMembers := make([]consistent.Member, len(commonCompartmentIDs))
  1344. for i, compartmentID := range commonCompartmentIDs {
  1345. consistentMembers[i] = consistentMember(compartmentID.String())
  1346. }
  1347. b.commonCompartments = consistent.New(
  1348. consistentMembers,
  1349. consistent.Config{
  1350. PartitionCount: len(consistentMembers),
  1351. ReplicationFactor: 1,
  1352. Load: 1,
  1353. Hasher: xxhasher{},
  1354. })
  1355. return nil
  1356. }
  1357. // xxhasher wraps github.com/cespare/xxhash.Sum64 in the interface expected by
  1358. // github.com/buraksezer/consistent. xxhash is a high quality hash function
  1359. // used in github.com/buraksezer/consistent examples.
  1360. type xxhasher struct{}
  1361. func (h xxhasher) Sum64(data []byte) uint64 {
  1362. return xxhash.Sum64(data)
  1363. }
  1364. // consistentMember wraps the string type with the interface expected by
  1365. // github.com/buraksezer/consistent.
  1366. type consistentMember string
  1367. func (m consistentMember) String() string {
  1368. return string(m)
  1369. }
  1370. func (b *Broker) selectCommonCompartmentID(proxyID ID) (ID, error) {
  1371. b.commonCompartmentsMutex.Lock()
  1372. defer b.commonCompartmentsMutex.Unlock()
  1373. compartmentID, err := IDFromString(
  1374. b.commonCompartments.LocateKey(proxyID[:]).String())
  1375. if err != nil {
  1376. return compartmentID, errors.Trace(err)
  1377. }
  1378. return compartmentID, nil
  1379. }