proxy.go 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  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. "io"
  23. "sync"
  24. "sync/atomic"
  25. "time"
  26. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  30. )
  31. const (
  32. proxyAnnounceDelay = 1 * time.Second
  33. proxyAnnounceDelayJitter = 0.5
  34. proxyAnnounceMaxBackoffDelay = 1 * time.Hour
  35. proxyAnnounceLogSampleSize = 2
  36. proxyAnnounceLogSamplePeriod = 30 * time.Minute
  37. proxyWebRTCAnswerTimeout = 20 * time.Second
  38. proxyDestinationDialTimeout = 20 * time.Second
  39. proxyRelayInactivityTimeout = 5 * time.Minute
  40. )
  41. // Proxy is the in-proxy proxying component, which relays traffic from a
  42. // client to a Psiphon server.
  43. type Proxy struct {
  44. // Note: 64-bit ints used with atomic operations are placed
  45. // at the start of struct to ensure 64-bit alignment.
  46. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  47. bytesUp int64
  48. bytesDown int64
  49. peakBytesUp int64
  50. peakBytesDown int64
  51. connectingClients int32
  52. connectedClients int32
  53. config *ProxyConfig
  54. activityUpdateWrapper *activityUpdateWrapper
  55. lastConnectingClients int32
  56. lastConnectedClients int32
  57. networkDiscoveryMutex sync.Mutex
  58. networkDiscoveryRunOnce bool
  59. networkDiscoveryNetworkID string
  60. nextAnnounceMutex sync.Mutex
  61. nextAnnounceBrokerClient *BrokerClient
  62. nextAnnounceNotBefore time.Time
  63. }
  64. // TODO: add PublicNetworkAddress/ListenNetworkAddress to facilitate manually
  65. // configured, permanent port mappings.
  66. // ProxyConfig specifies the configuration for a Proxy run.
  67. type ProxyConfig struct {
  68. // Logger is used to log events.
  69. Logger common.Logger
  70. // EnableWebRTCDebugLogging indicates whether to emit WebRTC debug logs.
  71. EnableWebRTCDebugLogging bool
  72. // WaitForNetworkConnectivity is a callback that should block until there
  73. // is network connectivity or shutdown. The return value is true when
  74. // there is network connectivity, and false for shutdown.
  75. WaitForNetworkConnectivity func() bool
  76. // GetBrokerClient provides a BrokerClient which the proxy will use for
  77. // making broker requests. If GetBrokerClient returns a shared
  78. // BrokerClient instance, the BrokerClient must support multiple,
  79. // concurrent round trips, as the proxy will use it to concurrently
  80. // announce many proxy instances. The BrokerClient should be implemented
  81. // using multiplexing over a shared network connection -- for example,
  82. // HTTP/2 -- and a shared broker session for optimal performance.
  83. GetBrokerClient func() (*BrokerClient, error)
  84. // GetBaseAPIParameters returns Psiphon API parameters to be sent to and
  85. // logged by the broker. Expected parameters include client/proxy
  86. // application and build version information. GetBaseAPIParameters also
  87. // returns the network ID, corresponding to the parameters, to be used in
  88. // tactics logic; the network ID is not sent to the broker.
  89. GetBaseAPIParameters func() (common.APIParameters, string, error)
  90. // MakeWebRTCDialCoordinator provides a WebRTCDialCoordinator which
  91. // specifies WebRTC-related dial parameters, including selected STUN
  92. // server addresses; network topology information for the current netork;
  93. // NAT logic settings; and other settings.
  94. //
  95. // MakeWebRTCDialCoordinator is invoked for each proxy/client connection,
  96. // and the provider can select new parameters per connection as reqired.
  97. MakeWebRTCDialCoordinator func() (WebRTCDialCoordinator, error)
  98. // HandleTacticsPayload is a callback that receives any tactics payload,
  99. // provided by the broker in proxy announcement request responses.
  100. // HandleTacticsPayload must return true when the tacticsPayload includes
  101. // new tactics, indicating that the proxy should reinitialize components
  102. // controlled by tactics parameters.
  103. HandleTacticsPayload func(networkID string, tacticsPayload []byte) bool
  104. // MustUpgrade is a callback that is invoked when a MustUpgrade flag is
  105. // received from the broker. When MustUpgrade is received, the proxy
  106. // should be stopped and the user should be prompted to upgrade before
  107. // restarting the proxy.
  108. MustUpgrade func()
  109. // MaxClients is the maximum number of clients that are allowed to connect
  110. // to the proxy. Must be > 0.
  111. MaxClients int
  112. // LimitUpstreamBytesPerSecond limits the upstream data transfer rate for
  113. // a single client. When 0, there is no limit.
  114. LimitUpstreamBytesPerSecond int
  115. // LimitDownstreamBytesPerSecond limits the downstream data transfer rate
  116. // for a single client. When 0, there is no limit.
  117. LimitDownstreamBytesPerSecond int
  118. // ActivityUpdater specifies an ActivityUpdater for activity associated
  119. // with this proxy.
  120. ActivityUpdater ActivityUpdater
  121. }
  122. // ActivityUpdater is a callback that is invoked when clients connect and
  123. // disconnect and periodically with data transfer updates (unless idle). This
  124. // callback may be used to update an activity UI. This callback should post
  125. // this data to another thread or handler and return immediately and not
  126. // block on UI updates.
  127. type ActivityUpdater func(
  128. connectingClients int32,
  129. connectedClients int32,
  130. bytesUp int64,
  131. bytesDown int64,
  132. bytesDuration time.Duration)
  133. // NewProxy initializes a new Proxy with the specified configuration.
  134. func NewProxy(config *ProxyConfig) (*Proxy, error) {
  135. if config.MaxClients <= 0 {
  136. return nil, errors.TraceNew("invalid MaxClients")
  137. }
  138. p := &Proxy{
  139. config: config,
  140. }
  141. p.activityUpdateWrapper = &activityUpdateWrapper{p: p}
  142. return p, nil
  143. }
  144. // activityUpdateWrapper implements the psiphon/common.ActivityUpdater
  145. // interface and is used to receive bytes transferred updates from the
  146. // ActivityConns wrapping proxied traffic. A wrapper is used so that
  147. // UpdateProgress is not exported from Proxy.
  148. type activityUpdateWrapper struct {
  149. p *Proxy
  150. }
  151. func (w *activityUpdateWrapper) UpdateProgress(bytesRead, bytesWritten int64, _ int64) {
  152. atomic.AddInt64(&w.p.bytesUp, bytesWritten)
  153. atomic.AddInt64(&w.p.bytesDown, bytesRead)
  154. }
  155. // Run runs the proxy. The proxy sends requests to the Broker announcing its
  156. // availability; the Broker matches the proxy with clients, and facilitates
  157. // an exchange of WebRTC connection information; the proxy and each client
  158. // attempt to establish a connection; and the client's traffic is relayed to
  159. // Psiphon server.
  160. //
  161. // Run ends when ctx is Done. A proxy run may continue across underlying
  162. // network changes assuming that the ProxyConfig GetBrokerClient and
  163. // MakeWebRTCDialCoordinator callbacks react to network changes and provide
  164. // instances that are reflect network changes.
  165. func (p *Proxy) Run(ctx context.Context) {
  166. // Run MaxClient proxying workers. Each worker handles one client at a time.
  167. proxyWaitGroup := new(sync.WaitGroup)
  168. // Launch the first proxy worker, passing a signal to be triggered once
  169. // the very first announcement round trip is complete. The first round
  170. // trip is awaited so that:
  171. //
  172. // - The first announce response will arrive with any new tactics,
  173. // which may be applied before launching additions workers.
  174. //
  175. // - The first worker gets no announcement delay and is also guaranteed to
  176. // be the shared session establisher. Since the announcement delays are
  177. // applied _after_ waitToShareSession, it would otherwise be possible,
  178. // with a race of MaxClient initial, concurrent announces, for the
  179. // session establisher to be a different worker than the no-delay worker.
  180. //
  181. // The first worker is the only proxy worker which sets
  182. // ProxyAnnounceRequest.CheckTactics.
  183. signalFirstAnnounceCtx, signalFirstAnnounceDone :=
  184. context.WithCancel(context.Background())
  185. proxyWaitGroup.Add(1)
  186. go func() {
  187. defer proxyWaitGroup.Done()
  188. p.proxyClients(ctx, signalFirstAnnounceDone)
  189. }()
  190. select {
  191. case <-signalFirstAnnounceCtx.Done():
  192. case <-ctx.Done():
  193. return
  194. }
  195. // Launch the remaining workers.
  196. for i := 0; i < p.config.MaxClients-1; i++ {
  197. proxyWaitGroup.Add(1)
  198. go func() {
  199. defer proxyWaitGroup.Done()
  200. p.proxyClients(ctx, nil)
  201. }()
  202. }
  203. // Capture activity updates every second, which is the required frequency
  204. // for PeakUp/DownstreamBytesPerSecond. This is also a reasonable
  205. // frequency for invoking the ActivityUpdater and updating UI widgets.
  206. p.lastConnectingClients = 0
  207. p.lastConnectedClients = 0
  208. activityUpdatePeriod := 1 * time.Second
  209. ticker := time.NewTicker(activityUpdatePeriod)
  210. defer ticker.Stop()
  211. loop:
  212. for {
  213. select {
  214. case <-ticker.C:
  215. p.activityUpdate(activityUpdatePeriod)
  216. case <-ctx.Done():
  217. break loop
  218. }
  219. }
  220. proxyWaitGroup.Wait()
  221. }
  222. // getAnnounceDelayParameters is a helper that fetches the proxy announcement
  223. // delay parameters from the current broker client.
  224. //
  225. // getAnnounceDelayParameters is used to configure a delay when
  226. // proxyOneClient fails. As having no broker clients is a possible
  227. // proxyOneClient failure case, GetBrokerClient errors are ignored here and
  228. // defaults used in that case.
  229. func (p *Proxy) getAnnounceDelayParameters() (time.Duration, float64) {
  230. brokerClient, err := p.config.GetBrokerClient()
  231. if err != nil {
  232. return proxyAnnounceDelay, proxyAnnounceDelayJitter
  233. }
  234. brokerCoordinator := brokerClient.GetBrokerDialCoordinator()
  235. return common.ValueOrDefault(brokerCoordinator.AnnounceDelay(), proxyAnnounceDelay),
  236. common.ValueOrDefault(brokerCoordinator.AnnounceDelayJitter(), proxyAnnounceDelayJitter)
  237. }
  238. func (p *Proxy) activityUpdate(period time.Duration) {
  239. connectingClients := atomic.LoadInt32(&p.connectingClients)
  240. connectedClients := atomic.LoadInt32(&p.connectedClients)
  241. bytesUp := atomic.SwapInt64(&p.bytesUp, 0)
  242. bytesDown := atomic.SwapInt64(&p.bytesDown, 0)
  243. greaterThanSwapInt64(&p.peakBytesUp, bytesUp)
  244. greaterThanSwapInt64(&p.peakBytesDown, bytesDown)
  245. clientsChanged := connectingClients != p.lastConnectingClients ||
  246. connectedClients != p.lastConnectedClients
  247. p.lastConnectingClients = connectingClients
  248. p.lastConnectedClients = connectedClients
  249. if !clientsChanged &&
  250. bytesUp == 0 &&
  251. bytesDown == 0 {
  252. // Skip the activity callback on idle bytes or no change in client counts.
  253. return
  254. }
  255. p.config.ActivityUpdater(
  256. connectingClients,
  257. connectedClients,
  258. bytesUp,
  259. bytesDown,
  260. period)
  261. }
  262. func greaterThanSwapInt64(addr *int64, new int64) bool {
  263. // Limitation: if there are two concurrent calls, the greater value could
  264. // get overwritten.
  265. old := atomic.LoadInt64(addr)
  266. if new > old {
  267. return atomic.CompareAndSwapInt64(addr, old, new)
  268. }
  269. return false
  270. }
  271. func (p *Proxy) proxyClients(
  272. ctx context.Context, signalAnnounceDone func()) {
  273. // Proxy one client, repeating until ctx is done.
  274. //
  275. // This worker starts with posting a long-polling announcement request.
  276. // The broker response with a matched client, and the proxy and client
  277. // attempt to establish a WebRTC connection for relaying traffic.
  278. //
  279. // Limitation: this design may not maximize the utility of the proxy,
  280. // since some proxy/client connections will fail at the WebRTC stage due
  281. // to NAT traversal failure, and at most MaxClient concurrent
  282. // establishments are attempted. Another scenario comes from the Psiphon
  283. // client horse race, which may start in-proxy dials but then abort them
  284. // when some other tunnel protocol succeeds.
  285. //
  286. // As a future enhancement, consider using M announcement goroutines and N
  287. // WebRTC dial goroutines. When an announcement gets a response,
  288. // immediately announce again unless there are already MaxClient active
  289. // connections established. This approach may require the proxy to
  290. // backpedal and reject connections when establishment is too successful.
  291. //
  292. // Another enhancement could be a signal from the client, to the broker,
  293. // relayed to the proxy, when a dial is aborted.
  294. failureDelayFactor := time.Duration(1)
  295. // To reduce diagnostic log noise, only log an initial sample of
  296. // announcement request timings (delays/elapsed time) and a periodic
  297. // sample of repeating errors such as "no match".
  298. logAnnounceCount := proxyAnnounceLogSampleSize
  299. logErrorsCount := proxyAnnounceLogSampleSize
  300. lastErrMsg := ""
  301. startLogSampleTime := time.Now()
  302. logAnnounce := func() bool {
  303. if logAnnounceCount > 0 {
  304. logAnnounceCount -= 1
  305. return true
  306. }
  307. return false
  308. }
  309. for ctx.Err() == nil {
  310. if !p.config.WaitForNetworkConnectivity() {
  311. break
  312. }
  313. if time.Since(startLogSampleTime) >= proxyAnnounceLogSamplePeriod {
  314. logAnnounceCount = proxyAnnounceLogSampleSize
  315. logErrorsCount = proxyAnnounceLogSampleSize
  316. lastErrMsg = ""
  317. startLogSampleTime = time.Now()
  318. }
  319. backOff, err := p.proxyOneClient(
  320. ctx, logAnnounce, signalAnnounceDone)
  321. if err != nil && ctx.Err() == nil {
  322. // Limitation: the lastErrMsg string comparison isn't compatible
  323. // with errors with minor variations, such as "unexpected
  324. // response status code %d after %v" from
  325. // InproxyBrokerRoundTripper.RoundTrip, with a time duration in
  326. // the second parameter.
  327. errMsg := err.Error()
  328. if lastErrMsg != errMsg {
  329. logErrorsCount = proxyAnnounceLogSampleSize
  330. lastErrMsg = errMsg
  331. }
  332. if logErrorsCount > 0 {
  333. p.config.Logger.WithTraceFields(
  334. common.LogFields{
  335. "error": errMsg,
  336. }).Error("proxy client failed")
  337. logErrorsCount -= 1
  338. }
  339. // Apply a simple exponential backoff based on whether
  340. // proxyOneClient either relayed client traffic or got no match,
  341. // or encountered a failure.
  342. //
  343. // The proxyOneClient failure could range from local
  344. // configuration (no broker clients) to network issues(failure to
  345. // completely establish WebRTC connection) and this backoff
  346. // prevents both excess local logging and churning in the former
  347. // case and excessive bad service to clients or unintentionally
  348. // overloading the broker in the latter case.
  349. //
  350. // TODO: specific tactics parameters to control this logic.
  351. delay, jitter := p.getAnnounceDelayParameters()
  352. if !backOff {
  353. failureDelayFactor = 1
  354. }
  355. delay = delay * failureDelayFactor
  356. if delay > proxyAnnounceMaxBackoffDelay {
  357. delay = proxyAnnounceMaxBackoffDelay
  358. }
  359. if failureDelayFactor < 1<<20 {
  360. failureDelayFactor *= 2
  361. }
  362. common.SleepWithJitter(ctx, delay, jitter)
  363. }
  364. }
  365. }
  366. // resetNetworkDiscovery resets the network discovery state, which will force
  367. // another network discovery when doNetworkDiscovery is invoked.
  368. // resetNetworkDiscovery is called when new tactics have been received from
  369. // the broker, as new tactics may change parameters that control network
  370. // discovery.
  371. func (p *Proxy) resetNetworkDiscovery() {
  372. p.networkDiscoveryMutex.Lock()
  373. defer p.networkDiscoveryMutex.Unlock()
  374. p.networkDiscoveryRunOnce = false
  375. p.networkDiscoveryNetworkID = ""
  376. }
  377. func (p *Proxy) doNetworkDiscovery(
  378. ctx context.Context,
  379. webRTCCoordinator WebRTCDialCoordinator) {
  380. // Allow only one concurrent network discovery. In practise, this may
  381. // block all other proxyOneClient goroutines while one single goroutine
  382. // runs doNetworkDiscovery. Subsequently, all other goroutines will find
  383. // networkDiscoveryRunOnce is true and use the cached results.
  384. p.networkDiscoveryMutex.Lock()
  385. defer p.networkDiscoveryMutex.Unlock()
  386. networkID := webRTCCoordinator.NetworkID()
  387. if p.networkDiscoveryRunOnce &&
  388. p.networkDiscoveryNetworkID == networkID {
  389. // Already ran discovery for this network.
  390. //
  391. // TODO: periodically re-probe for port mapping services?
  392. return
  393. }
  394. // Reset and configure port mapper component, as required. See
  395. // initPortMapper comment.
  396. initPortMapper(webRTCCoordinator)
  397. // Gather local network NAT/port mapping metrics and configuration before
  398. // sending any announce requests. NAT topology metrics are used by the
  399. // Broker to optimize client and in-proxy matching. Unlike the client, we
  400. // always perform this synchronous step here, since waiting doesn't
  401. // necessarily block a client tunnel dial.
  402. waitGroup := new(sync.WaitGroup)
  403. waitGroup.Add(1)
  404. go func() {
  405. defer waitGroup.Done()
  406. // NATDiscover may use cached NAT type/port mapping values from
  407. // DialParameters, based on the network ID. If discovery is not
  408. // successful, the proxy still proceeds to announce.
  409. NATDiscover(
  410. ctx,
  411. &NATDiscoverConfig{
  412. Logger: p.config.Logger,
  413. WebRTCDialCoordinator: webRTCCoordinator,
  414. })
  415. }()
  416. waitGroup.Wait()
  417. p.networkDiscoveryRunOnce = true
  418. p.networkDiscoveryNetworkID = networkID
  419. }
  420. func (p *Proxy) proxyOneClient(
  421. ctx context.Context,
  422. logAnnounce func() bool,
  423. signalAnnounceDone func()) (bool, error) {
  424. // Do not trigger back-off unless the proxy successfully announces and
  425. // only then performs poorly.
  426. //
  427. // A no-match response should not trigger back-off, nor should broker
  428. // request transport errors which may include non-200 responses due to
  429. // CDN timeout mismatches or TLS errors due to CDN TLS fingerprint
  430. // incompatibility.
  431. backOff := false
  432. // Get a new WebRTCDialCoordinator, which should be configured with the
  433. // latest network tactics.
  434. webRTCCoordinator, err := p.config.MakeWebRTCDialCoordinator()
  435. if err != nil {
  436. return backOff, errors.Trace(err)
  437. }
  438. // Perform network discovery, to determine NAT type and other network
  439. // topology information that is reported to the broker in the proxy
  440. // announcement and used to optimize proxy/client matching. Unlike
  441. // clients, which can't easily delay dials in the tunnel establishment
  442. // horse race, proxies will always perform network discovery.
  443. // doNetworkDiscovery allows only one concurrent discovery and caches
  444. // results for the current network (as determined by
  445. // WebRTCCoordinator.GetNetworkID), so when multiple proxyOneClient
  446. // goroutines call doNetworkDiscovery, at most one discovery is performed
  447. // per network.
  448. p.doNetworkDiscovery(ctx, webRTCCoordinator)
  449. // Send the announce request
  450. // At this point, no NAT traversal operations have been performed by the
  451. // proxy, since its announcement may sit idle for the long-polling period
  452. // and NAT hole punches or port mappings could expire before the
  453. // long-polling period.
  454. //
  455. // As a future enhancement, the proxy could begin gathering WebRTC ICE
  456. // candidates while awaiting a client match, reducing the turn around
  457. // time after a match. This would make sense if there's high demand for
  458. // proxies, and so hole punches unlikely to expire while awaiting a client match.
  459. //
  460. // Another possibility may be to prepare and send a full offer SDP in the
  461. // announcment; and have the broker modify either the proxy or client
  462. // offer SDP to produce an answer SDP. In this case, the entire
  463. // ProxyAnswerRequest could be skipped as the WebRTC dial can begin after
  464. // the ProxyAnnounceRequest response (and ClientOfferRequest response).
  465. //
  466. // Furthermore, if a port mapping can be established, instead of using
  467. // WebRTC the proxy could run a Psiphon tunnel protocol listener at the
  468. // mapped port and send the dial information -- including some secret to
  469. // authenticate the client -- in its announcement. The client would then
  470. // receive this direct dial information from the broker and connect. The
  471. // proxy should be able to send keep alives to extend the port mapping
  472. // lifetime.
  473. brokerClient, err := p.config.GetBrokerClient()
  474. if err != nil {
  475. return backOff, errors.Trace(err)
  476. }
  477. brokerCoordinator := brokerClient.GetBrokerDialCoordinator()
  478. // Get the base Psiphon API parameters and additional proxy metrics,
  479. // including performance information, which is sent to the broker in the
  480. // proxy announcment.
  481. //
  482. // tacticsNetworkID is the exact network ID that corresponds to the
  483. // tactics tag sent in the base parameters; this is passed to
  484. // HandleTacticsPayload in order to double check that any tactics
  485. // returned in the proxy announcment response are associated and stored
  486. // with the original network ID.
  487. metrics, tacticsNetworkID, err := p.getMetrics(
  488. brokerCoordinator, webRTCCoordinator)
  489. if err != nil {
  490. return backOff, errors.Trace(err)
  491. }
  492. // Set a delay before announcing, to stagger the announce request times.
  493. // The delay helps to avoid triggering rate limits or similar errors from
  494. // any intermediate CDN between the proxy and the broker; and provides a
  495. // nudge towards better load balancing across multiple large MaxClients
  496. // proxies, as the broker primarily matches enqueued announces in FIFO
  497. // order, since older announces expire earlier.
  498. //
  499. // The delay is intended to be applied after doNetworkDiscovery, which has
  500. // no reason to be delayed; and also after any waitToShareSession delay,
  501. // as delaying before waitToShareSession can result in the announce
  502. // request times collapsing back together. Delaying after
  503. // waitToShareSession is handled by brokerClient.ProxyAnnounce, which
  504. // will also extend the base request timeout, as required, to account for
  505. // any deliberate delay.
  506. requestDelay := time.Duration(0)
  507. announceDelay, announceDelayJitter := p.getAnnounceDelayParameters()
  508. p.nextAnnounceMutex.Lock()
  509. nextDelay := prng.JitterDuration(announceDelay, announceDelayJitter)
  510. if p.nextAnnounceBrokerClient != brokerClient {
  511. // Reset the delay when the broker client changes.
  512. p.nextAnnounceNotBefore = time.Time{}
  513. p.nextAnnounceBrokerClient = brokerClient
  514. }
  515. if p.nextAnnounceNotBefore.IsZero() {
  516. p.nextAnnounceNotBefore = time.Now().Add(nextDelay)
  517. // No delay for the very first announce request, so leave
  518. // announceRequestDelay set to 0.
  519. } else {
  520. requestDelay = time.Until(p.nextAnnounceNotBefore)
  521. if requestDelay < 0 {
  522. // This announce did not arrive until after the next delay already
  523. // passed, so proceed with no delay.
  524. p.nextAnnounceNotBefore = time.Now().Add(nextDelay)
  525. requestDelay = 0
  526. } else {
  527. p.nextAnnounceNotBefore = p.nextAnnounceNotBefore.Add(nextDelay)
  528. }
  529. }
  530. p.nextAnnounceMutex.Unlock()
  531. // Only the first worker, which has signalAnnounceDone configured, checks
  532. // for tactics.
  533. checkTactics := signalAnnounceDone != nil
  534. // A proxy ID is implicitly sent with requests; it's the proxy's session
  535. // public key.
  536. //
  537. // ProxyAnnounce applies an additional request timeout to facilitate
  538. // long-polling.
  539. announceStartTime := time.Now()
  540. personalCompartmentIDs := brokerCoordinator.PersonalCompartmentIDs()
  541. announceResponse, err := brokerClient.ProxyAnnounce(
  542. ctx,
  543. requestDelay,
  544. &ProxyAnnounceRequest{
  545. PersonalCompartmentIDs: personalCompartmentIDs,
  546. Metrics: metrics,
  547. CheckTactics: checkTactics,
  548. })
  549. if logAnnounce() {
  550. p.config.Logger.WithTraceFields(common.LogFields{
  551. "delay": requestDelay.String(),
  552. "elapsedTime": time.Since(announceStartTime).String(),
  553. }).Info("announcement request")
  554. }
  555. if err != nil {
  556. return backOff, errors.Trace(err)
  557. }
  558. if len(announceResponse.TacticsPayload) > 0 {
  559. // The TacticsPayload may include new tactics, or may simply signal,
  560. // to the Psiphon client, that its tactics tag remains up-to-date and
  561. // to extend cached tactics TTL. HandleTacticsPayload returns true
  562. // when tactics haved changed; in this case we clear cached network
  563. // discovery but proceed with handling the proxy announcement
  564. // response as there may still be a match.
  565. if p.config.HandleTacticsPayload(
  566. tacticsNetworkID, announceResponse.TacticsPayload) {
  567. p.resetNetworkDiscovery()
  568. }
  569. }
  570. // Signal that the announce round trip is complete. At this point, the
  571. // broker Noise session should be established and any fresh tactics
  572. // applied.
  573. if signalAnnounceDone != nil {
  574. signalAnnounceDone()
  575. }
  576. // MustUpgrade has precedence over other cases, to ensure the callback is
  577. // invoked. Trigger back-off back off when rate/entry limited or must
  578. // upgrade; no back-off for no-match.
  579. if announceResponse.MustUpgrade {
  580. if p.config.MustUpgrade != nil {
  581. p.config.MustUpgrade()
  582. }
  583. backOff = true
  584. return backOff, errors.TraceNew("must upgrade")
  585. } else if announceResponse.Limited {
  586. backOff = true
  587. return backOff, errors.TraceNew("limited")
  588. } else if announceResponse.NoMatch {
  589. return backOff, errors.TraceNew("no match")
  590. }
  591. if announceResponse.ClientProxyProtocolVersion != ProxyProtocolVersion1 {
  592. // This case is currently unexpected, as all clients and proxies use
  593. // ProxyProtocolVersion1.
  594. backOff = true
  595. return backOff, errors.Tracef(
  596. "Unsupported proxy protocol version: %d",
  597. announceResponse.ClientProxyProtocolVersion)
  598. }
  599. // Trigger back-off if the following WebRTC operations fail to establish a
  600. // connections.
  601. //
  602. // Limitation: the proxy answer request to the broker may fail due to the
  603. // non-back-off reasons documented above for the proxy announcment request;
  604. // however, these should be unlikely assuming that the broker client is
  605. // using a persistent transport connection.
  606. backOff = true
  607. // For activity updates, indicate that a client connection is now underway.
  608. atomic.AddInt32(&p.connectingClients, 1)
  609. connected := false
  610. defer func() {
  611. if !connected {
  612. atomic.AddInt32(&p.connectingClients, -1)
  613. }
  614. }()
  615. // Initialize WebRTC using the client's offer SDP
  616. webRTCAnswerCtx, webRTCAnswerCancelFunc := context.WithTimeout(
  617. ctx, common.ValueOrDefault(webRTCCoordinator.WebRTCAnswerTimeout(), proxyWebRTCAnswerTimeout))
  618. defer webRTCAnswerCancelFunc()
  619. // In personal pairing mode, RFC 1918/4193 private IP addresses are
  620. // included in SDPs.
  621. hasPersonalCompartmentIDs := len(personalCompartmentIDs) > 0
  622. webRTCConn, SDP, sdpMetrics, webRTCErr := newWebRTCConnForAnswer(
  623. webRTCAnswerCtx,
  624. &webRTCConfig{
  625. Logger: p.config.Logger,
  626. EnableDebugLogging: p.config.EnableWebRTCDebugLogging,
  627. WebRTCDialCoordinator: webRTCCoordinator,
  628. ClientRootObfuscationSecret: announceResponse.ClientRootObfuscationSecret,
  629. DoDTLSRandomization: announceResponse.DoDTLSRandomization,
  630. TrafficShapingParameters: announceResponse.TrafficShapingParameters,
  631. },
  632. announceResponse.ClientOfferSDP,
  633. hasPersonalCompartmentIDs)
  634. var webRTCRequestErr string
  635. if webRTCErr != nil {
  636. webRTCErr = errors.Trace(webRTCErr)
  637. webRTCRequestErr = webRTCErr.Error()
  638. SDP = WebRTCSessionDescription{}
  639. sdpMetrics = &webRTCSDPMetrics{}
  640. // Continue to report the error to the broker. The broker will respond
  641. // with failure to the client's offer request.
  642. } else {
  643. defer webRTCConn.Close()
  644. }
  645. // Send answer request with SDP or error.
  646. _, err = brokerClient.ProxyAnswer(
  647. ctx,
  648. &ProxyAnswerRequest{
  649. ConnectionID: announceResponse.ConnectionID,
  650. SelectedProxyProtocolVersion: announceResponse.ClientProxyProtocolVersion,
  651. ProxyAnswerSDP: SDP,
  652. ICECandidateTypes: sdpMetrics.iceCandidateTypes,
  653. AnswerError: webRTCRequestErr,
  654. })
  655. if err != nil {
  656. if webRTCErr != nil {
  657. // Prioritize returning any WebRTC error for logging.
  658. return backOff, webRTCErr
  659. }
  660. return backOff, errors.Trace(err)
  661. }
  662. // Now that an answer is sent, stop if WebRTC initialization failed.
  663. if webRTCErr != nil {
  664. return backOff, webRTCErr
  665. }
  666. // Await the WebRTC connection.
  667. // We could concurrently dial the destination, to have that network
  668. // connection available immediately once the WebRTC channel is
  669. // established. This would work only for TCP, not UDP, network protocols
  670. // and could only include the TCP connection, as client traffic is
  671. // required for all higher layers such as TLS, SSH, etc. This could also
  672. // create wasted load on destination Psiphon servers, particularly when
  673. // WebRTC connections fail.
  674. awaitDataChannelCtx, awaitDataChannelCancelFunc := context.WithTimeout(
  675. ctx,
  676. common.ValueOrDefault(
  677. webRTCCoordinator.WebRTCAwaitDataChannelTimeout(), dataChannelAwaitTimeout))
  678. defer awaitDataChannelCancelFunc()
  679. err = webRTCConn.AwaitInitialDataChannel(awaitDataChannelCtx)
  680. if err != nil {
  681. return backOff, errors.Trace(err)
  682. }
  683. p.config.Logger.WithTraceFields(common.LogFields{
  684. "connectionID": announceResponse.ConnectionID,
  685. }).Info("WebRTC data channel established")
  686. // Dial the destination, a Psiphon server. The broker validates that the
  687. // dial destination is a Psiphon server.
  688. destinationDialContext, destinationDialCancelFunc := context.WithTimeout(
  689. ctx,
  690. common.ValueOrDefault(
  691. webRTCCoordinator.ProxyDestinationDialTimeout(), proxyDestinationDialTimeout))
  692. defer destinationDialCancelFunc()
  693. // Use the custom resolver when resolving destination hostnames, such as
  694. // those used in domain fronted protocols.
  695. //
  696. // - Resolving at the in-proxy should yield a more optimal CDN edge, vs.
  697. // resolving at the client.
  698. //
  699. // - Sending unresolved hostnames to in-proxies can expose some domain
  700. // fronting configuration. This can be mitigated by enabling domain
  701. // fronting on this 2nd hop only when the in-proxy is located in a
  702. // region that may be censored or blocked; this is to be enforced by
  703. // the broker.
  704. //
  705. // - Any DNSResolverPreresolved tactics applied will be relative to the
  706. // in-proxy location.
  707. destinationAddress, err := webRTCCoordinator.ResolveAddress(
  708. ctx, "ip", announceResponse.DestinationAddress)
  709. if err != nil {
  710. return backOff, errors.Trace(err)
  711. }
  712. destinationConn, err := webRTCCoordinator.ProxyUpstreamDial(
  713. destinationDialContext,
  714. announceResponse.NetworkProtocol.String(),
  715. destinationAddress)
  716. if err != nil {
  717. return backOff, errors.Trace(err)
  718. }
  719. defer destinationConn.Close()
  720. // For activity updates, indicate that a client connection is established.
  721. connected = true
  722. atomic.AddInt32(&p.connectingClients, -1)
  723. atomic.AddInt32(&p.connectedClients, 1)
  724. defer func() {
  725. atomic.AddInt32(&p.connectedClients, -1)
  726. }()
  727. // Throttle the relay connection.
  728. //
  729. // Here, each client gets LimitUp/DownstreamBytesPerSecond. Proxy
  730. // operators may to want to limit their bandwidth usage with a single
  731. // up/down value, an overall limit. The ProxyConfig can simply be
  732. // generated by dividing the limit by MaxClients. This approach favors
  733. // performance stability: each client gets the same throttling limits
  734. // regardless of how many other clients are connected.
  735. destinationConn = common.NewThrottledConn(
  736. destinationConn,
  737. announceResponse.NetworkProtocol.IsStream(),
  738. common.RateLimits{
  739. ReadBytesPerSecond: int64(p.config.LimitUpstreamBytesPerSecond),
  740. WriteBytesPerSecond: int64(p.config.LimitDownstreamBytesPerSecond),
  741. })
  742. // Hook up bytes transferred counting for activity updates.
  743. // The ActivityMonitoredConn inactivity timeout is configured. For
  744. // upstream TCP connections, the destinationConn will close when the TCP
  745. // connection to the Psiphon server closes. But for upstream UDP flows,
  746. // the relay does not know when the upstream "connection" has closed.
  747. // Well-behaved clients will close the WebRTC half of the relay when
  748. // those clients know the UDP-based tunnel protocol connection is closed;
  749. // the inactivity timeout handles the remaining cases.
  750. inactivityTimeout :=
  751. common.ValueOrDefault(
  752. webRTCCoordinator.ProxyRelayInactivityTimeout(),
  753. proxyRelayInactivityTimeout)
  754. destinationConn, err = common.NewActivityMonitoredConn(
  755. destinationConn, inactivityTimeout, false, nil, p.activityUpdateWrapper)
  756. if err != nil {
  757. return backOff, errors.Trace(err)
  758. }
  759. // Relay the client traffic to the destination. The client traffic is a
  760. // standard Psiphon tunnel protocol destinated to a Psiphon server. Any
  761. // blocking/censorship at the 2nd hop will be mitigated by the use of
  762. // Psiphon circumvention protocols and techniques.
  763. // Limitation: clients may apply fragmentation to traffic relayed over the
  764. // data channel, and there's no guarantee that the fragmentation write
  765. // sizes or delays will carry over to the egress side.
  766. // The proxy operator's ISP may be able to observe that the operator's
  767. // host has nearly matching ingress and egress traffic. The traffic
  768. // content won't be the same: the ingress traffic is wrapped in a WebRTC
  769. // data channel, and the egress traffic is a Psiphon tunnel protocol.
  770. // With padding and decoy packets, the ingress and egress traffic shape
  771. // will differ beyond the basic WebRTC overheader. Even with this
  772. // measure, over time the number of bytes in and out of the proxy may
  773. // still indicate proxying.
  774. waitGroup := new(sync.WaitGroup)
  775. relayErrors := make(chan error, 2)
  776. var relayedUp, relayedDown int32
  777. waitGroup.Add(1)
  778. go func() {
  779. defer waitGroup.Done()
  780. // WebRTC data channels are based on SCTP, which is actually
  781. // message-based, not a stream. The (default) max message size for
  782. // pion/sctp is 65536:
  783. // https://github.com/pion/sctp/blob/44ed465396c880e379aae9c1bf81809a9e06b580/association.go#L52.
  784. //
  785. // As io.Copy uses a buffer size of 32K, each relayed message will be
  786. // less than the maximum. Calls to ClientConn.Write are also expected
  787. // to use io.Copy, keeping messages at most 32K in size.
  788. // io.Copy doesn't return an error on EOF, but we still want to signal
  789. // that relaying is done, so in this case a nil error is sent to the
  790. // channel.
  791. //
  792. // Limitation: if one io.Copy goproutine sends nil and the other
  793. // io.Copy goroutine sends a non-nil error concurrently, the non-nil
  794. // error isn't prioritized.
  795. n, err := io.Copy(webRTCConn, destinationConn)
  796. if n > 0 {
  797. atomic.StoreInt32(&relayedDown, 1)
  798. }
  799. relayErrors <- errors.Trace(err)
  800. }()
  801. waitGroup.Add(1)
  802. go func() {
  803. defer waitGroup.Done()
  804. n, err := io.Copy(destinationConn, webRTCConn)
  805. if n > 0 {
  806. atomic.StoreInt32(&relayedUp, 1)
  807. }
  808. relayErrors <- errors.Trace(err)
  809. }()
  810. select {
  811. case err = <-relayErrors:
  812. case <-ctx.Done():
  813. }
  814. // Interrupt the relay goroutines by closing the connections.
  815. webRTCConn.Close()
  816. destinationConn.Close()
  817. waitGroup.Wait()
  818. p.config.Logger.WithTraceFields(common.LogFields{
  819. "connectionID": announceResponse.ConnectionID,
  820. }).Info("connection closed")
  821. // Don't apply a back-off delay to the next announcement since this
  822. // iteration successfully relayed bytes.
  823. if atomic.LoadInt32(&relayedUp) == 1 || atomic.LoadInt32(&relayedDown) == 1 {
  824. backOff = false
  825. }
  826. return backOff, err
  827. }
  828. func (p *Proxy) getMetrics(
  829. brokerCoordinator BrokerDialCoordinator,
  830. webRTCCoordinator WebRTCDialCoordinator) (*ProxyMetrics, string, error) {
  831. // tacticsNetworkID records the exact network ID that corresponds to the
  832. // tactics tag sent in the base parameters, and is used when applying any
  833. // new tactics returned by the broker.
  834. baseParams, tacticsNetworkID, err := p.config.GetBaseAPIParameters()
  835. if err != nil {
  836. return nil, "", errors.Trace(err)
  837. }
  838. apiParams := common.APIParameters{}
  839. apiParams.Add(baseParams)
  840. apiParams.Add(common.APIParameters(brokerCoordinator.MetricsForBrokerRequests()))
  841. packedParams, err := protocol.EncodePackedAPIParameters(apiParams)
  842. if err != nil {
  843. return nil, "", errors.Trace(err)
  844. }
  845. return &ProxyMetrics{
  846. BaseAPIParameters: packedParams,
  847. ProxyProtocolVersion: proxyProtocolVersion,
  848. NATType: webRTCCoordinator.NATType(),
  849. PortMappingTypes: webRTCCoordinator.PortMappingTypes(),
  850. MaxClients: int32(p.config.MaxClients),
  851. ConnectingClients: atomic.LoadInt32(&p.connectingClients),
  852. ConnectedClients: atomic.LoadInt32(&p.connectedClients),
  853. LimitUpstreamBytesPerSecond: int64(p.config.LimitUpstreamBytesPerSecond),
  854. LimitDownstreamBytesPerSecond: int64(p.config.LimitDownstreamBytesPerSecond),
  855. PeakUpstreamBytesPerSecond: atomic.LoadInt64(&p.peakBytesUp),
  856. PeakDownstreamBytesPerSecond: atomic.LoadInt64(&p.peakBytesDown),
  857. }, tacticsNetworkID, nil
  858. }