proxy.go 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  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.ClientProxyProtocolVersion != ProxyProtocolVersion1 {
  610. // This case is currently unexpected, as all clients and proxies use
  611. // ProxyProtocolVersion1.
  612. backOff = true
  613. return backOff, errors.Tracef(
  614. "Unsupported proxy protocol version: %d",
  615. announceResponse.ClientProxyProtocolVersion)
  616. }
  617. // Trigger back-off if the following WebRTC operations fail to establish a
  618. // connections.
  619. //
  620. // Limitation: the proxy answer request to the broker may fail due to the
  621. // non-back-off reasons documented above for the proxy announcment request;
  622. // however, these should be unlikely assuming that the broker client is
  623. // using a persistent transport connection.
  624. backOff = true
  625. // For activity updates, indicate that a client connection is now underway.
  626. atomic.AddInt32(&p.connectingClients, 1)
  627. connected := false
  628. defer func() {
  629. if !connected {
  630. atomic.AddInt32(&p.connectingClients, -1)
  631. }
  632. }()
  633. // Initialize WebRTC using the client's offer SDP
  634. webRTCAnswerCtx, webRTCAnswerCancelFunc := context.WithTimeout(
  635. ctx, common.ValueOrDefault(webRTCCoordinator.WebRTCAnswerTimeout(), proxyWebRTCAnswerTimeout))
  636. defer webRTCAnswerCancelFunc()
  637. // In personal pairing mode, RFC 1918/4193 private IP addresses are
  638. // included in SDPs.
  639. hasPersonalCompartmentIDs := len(personalCompartmentIDs) > 0
  640. webRTCConn, SDP, sdpMetrics, webRTCErr := newWebRTCConnForAnswer(
  641. webRTCAnswerCtx,
  642. &webRTCConfig{
  643. Logger: p.config.Logger,
  644. EnableDebugLogging: p.config.EnableWebRTCDebugLogging,
  645. WebRTCDialCoordinator: webRTCCoordinator,
  646. ClientRootObfuscationSecret: announceResponse.ClientRootObfuscationSecret,
  647. DoDTLSRandomization: announceResponse.DoDTLSRandomization,
  648. TrafficShapingParameters: announceResponse.TrafficShapingParameters,
  649. },
  650. announceResponse.ClientOfferSDP,
  651. hasPersonalCompartmentIDs)
  652. var webRTCRequestErr string
  653. if webRTCErr != nil {
  654. webRTCErr = errors.Trace(webRTCErr)
  655. webRTCRequestErr = webRTCErr.Error()
  656. SDP = WebRTCSessionDescription{}
  657. sdpMetrics = &webRTCSDPMetrics{}
  658. // Continue to report the error to the broker. The broker will respond
  659. // with failure to the client's offer request.
  660. } else {
  661. defer webRTCConn.Close()
  662. }
  663. // Send answer request with SDP or error.
  664. _, err = brokerClient.ProxyAnswer(
  665. ctx,
  666. &ProxyAnswerRequest{
  667. ConnectionID: announceResponse.ConnectionID,
  668. SelectedProxyProtocolVersion: announceResponse.ClientProxyProtocolVersion,
  669. ProxyAnswerSDP: SDP,
  670. ICECandidateTypes: sdpMetrics.iceCandidateTypes,
  671. AnswerError: webRTCRequestErr,
  672. })
  673. if err != nil {
  674. if webRTCErr != nil {
  675. // Prioritize returning any WebRTC error for logging.
  676. return backOff, webRTCErr
  677. }
  678. return backOff, errors.Trace(err)
  679. }
  680. // Now that an answer is sent, stop if WebRTC initialization failed.
  681. if webRTCErr != nil {
  682. return backOff, webRTCErr
  683. }
  684. // Await the WebRTC connection.
  685. // We could concurrently dial the destination, to have that network
  686. // connection available immediately once the WebRTC channel is
  687. // established. This would work only for TCP, not UDP, network protocols
  688. // and could only include the TCP connection, as client traffic is
  689. // required for all higher layers such as TLS, SSH, etc. This could also
  690. // create wasted load on destination Psiphon servers, particularly when
  691. // WebRTC connections fail.
  692. awaitDataChannelCtx, awaitDataChannelCancelFunc := context.WithTimeout(
  693. ctx,
  694. common.ValueOrDefault(
  695. webRTCCoordinator.WebRTCAwaitDataChannelTimeout(), dataChannelAwaitTimeout))
  696. defer awaitDataChannelCancelFunc()
  697. err = webRTCConn.AwaitInitialDataChannel(awaitDataChannelCtx)
  698. if err != nil {
  699. return backOff, errors.Trace(err)
  700. }
  701. p.config.Logger.WithTraceFields(common.LogFields{
  702. "connectionID": announceResponse.ConnectionID,
  703. }).Info("WebRTC data channel established")
  704. // Dial the destination, a Psiphon server. The broker validates that the
  705. // dial destination is a Psiphon server.
  706. destinationDialContext, destinationDialCancelFunc := context.WithTimeout(
  707. ctx,
  708. common.ValueOrDefault(
  709. webRTCCoordinator.ProxyDestinationDialTimeout(), proxyDestinationDialTimeout))
  710. defer destinationDialCancelFunc()
  711. // Use the custom resolver when resolving destination hostnames, such as
  712. // those used in domain fronted protocols.
  713. //
  714. // - Resolving at the in-proxy should yield a more optimal CDN edge, vs.
  715. // resolving at the client.
  716. //
  717. // - Sending unresolved hostnames to in-proxies can expose some domain
  718. // fronting configuration. This can be mitigated by enabling domain
  719. // fronting on this 2nd hop only when the in-proxy is located in a
  720. // region that may be censored or blocked; this is to be enforced by
  721. // the broker.
  722. //
  723. // - Any DNSResolverPreresolved tactics applied will be relative to the
  724. // in-proxy location.
  725. destinationAddress, err := webRTCCoordinator.ResolveAddress(
  726. ctx, "ip", announceResponse.DestinationAddress)
  727. if err != nil {
  728. return backOff, errors.Trace(err)
  729. }
  730. destinationConn, err := webRTCCoordinator.ProxyUpstreamDial(
  731. destinationDialContext,
  732. announceResponse.NetworkProtocol.String(),
  733. destinationAddress)
  734. if err != nil {
  735. return backOff, errors.Trace(err)
  736. }
  737. defer destinationConn.Close()
  738. // For activity updates, indicate that a client connection is established.
  739. connected = true
  740. atomic.AddInt32(&p.connectingClients, -1)
  741. atomic.AddInt32(&p.connectedClients, 1)
  742. defer func() {
  743. atomic.AddInt32(&p.connectedClients, -1)
  744. }()
  745. // Throttle the relay connection.
  746. //
  747. // Here, each client gets LimitUp/DownstreamBytesPerSecond. Proxy
  748. // operators may to want to limit their bandwidth usage with a single
  749. // up/down value, an overall limit. The ProxyConfig can simply be
  750. // generated by dividing the limit by MaxClients. This approach favors
  751. // performance stability: each client gets the same throttling limits
  752. // regardless of how many other clients are connected.
  753. destinationConn = common.NewThrottledConn(
  754. destinationConn,
  755. announceResponse.NetworkProtocol.IsStream(),
  756. common.RateLimits{
  757. ReadBytesPerSecond: int64(p.config.LimitUpstreamBytesPerSecond),
  758. WriteBytesPerSecond: int64(p.config.LimitDownstreamBytesPerSecond),
  759. })
  760. // Hook up bytes transferred counting for activity updates.
  761. // The ActivityMonitoredConn inactivity timeout is configured. For
  762. // upstream TCP connections, the destinationConn will close when the TCP
  763. // connection to the Psiphon server closes. But for upstream UDP flows,
  764. // the relay does not know when the upstream "connection" has closed.
  765. // Well-behaved clients will close the WebRTC half of the relay when
  766. // those clients know the UDP-based tunnel protocol connection is closed;
  767. // the inactivity timeout handles the remaining cases.
  768. inactivityTimeout :=
  769. common.ValueOrDefault(
  770. webRTCCoordinator.ProxyRelayInactivityTimeout(),
  771. proxyRelayInactivityTimeout)
  772. destinationConn, err = common.NewActivityMonitoredConn(
  773. destinationConn, inactivityTimeout, false, nil, p.activityUpdateWrapper)
  774. if err != nil {
  775. return backOff, errors.Trace(err)
  776. }
  777. // Relay the client traffic to the destination. The client traffic is a
  778. // standard Psiphon tunnel protocol destinated to a Psiphon server. Any
  779. // blocking/censorship at the 2nd hop will be mitigated by the use of
  780. // Psiphon circumvention protocols and techniques.
  781. // Limitation: clients may apply fragmentation to traffic relayed over the
  782. // data channel, and there's no guarantee that the fragmentation write
  783. // sizes or delays will carry over to the egress side.
  784. // The proxy operator's ISP may be able to observe that the operator's
  785. // host has nearly matching ingress and egress traffic. The traffic
  786. // content won't be the same: the ingress traffic is wrapped in a WebRTC
  787. // data channel, and the egress traffic is a Psiphon tunnel protocol.
  788. // With padding and decoy packets, the ingress and egress traffic shape
  789. // will differ beyond the basic WebRTC overheader. Even with this
  790. // measure, over time the number of bytes in and out of the proxy may
  791. // still indicate proxying.
  792. waitGroup := new(sync.WaitGroup)
  793. relayErrors := make(chan error, 2)
  794. var relayedUp, relayedDown int32
  795. waitGroup.Add(1)
  796. go func() {
  797. defer waitGroup.Done()
  798. // WebRTC data channels are based on SCTP, which is actually
  799. // message-based, not a stream. The (default) max message size for
  800. // pion/sctp is 65536:
  801. // https://github.com/pion/sctp/blob/44ed465396c880e379aae9c1bf81809a9e06b580/association.go#L52.
  802. //
  803. // As io.Copy uses a buffer size of 32K, each relayed message will be
  804. // less than the maximum. Calls to ClientConn.Write are also expected
  805. // to use io.Copy, keeping messages at most 32K in size.
  806. // io.Copy doesn't return an error on EOF, but we still want to signal
  807. // that relaying is done, so in this case a nil error is sent to the
  808. // channel.
  809. //
  810. // Limitation: if one io.Copy goproutine sends nil and the other
  811. // io.Copy goroutine sends a non-nil error concurrently, the non-nil
  812. // error isn't prioritized.
  813. n, err := io.Copy(webRTCConn, destinationConn)
  814. if n > 0 {
  815. atomic.StoreInt32(&relayedDown, 1)
  816. }
  817. relayErrors <- errors.Trace(err)
  818. }()
  819. waitGroup.Add(1)
  820. go func() {
  821. defer waitGroup.Done()
  822. n, err := io.Copy(destinationConn, webRTCConn)
  823. if n > 0 {
  824. atomic.StoreInt32(&relayedUp, 1)
  825. }
  826. relayErrors <- errors.Trace(err)
  827. }()
  828. select {
  829. case err = <-relayErrors:
  830. case <-ctx.Done():
  831. }
  832. // Interrupt the relay goroutines by closing the connections.
  833. webRTCConn.Close()
  834. destinationConn.Close()
  835. waitGroup.Wait()
  836. p.config.Logger.WithTraceFields(common.LogFields{
  837. "connectionID": announceResponse.ConnectionID,
  838. }).Info("connection closed")
  839. // Don't apply a back-off delay to the next announcement since this
  840. // iteration successfully relayed bytes.
  841. if atomic.LoadInt32(&relayedUp) == 1 || atomic.LoadInt32(&relayedDown) == 1 {
  842. backOff = false
  843. }
  844. return backOff, err
  845. }
  846. func (p *Proxy) getMetrics(
  847. includeTacticsParameters bool,
  848. brokerCoordinator BrokerDialCoordinator,
  849. webRTCCoordinator WebRTCDialCoordinator) (*ProxyMetrics, string, error) {
  850. // tacticsNetworkID records the exact network ID that corresponds to the
  851. // tactics tag sent in the base parameters, and is used when applying any
  852. // new tactics returned by the broker.
  853. baseParams, tacticsNetworkID, err := p.config.GetBaseAPIParameters(
  854. includeTacticsParameters)
  855. if err != nil {
  856. return nil, "", errors.Trace(err)
  857. }
  858. apiParams := common.APIParameters{}
  859. apiParams.Add(baseParams)
  860. apiParams.Add(common.APIParameters(brokerCoordinator.MetricsForBrokerRequests()))
  861. packedParams, err := protocol.EncodePackedAPIParameters(apiParams)
  862. if err != nil {
  863. return nil, "", errors.Trace(err)
  864. }
  865. return &ProxyMetrics{
  866. BaseAPIParameters: packedParams,
  867. ProxyProtocolVersion: proxyProtocolVersion,
  868. NATType: webRTCCoordinator.NATType(),
  869. PortMappingTypes: webRTCCoordinator.PortMappingTypes(),
  870. MaxClients: int32(p.config.MaxClients),
  871. ConnectingClients: atomic.LoadInt32(&p.connectingClients),
  872. ConnectedClients: atomic.LoadInt32(&p.connectedClients),
  873. LimitUpstreamBytesPerSecond: int64(p.config.LimitUpstreamBytesPerSecond),
  874. LimitDownstreamBytesPerSecond: int64(p.config.LimitDownstreamBytesPerSecond),
  875. PeakUpstreamBytesPerSecond: atomic.LoadInt64(&p.peakBytesUp),
  876. PeakDownstreamBytesPerSecond: atomic.LoadInt64(&p.peakBytesDown),
  877. }, tacticsNetworkID, nil
  878. }