proxy.go 32 KB

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