proxy.go 36 KB

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