proxy.go 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  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. bytesUp atomic.Int64
  45. bytesDown atomic.Int64
  46. peakBytesUp atomic.Int64
  47. peakBytesDown atomic.Int64
  48. connectingClients int32
  49. connectedClients int32
  50. config *ProxyConfig
  51. activityUpdateWrapper *activityUpdateWrapper
  52. lastConnectingClients int32
  53. lastConnectedClients int32
  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. // GetCurrentNetworkContext is a callback that returns a context tied to
  74. // the lifetime of the host's current active network interface. If the
  75. // active network changes, the previous context returned by
  76. // GetCurrentNetworkContext should cancel. This context is used to
  77. // immediately cancel/close individual connections when the active
  78. // network changes.
  79. GetCurrentNetworkContext func() context.Context
  80. // GetBrokerClient provides a BrokerClient which the proxy will use for
  81. // making broker requests. If GetBrokerClient returns a shared
  82. // BrokerClient instance, the BrokerClient must support multiple,
  83. // concurrent round trips, as the proxy will use it to concurrently
  84. // announce many proxy instances. The BrokerClient should be implemented
  85. // using multiplexing over a shared network connection -- for example,
  86. // HTTP/2 -- and a shared broker session for optimal performance.
  87. GetBrokerClient func() (*BrokerClient, error)
  88. // GetBaseAPIParameters returns Psiphon API parameters to be sent to and
  89. // logged by the broker. Expected parameters include client/proxy
  90. // application and build version information. GetBaseAPIParameters also
  91. // returns the network ID, corresponding to the parameters, to be used in
  92. // tactics logic; the network ID is not sent to the broker.
  93. GetBaseAPIParameters func(includeTacticsParameters bool) (
  94. common.APIParameters, string, error)
  95. // MakeWebRTCDialCoordinator provides a WebRTCDialCoordinator which
  96. // specifies WebRTC-related dial parameters, including selected STUN
  97. // server addresses; network topology information for the current netork;
  98. // NAT logic settings; and other settings.
  99. //
  100. // MakeWebRTCDialCoordinator is invoked for each proxy/client connection,
  101. // and the provider can select new parameters per connection as reqired.
  102. MakeWebRTCDialCoordinator func() (WebRTCDialCoordinator, error)
  103. // HandleTacticsPayload is a callback that receives any tactics payload,
  104. // provided by the broker in proxy announcement request responses.
  105. // HandleTacticsPayload must return true when the tacticsPayload includes
  106. // new tactics, indicating that the proxy should reinitialize components
  107. // controlled by tactics parameters.
  108. HandleTacticsPayload func(
  109. networkID string, compressTactics bool, tacticsPayload []byte) bool
  110. // MustUpgrade is a callback that is invoked when a MustUpgrade flag is
  111. // received from the broker. When MustUpgrade is received, the proxy
  112. // should be stopped and the user should be prompted to upgrade before
  113. // restarting the proxy.
  114. MustUpgrade func()
  115. // MaxClients is the maximum number of clients that are allowed to connect
  116. // to the proxy. Must be > 0.
  117. MaxClients int
  118. // LimitUpstreamBytesPerSecond limits the upstream data transfer rate for
  119. // a single client. When 0, there is no limit.
  120. LimitUpstreamBytesPerSecond int
  121. // LimitDownstreamBytesPerSecond limits the downstream data transfer rate
  122. // for a single client. When 0, there is no limit.
  123. LimitDownstreamBytesPerSecond int
  124. // ActivityUpdater specifies an ActivityUpdater for activity associated
  125. // with this proxy.
  126. ActivityUpdater ActivityUpdater
  127. }
  128. // ActivityUpdater is a callback that is invoked when clients connect and
  129. // disconnect and periodically with data transfer updates (unless idle). This
  130. // callback may be used to update an activity UI. This callback should post
  131. // this data to another thread or handler and return immediately and not
  132. // block on UI updates.
  133. type ActivityUpdater func(
  134. connectingClients int32,
  135. connectedClients int32,
  136. bytesUp int64,
  137. bytesDown int64,
  138. bytesDuration time.Duration)
  139. // NewProxy initializes a new Proxy with the specified configuration.
  140. func NewProxy(config *ProxyConfig) (*Proxy, error) {
  141. if config.MaxClients <= 0 {
  142. return nil, errors.TraceNew("invalid MaxClients")
  143. }
  144. p := &Proxy{
  145. config: config,
  146. }
  147. p.activityUpdateWrapper = &activityUpdateWrapper{p: p}
  148. return p, nil
  149. }
  150. // activityUpdateWrapper implements the psiphon/common.ActivityUpdater
  151. // interface and is used to receive bytes transferred updates from the
  152. // ActivityConns wrapping proxied traffic. A wrapper is used so that
  153. // UpdateProgress is not exported from Proxy.
  154. type activityUpdateWrapper struct {
  155. p *Proxy
  156. }
  157. func (w *activityUpdateWrapper) UpdateProgress(bytesRead, bytesWritten int64, _ int64) {
  158. w.p.bytesUp.Add(bytesWritten)
  159. w.p.bytesDown.Add(bytesRead)
  160. }
  161. // Run runs the proxy. The proxy sends requests to the Broker announcing its
  162. // availability; the Broker matches the proxy with clients, and facilitates
  163. // an exchange of WebRTC connection information; the proxy and each client
  164. // attempt to establish a connection; and the client's traffic is relayed to
  165. // Psiphon server.
  166. //
  167. // Run ends when ctx is Done. A proxy run may continue across underlying
  168. // network changes assuming that the ProxyConfig GetBrokerClient and
  169. // MakeWebRTCDialCoordinator callbacks react to network changes and provide
  170. // instances that are reflect network changes.
  171. func (p *Proxy) Run(ctx context.Context) {
  172. // Run MaxClient proxying workers. Each worker handles one client at a time.
  173. proxyWaitGroup := new(sync.WaitGroup)
  174. // Launch the first proxy worker, passing a signal to be triggered once
  175. // the very first announcement round trip is complete. The first round
  176. // trip is awaited so that:
  177. //
  178. // - The first announce response will arrive with any new tactics,
  179. // which may be applied before launching additions workers.
  180. //
  181. // - The first worker gets no announcement delay and is also guaranteed to
  182. // be the shared session establisher. Since the announcement delays are
  183. // applied _after_ waitToShareSession, it would otherwise be possible,
  184. // with a race of MaxClient initial, concurrent announces, for the
  185. // session establisher to be a different worker than the no-delay worker.
  186. //
  187. // The first worker is the only proxy worker which sets
  188. // ProxyAnnounceRequest.CheckTactics.
  189. signalFirstAnnounceCtx, signalFirstAnnounceDone :=
  190. context.WithCancel(context.Background())
  191. proxyWaitGroup.Add(1)
  192. go func() {
  193. defer proxyWaitGroup.Done()
  194. p.proxyClients(ctx, signalFirstAnnounceDone)
  195. }()
  196. select {
  197. case <-signalFirstAnnounceCtx.Done():
  198. case <-ctx.Done():
  199. return
  200. }
  201. // Launch the remaining workers.
  202. for i := 0; i < p.config.MaxClients-1; i++ {
  203. proxyWaitGroup.Add(1)
  204. go func() {
  205. defer proxyWaitGroup.Done()
  206. p.proxyClients(ctx, nil)
  207. }()
  208. }
  209. // Capture activity updates every second, which is the required frequency
  210. // for PeakUp/DownstreamBytesPerSecond. This is also a reasonable
  211. // frequency for invoking the ActivityUpdater and updating UI widgets.
  212. p.lastConnectingClients = 0
  213. p.lastConnectedClients = 0
  214. activityUpdatePeriod := 1 * time.Second
  215. ticker := time.NewTicker(activityUpdatePeriod)
  216. defer ticker.Stop()
  217. loop:
  218. for {
  219. select {
  220. case <-ticker.C:
  221. p.activityUpdate(activityUpdatePeriod)
  222. case <-ctx.Done():
  223. break loop
  224. }
  225. }
  226. proxyWaitGroup.Wait()
  227. }
  228. // getAnnounceDelayParameters is a helper that fetches the proxy announcement
  229. // delay parameters from the current broker client.
  230. //
  231. // getAnnounceDelayParameters is used to configure a delay when
  232. // proxyOneClient fails. As having no broker clients is a possible
  233. // proxyOneClient failure case, GetBrokerClient errors are ignored here and
  234. // defaults used in that case.
  235. func (p *Proxy) getAnnounceDelayParameters() (time.Duration, time.Duration, float64) {
  236. brokerClient, err := p.config.GetBrokerClient()
  237. if err != nil {
  238. return proxyAnnounceDelay, proxyAnnounceMaxBackoffDelay, proxyAnnounceDelayJitter
  239. }
  240. brokerCoordinator := brokerClient.GetBrokerDialCoordinator()
  241. return common.ValueOrDefault(brokerCoordinator.AnnounceDelay(), proxyAnnounceDelay),
  242. common.ValueOrDefault(brokerCoordinator.AnnounceMaxBackoffDelay(), proxyAnnounceMaxBackoffDelay),
  243. common.ValueOrDefault(brokerCoordinator.AnnounceDelayJitter(), proxyAnnounceDelayJitter)
  244. }
  245. func (p *Proxy) activityUpdate(period time.Duration) {
  246. connectingClients := atomic.LoadInt32(&p.connectingClients)
  247. connectedClients := atomic.LoadInt32(&p.connectedClients)
  248. bytesUp := p.bytesUp.Swap(0)
  249. bytesDown := p.bytesDown.Swap(0)
  250. greaterThanSwapInt64(&p.peakBytesUp, bytesUp)
  251. greaterThanSwapInt64(&p.peakBytesDown, bytesDown)
  252. clientsChanged := connectingClients != p.lastConnectingClients ||
  253. connectedClients != p.lastConnectedClients
  254. p.lastConnectingClients = connectingClients
  255. p.lastConnectedClients = connectedClients
  256. if !clientsChanged &&
  257. bytesUp == 0 &&
  258. bytesDown == 0 {
  259. // Skip the activity callback on idle bytes or no change in client counts.
  260. return
  261. }
  262. p.config.ActivityUpdater(
  263. connectingClients,
  264. connectedClients,
  265. bytesUp,
  266. bytesDown,
  267. period)
  268. }
  269. func greaterThanSwapInt64(addr *atomic.Int64, new int64) bool {
  270. // Limitation: if there are two concurrent calls, the greater value could
  271. // get overwritten.
  272. old := addr.Load()
  273. if new > old {
  274. return addr.CompareAndSwap(old, new)
  275. }
  276. return false
  277. }
  278. func (p *Proxy) proxyClients(
  279. ctx context.Context, signalAnnounceDone func()) {
  280. // Proxy one client, repeating until ctx is done.
  281. //
  282. // This worker starts with posting a long-polling announcement request.
  283. // The broker response with a matched client, and the proxy and client
  284. // attempt to establish a WebRTC connection for relaying traffic.
  285. //
  286. // Limitation: this design may not maximize the utility of the proxy,
  287. // since some proxy/client connections will fail at the WebRTC stage due
  288. // to NAT traversal failure, and at most MaxClient concurrent
  289. // establishments are attempted. Another scenario comes from the Psiphon
  290. // client horse race, which may start in-proxy dials but then abort them
  291. // when some other tunnel protocol succeeds.
  292. //
  293. // As a future enhancement, consider using M announcement goroutines and N
  294. // WebRTC dial goroutines. When an announcement gets a response,
  295. // immediately announce again unless there are already MaxClient active
  296. // connections established. This approach may require the proxy to
  297. // backpedal and reject connections when establishment is too successful.
  298. //
  299. // Another enhancement could be a signal from the client, to the broker,
  300. // relayed to the proxy, when a dial is aborted.
  301. failureDelayFactor := time.Duration(1)
  302. // To reduce diagnostic log noise, only log an initial sample of
  303. // announcement request timings (delays/elapsed time) and a periodic
  304. // sample of repeating errors such as "no match".
  305. logAnnounceCount := proxyAnnounceLogSampleSize
  306. logErrorsCount := proxyAnnounceLogSampleSize
  307. lastErrMsg := ""
  308. startLogSampleTime := time.Now()
  309. logAnnounce := func() bool {
  310. if logAnnounceCount > 0 {
  311. logAnnounceCount -= 1
  312. return true
  313. }
  314. return false
  315. }
  316. for ctx.Err() == nil {
  317. if !p.config.WaitForNetworkConnectivity() {
  318. break
  319. }
  320. if time.Since(startLogSampleTime) >= proxyAnnounceLogSamplePeriod {
  321. logAnnounceCount = proxyAnnounceLogSampleSize
  322. logErrorsCount = proxyAnnounceLogSampleSize
  323. lastErrMsg = ""
  324. startLogSampleTime = time.Now()
  325. }
  326. backOff, err := p.proxyOneClient(
  327. ctx, logAnnounce, signalAnnounceDone)
  328. if !backOff || err == nil {
  329. failureDelayFactor = 1
  330. }
  331. if err != nil && ctx.Err() == nil {
  332. // Apply a simple exponential backoff based on whether
  333. // proxyOneClient either relayed client traffic or got no match,
  334. // or encountered a failure.
  335. //
  336. // The proxyOneClient failure could range from local
  337. // configuration (no broker clients) to network issues(failure to
  338. // completely establish WebRTC connection) and this backoff
  339. // prevents both excess local logging and churning in the former
  340. // case and excessive bad service to clients or unintentionally
  341. // overloading the broker in the latter case.
  342. delay, maxBackoffDelay, jitter := p.getAnnounceDelayParameters()
  343. delay = delay * failureDelayFactor
  344. if delay > maxBackoffDelay {
  345. delay = maxBackoffDelay
  346. }
  347. if failureDelayFactor < 1<<20 {
  348. failureDelayFactor *= 2
  349. }
  350. // Sample error log.
  351. //
  352. // Limitation: the lastErrMsg string comparison isn't compatible
  353. // with errors with minor variations, such as "unexpected
  354. // response status code %d after %v" from
  355. // InproxyBrokerRoundTripper.RoundTrip, with a time duration in
  356. // the second parameter.
  357. errMsg := err.Error()
  358. if lastErrMsg != errMsg {
  359. logErrorsCount = proxyAnnounceLogSampleSize
  360. lastErrMsg = errMsg
  361. }
  362. if logErrorsCount > 0 {
  363. p.config.Logger.WithTraceFields(
  364. common.LogFields{
  365. "error": errMsg,
  366. "delay": delay.String(),
  367. "jitter": jitter,
  368. }).Error("proxy client failed")
  369. logErrorsCount -= 1
  370. }
  371. common.SleepWithJitter(ctx, delay, jitter)
  372. }
  373. }
  374. }
  375. // resetNetworkDiscovery resets the network discovery state, which will force
  376. // another network discovery when doNetworkDiscovery is invoked.
  377. // resetNetworkDiscovery is called when new tactics have been received from
  378. // the broker, as new tactics may change parameters that control network
  379. // discovery.
  380. func (p *Proxy) resetNetworkDiscovery() {
  381. p.networkDiscoveryMutex.Lock()
  382. defer p.networkDiscoveryMutex.Unlock()
  383. p.networkDiscoveryRunOnce = false
  384. p.networkDiscoveryNetworkID = ""
  385. }
  386. func (p *Proxy) doNetworkDiscovery(
  387. ctx context.Context,
  388. webRTCCoordinator WebRTCDialCoordinator) {
  389. // Allow only one concurrent network discovery. In practise, this may
  390. // block all other proxyOneClient goroutines while one single goroutine
  391. // runs doNetworkDiscovery. Subsequently, all other goroutines will find
  392. // networkDiscoveryRunOnce is true and use the cached results.
  393. p.networkDiscoveryMutex.Lock()
  394. defer p.networkDiscoveryMutex.Unlock()
  395. networkID := webRTCCoordinator.NetworkID()
  396. if p.networkDiscoveryRunOnce &&
  397. p.networkDiscoveryNetworkID == networkID {
  398. // Already ran discovery for this network.
  399. //
  400. // TODO: periodically re-probe for port mapping services?
  401. return
  402. }
  403. // Reset and configure port mapper component, as required. See
  404. // initPortMapper comment.
  405. initPortMapper(webRTCCoordinator)
  406. // Gather local network NAT/port mapping metrics and configuration before
  407. // sending any announce requests. NAT topology metrics are used by the
  408. // Broker to optimize client and in-proxy matching. Unlike the client, we
  409. // always perform this synchronous step here, since waiting doesn't
  410. // necessarily block a client tunnel dial.
  411. waitGroup := new(sync.WaitGroup)
  412. waitGroup.Add(1)
  413. go func() {
  414. defer waitGroup.Done()
  415. // NATDiscover may use cached NAT type/port mapping values from
  416. // DialParameters, based on the network ID. If discovery is not
  417. // successful, the proxy still proceeds to announce.
  418. NATDiscover(
  419. ctx,
  420. &NATDiscoverConfig{
  421. Logger: p.config.Logger,
  422. WebRTCDialCoordinator: webRTCCoordinator,
  423. })
  424. }()
  425. waitGroup.Wait()
  426. p.networkDiscoveryRunOnce = true
  427. p.networkDiscoveryNetworkID = networkID
  428. }
  429. func (p *Proxy) proxyOneClient(
  430. ctx context.Context,
  431. logAnnounce func() bool,
  432. signalAnnounceDone func()) (bool, error) {
  433. // Cancel/close this connection immediately if the network changes.
  434. if p.config.GetCurrentNetworkContext != nil {
  435. var cancelFunc context.CancelFunc
  436. ctx, cancelFunc = common.MergeContextCancel(
  437. ctx, p.config.GetCurrentNetworkContext())
  438. defer cancelFunc()
  439. }
  440. // Do not trigger back-off unless the proxy successfully announces and
  441. // only then performs poorly.
  442. //
  443. // A no-match response should not trigger back-off, nor should broker
  444. // request transport errors which may include non-200 responses due to
  445. // CDN timeout mismatches or TLS errors due to CDN TLS fingerprint
  446. // incompatibility.
  447. backOff := false
  448. // Get a new WebRTCDialCoordinator, which should be configured with the
  449. // latest network tactics.
  450. webRTCCoordinator, err := p.config.MakeWebRTCDialCoordinator()
  451. if err != nil {
  452. return backOff, errors.Trace(err)
  453. }
  454. // Perform network discovery, to determine NAT type and other network
  455. // topology information that is reported to the broker in the proxy
  456. // announcement and used to optimize proxy/client matching. Unlike
  457. // clients, which can't easily delay dials in the tunnel establishment
  458. // horse race, proxies will always perform network discovery.
  459. // doNetworkDiscovery allows only one concurrent discovery and caches
  460. // results for the current network (as determined by
  461. // WebRTCCoordinator.GetNetworkID), so when multiple proxyOneClient
  462. // goroutines call doNetworkDiscovery, at most one discovery is performed
  463. // per network.
  464. p.doNetworkDiscovery(ctx, webRTCCoordinator)
  465. // Send the announce request
  466. // At this point, no NAT traversal operations have been performed by the
  467. // proxy, since its announcement may sit idle for the long-polling period
  468. // and NAT hole punches or port mappings could expire before the
  469. // long-polling period.
  470. //
  471. // As a future enhancement, the proxy could begin gathering WebRTC ICE
  472. // candidates while awaiting a client match, reducing the turn around
  473. // time after a match. This would make sense if there's high demand for
  474. // proxies, and so hole punches unlikely to expire while awaiting a client match.
  475. //
  476. // Another possibility may be to prepare and send a full offer SDP in the
  477. // announcment; and have the broker modify either the proxy or client
  478. // offer SDP to produce an answer SDP. In this case, the entire
  479. // ProxyAnswerRequest could be skipped as the WebRTC dial can begin after
  480. // the ProxyAnnounceRequest response (and ClientOfferRequest response).
  481. //
  482. // Furthermore, if a port mapping can be established, instead of using
  483. // WebRTC the proxy could run a Psiphon tunnel protocol listener at the
  484. // mapped port and send the dial information -- including some secret to
  485. // authenticate the client -- in its announcement. The client would then
  486. // receive this direct dial information from the broker and connect. The
  487. // proxy should be able to send keep alives to extend the port mapping
  488. // lifetime.
  489. brokerClient, err := p.config.GetBrokerClient()
  490. if err != nil {
  491. return backOff, errors.Trace(err)
  492. }
  493. brokerCoordinator := brokerClient.GetBrokerDialCoordinator()
  494. // Only the first worker, which has signalAnnounceDone configured, checks
  495. // for tactics.
  496. checkTactics := signalAnnounceDone != nil
  497. // Get the base Psiphon API parameters and additional proxy metrics,
  498. // including performance information, which is sent to the broker in the
  499. // proxy announcment.
  500. //
  501. // tacticsNetworkID is the exact network ID that corresponds to the
  502. // tactics tag sent in the base parameters; this is passed to
  503. // HandleTacticsPayload in order to double check that any tactics
  504. // returned in the proxy announcment response are associated and stored
  505. // with the original network ID.
  506. metrics, tacticsNetworkID, compressTactics, err := p.getMetrics(
  507. checkTactics, brokerCoordinator, webRTCCoordinator)
  508. if err != nil {
  509. return backOff, errors.Trace(err)
  510. }
  511. // Set a delay before announcing, to stagger the announce request times.
  512. // The delay helps to avoid triggering rate limits or similar errors from
  513. // any intermediate CDN between the proxy and the broker; and provides a
  514. // nudge towards better load balancing across multiple large MaxClients
  515. // proxies, as the broker primarily matches enqueued announces in FIFO
  516. // order, since older announces expire earlier.
  517. //
  518. // The delay is intended to be applied after doNetworkDiscovery, which has
  519. // no reason to be delayed; and also after any waitToShareSession delay,
  520. // as delaying before waitToShareSession can result in the announce
  521. // request times collapsing back together. Delaying after
  522. // waitToShareSession is handled by brokerClient.ProxyAnnounce, which
  523. // will also extend the base request timeout, as required, to account for
  524. // any deliberate delay.
  525. requestDelay := time.Duration(0)
  526. announceDelay, _, announceDelayJitter := p.getAnnounceDelayParameters()
  527. p.nextAnnounceMutex.Lock()
  528. nextDelay := prng.JitterDuration(announceDelay, announceDelayJitter)
  529. if p.nextAnnounceBrokerClient != brokerClient {
  530. // Reset the delay when the broker client changes.
  531. p.nextAnnounceNotBefore = time.Time{}
  532. p.nextAnnounceBrokerClient = brokerClient
  533. }
  534. if p.nextAnnounceNotBefore.IsZero() {
  535. p.nextAnnounceNotBefore = time.Now().Add(nextDelay)
  536. // No delay for the very first announce request, so leave
  537. // announceRequestDelay set to 0.
  538. } else {
  539. requestDelay = time.Until(p.nextAnnounceNotBefore)
  540. if requestDelay < 0 {
  541. // This announce did not arrive until after the next delay already
  542. // passed, so proceed with no delay.
  543. p.nextAnnounceNotBefore = time.Now().Add(nextDelay)
  544. requestDelay = 0
  545. } else {
  546. p.nextAnnounceNotBefore = p.nextAnnounceNotBefore.Add(nextDelay)
  547. }
  548. }
  549. p.nextAnnounceMutex.Unlock()
  550. // A proxy ID is implicitly sent with requests; it's the proxy's session
  551. // public key.
  552. //
  553. // ProxyAnnounce applies an additional request timeout to facilitate
  554. // long-polling.
  555. announceStartTime := time.Now()
  556. personalCompartmentIDs := brokerCoordinator.PersonalCompartmentIDs()
  557. announceResponse, err := brokerClient.ProxyAnnounce(
  558. ctx,
  559. requestDelay,
  560. &ProxyAnnounceRequest{
  561. PersonalCompartmentIDs: personalCompartmentIDs,
  562. Metrics: metrics,
  563. CheckTactics: checkTactics,
  564. })
  565. if logAnnounce() {
  566. p.config.Logger.WithTraceFields(common.LogFields{
  567. "delay": requestDelay.String(),
  568. "elapsedTime": time.Since(announceStartTime).String(),
  569. }).Info("announcement request")
  570. }
  571. if err != nil {
  572. return backOff, errors.Trace(err)
  573. }
  574. if len(announceResponse.TacticsPayload) > 0 {
  575. // The TacticsPayload may include new tactics, or may simply signal,
  576. // to the Psiphon client, that its tactics tag remains up-to-date and
  577. // to extend cached tactics TTL. HandleTacticsPayload returns true
  578. // when tactics haved changed; in this case we clear cached network
  579. // discovery but proceed with handling the proxy announcement
  580. // response as there may still be a match.
  581. if p.config.HandleTacticsPayload(
  582. tacticsNetworkID,
  583. compressTactics,
  584. 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) (
  855. *ProxyMetrics, string, bool, error) {
  856. // tacticsNetworkID records the exact network ID that corresponds to the
  857. // tactics tag sent in the base parameters, and is used when applying any
  858. // new tactics returned by the broker.
  859. baseParams, tacticsNetworkID, err := p.config.GetBaseAPIParameters(
  860. includeTacticsParameters)
  861. if err != nil {
  862. return nil, "", false, errors.Trace(err)
  863. }
  864. apiParams := common.APIParameters{}
  865. apiParams.Add(baseParams)
  866. apiParams.Add(common.APIParameters(brokerCoordinator.MetricsForBrokerRequests()))
  867. compressTactics := protocol.GetCompressTactics(apiParams)
  868. packedParams, err := protocol.EncodePackedAPIParameters(apiParams)
  869. if err != nil {
  870. return nil, "", false, errors.Trace(err)
  871. }
  872. return &ProxyMetrics{
  873. BaseAPIParameters: packedParams,
  874. ProtocolVersion: LatestProtocolVersion,
  875. NATType: webRTCCoordinator.NATType(),
  876. PortMappingTypes: webRTCCoordinator.PortMappingTypes(),
  877. MaxClients: int32(p.config.MaxClients),
  878. ConnectingClients: atomic.LoadInt32(&p.connectingClients),
  879. ConnectedClients: atomic.LoadInt32(&p.connectedClients),
  880. LimitUpstreamBytesPerSecond: int64(p.config.LimitUpstreamBytesPerSecond),
  881. LimitDownstreamBytesPerSecond: int64(p.config.LimitDownstreamBytesPerSecond),
  882. PeakUpstreamBytesPerSecond: p.peakBytesUp.Load(),
  883. PeakDownstreamBytesPerSecond: p.peakBytesDown.Load(),
  884. }, tacticsNetworkID, compressTactics, nil
  885. }