proxy.go 36 KB

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