broker.go 47 KB

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