proxy.go 34 KB

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