tunnel.go 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848
  1. /*
  2. * Copyright (c) 2015, 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 psiphon
  20. import (
  21. "bytes"
  22. "context"
  23. "crypto/rand"
  24. "encoding/base64"
  25. "encoding/json"
  26. std_errors "errors"
  27. "fmt"
  28. "io"
  29. "io/ioutil"
  30. "net"
  31. "net/http"
  32. "sync"
  33. "sync/atomic"
  34. "time"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/ssh"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/obfuscator"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/refraction"
  44. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  45. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/transferstats"
  46. )
  47. // Tunneler specifies the interface required by components that use tunnels.
  48. type Tunneler interface {
  49. // Dial creates a tunneled connection.
  50. //
  51. // When split tunnel mode is enabled, the connection may be untunneled,
  52. // depending on GeoIP classification of the destination.
  53. //
  54. // downstreamConn is an optional parameter which specifies a connection to be
  55. // explicitly closed when the Dialed connection is closed. For instance, this
  56. // is used to close downstreamConn App<->LocalProxy connections when the related
  57. // LocalProxy<->SshPortForward connections close.
  58. Dial(remoteAddr string, downstreamConn net.Conn) (conn net.Conn, err error)
  59. DirectDial(remoteAddr string) (conn net.Conn, err error)
  60. SignalComponentFailure()
  61. }
  62. // TunnelOwner specifies the interface required by Tunnel to notify its
  63. // owner when it has failed. The owner may, as in the case of the Controller,
  64. // remove the tunnel from its list of active tunnels.
  65. type TunnelOwner interface {
  66. SignalSeededNewSLOK()
  67. SignalTunnelFailure(tunnel *Tunnel)
  68. }
  69. // Tunnel is a connection to a Psiphon server. An established
  70. // tunnel includes a network connection to the specified server
  71. // and an SSH session built on top of that transport.
  72. type Tunnel struct {
  73. mutex *sync.Mutex
  74. config *Config
  75. isActivated bool
  76. isDiscarded bool
  77. isClosed bool
  78. dialParams *DialParameters
  79. livenessTestMetrics *livenessTestMetrics
  80. extraFailureAction func()
  81. serverContext *ServerContext
  82. monitoringStartTime time.Time
  83. conn *common.BurstMonitoredConn
  84. sshClient *ssh.Client
  85. sshServerRequests <-chan *ssh.Request
  86. operateWaitGroup *sync.WaitGroup
  87. operateCtx context.Context
  88. stopOperate context.CancelFunc
  89. signalPortForwardFailure chan struct{}
  90. totalPortForwardFailures int
  91. adjustedEstablishStartTime time.Time
  92. establishDuration time.Duration
  93. establishedTime time.Time
  94. handledSSHKeepAliveFailure int32
  95. inFlightConnectedRequestSignal chan struct{}
  96. }
  97. // getCustomParameters helpers wrap the verbose function call chain required
  98. // to get a current snapshot of the parameters.Parameters customized with the
  99. // dial parameters associated with a tunnel.
  100. func (tunnel *Tunnel) getCustomParameters() parameters.ParametersAccessor {
  101. return getCustomParameters(tunnel.config, tunnel.dialParams)
  102. }
  103. func getCustomParameters(
  104. config *Config, dialParams *DialParameters) parameters.ParametersAccessor {
  105. return config.GetParameters().GetCustom(dialParams.NetworkLatencyMultiplier)
  106. }
  107. // ConnectTunnel first makes a network transport connection to the
  108. // Psiphon server and then establishes an SSH client session on top of
  109. // that transport. The SSH server is authenticated using the public
  110. // key in the server entry.
  111. // Depending on the server's capabilities, the connection may use
  112. // plain SSH over TCP, obfuscated SSH over TCP, or obfuscated SSH over
  113. // HTTP (meek protocol).
  114. // When requiredProtocol is not blank, that protocol is used. Otherwise,
  115. // the a random supported protocol is used.
  116. //
  117. // Call Activate on a connected tunnel to complete its establishment
  118. // before using.
  119. //
  120. // Tunnel establishment is split into two phases: connection, and
  121. // activation. The Controller will run many ConnectTunnel calls
  122. // concurrently and then, to avoid unnecessary overhead from making
  123. // handshake requests and starting operateTunnel from tunnels which
  124. // may be discarded, call Activate on connected tunnels sequentially
  125. // as necessary.
  126. func ConnectTunnel(
  127. ctx context.Context,
  128. config *Config,
  129. adjustedEstablishStartTime time.Time,
  130. dialParams *DialParameters) (*Tunnel, error) {
  131. // Build transport layers and establish SSH connection. Note that
  132. // dialConn and monitoredConn are the same network connection.
  133. dialResult, err := dialTunnel(ctx, config, dialParams)
  134. if err != nil {
  135. return nil, errors.Trace(err)
  136. }
  137. // The tunnel is now connected
  138. return &Tunnel{
  139. mutex: new(sync.Mutex),
  140. config: config,
  141. dialParams: dialParams,
  142. livenessTestMetrics: dialResult.livenessTestMetrics,
  143. extraFailureAction: dialResult.extraFailureAction,
  144. monitoringStartTime: dialResult.monitoringStartTime,
  145. conn: dialResult.monitoredConn,
  146. sshClient: dialResult.sshClient,
  147. sshServerRequests: dialResult.sshRequests,
  148. // A buffer allows at least one signal to be sent even when the receiver is
  149. // not listening. Senders should not block.
  150. signalPortForwardFailure: make(chan struct{}, 1),
  151. adjustedEstablishStartTime: adjustedEstablishStartTime,
  152. }, nil
  153. }
  154. // Activate completes the tunnel establishment, performing the handshake
  155. // request and starting operateTunnel, the worker that monitors the tunnel
  156. // and handles periodic management.
  157. func (tunnel *Tunnel) Activate(
  158. ctx context.Context, tunnelOwner TunnelOwner) (retErr error) {
  159. // Ensure that, unless the base context is cancelled, any replayed dial
  160. // parameters are cleared, no longer to be retried, if the tunnel fails to
  161. // activate.
  162. activationSucceeded := false
  163. baseCtx := ctx
  164. defer func() {
  165. if !activationSucceeded && baseCtx.Err() != context.Canceled {
  166. tunnel.dialParams.Failed(tunnel.config)
  167. if tunnel.extraFailureAction != nil {
  168. tunnel.extraFailureAction()
  169. }
  170. if retErr != nil {
  171. _ = RecordFailedTunnelStat(
  172. tunnel.config,
  173. tunnel.dialParams,
  174. tunnel.livenessTestMetrics,
  175. -1,
  176. -1,
  177. retErr)
  178. }
  179. }
  180. }()
  181. // Create a new Psiphon API server context for this tunnel. This includes
  182. // performing a handshake request. If the handshake fails, this activation
  183. // fails.
  184. var serverContext *ServerContext
  185. if !tunnel.config.DisableApi {
  186. NoticeInfo(
  187. "starting server context for %s",
  188. tunnel.dialParams.ServerEntry.GetDiagnosticID())
  189. // Call NewServerContext in a goroutine, as it blocks on a network operation,
  190. // the handshake request, and would block shutdown. If the shutdown signal is
  191. // received, close the tunnel, which will interrupt the handshake request
  192. // that may be blocking NewServerContext.
  193. //
  194. // Timeout after PsiphonApiServerTimeoutSeconds. NewServerContext may not
  195. // return if the tunnel network connection is unstable during the handshake
  196. // request. At this point, there is no operateTunnel monitor that will detect
  197. // this condition with SSH keep alives.
  198. timeout := tunnel.getCustomParameters().Duration(
  199. parameters.PsiphonAPIRequestTimeout)
  200. if timeout > 0 {
  201. var cancelFunc context.CancelFunc
  202. ctx, cancelFunc = context.WithTimeout(ctx, timeout)
  203. defer cancelFunc()
  204. }
  205. type newServerContextResult struct {
  206. serverContext *ServerContext
  207. err error
  208. }
  209. resultChannel := make(chan newServerContextResult)
  210. go func() {
  211. serverContext, err := NewServerContext(tunnel)
  212. resultChannel <- newServerContextResult{
  213. serverContext: serverContext,
  214. err: err,
  215. }
  216. }()
  217. var result newServerContextResult
  218. select {
  219. case result = <-resultChannel:
  220. case <-ctx.Done():
  221. result.err = ctx.Err()
  222. // Interrupt the goroutine
  223. tunnel.Close(true)
  224. <-resultChannel
  225. }
  226. if result.err != nil {
  227. return errors.Trace(result.err)
  228. }
  229. serverContext = result.serverContext
  230. }
  231. // The activation succeeded.
  232. activationSucceeded = true
  233. tunnel.mutex.Lock()
  234. // It may happen that the tunnel gets closed while Activate is running.
  235. // In this case, abort here, to ensure that the operateTunnel goroutine
  236. // will not be launched after Close is called.
  237. if tunnel.isClosed {
  238. return errors.TraceNew("tunnel is closed")
  239. }
  240. tunnel.isActivated = true
  241. tunnel.serverContext = serverContext
  242. // establishDuration is the elapsed time between the controller starting tunnel
  243. // establishment and this tunnel being established. The reported value represents
  244. // how long the user waited between starting the client and having a usable tunnel;
  245. // or how long between the client detecting an unexpected tunnel disconnect and
  246. // completing automatic reestablishment.
  247. //
  248. // This time period may include time spent unsuccessfully connecting to other
  249. // servers. Time spent waiting for network connectivity is excluded.
  250. tunnel.establishDuration = time.Since(tunnel.adjustedEstablishStartTime)
  251. tunnel.establishedTime = time.Now()
  252. // Use the Background context instead of the controller run context, as tunnels
  253. // are terminated when the controller calls tunnel.Close.
  254. tunnel.operateCtx, tunnel.stopOperate = context.WithCancel(context.Background())
  255. tunnel.operateWaitGroup = new(sync.WaitGroup)
  256. // Spawn the operateTunnel goroutine, which monitors the tunnel and handles periodic
  257. // stats updates.
  258. tunnel.operateWaitGroup.Add(1)
  259. go tunnel.operateTunnel(tunnelOwner)
  260. tunnel.mutex.Unlock()
  261. return nil
  262. }
  263. // Close stops operating the tunnel and closes the underlying connection.
  264. // Supports multiple and/or concurrent calls to Close().
  265. // When isDiscarded is set, operateTunnel will not attempt to send final
  266. // status requests.
  267. func (tunnel *Tunnel) Close(isDiscarded bool) {
  268. tunnel.mutex.Lock()
  269. tunnel.isDiscarded = isDiscarded
  270. isActivated := tunnel.isActivated
  271. isClosed := tunnel.isClosed
  272. tunnel.isClosed = true
  273. tunnel.mutex.Unlock()
  274. if !isClosed {
  275. // Signal operateTunnel to stop before closing the tunnel -- this
  276. // allows a final status request to be made in the case of an orderly
  277. // shutdown.
  278. // A timer is set, so if operateTunnel takes too long to stop, the
  279. // tunnel is closed, which will interrupt any slow final status request.
  280. if isActivated {
  281. timeout := tunnel.getCustomParameters().Duration(
  282. parameters.TunnelOperateShutdownTimeout)
  283. afterFunc := time.AfterFunc(
  284. timeout,
  285. func() { tunnel.conn.Close() })
  286. tunnel.stopOperate()
  287. tunnel.operateWaitGroup.Wait()
  288. afterFunc.Stop()
  289. }
  290. tunnel.sshClient.Close()
  291. // tunnel.conn.Close() may get called multiple times, which is allowed.
  292. tunnel.conn.Close()
  293. err := tunnel.sshClient.Wait()
  294. if err != nil {
  295. NoticeWarning("close tunnel ssh error: %s", err)
  296. }
  297. }
  298. // Log burst metrics now that the BurstMonitoredConn is closed.
  299. // Metrics will be empty when burst monitoring is disabled.
  300. if !isDiscarded && isActivated {
  301. burstMetrics := tunnel.conn.GetMetrics(tunnel.monitoringStartTime)
  302. if len(burstMetrics) > 0 {
  303. NoticeBursts(
  304. tunnel.dialParams.ServerEntry.GetDiagnosticID(),
  305. burstMetrics)
  306. }
  307. }
  308. }
  309. // SetInFlightConnectedRequest checks if a connected request can begin and
  310. // sets the channel used to signal that the request is complete.
  311. //
  312. // The caller must not initiate a connected request when
  313. // SetInFlightConnectedRequest returns false. When SetInFlightConnectedRequest
  314. // returns true, the caller must call SetInFlightConnectedRequest(nil) when
  315. // the connected request completes.
  316. func (tunnel *Tunnel) SetInFlightConnectedRequest(requestSignal chan struct{}) bool {
  317. tunnel.mutex.Lock()
  318. defer tunnel.mutex.Unlock()
  319. // If already closing, don't start a connected request: the
  320. // TunnelOperateShutdownTimeout period may be nearly expired.
  321. if tunnel.isClosed {
  322. return false
  323. }
  324. if requestSignal == nil {
  325. // Not already in-flight (not expected)
  326. if tunnel.inFlightConnectedRequestSignal == nil {
  327. return false
  328. }
  329. } else {
  330. // Already in-flight (not expected)
  331. if tunnel.inFlightConnectedRequestSignal != nil {
  332. return false
  333. }
  334. }
  335. tunnel.inFlightConnectedRequestSignal = requestSignal
  336. return true
  337. }
  338. // AwaitInFlightConnectedRequest waits for the signal that any in-flight
  339. // connected request is complete.
  340. //
  341. // AwaitInFlightConnectedRequest may block until the connected request is
  342. // aborted by terminating the tunnel.
  343. func (tunnel *Tunnel) AwaitInFlightConnectedRequest() {
  344. tunnel.mutex.Lock()
  345. requestSignal := tunnel.inFlightConnectedRequestSignal
  346. tunnel.mutex.Unlock()
  347. if requestSignal != nil {
  348. <-requestSignal
  349. }
  350. }
  351. // IsActivated returns the tunnel's activated flag.
  352. func (tunnel *Tunnel) IsActivated() bool {
  353. tunnel.mutex.Lock()
  354. defer tunnel.mutex.Unlock()
  355. return tunnel.isActivated
  356. }
  357. // IsDiscarded returns the tunnel's discarded flag.
  358. func (tunnel *Tunnel) IsDiscarded() bool {
  359. tunnel.mutex.Lock()
  360. defer tunnel.mutex.Unlock()
  361. return tunnel.isDiscarded
  362. }
  363. // SendAPIRequest sends an API request as an SSH request through the tunnel.
  364. // This function blocks awaiting a response. Only one request may be in-flight
  365. // at once; a concurrent SendAPIRequest will block until an active request
  366. // receives its response (or the SSH connection is terminated).
  367. func (tunnel *Tunnel) SendAPIRequest(
  368. name string, requestPayload []byte) ([]byte, error) {
  369. ok, responsePayload, err := tunnel.sshClient.Conn.SendRequest(
  370. name, true, requestPayload)
  371. if err != nil {
  372. return nil, errors.Trace(err)
  373. }
  374. if !ok {
  375. return nil, errors.TraceNew("API request rejected")
  376. }
  377. return responsePayload, nil
  378. }
  379. // DialTCPChannel establishes a TCP port forward connection through the
  380. // tunnel.
  381. //
  382. // When split tunnel mode is enabled, and unless alwaysTunneled is set, the
  383. // server may reject the port forward and indicate that the client is to make
  384. // direct, untunneled connection. In this case, the bool return value is true
  385. // and net.Conn and error are nil.
  386. //
  387. // downstreamConn is an optional parameter which specifies a connection to be
  388. // explicitly closed when the dialed connection is closed.
  389. func (tunnel *Tunnel) DialTCPChannel(
  390. remoteAddr string,
  391. alwaysTunneled bool,
  392. downstreamConn net.Conn) (net.Conn, bool, error) {
  393. channelType := "direct-tcpip"
  394. if alwaysTunneled && tunnel.config.IsSplitTunnelEnabled() {
  395. // This channel type is only necessary in split tunnel mode.
  396. channelType = protocol.TCP_PORT_FORWARD_NO_SPLIT_TUNNEL_TYPE
  397. }
  398. channel, err := tunnel.dialChannel(channelType, remoteAddr)
  399. if err != nil {
  400. if isSplitTunnelRejectReason(err) {
  401. return nil, true, nil
  402. }
  403. return nil, false, errors.Trace(err)
  404. }
  405. netConn, ok := channel.(net.Conn)
  406. if !ok {
  407. return nil, false, errors.Tracef("unexpected channel type: %T", channel)
  408. }
  409. conn := &TunneledConn{
  410. Conn: netConn,
  411. tunnel: tunnel,
  412. downstreamConn: downstreamConn}
  413. return tunnel.wrapWithTransferStats(conn), false, nil
  414. }
  415. func (tunnel *Tunnel) DialPacketTunnelChannel() (net.Conn, error) {
  416. channel, err := tunnel.dialChannel(protocol.PACKET_TUNNEL_CHANNEL_TYPE, "")
  417. if err != nil {
  418. return nil, errors.Trace(err)
  419. }
  420. sshChannel, ok := channel.(ssh.Channel)
  421. if !ok {
  422. return nil, errors.Tracef("unexpected channel type: %T", channel)
  423. }
  424. NoticeInfo("DialPacketTunnelChannel: established channel")
  425. conn := newChannelConn(sshChannel)
  426. // wrapWithTransferStats will track bytes transferred for the
  427. // packet tunnel. It will count packet overhead (TCP/UDP/IP headers).
  428. //
  429. // Since the data in the channel is not HTTP or TLS, no domain bytes
  430. // counting is expected.
  431. //
  432. // transferstats are also used to determine that there's been recent
  433. // activity and skip periodic SSH keep alives; see Tunnel.operateTunnel.
  434. return tunnel.wrapWithTransferStats(conn), nil
  435. }
  436. func (tunnel *Tunnel) dialChannel(channelType, remoteAddr string) (interface{}, error) {
  437. if !tunnel.IsActivated() {
  438. return nil, errors.TraceNew("tunnel is not activated")
  439. }
  440. // Note: there is no dial context since SSH port forward dials cannot
  441. // be interrupted directly. Closing the tunnel will interrupt the dials.
  442. // A timeout is set to unblock this function, but the goroutine may
  443. // not exit until the tunnel is closed.
  444. type channelDialResult struct {
  445. channel interface{}
  446. err error
  447. }
  448. // Use a buffer of 1 as there are two senders and only one guaranteed receive.
  449. results := make(chan *channelDialResult, 1)
  450. afterFunc := time.AfterFunc(
  451. tunnel.getCustomParameters().Duration(
  452. parameters.TunnelPortForwardDialTimeout),
  453. func() {
  454. results <- &channelDialResult{
  455. nil, errors.Tracef("channel dial timeout: %s", channelType)}
  456. })
  457. defer afterFunc.Stop()
  458. go func() {
  459. result := new(channelDialResult)
  460. switch channelType {
  461. case "direct-tcpip", protocol.TCP_PORT_FORWARD_NO_SPLIT_TUNNEL_TYPE:
  462. // The protocol.TCP_PORT_FORWARD_NO_SPLIT_TUNNEL_TYPE is the same as
  463. // "direct-tcpip", except split tunnel channel rejections are disallowed
  464. // even when split tunnel mode is enabled.
  465. result.channel, result.err =
  466. tunnel.sshClient.Dial(channelType, remoteAddr)
  467. default:
  468. var sshRequests <-chan *ssh.Request
  469. result.channel, sshRequests, result.err =
  470. tunnel.sshClient.OpenChannel(channelType, nil)
  471. if result.err == nil {
  472. go ssh.DiscardRequests(sshRequests)
  473. }
  474. }
  475. if result.err != nil {
  476. result.err = errors.Trace(result.err)
  477. }
  478. results <- result
  479. }()
  480. result := <-results
  481. if result.err != nil {
  482. if !isSplitTunnelRejectReason(result.err) {
  483. select {
  484. case tunnel.signalPortForwardFailure <- struct{}{}:
  485. default:
  486. }
  487. }
  488. return nil, errors.Trace(result.err)
  489. }
  490. return result.channel, nil
  491. }
  492. func isSplitTunnelRejectReason(err error) bool {
  493. var openChannelErr *ssh.OpenChannelError
  494. if std_errors.As(err, &openChannelErr) {
  495. return openChannelErr.Reason ==
  496. ssh.RejectionReason(protocol.CHANNEL_REJECT_REASON_SPLIT_TUNNEL)
  497. }
  498. return false
  499. }
  500. func (tunnel *Tunnel) wrapWithTransferStats(conn net.Conn) net.Conn {
  501. // Tunnel does not have a serverContext when DisableApi is set. We still use
  502. // transferstats.Conn to count bytes transferred for monitoring tunnel
  503. // quality.
  504. var regexps *transferstats.Regexps
  505. if tunnel.serverContext != nil {
  506. regexps = tunnel.serverContext.StatsRegexps()
  507. }
  508. return transferstats.NewConn(
  509. conn, tunnel.dialParams.ServerEntry.IpAddress, regexps)
  510. }
  511. // SignalComponentFailure notifies the tunnel that an associated component has failed.
  512. // This will terminate the tunnel.
  513. func (tunnel *Tunnel) SignalComponentFailure() {
  514. NoticeWarning("tunnel received component failure signal")
  515. tunnel.Close(false)
  516. }
  517. // TunneledConn implements net.Conn and wraps a port forward connection.
  518. // It is used to hook into Read and Write to observe I/O errors and
  519. // report these errors back to the tunnel monitor as port forward failures.
  520. // TunneledConn optionally tracks a peer connection to be explicitly closed
  521. // when the TunneledConn is closed.
  522. type TunneledConn struct {
  523. net.Conn
  524. tunnel *Tunnel
  525. downstreamConn net.Conn
  526. }
  527. func (conn *TunneledConn) Read(buffer []byte) (n int, err error) {
  528. n, err = conn.Conn.Read(buffer)
  529. if err != nil && err != io.EOF {
  530. // Report new failure. Won't block; assumes the receiver
  531. // has a sufficient buffer for the threshold number of reports.
  532. // TODO: conditional on type of error or error message?
  533. select {
  534. case conn.tunnel.signalPortForwardFailure <- struct{}{}:
  535. default:
  536. }
  537. }
  538. return
  539. }
  540. func (conn *TunneledConn) Write(buffer []byte) (n int, err error) {
  541. n, err = conn.Conn.Write(buffer)
  542. if err != nil && err != io.EOF {
  543. // Same as TunneledConn.Read()
  544. select {
  545. case conn.tunnel.signalPortForwardFailure <- struct{}{}:
  546. default:
  547. }
  548. }
  549. return
  550. }
  551. func (conn *TunneledConn) Close() error {
  552. if conn.downstreamConn != nil {
  553. conn.downstreamConn.Close()
  554. }
  555. return conn.Conn.Close()
  556. }
  557. type dialResult struct {
  558. dialConn net.Conn
  559. monitoringStartTime time.Time
  560. monitoredConn *common.BurstMonitoredConn
  561. sshClient *ssh.Client
  562. sshRequests <-chan *ssh.Request
  563. livenessTestMetrics *livenessTestMetrics
  564. extraFailureAction func()
  565. }
  566. // dialTunnel is a helper that builds the transport layers and establishes the
  567. // SSH connection. When additional dial configuration is used, dial metrics
  568. // are recorded and returned.
  569. func dialTunnel(
  570. ctx context.Context,
  571. config *Config,
  572. dialParams *DialParameters) (_ *dialResult, retErr error) {
  573. // Return immediately when overall context is canceled or timed-out. This
  574. // avoids notice noise.
  575. err := ctx.Err()
  576. if err != nil {
  577. return nil, errors.Trace(err)
  578. }
  579. p := getCustomParameters(config, dialParams)
  580. timeout := p.Duration(parameters.TunnelConnectTimeout)
  581. rateLimits := p.RateLimits(parameters.TunnelRateLimits)
  582. obfuscatedSSHMinPadding := p.Int(parameters.ObfuscatedSSHMinPadding)
  583. obfuscatedSSHMaxPadding := p.Int(parameters.ObfuscatedSSHMaxPadding)
  584. livenessTestMinUpstreamBytes := p.Int(parameters.LivenessTestMinUpstreamBytes)
  585. livenessTestMaxUpstreamBytes := p.Int(parameters.LivenessTestMaxUpstreamBytes)
  586. livenessTestMinDownstreamBytes := p.Int(parameters.LivenessTestMinDownstreamBytes)
  587. livenessTestMaxDownstreamBytes := p.Int(parameters.LivenessTestMaxDownstreamBytes)
  588. burstUpstreamTargetBytes := int64(p.Int(parameters.ClientBurstUpstreamTargetBytes))
  589. burstUpstreamDeadline := p.Duration(parameters.ClientBurstUpstreamDeadline)
  590. burstDownstreamTargetBytes := int64(p.Int(parameters.ClientBurstDownstreamTargetBytes))
  591. burstDownstreamDeadline := p.Duration(parameters.ClientBurstDownstreamDeadline)
  592. p.Close()
  593. // Ensure that, unless the base context is cancelled, any replayed dial
  594. // parameters are cleared, no longer to be retried, if the tunnel fails to
  595. // connect.
  596. //
  597. // Limitation: dials that fail to connect due to the server being in a
  598. // load-limiting state are not distinguished and excepted from this
  599. // logic.
  600. dialSucceeded := false
  601. baseCtx := ctx
  602. var failedTunnelLivenessTestMetrics *livenessTestMetrics
  603. var extraFailureAction func()
  604. defer func() {
  605. if !dialSucceeded && baseCtx.Err() != context.Canceled {
  606. dialParams.Failed(config)
  607. if extraFailureAction != nil {
  608. extraFailureAction()
  609. }
  610. if retErr != nil {
  611. _ = RecordFailedTunnelStat(
  612. config,
  613. dialParams,
  614. failedTunnelLivenessTestMetrics,
  615. -1,
  616. -1,
  617. retErr)
  618. }
  619. }
  620. }()
  621. var cancelFunc context.CancelFunc
  622. ctx, cancelFunc = context.WithTimeout(ctx, timeout)
  623. defer cancelFunc()
  624. // DialDuration is the elapsed time for both successful and failed tunnel
  625. // dials. For successful tunnels, it includes any the network protocol
  626. // handshake(s), obfuscation protocol handshake(s), SSH handshake, and
  627. // liveness test, when performed.
  628. //
  629. // Note: ensure DialDuration is set before calling any function which logs
  630. // dial_duration.
  631. startDialTime := time.Now()
  632. defer func() {
  633. dialParams.DialDuration = time.Since(startDialTime)
  634. }()
  635. // Note: dialParams.MeekResolvedIPAddress isn't set until the dial begins,
  636. // so it will always be blank in NoticeConnectingServer.
  637. NoticeConnectingServer(dialParams)
  638. // Create the base transport: meek or direct connection
  639. var dialConn net.Conn
  640. if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
  641. dialConn, err = DialMeek(
  642. ctx,
  643. dialParams.GetMeekConfig(),
  644. dialParams.GetDialConfig())
  645. if err != nil {
  646. return nil, errors.Trace(err)
  647. }
  648. } else if protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
  649. packetConn, remoteAddr, err := NewUDPConn(
  650. ctx,
  651. dialParams.DirectDialAddress,
  652. dialParams.GetDialConfig())
  653. if err != nil {
  654. return nil, errors.Trace(err)
  655. }
  656. dialConn, err = quic.Dial(
  657. ctx,
  658. packetConn,
  659. remoteAddr,
  660. dialParams.QUICDialSNIAddress,
  661. dialParams.QUICVersion,
  662. dialParams.QUICClientHelloSeed,
  663. dialParams.ServerEntry.SshObfuscatedKey,
  664. dialParams.ObfuscatedQUICPaddingSeed,
  665. dialParams.QUICDisablePathMTUDiscovery)
  666. if err != nil {
  667. return nil, errors.Trace(err)
  668. }
  669. } else if protocol.TunnelProtocolUsesTapDance(dialParams.TunnelProtocol) {
  670. dialConn, err = refraction.DialTapDance(
  671. ctx,
  672. config.EmitRefractionNetworkingLogs,
  673. config.GetPsiphonDataDirectory(),
  674. NewNetDialer(dialParams.GetDialConfig()),
  675. dialParams.DirectDialAddress)
  676. if err != nil {
  677. return nil, errors.Trace(err)
  678. }
  679. } else if protocol.TunnelProtocolUsesConjure(dialParams.TunnelProtocol) {
  680. // Specify a cache key with a scope that ensures that:
  681. //
  682. // (a) cached registrations aren't used across different networks, as a
  683. // registration requires the client's public IP to match the value at time
  684. // of registration;
  685. //
  686. // (b) cached registrations are associated with specific Psiphon server
  687. // candidates, to ensure that replay will use the same phantom IP(s).
  688. //
  689. // This scheme allows for reuse of cached registrations on network A when a
  690. // client roams from network A to network B and back to network A.
  691. //
  692. // Using the network ID as a proxy for client public IP address is a
  693. // heurisitic: it's possible that a clients public IP address changes
  694. // without the network ID changing, and it's not guaranteed that the client
  695. // will be assigned the original public IP on network A; so there's some
  696. // chance the registration cannot be reused.
  697. diagnosticID := dialParams.ServerEntry.GetDiagnosticID()
  698. cacheKey := dialParams.NetworkID + "-" + diagnosticID
  699. conjureConfig := &refraction.ConjureConfig{
  700. RegistrationCacheTTL: dialParams.ConjureCachedRegistrationTTL,
  701. RegistrationCacheKey: cacheKey,
  702. Transport: dialParams.ConjureTransport,
  703. DiagnosticID: diagnosticID,
  704. Logger: NoticeCommonLogger(),
  705. }
  706. // Set extraFailureAction, which is invoked whenever the tunnel fails (i.e.,
  707. // where RecordFailedTunnelStat is invoked). The action will remove any
  708. // cached registration. When refraction.DialConjure succeeds, the underlying
  709. // registration is cached. After refraction.DialConjure returns, it no
  710. // longer modifies the cached state of that registration, assuming that it
  711. // remains valid and effective. However adversarial impact on a given
  712. // phantom IP may not become evident until after the initial TCP connection
  713. // establishment and handshake performed by refraction.DialConjure. For
  714. // example, it may be that the phantom dial is targeted for severe
  715. // throttling which begins or is only evident later in the flow. Scheduling
  716. // a call to DeleteCachedConjureRegistration allows us to invalidate the
  717. // cached registration for a tunnel that fails later in its lifecycle.
  718. //
  719. // Note that extraFailureAction will retain a reference to conjureConfig for
  720. // the lifetime of the tunnel.
  721. extraFailureAction = func() {
  722. refraction.DeleteCachedConjureRegistration(conjureConfig)
  723. }
  724. if dialParams.ConjureAPIRegistration {
  725. // Use MeekConn to domain front Conjure API registration.
  726. //
  727. // ConjureAPIRegistrarFrontingSpecs are applied via
  728. // dialParams.GetMeekConfig, and will be subject to replay.
  729. //
  730. // Since DialMeek will create a TLS connection immediately, and a cached
  731. // registration may be used, we will delay initializing the MeekConn-based
  732. // RoundTripper until we know it's needed. This is implemented by passing
  733. // in a RoundTripper that establishes a MeekConn when RoundTrip is called.
  734. //
  735. // In refraction.dial we configure 0 retries for API registration requests,
  736. // assuming it's better to let another Psiphon candidate retry, with new
  737. // domaing fronting parameters. As such, we expect only one round trip call
  738. // per NewHTTPRoundTripper, so, in practise, there's no performance penalty
  739. // from establishing a new MeekConn per round trip.
  740. //
  741. // Performing the full DialMeek/RoundTrip operation here allows us to call
  742. // MeekConn.Close and ensure all resources are immediately cleaned up.
  743. roundTrip := func(request *http.Request) (*http.Response, error) {
  744. conn, err := DialMeek(
  745. ctx, dialParams.GetMeekConfig(), dialParams.GetDialConfig())
  746. if err != nil {
  747. return nil, errors.Trace(err)
  748. }
  749. defer conn.Close()
  750. response, err := conn.RoundTrip(request)
  751. if err != nil {
  752. return nil, errors.Trace(err)
  753. }
  754. // Read the response into a buffer and close the response
  755. // body, ensuring that MeekConn.Close closes all idle connections.
  756. //
  757. // Alternatively, we could Clone the request to set
  758. // http.Request.Close and avoid keeping any idle connection
  759. // open after the response body is read by gotapdance. Since
  760. // the response body is small and since gotapdance does not
  761. // stream the response body, we're taking this approach which
  762. // ensures cleanup.
  763. body, err := ioutil.ReadAll(response.Body)
  764. _ = response.Body.Close()
  765. if err != nil {
  766. return nil, errors.Trace(err)
  767. }
  768. response.Body = io.NopCloser(bytes.NewReader(body))
  769. return response, nil
  770. }
  771. conjureConfig.APIRegistrarHTTPClient = &http.Client{
  772. Transport: common.NewHTTPRoundTripper(roundTrip),
  773. }
  774. conjureConfig.APIRegistrarBidirectionalURL =
  775. dialParams.ConjureAPIRegistrarBidirectionalURL
  776. conjureConfig.APIRegistrarDelay = dialParams.ConjureAPIRegistrarDelay
  777. } else if dialParams.ConjureDecoyRegistration {
  778. // The Conjure "phantom" connection is compatible with fragmentation, but
  779. // the decoy registrar connection, like Tapdance, is not, so force it off.
  780. // Any tunnel fragmentation metrics will refer to the "phantom" connection
  781. // only.
  782. conjureConfig.DecoyRegistrarDialer = NewNetDialer(
  783. dialParams.GetDialConfig().WithoutFragmentor())
  784. conjureConfig.DecoyRegistrarWidth = dialParams.ConjureDecoyRegistrarWidth
  785. conjureConfig.DecoyRegistrarDelay = dialParams.ConjureDecoyRegistrarDelay
  786. }
  787. dialConn, err = refraction.DialConjure(
  788. ctx,
  789. config.EmitRefractionNetworkingLogs,
  790. config.GetPsiphonDataDirectory(),
  791. NewNetDialer(dialParams.GetDialConfig()),
  792. dialParams.DirectDialAddress,
  793. conjureConfig)
  794. if err != nil {
  795. return nil, errors.Trace(err)
  796. }
  797. } else {
  798. dialConn, err = DialTCP(
  799. ctx,
  800. dialParams.DirectDialAddress,
  801. dialParams.GetDialConfig())
  802. if err != nil {
  803. return nil, errors.Trace(err)
  804. }
  805. }
  806. // Some conns report additional metrics. fragmentor.Conns report
  807. // fragmentor configs.
  808. if metricsSource, ok := dialConn.(common.MetricsSource); ok {
  809. dialParams.DialConnMetrics = metricsSource
  810. }
  811. if noticeMetricsSource, ok := dialConn.(common.NoticeMetricsSource); ok {
  812. dialParams.DialConnNoticeMetrics = noticeMetricsSource
  813. }
  814. // If dialConn is not a Closer, tunnel failure detection may be slower
  815. if _, ok := dialConn.(common.Closer); !ok {
  816. NoticeWarning("tunnel.dialTunnel: dialConn is not a Closer")
  817. }
  818. cleanupConn := dialConn
  819. defer func() {
  820. // Cleanup on error
  821. if cleanupConn != nil {
  822. cleanupConn.Close()
  823. }
  824. }()
  825. monitoringStartTime := time.Now()
  826. monitoredConn := common.NewBurstMonitoredConn(
  827. dialConn,
  828. false,
  829. burstUpstreamTargetBytes, burstUpstreamDeadline,
  830. burstDownstreamTargetBytes, burstDownstreamDeadline)
  831. // Apply throttling (if configured)
  832. throttledConn := common.NewThrottledConn(
  833. monitoredConn,
  834. rateLimits)
  835. // Add obfuscated SSH layer
  836. var sshConn net.Conn = throttledConn
  837. if protocol.TunnelProtocolUsesObfuscatedSSH(dialParams.TunnelProtocol) {
  838. obfuscatedSSHConn, err := obfuscator.NewClientObfuscatedSSHConn(
  839. throttledConn,
  840. dialParams.ServerEntry.SshObfuscatedKey,
  841. dialParams.ObfuscatorPaddingSeed,
  842. &obfuscatedSSHMinPadding,
  843. &obfuscatedSSHMaxPadding)
  844. if err != nil {
  845. return nil, errors.Trace(err)
  846. }
  847. sshConn = obfuscatedSSHConn
  848. dialParams.ObfuscatedSSHConnMetrics = obfuscatedSSHConn
  849. }
  850. // Now establish the SSH session over the conn transport
  851. expectedPublicKey, err := base64.StdEncoding.DecodeString(
  852. dialParams.ServerEntry.SshHostKey)
  853. if err != nil {
  854. return nil, errors.Trace(err)
  855. }
  856. sshCertChecker := &ssh.CertChecker{
  857. IsHostAuthority: func(auth ssh.PublicKey, address string) bool {
  858. // Psiphon servers do not currently use SSH certificates. This CertChecker
  859. // code path may still be hit if a client attempts to connect using an
  860. // obsolete server entry.
  861. return false
  862. },
  863. HostKeyFallback: func(addr string, remote net.Addr, publicKey ssh.PublicKey) error {
  864. if !bytes.Equal(expectedPublicKey, publicKey.Marshal()) {
  865. return errors.TraceNew("unexpected host public key")
  866. }
  867. return nil
  868. },
  869. }
  870. sshPasswordPayload := &protocol.SSHPasswordPayload{
  871. SessionId: config.SessionID,
  872. SshPassword: dialParams.ServerEntry.SshPassword,
  873. ClientCapabilities: []string{protocol.CLIENT_CAPABILITY_SERVER_REQUESTS},
  874. }
  875. payload, err := json.Marshal(sshPasswordPayload)
  876. if err != nil {
  877. return nil, errors.Trace(err)
  878. }
  879. sshClientConfig := &ssh.ClientConfig{
  880. User: dialParams.ServerEntry.SshUsername,
  881. Auth: []ssh.AuthMethod{
  882. ssh.Password(string(payload)),
  883. },
  884. HostKeyCallback: sshCertChecker.CheckHostKey,
  885. ClientVersion: dialParams.SSHClientVersion,
  886. }
  887. sshClientConfig.KEXPRNGSeed = dialParams.SSHKEXSeed
  888. if protocol.TunnelProtocolUsesObfuscatedSSH(dialParams.TunnelProtocol) {
  889. if config.ObfuscatedSSHAlgorithms != nil {
  890. sshClientConfig.KeyExchanges = []string{config.ObfuscatedSSHAlgorithms[0]}
  891. sshClientConfig.Ciphers = []string{config.ObfuscatedSSHAlgorithms[1]}
  892. sshClientConfig.MACs = []string{config.ObfuscatedSSHAlgorithms[2]}
  893. sshClientConfig.HostKeyAlgorithms = []string{config.ObfuscatedSSHAlgorithms[3]}
  894. } else {
  895. // With Encrypt-then-MAC hash algorithms, packet length is
  896. // transmitted in plaintext, which aids in traffic analysis.
  897. //
  898. // TUNNEL_PROTOCOL_SSH is excepted since its KEX appears in plaintext,
  899. // and the protocol is intended to look like SSH on the wire.
  900. sshClientConfig.NoEncryptThenMACHash = true
  901. }
  902. } else {
  903. // For TUNNEL_PROTOCOL_SSH only, the server is expected to randomize
  904. // its KEX; setting PeerKEXPRNGSeed will ensure successful negotiation
  905. // betweem two randomized KEXes.
  906. if dialParams.ServerEntry.SshObfuscatedKey != "" {
  907. sshClientConfig.PeerKEXPRNGSeed, err = protocol.DeriveSSHServerKEXPRNGSeed(
  908. dialParams.ServerEntry.SshObfuscatedKey)
  909. if err != nil {
  910. return nil, errors.Trace(err)
  911. }
  912. }
  913. }
  914. // The ssh session establishment (via ssh.NewClientConn) is wrapped
  915. // in a timeout to ensure it won't hang. We've encountered firewalls
  916. // that allow the TCP handshake to complete but then send a RST to the
  917. // server-side and nothing to the client-side, and if that happens
  918. // while ssh.NewClientConn is reading, it may wait forever. The timeout
  919. // closes the conn, which interrupts it.
  920. // Note: TCP handshake timeouts are provided by TCPConn, and session
  921. // timeouts *after* ssh establishment are provided by the ssh keep alive
  922. // in operate tunnel.
  923. type sshNewClientResult struct {
  924. sshClient *ssh.Client
  925. sshRequests <-chan *ssh.Request
  926. livenessTestMetrics *livenessTestMetrics
  927. err error
  928. }
  929. resultChannel := make(chan sshNewClientResult)
  930. // Call NewClientConn in a goroutine, as it blocks on SSH handshake network
  931. // operations, and would block canceling or shutdown. If the parent context
  932. // is canceled, close the net.Conn underlying SSH, which will interrupt the
  933. // SSH handshake that may be blocking NewClientConn.
  934. go func() {
  935. // The following is adapted from ssh.Dial(), here using a custom conn
  936. // The sshAddress is passed through to host key verification callbacks; we don't use it.
  937. sshAddress := ""
  938. sshClientConn, sshChannels, sshRequests, err := ssh.NewClientConn(
  939. sshConn, sshAddress, sshClientConfig)
  940. var sshClient *ssh.Client
  941. var metrics *livenessTestMetrics
  942. if err == nil {
  943. // sshRequests is handled by operateTunnel.
  944. // ssh.NewClient also expects to handle the sshRequests
  945. // value from ssh.NewClientConn and will spawn a goroutine
  946. // to handle the <-chan *ssh.Request, so we must provide
  947. // a closed channel to ensure that goroutine halts instead
  948. // of hanging on a nil channel.
  949. noRequests := make(chan *ssh.Request)
  950. close(noRequests)
  951. sshClient = ssh.NewClient(sshClientConn, sshChannels, noRequests)
  952. if livenessTestMaxUpstreamBytes > 0 || livenessTestMaxDownstreamBytes > 0 {
  953. // When configured, perform a liveness test which sends and
  954. // receives bytes through the tunnel to ensure the tunnel had
  955. // not been blocked upon or shortly after connecting. This
  956. // test is performed concurrently for each establishment
  957. // candidate before selecting a successful tunnel.
  958. //
  959. // Note that the liveness test is subject to the
  960. // TunnelConnectTimeout, which should be adjusted
  961. // accordinging.
  962. metrics, err = performLivenessTest(
  963. sshClient,
  964. livenessTestMinUpstreamBytes, livenessTestMaxUpstreamBytes,
  965. livenessTestMinDownstreamBytes, livenessTestMaxDownstreamBytes,
  966. dialParams.LivenessTestSeed)
  967. // Skip notice when cancelling.
  968. if baseCtx.Err() == nil {
  969. NoticeLivenessTest(
  970. dialParams.ServerEntry.GetDiagnosticID(), metrics, err == nil)
  971. }
  972. }
  973. }
  974. resultChannel <- sshNewClientResult{sshClient, sshRequests, metrics, err}
  975. }()
  976. var result sshNewClientResult
  977. select {
  978. case result = <-resultChannel:
  979. case <-ctx.Done():
  980. // Interrupt the goroutine and capture its error context to
  981. // distinguish point of failure.
  982. err := ctx.Err()
  983. sshConn.Close()
  984. result = <-resultChannel
  985. if result.err != nil {
  986. result.err = fmt.Errorf("%s: %s", err, result.err)
  987. } else {
  988. result.err = err
  989. }
  990. }
  991. if result.err != nil {
  992. failedTunnelLivenessTestMetrics = result.livenessTestMetrics
  993. return nil, errors.Trace(result.err)
  994. }
  995. dialSucceeded = true
  996. NoticeConnectedServer(dialParams)
  997. cleanupConn = nil
  998. // Invoke DNS cache extension (if enabled in the resolver) now that the
  999. // tunnel is connected and the Psiphon server is authenticated. This
  1000. // demonstrates that any domain name resolved to an endpoint that is or
  1001. // is forwarded to the expected Psiphon server.
  1002. //
  1003. // Limitation: DNS cache extension is not implemented for Refraction
  1004. // Networking protocols. iOS VPN, the primary use case for DNS cache
  1005. // extension, does not enable Refraction Networking.
  1006. if protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) {
  1007. resolver := config.GetResolver()
  1008. if resolver != nil {
  1009. resolver.VerifyCacheExtension(dialParams.MeekFrontingDialAddress)
  1010. }
  1011. }
  1012. // When configured to do so, hold-off on activating this tunnel. This allows
  1013. // some extra time for slower but less resource intensive protocols to
  1014. // establish tunnels. By holding off post-connect, the client has this
  1015. // established tunnel ready to activate in case other protocols fail to
  1016. // establish. This hold-off phase continues to consume one connection worker.
  1017. //
  1018. // The network latency multiplier is not applied to HoldOffTunnelDuration,
  1019. // as the goal is to apply a consistent hold-off range across all tunnel
  1020. // candidates; and this avoids scaling up any delay users experience.
  1021. //
  1022. // The hold-off is applied regardless of whether this is the first tunnel
  1023. // in a session or a reconnection, even to a server affinity candidate,
  1024. // so that the advantage for other protocols persists.
  1025. if dialParams.HoldOffTunnelDuration > 0 {
  1026. NoticeHoldOffTunnel(dialParams.ServerEntry.GetDiagnosticID(), dialParams.HoldOffTunnelDuration)
  1027. common.SleepWithContext(ctx, dialParams.HoldOffTunnelDuration)
  1028. }
  1029. // Note: dialConn may be used to close the underlying network connection
  1030. // but should not be used to perform I/O as that would interfere with SSH
  1031. // (and also bypasses throttling).
  1032. return &dialResult{
  1033. dialConn: dialConn,
  1034. monitoringStartTime: monitoringStartTime,
  1035. monitoredConn: monitoredConn,
  1036. sshClient: result.sshClient,
  1037. sshRequests: result.sshRequests,
  1038. livenessTestMetrics: result.livenessTestMetrics,
  1039. extraFailureAction: extraFailureAction,
  1040. },
  1041. nil
  1042. }
  1043. // Fields are exported for JSON encoding in NoticeLivenessTest.
  1044. type livenessTestMetrics struct {
  1045. Duration string
  1046. UpstreamBytes int
  1047. SentUpstreamBytes int
  1048. DownstreamBytes int
  1049. ReceivedDownstreamBytes int
  1050. }
  1051. func performLivenessTest(
  1052. sshClient *ssh.Client,
  1053. minUpstreamBytes, maxUpstreamBytes int,
  1054. minDownstreamBytes, maxDownstreamBytes int,
  1055. livenessTestPRNGSeed *prng.Seed) (*livenessTestMetrics, error) {
  1056. metrics := new(livenessTestMetrics)
  1057. defer func(startTime time.Time) {
  1058. metrics.Duration = time.Since(startTime).String()
  1059. }(time.Now())
  1060. PRNG := prng.NewPRNGWithSeed(livenessTestPRNGSeed)
  1061. metrics.UpstreamBytes = PRNG.Range(minUpstreamBytes, maxUpstreamBytes)
  1062. metrics.DownstreamBytes = PRNG.Range(minDownstreamBytes, maxDownstreamBytes)
  1063. request := &protocol.RandomStreamRequest{
  1064. UpstreamBytes: metrics.UpstreamBytes,
  1065. DownstreamBytes: metrics.DownstreamBytes,
  1066. }
  1067. extraData, err := json.Marshal(request)
  1068. if err != nil {
  1069. return metrics, errors.Trace(err)
  1070. }
  1071. channel, requests, err := sshClient.OpenChannel(
  1072. protocol.RANDOM_STREAM_CHANNEL_TYPE, extraData)
  1073. if err != nil {
  1074. return metrics, errors.Trace(err)
  1075. }
  1076. defer channel.Close()
  1077. go ssh.DiscardRequests(requests)
  1078. sent := 0
  1079. received := 0
  1080. upstream := new(sync.WaitGroup)
  1081. var errUpstream, errDownstream error
  1082. if metrics.UpstreamBytes > 0 {
  1083. // Process streams concurrently to minimize elapsed time. This also
  1084. // avoids a unidirectional flow burst early in the tunnel lifecycle.
  1085. upstream.Add(1)
  1086. go func() {
  1087. defer upstream.Done()
  1088. // In consideration of memory-constrained environments, use modest-sized copy
  1089. // buffers since many tunnel establishment workers may run the liveness test
  1090. // concurrently.
  1091. var buffer [4096]byte
  1092. n, err := common.CopyNBuffer(channel, rand.Reader, int64(metrics.UpstreamBytes), buffer[:])
  1093. sent = int(n)
  1094. if err != nil {
  1095. errUpstream = errors.Trace(err)
  1096. }
  1097. }()
  1098. }
  1099. if metrics.DownstreamBytes > 0 {
  1100. var buffer [4096]byte
  1101. n, err := common.CopyNBuffer(ioutil.Discard, channel, int64(metrics.DownstreamBytes), buffer[:])
  1102. received = int(n)
  1103. if err != nil {
  1104. errDownstream = errors.Trace(err)
  1105. }
  1106. }
  1107. upstream.Wait()
  1108. metrics.SentUpstreamBytes = sent
  1109. metrics.ReceivedDownstreamBytes = received
  1110. if errUpstream != nil {
  1111. return metrics, errUpstream
  1112. } else if errDownstream != nil {
  1113. return metrics, errDownstream
  1114. }
  1115. return metrics, nil
  1116. }
  1117. // operateTunnel monitors the health of the tunnel and performs
  1118. // periodic work.
  1119. //
  1120. // BytesTransferred and TotalBytesTransferred notices are emitted
  1121. // for live reporting and diagnostics reporting, respectively.
  1122. //
  1123. // Status requests are sent to the Psiphon API to report bytes
  1124. // transferred.
  1125. //
  1126. // Periodic SSH keep alive packets are sent to ensure the underlying
  1127. // TCP connection isn't terminated by NAT, or other network
  1128. // interference -- or test if it has been terminated while the device
  1129. // has been asleep. When a keep alive times out, the tunnel is
  1130. // considered failed.
  1131. //
  1132. // An immediate SSH keep alive "probe" is sent to test the tunnel and
  1133. // server responsiveness when a port forward failure is detected: a
  1134. // failed dial or failed read/write. This keep alive has a shorter
  1135. // timeout.
  1136. //
  1137. // Note that port forward failures may be due to non-failure conditions.
  1138. // For example, when the user inputs an invalid domain name and
  1139. // resolution is done by the ssh server; or trying to connect to a
  1140. // non-white-listed port; and the error message in these cases is not
  1141. // distinguishable from a a true server error (a common error message,
  1142. // "ssh: rejected: administratively prohibited (open failed)", may be
  1143. // returned for these cases but also if the server has run out of
  1144. // ephemeral ports, for example).
  1145. //
  1146. // SSH keep alives are not sent when the tunnel has been recently
  1147. // active (not only does tunnel activity obviate the necessity of a keep
  1148. // alive, testing has shown that keep alives may time out for "busy"
  1149. // tunnels, especially over meek protocol and other high latency
  1150. // conditions).
  1151. //
  1152. // "Recently active" is defined has having received payload bytes. Sent
  1153. // bytes are not considered as testing has shown bytes may appear to
  1154. // send when certain NAT devices have interfered with the tunnel, while
  1155. // no bytes are received. In a pathological case, with DNS implemented
  1156. // as tunneled UDP, a browser may wait excessively for a domain name to
  1157. // resolve, while no new port forward is attempted which would otherwise
  1158. // result in a tunnel failure detection.
  1159. //
  1160. // TODO: change "recently active" to include having received any
  1161. // SSH protocol messages from the server, not just user payload?
  1162. func (tunnel *Tunnel) operateTunnel(tunnelOwner TunnelOwner) {
  1163. defer tunnel.operateWaitGroup.Done()
  1164. now := time.Now()
  1165. lastBytesReceivedTime := now
  1166. lastTotalBytesTransferedTime := now
  1167. totalSent := int64(0)
  1168. totalReceived := int64(0)
  1169. setDialParamsSucceeded := false
  1170. noticeBytesTransferredTicker := time.NewTicker(1 * time.Second)
  1171. defer noticeBytesTransferredTicker.Stop()
  1172. // The next status request and ssh keep alive times are picked at random,
  1173. // from a range, to make the resulting traffic less fingerprintable,
  1174. // Note: not using Tickers since these are not fixed time periods.
  1175. nextStatusRequestPeriod := func() time.Duration {
  1176. p := tunnel.getCustomParameters()
  1177. return prng.Period(
  1178. p.Duration(parameters.PsiphonAPIStatusRequestPeriodMin),
  1179. p.Duration(parameters.PsiphonAPIStatusRequestPeriodMax))
  1180. }
  1181. statsTimer := time.NewTimer(nextStatusRequestPeriod())
  1182. defer statsTimer.Stop()
  1183. // Schedule an almost-immediate status request to deliver any unreported
  1184. // persistent stats.
  1185. unreported := CountUnreportedPersistentStats()
  1186. if unreported > 0 {
  1187. NoticeInfo("Unreported persistent stats: %d", unreported)
  1188. p := tunnel.getCustomParameters()
  1189. statsTimer.Reset(
  1190. prng.Period(
  1191. p.Duration(parameters.PsiphonAPIStatusRequestShortPeriodMin),
  1192. p.Duration(parameters.PsiphonAPIStatusRequestShortPeriodMax)))
  1193. }
  1194. nextSshKeepAlivePeriod := func() time.Duration {
  1195. p := tunnel.getCustomParameters()
  1196. return prng.Period(
  1197. p.Duration(parameters.SSHKeepAlivePeriodMin),
  1198. p.Duration(parameters.SSHKeepAlivePeriodMax))
  1199. }
  1200. // TODO: don't initialize timer when config.DisablePeriodicSshKeepAlive is set
  1201. sshKeepAliveTimer := time.NewTimer(nextSshKeepAlivePeriod())
  1202. if tunnel.config.DisablePeriodicSshKeepAlive {
  1203. sshKeepAliveTimer.Stop()
  1204. } else {
  1205. defer sshKeepAliveTimer.Stop()
  1206. }
  1207. // Perform network requests in separate goroutines so as not to block
  1208. // other operations.
  1209. requestsWaitGroup := new(sync.WaitGroup)
  1210. requestsWaitGroup.Add(1)
  1211. signalStatusRequest := make(chan struct{})
  1212. go func() {
  1213. defer requestsWaitGroup.Done()
  1214. for range signalStatusRequest {
  1215. sendStats(tunnel)
  1216. }
  1217. }()
  1218. requestsWaitGroup.Add(1)
  1219. signalPeriodicSshKeepAlive := make(chan time.Duration)
  1220. sshKeepAliveError := make(chan error, 1)
  1221. go func() {
  1222. defer requestsWaitGroup.Done()
  1223. isFirstPeriodicKeepAlive := true
  1224. for timeout := range signalPeriodicSshKeepAlive {
  1225. bytesUp := atomic.LoadInt64(&totalSent)
  1226. bytesDown := atomic.LoadInt64(&totalReceived)
  1227. err := tunnel.sendSshKeepAlive(
  1228. isFirstPeriodicKeepAlive, false, timeout, bytesUp, bytesDown)
  1229. if err != nil {
  1230. select {
  1231. case sshKeepAliveError <- err:
  1232. default:
  1233. }
  1234. }
  1235. isFirstPeriodicKeepAlive = false
  1236. }
  1237. }()
  1238. // Probe-type SSH keep alives have a distinct send worker and may be sent
  1239. // concurrently, to ensure a long period keep alive timeout doesn't delay
  1240. // failed tunnel detection.
  1241. requestsWaitGroup.Add(1)
  1242. signalProbeSshKeepAlive := make(chan time.Duration)
  1243. go func() {
  1244. defer requestsWaitGroup.Done()
  1245. for timeout := range signalProbeSshKeepAlive {
  1246. bytesUp := atomic.LoadInt64(&totalSent)
  1247. bytesDown := atomic.LoadInt64(&totalReceived)
  1248. err := tunnel.sendSshKeepAlive(
  1249. false, true, timeout, bytesUp, bytesDown)
  1250. if err != nil {
  1251. select {
  1252. case sshKeepAliveError <- err:
  1253. default:
  1254. }
  1255. }
  1256. }
  1257. }()
  1258. shutdown := false
  1259. var err error
  1260. for !shutdown && err == nil {
  1261. select {
  1262. case <-noticeBytesTransferredTicker.C:
  1263. sent, received := transferstats.ReportRecentBytesTransferredForServer(
  1264. tunnel.dialParams.ServerEntry.IpAddress)
  1265. if received > 0 {
  1266. lastBytesReceivedTime = time.Now()
  1267. }
  1268. bytesUp := atomic.AddInt64(&totalSent, sent)
  1269. bytesDown := atomic.AddInt64(&totalReceived, received)
  1270. p := tunnel.getCustomParameters()
  1271. noticePeriod := p.Duration(parameters.TotalBytesTransferredNoticePeriod)
  1272. doEmitMemoryMetrics := p.Bool(parameters.TotalBytesTransferredEmitMemoryMetrics)
  1273. replayTargetUpstreamBytes := p.Int(parameters.ReplayTargetUpstreamBytes)
  1274. replayTargetDownstreamBytes := p.Int(parameters.ReplayTargetDownstreamBytes)
  1275. replayTargetTunnelDuration := p.Duration(parameters.ReplayTargetTunnelDuration)
  1276. if lastTotalBytesTransferedTime.Add(noticePeriod).Before(time.Now()) {
  1277. NoticeTotalBytesTransferred(
  1278. tunnel.dialParams.ServerEntry.GetDiagnosticID(), bytesUp, bytesDown)
  1279. if doEmitMemoryMetrics {
  1280. emitMemoryMetrics()
  1281. }
  1282. lastTotalBytesTransferedTime = time.Now()
  1283. }
  1284. // Only emit the frequent BytesTransferred notice when tunnel is not idle.
  1285. if tunnel.config.EmitBytesTransferred && (sent > 0 || received > 0) {
  1286. NoticeBytesTransferred(
  1287. tunnel.dialParams.ServerEntry.GetDiagnosticID(), sent, received)
  1288. }
  1289. // Once the tunnel has connected, activated, successfully transmitted the
  1290. // targeted number of bytes, and been up for the targeted duration
  1291. // (measured from the end of establishment), store its dial parameters for
  1292. // subsequent replay.
  1293. //
  1294. // Even when target bytes and duration are all 0, the tunnel must remain up
  1295. // for at least 1 second due to use of noticeBytesTransferredTicker; for
  1296. // the same reason the granularity of ReplayTargetTunnelDuration is
  1297. // seconds.
  1298. if !setDialParamsSucceeded &&
  1299. bytesUp >= int64(replayTargetUpstreamBytes) &&
  1300. bytesDown >= int64(replayTargetDownstreamBytes) &&
  1301. time.Since(tunnel.establishedTime) >= replayTargetTunnelDuration {
  1302. tunnel.dialParams.Succeeded()
  1303. setDialParamsSucceeded = true
  1304. }
  1305. case <-statsTimer.C:
  1306. select {
  1307. case signalStatusRequest <- struct{}{}:
  1308. default:
  1309. }
  1310. statsTimer.Reset(nextStatusRequestPeriod())
  1311. case <-sshKeepAliveTimer.C:
  1312. p := tunnel.getCustomParameters()
  1313. inactivePeriod := p.Duration(parameters.SSHKeepAlivePeriodicInactivePeriod)
  1314. if lastBytesReceivedTime.Add(inactivePeriod).Before(time.Now()) {
  1315. timeout := p.Duration(parameters.SSHKeepAlivePeriodicTimeout)
  1316. select {
  1317. case signalPeriodicSshKeepAlive <- timeout:
  1318. default:
  1319. }
  1320. }
  1321. sshKeepAliveTimer.Reset(nextSshKeepAlivePeriod())
  1322. case <-tunnel.signalPortForwardFailure:
  1323. // Note: no mutex on portForwardFailureTotal; only referenced here
  1324. tunnel.totalPortForwardFailures++
  1325. NoticeInfo("port forward failures for %s: %d",
  1326. tunnel.dialParams.ServerEntry.GetDiagnosticID(),
  1327. tunnel.totalPortForwardFailures)
  1328. // If the underlying Conn has closed (meek and other plugin protocols may
  1329. // close themselves in certain error conditions), the tunnel has certainly
  1330. // failed. Otherwise, probe with an SSH keep alive.
  1331. //
  1332. // TODO: the IsClosed case omits the failed tunnel logging and reset
  1333. // actions performed by sendSshKeepAlive. Should self-closing protocols
  1334. // perform these actions themselves?
  1335. if tunnel.conn.IsClosed() {
  1336. err = errors.TraceNew("underlying conn is closed")
  1337. } else {
  1338. p := tunnel.getCustomParameters()
  1339. inactivePeriod := p.Duration(parameters.SSHKeepAliveProbeInactivePeriod)
  1340. if lastBytesReceivedTime.Add(inactivePeriod).Before(time.Now()) {
  1341. timeout := p.Duration(parameters.SSHKeepAliveProbeTimeout)
  1342. select {
  1343. case signalProbeSshKeepAlive <- timeout:
  1344. default:
  1345. }
  1346. }
  1347. if !tunnel.config.DisablePeriodicSshKeepAlive {
  1348. sshKeepAliveTimer.Reset(nextSshKeepAlivePeriod())
  1349. }
  1350. }
  1351. case err = <-sshKeepAliveError:
  1352. case serverRequest := <-tunnel.sshServerRequests:
  1353. if serverRequest != nil {
  1354. err := HandleServerRequest(tunnelOwner, tunnel, serverRequest.Type, serverRequest.Payload)
  1355. if err == nil {
  1356. serverRequest.Reply(true, nil)
  1357. } else {
  1358. NoticeWarning("HandleServerRequest for %s failed: %s", serverRequest.Type, err)
  1359. serverRequest.Reply(false, nil)
  1360. }
  1361. }
  1362. case <-tunnel.operateCtx.Done():
  1363. shutdown = true
  1364. }
  1365. }
  1366. close(signalPeriodicSshKeepAlive)
  1367. close(signalProbeSshKeepAlive)
  1368. close(signalStatusRequest)
  1369. requestsWaitGroup.Wait()
  1370. // Capture bytes transferred since the last noticeBytesTransferredTicker tick
  1371. sent, received := transferstats.ReportRecentBytesTransferredForServer(
  1372. tunnel.dialParams.ServerEntry.IpAddress)
  1373. bytesUp := atomic.AddInt64(&totalSent, sent)
  1374. bytesDown := atomic.AddInt64(&totalReceived, received)
  1375. // Always emit a final NoticeTotalBytesTransferred
  1376. NoticeTotalBytesTransferred(
  1377. tunnel.dialParams.ServerEntry.GetDiagnosticID(), bytesUp, bytesDown)
  1378. if err == nil {
  1379. NoticeInfo("shutdown operate tunnel")
  1380. // This commanded shutdown case is initiated by Tunnel.Close, which will
  1381. // wait up to parameters.TunnelOperateShutdownTimeout to allow the following
  1382. // requests to complete.
  1383. // Send a final status request in order to report any outstanding persistent
  1384. // stats and domain bytes transferred as soon as possible.
  1385. sendStats(tunnel)
  1386. // The controller connectedReporter may have initiated a connected request
  1387. // concurrent to this commanded shutdown. SetInFlightConnectedRequest
  1388. // ensures that a connected request doesn't start after the commanded
  1389. // shutdown. AwaitInFlightConnectedRequest blocks until any in flight
  1390. // request completes or is aborted after TunnelOperateShutdownTimeout.
  1391. //
  1392. // As any connected request is performed by a concurrent goroutine,
  1393. // sendStats is called first and AwaitInFlightConnectedRequest second.
  1394. tunnel.AwaitInFlightConnectedRequest()
  1395. } else {
  1396. NoticeWarning("operate tunnel error for %s: %s",
  1397. tunnel.dialParams.ServerEntry.GetDiagnosticID(), err)
  1398. tunnelOwner.SignalTunnelFailure(tunnel)
  1399. }
  1400. }
  1401. // sendSshKeepAlive is a helper which sends a keepalive@openssh.com request
  1402. // on the specified SSH connections and returns true of the request succeeds
  1403. // within a specified timeout. If the request fails, the associated conn is
  1404. // closed, which will terminate the associated tunnel.
  1405. func (tunnel *Tunnel) sendSshKeepAlive(
  1406. isFirstPeriodicKeepAlive bool,
  1407. isProbeKeepAlive bool,
  1408. timeout time.Duration,
  1409. bytesUp int64,
  1410. bytesDown int64) error {
  1411. p := tunnel.getCustomParameters()
  1412. // Random padding to frustrate fingerprinting.
  1413. request := prng.Padding(
  1414. p.Int(parameters.SSHKeepAlivePaddingMinBytes),
  1415. p.Int(parameters.SSHKeepAlivePaddingMaxBytes))
  1416. speedTestSample := isFirstPeriodicKeepAlive
  1417. if !speedTestSample {
  1418. speedTestSample = p.WeightedCoinFlip(
  1419. parameters.SSHKeepAliveSpeedTestSampleProbability)
  1420. }
  1421. networkConnectivityPollPeriod := p.Duration(
  1422. parameters.SSHKeepAliveNetworkConnectivityPollingPeriod)
  1423. resetOnFailure := p.WeightedCoinFlip(
  1424. parameters.SSHKeepAliveResetOnFailureProbability)
  1425. p.Close()
  1426. // Note: there is no request context since SSH requests cannot be interrupted
  1427. // directly. Closing the tunnel will interrupt the request. A timeout is set
  1428. // to unblock this function, but the goroutine may not exit until the tunnel
  1429. // is closed.
  1430. // Use a buffer of 1 as there are two senders and only one guaranteed receive.
  1431. errChannel := make(chan error, 1)
  1432. afterFunc := time.AfterFunc(timeout, func() {
  1433. errChannel <- errors.TraceNew("timed out")
  1434. })
  1435. defer afterFunc.Stop()
  1436. go func() {
  1437. startTime := time.Now()
  1438. // Note: reading a reply is important for last-received-time tunnel
  1439. // duration calculation.
  1440. requestOk, response, err := tunnel.sshClient.SendRequest(
  1441. "keepalive@openssh.com", true, request)
  1442. elapsedTime := time.Since(startTime)
  1443. errChannel <- err
  1444. success := (err == nil && requestOk)
  1445. if success && isProbeKeepAlive {
  1446. NoticeInfo("Probe SSH keep-alive RTT: %s", elapsedTime)
  1447. }
  1448. // Record the keep alive round trip as a speed test sample. The first
  1449. // periodic keep alive is always recorded, as many tunnels are short-lived
  1450. // and we want to ensure that some data is gathered. Subsequent keep alives
  1451. // are recorded with some configurable probability, which, considering that
  1452. // only the last SpeedTestMaxSampleCount samples are retained, enables
  1453. // tuning the sampling frequency.
  1454. if success && speedTestSample {
  1455. err = tactics.AddSpeedTestSample(
  1456. tunnel.config.GetParameters(),
  1457. GetTacticsStorer(tunnel.config),
  1458. tunnel.config.GetNetworkID(),
  1459. tunnel.dialParams.ServerEntry.Region,
  1460. tunnel.dialParams.TunnelProtocol,
  1461. elapsedTime,
  1462. request,
  1463. response)
  1464. if err != nil {
  1465. NoticeWarning("AddSpeedTestSample failed: %s", errors.Trace(err))
  1466. }
  1467. }
  1468. }()
  1469. // While awaiting the response, poll the network connectivity state. If there
  1470. // is network connectivity, on the same network, for the entire duration of
  1471. // the keep alive request and the request fails, record a failed tunnel
  1472. // event.
  1473. //
  1474. // The network connectivity heuristic is intended to reduce the number of
  1475. // failed tunnels reported due to routine situations such as varying mobile
  1476. // network conditions. The polling may produce false positives if the network
  1477. // goes down and up between polling periods, or changes to a new network and
  1478. // back to the previous network between polling periods.
  1479. //
  1480. // For platforms that don't provide a NetworkConnectivityChecker, it is
  1481. // assumed that there is network connectivity.
  1482. //
  1483. // The approximate number of tunneled bytes successfully sent and received is
  1484. // recorded in the failed tunnel event as a quality indicator.
  1485. ticker := time.NewTicker(networkConnectivityPollPeriod)
  1486. defer ticker.Stop()
  1487. continuousNetworkConnectivity := true
  1488. networkID := tunnel.config.GetNetworkID()
  1489. var err error
  1490. loop:
  1491. for {
  1492. select {
  1493. case err = <-errChannel:
  1494. break loop
  1495. case <-ticker.C:
  1496. connectivityChecker := tunnel.config.NetworkConnectivityChecker
  1497. if (connectivityChecker != nil &&
  1498. connectivityChecker.HasNetworkConnectivity() != 1) ||
  1499. (networkID != tunnel.config.GetNetworkID()) {
  1500. continuousNetworkConnectivity = false
  1501. }
  1502. }
  1503. }
  1504. err = errors.Trace(err)
  1505. if err != nil {
  1506. tunnel.sshClient.Close()
  1507. tunnel.conn.Close()
  1508. // Don't perform log or reset actions when the keep alive may have been
  1509. // interrupted due to shutdown.
  1510. isShutdown := false
  1511. select {
  1512. case <-tunnel.operateCtx.Done():
  1513. isShutdown = true
  1514. default:
  1515. }
  1516. // Ensure that at most one of the two SSH keep alive workers (periodic and
  1517. // probe) perform the log and reset actions.
  1518. wasHandled := atomic.CompareAndSwapInt32(&tunnel.handledSSHKeepAliveFailure, 0, 1)
  1519. if continuousNetworkConnectivity &&
  1520. !isShutdown &&
  1521. !wasHandled {
  1522. _ = RecordFailedTunnelStat(
  1523. tunnel.config,
  1524. tunnel.dialParams,
  1525. tunnel.livenessTestMetrics,
  1526. bytesUp,
  1527. bytesDown,
  1528. err)
  1529. if tunnel.extraFailureAction != nil {
  1530. tunnel.extraFailureAction()
  1531. }
  1532. // SSHKeepAliveResetOnFailureProbability is set when a late-lifecycle
  1533. // impaired protocol attack is suspected. With the given probability, reset
  1534. // server affinity and replay parameters for this server to avoid
  1535. // continuously reconnecting to the server and/or using the same protocol
  1536. // and dial parameters.
  1537. if resetOnFailure {
  1538. NoticeInfo("Delete dial parameters for %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  1539. err := DeleteDialParameters(tunnel.dialParams.ServerEntry.IpAddress, tunnel.dialParams.NetworkID)
  1540. if err != nil {
  1541. NoticeWarning("DeleteDialParameters failed: %s", err)
  1542. }
  1543. NoticeInfo("Delete server affinity for %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  1544. err = DeleteServerEntryAffinity(tunnel.dialParams.ServerEntry.IpAddress)
  1545. if err != nil {
  1546. NoticeWarning("DeleteServerEntryAffinity failed: %s", err)
  1547. }
  1548. }
  1549. }
  1550. }
  1551. return err
  1552. }
  1553. // sendStats is a helper for sending session stats to the server.
  1554. func sendStats(tunnel *Tunnel) bool {
  1555. // Tunnel does not have a serverContext when DisableApi is set
  1556. if tunnel.serverContext == nil {
  1557. return true
  1558. }
  1559. // Skip when tunnel is discarded
  1560. if tunnel.IsDiscarded() {
  1561. return true
  1562. }
  1563. err := tunnel.serverContext.DoStatusRequest(tunnel)
  1564. if err != nil {
  1565. NoticeWarning("DoStatusRequest failed for %s: %s",
  1566. tunnel.dialParams.ServerEntry.GetDiagnosticID(), err)
  1567. }
  1568. return err == nil
  1569. }