tunnel.go 76 KB

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