proxy.go 30 KB

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