proxy.go 33 KB

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