proxy.go 37 KB

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