tunnel.go 71 KB

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