tunnel.go 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  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. "encoding/base64"
  23. "encoding/json"
  24. "errors"
  25. "fmt"
  26. "io"
  27. "net"
  28. "net/url"
  29. "sync"
  30. "sync/atomic"
  31. "time"
  32. "github.com/Psiphon-Inc/crypto/ssh"
  33. "github.com/Psiphon-Inc/goarista/monotime"
  34. regen "github.com/Psiphon-Inc/goregen"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/transferstats"
  38. )
  39. // Tunneler specifies the interface required by components that use a tunnel.
  40. // Components which use this interface may be serviced by a single Tunnel instance,
  41. // or a Controller which manages a pool of tunnels, or any other object which
  42. // implements Tunneler.
  43. // alwaysTunnel indicates that the connection should always be tunneled. If this
  44. // is not set, the connection may be made directly, depending on split tunnel
  45. // classification, when that feature is supported and active.
  46. // downstreamConn is an optional parameter which specifies a connection to be
  47. // explictly closed when the Dialed connection is closed. For instance, this
  48. // is used to close downstreamConn App<->LocalProxy connections when the related
  49. // LocalProxy<->SshPortForward connections close.
  50. type Tunneler interface {
  51. Dial(remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (conn net.Conn, err error)
  52. SignalComponentFailure()
  53. }
  54. // TunnerOwner specifies the interface required by Tunnel to notify its
  55. // owner when it has failed. The owner may, as in the case of the Controller,
  56. // remove the tunnel from its list of active tunnels.
  57. type TunnelOwner interface {
  58. SignalSeededNewSLOK()
  59. SignalTunnelFailure(tunnel *Tunnel)
  60. }
  61. // Tunnel is a connection to a Psiphon server. An established
  62. // tunnel includes a network connection to the specified server
  63. // and an SSH session built on top of that transport.
  64. type Tunnel struct {
  65. mutex *sync.Mutex
  66. config *Config
  67. untunneledDialConfig *DialConfig
  68. isDiscarded bool
  69. isClosed bool
  70. serverEntry *protocol.ServerEntry
  71. serverContext *ServerContext
  72. protocol string
  73. conn *common.ActivityMonitoredConn
  74. sshClient *ssh.Client
  75. sshServerRequests <-chan *ssh.Request
  76. operateWaitGroup *sync.WaitGroup
  77. shutdownOperateBroadcast chan struct{}
  78. signalPortForwardFailure chan struct{}
  79. totalPortForwardFailures int
  80. establishDuration time.Duration
  81. establishedTime monotime.Time
  82. dialStats *TunnelDialStats
  83. newClientVerificationPayload chan string
  84. }
  85. // TunnelDialStats records additional dial config that is sent to the server for stats
  86. // recording. This data is used to analyze which configuration settings are successful
  87. // in various circumvention contexts, and includes meek dial params and upstream proxy
  88. // params.
  89. // For upstream proxy, only proxy type and custom header names are recorded; proxy
  90. // address and custom header values are considered PII.
  91. type TunnelDialStats struct {
  92. UpstreamProxyType string
  93. UpstreamProxyCustomHeaderNames []string
  94. MeekDialAddress string
  95. MeekResolvedIPAddress string
  96. MeekSNIServerName string
  97. MeekHostHeader string
  98. MeekTransformedHostName bool
  99. }
  100. // EstablishTunnel first makes a network transport connection to the
  101. // Psiphon server and then establishes an SSH client session on top of
  102. // that transport. The SSH server is authenticated using the public
  103. // key in the server entry.
  104. // Depending on the server's capabilities, the connection may use
  105. // plain SSH over TCP, obfuscated SSH over TCP, or obfuscated SSH over
  106. // HTTP (meek protocol).
  107. // When requiredProtocol is not blank, that protocol is used. Otherwise,
  108. // the a random supported protocol is used.
  109. // untunneledDialConfig is used for untunneled final status requests.
  110. func EstablishTunnel(
  111. config *Config,
  112. untunneledDialConfig *DialConfig,
  113. sessionId string,
  114. pendingConns *common.Conns,
  115. serverEntry *protocol.ServerEntry,
  116. adjustedEstablishStartTime monotime.Time,
  117. tunnelOwner TunnelOwner) (tunnel *Tunnel, err error) {
  118. selectedProtocol, err := selectProtocol(config, serverEntry)
  119. if err != nil {
  120. return nil, common.ContextError(err)
  121. }
  122. // Build transport layers and establish SSH connection. Note that
  123. // dialConn and monitoredConn are the same network connection.
  124. dialResult, err := dialSsh(
  125. config, pendingConns, serverEntry, selectedProtocol, sessionId)
  126. if err != nil {
  127. return nil, common.ContextError(err)
  128. }
  129. // Cleanup on error
  130. defer func() {
  131. if err != nil {
  132. dialResult.sshClient.Close()
  133. dialResult.monitoredConn.Close()
  134. pendingConns.Remove(dialResult.dialConn)
  135. }
  136. }()
  137. // The tunnel is now connected
  138. tunnel = &Tunnel{
  139. mutex: new(sync.Mutex),
  140. config: config,
  141. untunneledDialConfig: untunneledDialConfig,
  142. isClosed: false,
  143. serverEntry: serverEntry,
  144. protocol: selectedProtocol,
  145. conn: dialResult.monitoredConn,
  146. sshClient: dialResult.sshClient,
  147. sshServerRequests: dialResult.sshRequests,
  148. operateWaitGroup: new(sync.WaitGroup),
  149. shutdownOperateBroadcast: make(chan struct{}),
  150. // A buffer allows at least one signal to be sent even when the receiver is
  151. // not listening. Senders should not block.
  152. signalPortForwardFailure: make(chan struct{}, 1),
  153. dialStats: dialResult.dialStats,
  154. // Buffer allows SetClientVerificationPayload to submit one new payload
  155. // without blocking or dropping it.
  156. newClientVerificationPayload: make(chan string, 1),
  157. }
  158. // Create a new Psiphon API server context for this tunnel. This includes
  159. // performing a handshake request. If the handshake fails, this establishment
  160. // fails.
  161. if !config.DisableApi {
  162. NoticeInfo("starting server context for %s", tunnel.serverEntry.IpAddress)
  163. tunnel.serverContext, err = NewServerContext(tunnel, sessionId)
  164. if err != nil {
  165. return nil, common.ContextError(
  166. fmt.Errorf("error starting server context for %s: %s",
  167. tunnel.serverEntry.IpAddress, err))
  168. }
  169. }
  170. // establishDuration is the elapsed time between the controller starting tunnel
  171. // establishment and this tunnel being established. The reported value represents
  172. // how long the user waited between starting the client and having a usable tunnel;
  173. // or how long between the client detecting an unexpected tunnel disconnect and
  174. // completing automatic reestablishment.
  175. //
  176. // This time period may include time spent unsuccessfully connecting to other
  177. // servers. Time spent waiting for network connectivity is excluded.
  178. tunnel.establishDuration = monotime.Since(adjustedEstablishStartTime)
  179. tunnel.establishedTime = monotime.Now()
  180. // Now that network operations are complete, cancel interruptibility
  181. pendingConns.Remove(dialResult.dialConn)
  182. // Spawn the operateTunnel goroutine, which monitors the tunnel and handles periodic stats updates.
  183. tunnel.operateWaitGroup.Add(1)
  184. go tunnel.operateTunnel(tunnelOwner)
  185. return tunnel, nil
  186. }
  187. // Close stops operating the tunnel and closes the underlying connection.
  188. // Supports multiple and/or concurrent calls to Close().
  189. // When isDiscarded is set, operateTunnel will not attempt to send final
  190. // status requests.
  191. func (tunnel *Tunnel) Close(isDiscarded bool) {
  192. tunnel.mutex.Lock()
  193. tunnel.isDiscarded = isDiscarded
  194. isClosed := tunnel.isClosed
  195. tunnel.isClosed = true
  196. tunnel.mutex.Unlock()
  197. if !isClosed {
  198. // Signal operateTunnel to stop before closing the tunnel -- this
  199. // allows a final status request to be made in the case of an orderly
  200. // shutdown.
  201. // A timer is set, so if operateTunnel takes too long to stop, the
  202. // tunnel is closed, which will interrupt any slow final status request.
  203. // In effect, the TUNNEL_OPERATE_SHUTDOWN_TIMEOUT value will take
  204. // precedence over the PSIPHON_API_SERVER_TIMEOUT http.Client.Timeout
  205. // value set in makePsiphonHttpsClient.
  206. timer := time.AfterFunc(TUNNEL_OPERATE_SHUTDOWN_TIMEOUT, func() { tunnel.conn.Close() })
  207. close(tunnel.shutdownOperateBroadcast)
  208. tunnel.operateWaitGroup.Wait()
  209. timer.Stop()
  210. tunnel.sshClient.Close()
  211. // tunnel.conn.Close() may get called multiple times, which is allowed.
  212. tunnel.conn.Close()
  213. }
  214. }
  215. // IsDiscarded returns the tunnel's discarded flag.
  216. func (tunnel *Tunnel) IsDiscarded() bool {
  217. tunnel.mutex.Lock()
  218. defer tunnel.mutex.Unlock()
  219. return tunnel.isDiscarded
  220. }
  221. // SendAPIRequest sends an API request as an SSH request through the tunnel.
  222. // This function blocks awaiting a response. Only one request may be in-flight
  223. // at once; a concurrent SendAPIRequest will block until an active request
  224. // receives its response (or the SSH connection is terminated).
  225. func (tunnel *Tunnel) SendAPIRequest(
  226. name string, requestPayload []byte) ([]byte, error) {
  227. ok, responsePayload, err := tunnel.sshClient.Conn.SendRequest(
  228. name, true, requestPayload)
  229. if err != nil {
  230. return nil, common.ContextError(err)
  231. }
  232. if !ok {
  233. return nil, common.ContextError(errors.New("API request rejected"))
  234. }
  235. return responsePayload, nil
  236. }
  237. // Dial establishes a port forward connection through the tunnel
  238. // This Dial doesn't support split tunnel, so alwaysTunnel is not referenced
  239. func (tunnel *Tunnel) Dial(
  240. remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (conn net.Conn, err error) {
  241. type tunnelDialResult struct {
  242. sshPortForwardConn net.Conn
  243. err error
  244. }
  245. resultChannel := make(chan *tunnelDialResult, 2)
  246. if *tunnel.config.TunnelPortForwardDialTimeoutSeconds > 0 {
  247. time.AfterFunc(time.Duration(*tunnel.config.TunnelPortForwardDialTimeoutSeconds)*time.Second, func() {
  248. resultChannel <- &tunnelDialResult{nil, errors.New("tunnel dial timeout")}
  249. })
  250. }
  251. go func() {
  252. sshPortForwardConn, err := tunnel.sshClient.Dial("tcp", remoteAddr)
  253. resultChannel <- &tunnelDialResult{sshPortForwardConn, err}
  254. }()
  255. result := <-resultChannel
  256. if result.err != nil {
  257. // TODO: conditional on type of error or error message?
  258. select {
  259. case tunnel.signalPortForwardFailure <- *new(struct{}):
  260. default:
  261. }
  262. return nil, common.ContextError(result.err)
  263. }
  264. conn = &TunneledConn{
  265. Conn: result.sshPortForwardConn,
  266. tunnel: tunnel,
  267. downstreamConn: downstreamConn}
  268. // Tunnel does not have a serverContext when DisableApi is set. We still use
  269. // transferstats.Conn to count bytes transferred for monitoring tunnel
  270. // quality.
  271. var regexps *transferstats.Regexps
  272. if tunnel.serverContext != nil {
  273. regexps = tunnel.serverContext.StatsRegexps()
  274. }
  275. conn = transferstats.NewConn(conn, tunnel.serverEntry.IpAddress, regexps)
  276. return conn, nil
  277. }
  278. // SignalComponentFailure notifies the tunnel that an associated component has failed.
  279. // This will terminate the tunnel.
  280. func (tunnel *Tunnel) SignalComponentFailure() {
  281. NoticeAlert("tunnel received component failure signal")
  282. tunnel.Close(false)
  283. }
  284. // SetClientVerificationPayload triggers a client verification request, for this
  285. // tunnel, with the specified verifiction payload. If the tunnel is not yet established,
  286. // the payload/request is enqueued. If a payload/request is already eneueued, the
  287. // new payload is dropped.
  288. func (tunnel *Tunnel) SetClientVerificationPayload(clientVerificationPayload string) {
  289. select {
  290. case tunnel.newClientVerificationPayload <- clientVerificationPayload:
  291. default:
  292. }
  293. }
  294. // TunneledConn implements net.Conn and wraps a port foward connection.
  295. // It is used to hook into Read and Write to observe I/O errors and
  296. // report these errors back to the tunnel monitor as port forward failures.
  297. // TunneledConn optionally tracks a peer connection to be explictly closed
  298. // when the TunneledConn is closed.
  299. type TunneledConn struct {
  300. net.Conn
  301. tunnel *Tunnel
  302. downstreamConn net.Conn
  303. }
  304. func (conn *TunneledConn) Read(buffer []byte) (n int, err error) {
  305. n, err = conn.Conn.Read(buffer)
  306. if err != nil && err != io.EOF {
  307. // Report new failure. Won't block; assumes the receiver
  308. // has a sufficient buffer for the threshold number of reports.
  309. // TODO: conditional on type of error or error message?
  310. select {
  311. case conn.tunnel.signalPortForwardFailure <- *new(struct{}):
  312. default:
  313. }
  314. }
  315. return
  316. }
  317. func (conn *TunneledConn) Write(buffer []byte) (n int, err error) {
  318. n, err = conn.Conn.Write(buffer)
  319. if err != nil && err != io.EOF {
  320. // Same as TunneledConn.Read()
  321. select {
  322. case conn.tunnel.signalPortForwardFailure <- *new(struct{}):
  323. default:
  324. }
  325. }
  326. return
  327. }
  328. func (conn *TunneledConn) Close() error {
  329. if conn.downstreamConn != nil {
  330. conn.downstreamConn.Close()
  331. }
  332. return conn.Conn.Close()
  333. }
  334. // selectProtocol is a helper that picks the tunnel protocol
  335. func selectProtocol(
  336. config *Config, serverEntry *protocol.ServerEntry) (selectedProtocol string, err error) {
  337. // TODO: properly handle protocols (e.g. FRONTED-MEEK-OSSH) vs. capabilities (e.g., {FRONTED-MEEK, OSSH})
  338. // for now, the code is simply assuming that MEEK capabilities imply OSSH capability.
  339. if config.TunnelProtocol != "" {
  340. if !serverEntry.SupportsProtocol(config.TunnelProtocol) {
  341. return "", common.ContextError(fmt.Errorf("server does not have required capability"))
  342. }
  343. selectedProtocol = config.TunnelProtocol
  344. } else {
  345. // Pick at random from the supported protocols. This ensures that we'll eventually
  346. // try all possible protocols. Depending on network configuration, it may be the
  347. // case that some protocol is only available through multi-capability servers,
  348. // and a simpler ranked preference of protocols could lead to that protocol never
  349. // being selected.
  350. candidateProtocols := serverEntry.GetSupportedProtocols()
  351. if len(candidateProtocols) == 0 {
  352. return "", common.ContextError(fmt.Errorf("server does not have any supported capabilities"))
  353. }
  354. index, err := common.MakeSecureRandomInt(len(candidateProtocols))
  355. if err != nil {
  356. return "", common.ContextError(err)
  357. }
  358. selectedProtocol = candidateProtocols[index]
  359. }
  360. return selectedProtocol, nil
  361. }
  362. // selectFrontingParameters is a helper which selects/generates meek fronting
  363. // parameters where the server entry provides multiple options or patterns.
  364. func selectFrontingParameters(
  365. serverEntry *protocol.ServerEntry) (frontingAddress, frontingHost string, err error) {
  366. if len(serverEntry.MeekFrontingAddressesRegex) > 0 {
  367. // Generate a front address based on the regex.
  368. frontingAddress, err = regen.Generate(serverEntry.MeekFrontingAddressesRegex)
  369. if err != nil {
  370. return "", "", common.ContextError(err)
  371. }
  372. } else {
  373. // Randomly select, for this connection attempt, one front address for
  374. // fronting-capable servers.
  375. if len(serverEntry.MeekFrontingAddresses) == 0 {
  376. return "", "", common.ContextError(errors.New("MeekFrontingAddresses is empty"))
  377. }
  378. index, err := common.MakeSecureRandomInt(len(serverEntry.MeekFrontingAddresses))
  379. if err != nil {
  380. return "", "", common.ContextError(err)
  381. }
  382. frontingAddress = serverEntry.MeekFrontingAddresses[index]
  383. }
  384. if len(serverEntry.MeekFrontingHosts) > 0 {
  385. index, err := common.MakeSecureRandomInt(len(serverEntry.MeekFrontingHosts))
  386. if err != nil {
  387. return "", "", common.ContextError(err)
  388. }
  389. frontingHost = serverEntry.MeekFrontingHosts[index]
  390. } else {
  391. // Backwards compatibility case
  392. frontingHost = serverEntry.MeekFrontingHost
  393. }
  394. return
  395. }
  396. func doMeekTransformHostName(config *Config) bool {
  397. switch config.TransformHostNames {
  398. case TRANSFORM_HOST_NAMES_ALWAYS:
  399. return true
  400. case TRANSFORM_HOST_NAMES_NEVER:
  401. return false
  402. }
  403. return common.FlipCoin()
  404. }
  405. // initMeekConfig is a helper that creates a MeekConfig suitable for the
  406. // selected meek tunnel protocol.
  407. func initMeekConfig(
  408. config *Config,
  409. serverEntry *protocol.ServerEntry,
  410. selectedProtocol,
  411. sessionId string) (*MeekConfig, error) {
  412. // The meek protocol always uses OSSH
  413. psiphonServerAddress := fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedPort)
  414. var dialAddress string
  415. useHTTPS := false
  416. useObfuscatedSessionTickets := false
  417. var SNIServerName, hostHeader string
  418. transformedHostName := false
  419. switch selectedProtocol {
  420. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK:
  421. frontingAddress, frontingHost, err := selectFrontingParameters(serverEntry)
  422. if err != nil {
  423. return nil, common.ContextError(err)
  424. }
  425. dialAddress = fmt.Sprintf("%s:443", frontingAddress)
  426. useHTTPS = true
  427. if !serverEntry.MeekFrontingDisableSNI {
  428. SNIServerName = frontingAddress
  429. if doMeekTransformHostName(config) {
  430. SNIServerName = common.GenerateHostName()
  431. transformedHostName = true
  432. }
  433. }
  434. hostHeader = frontingHost
  435. case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
  436. frontingAddress, frontingHost, err := selectFrontingParameters(serverEntry)
  437. if err != nil {
  438. return nil, common.ContextError(err)
  439. }
  440. dialAddress = fmt.Sprintf("%s:80", frontingAddress)
  441. hostHeader = frontingHost
  442. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  443. dialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.MeekServerPort)
  444. hostname := serverEntry.IpAddress
  445. if doMeekTransformHostName(config) {
  446. hostname = common.GenerateHostName()
  447. transformedHostName = true
  448. }
  449. if serverEntry.MeekServerPort == 80 {
  450. hostHeader = hostname
  451. } else {
  452. hostHeader = fmt.Sprintf("%s:%d", hostname, serverEntry.MeekServerPort)
  453. }
  454. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  455. protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET:
  456. dialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.MeekServerPort)
  457. useHTTPS = true
  458. if selectedProtocol == protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET {
  459. useObfuscatedSessionTickets = true
  460. }
  461. SNIServerName = serverEntry.IpAddress
  462. if doMeekTransformHostName(config) {
  463. SNIServerName = common.GenerateHostName()
  464. transformedHostName = true
  465. }
  466. if serverEntry.MeekServerPort == 443 {
  467. hostHeader = serverEntry.IpAddress
  468. } else {
  469. hostHeader = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.MeekServerPort)
  470. }
  471. default:
  472. return nil, common.ContextError(errors.New("unexpected selectedProtocol"))
  473. }
  474. // The unnderlying TLS will automatically disable SNI for IP address server name
  475. // values; we have this explicit check here so we record the correct value for stats.
  476. if net.ParseIP(SNIServerName) != nil {
  477. SNIServerName = ""
  478. }
  479. return &MeekConfig{
  480. DialAddress: dialAddress,
  481. UseHTTPS: useHTTPS,
  482. UseObfuscatedSessionTickets: useObfuscatedSessionTickets,
  483. SNIServerName: SNIServerName,
  484. HostHeader: hostHeader,
  485. TransformedHostName: transformedHostName,
  486. PsiphonServerAddress: psiphonServerAddress,
  487. SessionID: sessionId,
  488. MeekCookieEncryptionPublicKey: serverEntry.MeekCookieEncryptionPublicKey,
  489. MeekObfuscatedKey: serverEntry.MeekObfuscatedKey,
  490. }, nil
  491. }
  492. type dialResult struct {
  493. dialConn net.Conn
  494. monitoredConn *common.ActivityMonitoredConn
  495. sshClient *ssh.Client
  496. sshRequests <-chan *ssh.Request
  497. dialStats *TunnelDialStats
  498. }
  499. // dialSsh is a helper that builds the transport layers and establishes the SSH connection.
  500. // When additional dial configuration is used, DialStats are recorded and returned.
  501. //
  502. // The net.Conn return value is the value to be removed from pendingConns; additional
  503. // layering (ThrottledConn, ActivityMonitoredConn) is applied, but this return value is the
  504. // base dial conn. The *ActivityMonitoredConn return value is the layered conn passed into
  505. // the ssh.Client.
  506. func dialSsh(
  507. config *Config,
  508. pendingConns *common.Conns,
  509. serverEntry *protocol.ServerEntry,
  510. selectedProtocol,
  511. sessionId string) (*dialResult, error) {
  512. // The meek protocols tunnel obfuscated SSH. Obfuscated SSH is layered on top of SSH.
  513. // So depending on which protocol is used, multiple layers are initialized.
  514. useObfuscatedSsh := false
  515. var directTCPDialAddress string
  516. var meekConfig *MeekConfig
  517. var err error
  518. switch selectedProtocol {
  519. case protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH:
  520. useObfuscatedSsh = true
  521. directTCPDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedPort)
  522. case protocol.TUNNEL_PROTOCOL_SSH:
  523. directTCPDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshPort)
  524. default:
  525. useObfuscatedSsh = true
  526. meekConfig, err = initMeekConfig(config, serverEntry, selectedProtocol, sessionId)
  527. if err != nil {
  528. return nil, common.ContextError(err)
  529. }
  530. }
  531. NoticeConnectingServer(
  532. serverEntry.IpAddress,
  533. serverEntry.Region,
  534. selectedProtocol,
  535. directTCPDialAddress,
  536. meekConfig)
  537. // Use an asynchronous callback to record the resolved IP address when
  538. // dialing a domain name. Note that DialMeek doesn't immediately
  539. // establish any HTTPS connections, so the resolved IP address won't be
  540. // reported until during/after ssh session establishment (the ssh traffic
  541. // is meek payload). So don't Load() the IP address value until after that
  542. // has completed to ensure a result.
  543. var resolvedIPAddress atomic.Value
  544. resolvedIPAddress.Store("")
  545. setResolvedIPAddress := func(IPAddress string) {
  546. resolvedIPAddress.Store(IPAddress)
  547. }
  548. // Create the base transport: meek or direct connection
  549. dialConfig := &DialConfig{
  550. UpstreamProxyUrl: config.UpstreamProxyUrl,
  551. UpstreamProxyCustomHeaders: config.UpstreamProxyCustomHeaders,
  552. ConnectTimeout: time.Duration(*config.TunnelConnectTimeoutSeconds) * time.Second,
  553. PendingConns: pendingConns,
  554. DeviceBinder: config.DeviceBinder,
  555. DnsServerGetter: config.DnsServerGetter,
  556. UseIndistinguishableTLS: config.UseIndistinguishableTLS,
  557. TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
  558. DeviceRegion: config.DeviceRegion,
  559. ResolvedIPCallback: setResolvedIPAddress,
  560. }
  561. var dialConn net.Conn
  562. if meekConfig != nil {
  563. dialConn, err = DialMeek(meekConfig, dialConfig)
  564. if err != nil {
  565. return nil, common.ContextError(err)
  566. }
  567. } else {
  568. dialConn, err = DialTCP(directTCPDialAddress, dialConfig)
  569. if err != nil {
  570. return nil, common.ContextError(err)
  571. }
  572. }
  573. cleanupConn := dialConn
  574. defer func() {
  575. // Cleanup on error
  576. if cleanupConn != nil {
  577. cleanupConn.Close()
  578. pendingConns.Remove(cleanupConn)
  579. }
  580. }()
  581. // Activity monitoring is used to measure tunnel duration
  582. monitoredConn, err := common.NewActivityMonitoredConn(dialConn, 0, false, nil, nil)
  583. if err != nil {
  584. return nil, common.ContextError(err)
  585. }
  586. // Apply throttling (if configured)
  587. throttledConn := common.NewThrottledConn(monitoredConn, config.RateLimits)
  588. // Add obfuscated SSH layer
  589. var sshConn net.Conn = throttledConn
  590. if useObfuscatedSsh {
  591. sshConn, err = common.NewObfuscatedSshConn(
  592. common.OBFUSCATION_CONN_MODE_CLIENT, throttledConn, serverEntry.SshObfuscatedKey)
  593. if err != nil {
  594. return nil, common.ContextError(err)
  595. }
  596. }
  597. // Now establish the SSH session over the conn transport
  598. expectedPublicKey, err := base64.StdEncoding.DecodeString(serverEntry.SshHostKey)
  599. if err != nil {
  600. return nil, common.ContextError(err)
  601. }
  602. sshCertChecker := &ssh.CertChecker{
  603. HostKeyFallback: func(addr string, remote net.Addr, publicKey ssh.PublicKey) error {
  604. if !bytes.Equal(expectedPublicKey, publicKey.Marshal()) {
  605. return common.ContextError(errors.New("unexpected host public key"))
  606. }
  607. return nil
  608. },
  609. }
  610. sshPasswordPayload := &protocol.SSHPasswordPayload{
  611. SessionId: sessionId,
  612. SshPassword: serverEntry.SshPassword,
  613. ClientCapabilities: []string{protocol.CLIENT_CAPABILITY_SERVER_REQUESTS},
  614. }
  615. payload, err := json.Marshal(sshPasswordPayload)
  616. if err != nil {
  617. return nil, common.ContextError(err)
  618. }
  619. sshClientConfig := &ssh.ClientConfig{
  620. User: serverEntry.SshUsername,
  621. Auth: []ssh.AuthMethod{
  622. ssh.Password(string(payload)),
  623. },
  624. HostKeyCallback: sshCertChecker.CheckHostKey,
  625. }
  626. // The ssh session establishment (via ssh.NewClientConn) is wrapped
  627. // in a timeout to ensure it won't hang. We've encountered firewalls
  628. // that allow the TCP handshake to complete but then send a RST to the
  629. // server-side and nothing to the client-side, and if that happens
  630. // while ssh.NewClientConn is reading, it may wait forever. The timeout
  631. // closes the conn, which interrupts it.
  632. // Note: TCP handshake timeouts are provided by TCPConn, and session
  633. // timeouts *after* ssh establishment are provided by the ssh keep alive
  634. // in operate tunnel.
  635. // TODO: adjust the timeout to account for time-elapsed-from-start
  636. type sshNewClientResult struct {
  637. sshClient *ssh.Client
  638. sshRequests <-chan *ssh.Request
  639. err error
  640. }
  641. resultChannel := make(chan *sshNewClientResult, 2)
  642. if *config.TunnelConnectTimeoutSeconds > 0 {
  643. time.AfterFunc(time.Duration(*config.TunnelConnectTimeoutSeconds)*time.Second, func() {
  644. resultChannel <- &sshNewClientResult{nil, nil, errors.New("ssh dial timeout")}
  645. })
  646. }
  647. go func() {
  648. // The following is adapted from ssh.Dial(), here using a custom conn
  649. // The sshAddress is passed through to host key verification callbacks; we don't use it.
  650. sshAddress := ""
  651. sshClientConn, sshChannels, sshRequests, err := ssh.NewClientConn(
  652. sshConn, sshAddress, sshClientConfig)
  653. var sshClient *ssh.Client
  654. if err == nil {
  655. sshClient = ssh.NewClient(sshClientConn, sshChannels, nil)
  656. }
  657. resultChannel <- &sshNewClientResult{sshClient, sshRequests, err}
  658. }()
  659. result := <-resultChannel
  660. if result.err != nil {
  661. return nil, common.ContextError(result.err)
  662. }
  663. var dialStats *TunnelDialStats
  664. if dialConfig.UpstreamProxyUrl != "" || meekConfig != nil {
  665. dialStats = &TunnelDialStats{}
  666. if dialConfig.UpstreamProxyUrl != "" {
  667. // Note: UpstreamProxyUrl should have parsed correctly in the dial
  668. proxyURL, err := url.Parse(dialConfig.UpstreamProxyUrl)
  669. if err == nil {
  670. dialStats.UpstreamProxyType = proxyURL.Scheme
  671. }
  672. dialStats.UpstreamProxyCustomHeaderNames = make([]string, 0)
  673. for name, _ := range dialConfig.UpstreamProxyCustomHeaders {
  674. dialStats.UpstreamProxyCustomHeaderNames = append(dialStats.UpstreamProxyCustomHeaderNames, name)
  675. }
  676. }
  677. if meekConfig != nil {
  678. dialStats.MeekDialAddress = meekConfig.DialAddress
  679. dialStats.MeekResolvedIPAddress = resolvedIPAddress.Load().(string)
  680. dialStats.MeekSNIServerName = meekConfig.SNIServerName
  681. dialStats.MeekHostHeader = meekConfig.HostHeader
  682. dialStats.MeekTransformedHostName = meekConfig.TransformedHostName
  683. }
  684. NoticeConnectedTunnelDialStats(serverEntry.IpAddress, dialStats)
  685. }
  686. cleanupConn = nil
  687. // Note: dialConn may be used to close the underlying network connection
  688. // but should not be used to perform I/O as that would interfere with SSH
  689. // (and also bypasses throttling).
  690. return &dialResult{
  691. dialConn: dialConn,
  692. monitoredConn: monitoredConn,
  693. sshClient: result.sshClient,
  694. sshRequests: result.sshRequests,
  695. dialStats: dialStats},
  696. nil
  697. }
  698. func makeRandomPeriod(min, max time.Duration) time.Duration {
  699. period, err := common.MakeRandomPeriod(min, max)
  700. if err != nil {
  701. NoticeAlert("MakeRandomPeriod failed: %s", err)
  702. // Proceed without random period
  703. period = max
  704. }
  705. return period
  706. }
  707. // operateTunnel monitors the health of the tunnel and performs
  708. // periodic work.
  709. //
  710. // BytesTransferred and TotalBytesTransferred notices are emitted
  711. // for live reporting and diagnostics reporting, respectively.
  712. //
  713. // Status requests are sent to the Psiphon API to report bytes
  714. // transferred.
  715. //
  716. // Periodic SSH keep alive packets are sent to ensure the underlying
  717. // TCP connection isn't terminated by NAT, or other network
  718. // interference -- or test if it has been terminated while the device
  719. // has been asleep. When a keep alive times out, the tunnel is
  720. // considered failed.
  721. //
  722. // An immediate SSH keep alive "probe" is sent to test the tunnel and
  723. // server responsiveness when a port forward failure is detected: a
  724. // failed dial or failed read/write. This keep alive has a shorter
  725. // timeout.
  726. //
  727. // Note that port foward failures may be due to non-failure conditions.
  728. // For example, when the user inputs an invalid domain name and
  729. // resolution is done by the ssh server; or trying to connect to a
  730. // non-white-listed port; and the error message in these cases is not
  731. // distinguishable from a a true server error (a common error message,
  732. // "ssh: rejected: administratively prohibited (open failed)", may be
  733. // returned for these cases but also if the server has run out of
  734. // ephemeral ports, for example).
  735. //
  736. // SSH keep alives are not sent when the tunnel has been recently
  737. // active (not only does tunnel activity obviate the necessity of a keep
  738. // alive, testing has shown that keep alives may time out for "busy"
  739. // tunnels, especially over meek protocol and other high latency
  740. // conditions).
  741. //
  742. // "Recently active" is defined has having received payload bytes. Sent
  743. // bytes are not considered as testing has shown bytes may appear to
  744. // send when certain NAT devices have interfered with the tunnel, while
  745. // no bytes are received. In a pathological case, with DNS implemented
  746. // as tunneled UDP, a browser may wait excessively for a domain name to
  747. // resolve, while no new port forward is attempted which would otherwise
  748. // result in a tunnel failure detection.
  749. //
  750. // TODO: change "recently active" to include having received any
  751. // SSH protocol messages from the server, not just user payload?
  752. //
  753. func (tunnel *Tunnel) operateTunnel(tunnelOwner TunnelOwner) {
  754. defer tunnel.operateWaitGroup.Done()
  755. lastBytesReceivedTime := monotime.Now()
  756. lastTotalBytesTransferedTime := monotime.Now()
  757. totalSent := int64(0)
  758. totalReceived := int64(0)
  759. noticeBytesTransferredTicker := time.NewTicker(1 * time.Second)
  760. defer noticeBytesTransferredTicker.Stop()
  761. // The next status request and ssh keep alive times are picked at random,
  762. // from a range, to make the resulting traffic less fingerprintable,
  763. // Note: not using Tickers since these are not fixed time periods.
  764. nextStatusRequestPeriod := func() time.Duration {
  765. return makeRandomPeriod(
  766. PSIPHON_API_STATUS_REQUEST_PERIOD_MIN,
  767. PSIPHON_API_STATUS_REQUEST_PERIOD_MAX)
  768. }
  769. statsTimer := time.NewTimer(nextStatusRequestPeriod())
  770. defer statsTimer.Stop()
  771. // Schedule an immediate status request to deliver any unreported
  772. // persistent stats.
  773. // Note: this may not be effective when there's an outstanding
  774. // asynchronous untunneled final status request is holding the
  775. // persistent stats records. It may also conflict with other
  776. // tunnel candidates which attempt to send an immediate request
  777. // before being discarded. For now, we mitigate this with a short,
  778. // random delay.
  779. unreported := CountUnreportedPersistentStats()
  780. if unreported > 0 {
  781. NoticeInfo("Unreported persistent stats: %d", unreported)
  782. statsTimer.Reset(makeRandomPeriod(
  783. PSIPHON_API_STATUS_REQUEST_SHORT_PERIOD_MIN,
  784. PSIPHON_API_STATUS_REQUEST_SHORT_PERIOD_MAX))
  785. }
  786. nextSshKeepAlivePeriod := func() time.Duration {
  787. return makeRandomPeriod(
  788. TUNNEL_SSH_KEEP_ALIVE_PERIOD_MIN,
  789. TUNNEL_SSH_KEEP_ALIVE_PERIOD_MAX)
  790. }
  791. // TODO: don't initialize timer when config.DisablePeriodicSshKeepAlive is set
  792. sshKeepAliveTimer := time.NewTimer(nextSshKeepAlivePeriod())
  793. if tunnel.config.DisablePeriodicSshKeepAlive {
  794. sshKeepAliveTimer.Stop()
  795. } else {
  796. defer sshKeepAliveTimer.Stop()
  797. }
  798. // Perform network requests in separate goroutines so as not to block
  799. // other operations.
  800. requestsWaitGroup := new(sync.WaitGroup)
  801. requestsWaitGroup.Add(1)
  802. signalStatusRequest := make(chan struct{})
  803. go func() {
  804. defer requestsWaitGroup.Done()
  805. for _ = range signalStatusRequest {
  806. sendStats(tunnel)
  807. }
  808. }()
  809. requestsWaitGroup.Add(1)
  810. signalSshKeepAlive := make(chan time.Duration)
  811. sshKeepAliveError := make(chan error, 1)
  812. go func() {
  813. defer requestsWaitGroup.Done()
  814. for timeout := range signalSshKeepAlive {
  815. err := sendSshKeepAlive(tunnel.sshClient, tunnel.conn, timeout)
  816. if err != nil {
  817. select {
  818. case sshKeepAliveError <- err:
  819. default:
  820. }
  821. }
  822. }
  823. }()
  824. requestsWaitGroup.Add(1)
  825. signalStopClientVerificationRequests := make(chan struct{})
  826. go func() {
  827. defer requestsWaitGroup.Done()
  828. clientVerificationRequestSuccess := true
  829. clientVerificationPayload := ""
  830. failCount := 0
  831. for {
  832. // TODO: use reflect.SelectCase?
  833. if clientVerificationRequestSuccess == true {
  834. failCount = 0
  835. select {
  836. case clientVerificationPayload = <-tunnel.newClientVerificationPayload:
  837. case <-signalStopClientVerificationRequests:
  838. return
  839. }
  840. } else {
  841. // If sendClientVerification failed to send the payload we
  842. // will retry after a delay. Will use a new payload instead
  843. // if that arrives in the meantime.
  844. // If failures count is more than PSIPHON_API_CLIENT_VERIFICATION_REQUEST_MAX_RETRIES
  845. // stop retrying for this tunnel.
  846. failCount += 1
  847. if failCount > PSIPHON_API_CLIENT_VERIFICATION_REQUEST_MAX_RETRIES {
  848. return
  849. }
  850. timeout := time.After(PSIPHON_API_CLIENT_VERIFICATION_REQUEST_RETRY_PERIOD)
  851. select {
  852. case <-timeout:
  853. case clientVerificationPayload = <-tunnel.newClientVerificationPayload:
  854. case <-signalStopClientVerificationRequests:
  855. return
  856. }
  857. }
  858. clientVerificationRequestSuccess = sendClientVerification(tunnel, clientVerificationPayload)
  859. }
  860. }()
  861. shutdown := false
  862. var err error
  863. for !shutdown && err == nil {
  864. select {
  865. case <-noticeBytesTransferredTicker.C:
  866. sent, received := transferstats.ReportRecentBytesTransferredForServer(
  867. tunnel.serverEntry.IpAddress)
  868. if received > 0 {
  869. lastBytesReceivedTime = monotime.Now()
  870. }
  871. totalSent += sent
  872. totalReceived += received
  873. if lastTotalBytesTransferedTime.Add(TOTAL_BYTES_TRANSFERRED_NOTICE_PERIOD).Before(monotime.Now()) {
  874. NoticeTotalBytesTransferred(tunnel.serverEntry.IpAddress, totalSent, totalReceived)
  875. lastTotalBytesTransferedTime = monotime.Now()
  876. }
  877. // Only emit the frequent BytesTransferred notice when tunnel is not idle.
  878. if tunnel.config.EmitBytesTransferred && (sent > 0 || received > 0) {
  879. NoticeBytesTransferred(tunnel.serverEntry.IpAddress, sent, received)
  880. }
  881. case <-statsTimer.C:
  882. select {
  883. case signalStatusRequest <- *new(struct{}):
  884. default:
  885. }
  886. statsTimer.Reset(nextStatusRequestPeriod())
  887. case <-sshKeepAliveTimer.C:
  888. if lastBytesReceivedTime.Add(TUNNEL_SSH_KEEP_ALIVE_PERIODIC_INACTIVE_PERIOD).Before(monotime.Now()) {
  889. select {
  890. case signalSshKeepAlive <- time.Duration(*tunnel.config.TunnelSshKeepAlivePeriodicTimeoutSeconds) * time.Second:
  891. default:
  892. }
  893. }
  894. sshKeepAliveTimer.Reset(nextSshKeepAlivePeriod())
  895. case <-tunnel.signalPortForwardFailure:
  896. // Note: no mutex on portForwardFailureTotal; only referenced here
  897. tunnel.totalPortForwardFailures++
  898. NoticeInfo("port forward failures for %s: %d",
  899. tunnel.serverEntry.IpAddress, tunnel.totalPortForwardFailures)
  900. if lastBytesReceivedTime.Add(TUNNEL_SSH_KEEP_ALIVE_PROBE_INACTIVE_PERIOD).Before(monotime.Now()) {
  901. select {
  902. case signalSshKeepAlive <- time.Duration(*tunnel.config.TunnelSshKeepAliveProbeTimeoutSeconds) * time.Second:
  903. default:
  904. }
  905. }
  906. if !tunnel.config.DisablePeriodicSshKeepAlive {
  907. sshKeepAliveTimer.Reset(nextSshKeepAlivePeriod())
  908. }
  909. case err = <-sshKeepAliveError:
  910. case serverRequest := <-tunnel.sshServerRequests:
  911. if serverRequest != nil {
  912. err := HandleServerRequest(tunnelOwner, tunnel, serverRequest.Type, serverRequest.Payload)
  913. if err == nil {
  914. serverRequest.Reply(true, nil)
  915. } else {
  916. NoticeAlert("HandleServerRequest for %s failed: %s", serverRequest.Type, err)
  917. serverRequest.Reply(false, nil)
  918. }
  919. }
  920. case <-tunnel.shutdownOperateBroadcast:
  921. shutdown = true
  922. }
  923. }
  924. close(signalSshKeepAlive)
  925. close(signalStatusRequest)
  926. close(signalStopClientVerificationRequests)
  927. requestsWaitGroup.Wait()
  928. // Capture bytes transferred since the last noticeBytesTransferredTicker tick
  929. sent, received := transferstats.ReportRecentBytesTransferredForServer(tunnel.serverEntry.IpAddress)
  930. totalSent += sent
  931. totalReceived += received
  932. // Always emit a final NoticeTotalBytesTransferred
  933. NoticeTotalBytesTransferred(tunnel.serverEntry.IpAddress, totalSent, totalReceived)
  934. // Tunnel does not have a serverContext when DisableApi is set.
  935. if tunnel.serverContext != nil && !tunnel.IsDiscarded() {
  936. // The stats for this tunnel will be reported via the next successful
  937. // status request.
  938. // Since client clocks are unreliable, we report the server's timestamp from
  939. // the handshake response as the absolute tunnel start time. This time
  940. // will be slightly earlier than the actual tunnel activation time, as the
  941. // client has to receive and parse the response and activate the tunnel.
  942. tunnelStartTime := tunnel.serverContext.serverHandshakeTimestamp
  943. // For the tunnel duration calculation, we use the local clock. The start time
  944. // is tunnel.establishedTime as recorded when the tunnel was established. For the
  945. // end time, we do not use the current time as we may now be long past the
  946. // actual termination time of the tunnel. For example, the host or device may
  947. // have resumed after a long sleep (it's not clear that the monotonic clock service
  948. // used to measure elapsed time will or will not stop during device sleep). Instead,
  949. // we use the last data received time as the estimated tunnel end time.
  950. //
  951. // One potential issue with using the last received time is receiving data
  952. // after an extended sleep because the device sleep occured with data still in
  953. // the OS socket read buffer. This is not expected to happen on Android, as the
  954. // OS will wake a process when it has TCP data available to read. (For this reason,
  955. // the actual long sleep issue is only with an idle tunnel; in this case the client
  956. // is responsible for sending SSH keep alives but a device sleep will delay the
  957. // golang SSH keep alive timer.)
  958. //
  959. // Idle tunnels will only read data when a SSH keep alive is sent. As a result,
  960. // the last-received-time scheme can undercount tunnel durations by up to
  961. // TUNNEL_SSH_KEEP_ALIVE_PERIOD_MAX for idle tunnels.
  962. tunnelDuration := tunnel.conn.GetLastActivityMonotime().Sub(tunnel.establishedTime)
  963. err := RecordTunnelStat(
  964. tunnel.serverContext.sessionId,
  965. tunnel.serverContext.tunnelNumber,
  966. tunnel.serverEntry.IpAddress,
  967. fmt.Sprintf("%d", tunnel.establishDuration),
  968. tunnelStartTime,
  969. fmt.Sprintf("%d", tunnelDuration),
  970. totalSent,
  971. totalReceived)
  972. if err != nil {
  973. NoticeAlert("RecordTunnelStats failed: %s", common.ContextError(err))
  974. }
  975. }
  976. // Final status request notes:
  977. //
  978. // It's highly desirable to send a final status request in order to report
  979. // domain bytes transferred stats as well as to report tunnel stats as
  980. // soon as possible. For this reason, we attempt untunneled requests when
  981. // the tunneled request isn't possible or has failed.
  982. //
  983. // In an orderly shutdown (err == nil), the Controller is stopping and
  984. // everything must be wrapped up quickly. Also, we still have a working
  985. // tunnel. So we first attempt a tunneled status request (with a short
  986. // timeout) and then attempt, synchronously -- otherwise the Contoller's
  987. // runWaitGroup.Wait() will return while a request is still in progress
  988. // -- untunneled requests (also with short timeouts). Note that in this
  989. // case the untunneled request will opt out of untunneledPendingConns so
  990. // that it's not inadvertently canceled by the Controller shutdown
  991. // sequence (see doUntunneledStatusRequest).
  992. //
  993. // If the tunnel has failed, the Controller may continue working. We want
  994. // to re-establish as soon as possible (so don't want to block on status
  995. // requests, even for a second). We may have a long time to attempt
  996. // untunneled requests in the background. And there is no tunnel through
  997. // which to attempt tunneled requests. So we spawn a goroutine to run the
  998. // untunneled requests, which are allowed a longer timeout. These requests
  999. // will be interrupted by the Controller's untunneledPendingConns.CloseAll()
  1000. // in the case of a shutdown.
  1001. if err == nil {
  1002. NoticeInfo("shutdown operate tunnel")
  1003. if !sendStats(tunnel) {
  1004. sendUntunneledStats(tunnel, true)
  1005. }
  1006. } else {
  1007. NoticeAlert("operate tunnel error for %s: %s", tunnel.serverEntry.IpAddress, err)
  1008. go sendUntunneledStats(tunnel, false)
  1009. tunnelOwner.SignalTunnelFailure(tunnel)
  1010. }
  1011. }
  1012. // sendSshKeepAlive is a helper which sends a keepalive@openssh.com request
  1013. // on the specified SSH connections and returns true of the request succeeds
  1014. // within a specified timeout. If the request fails, the associated conn is
  1015. // closed, which will terminate the associated tunnel.
  1016. func sendSshKeepAlive(
  1017. sshClient *ssh.Client, conn net.Conn, timeout time.Duration) error {
  1018. errChannel := make(chan error, 2)
  1019. if timeout > 0 {
  1020. time.AfterFunc(timeout, func() {
  1021. errChannel <- TimeoutError{}
  1022. })
  1023. }
  1024. go func() {
  1025. // Random padding to frustrate fingerprinting
  1026. randomPadding, err := common.MakeSecureRandomPadding(0, TUNNEL_SSH_KEEP_ALIVE_PAYLOAD_MAX_BYTES)
  1027. if err != nil {
  1028. NoticeAlert("MakeSecureRandomPadding failed: %s", err)
  1029. // Proceed without random padding
  1030. randomPadding = make([]byte, 0)
  1031. }
  1032. // Note: reading a reply is important for last-received-time tunnel
  1033. // duration calculation.
  1034. _, _, err = sshClient.SendRequest("keepalive@openssh.com", true, randomPadding)
  1035. errChannel <- err
  1036. }()
  1037. err := <-errChannel
  1038. if err != nil {
  1039. sshClient.Close()
  1040. conn.Close()
  1041. }
  1042. return common.ContextError(err)
  1043. }
  1044. // sendStats is a helper for sending session stats to the server.
  1045. func sendStats(tunnel *Tunnel) bool {
  1046. // Tunnel does not have a serverContext when DisableApi is set
  1047. if tunnel.serverContext == nil {
  1048. return true
  1049. }
  1050. // Skip when tunnel is discarded
  1051. if tunnel.IsDiscarded() {
  1052. return true
  1053. }
  1054. err := tunnel.serverContext.DoStatusRequest(tunnel)
  1055. if err != nil {
  1056. NoticeAlert("DoStatusRequest failed for %s: %s", tunnel.serverEntry.IpAddress, err)
  1057. }
  1058. return err == nil
  1059. }
  1060. // sendUntunnelStats sends final status requests directly to Psiphon
  1061. // servers after the tunnel has already failed. This is an attempt
  1062. // to retain useful bytes transferred stats.
  1063. func sendUntunneledStats(tunnel *Tunnel, isShutdown bool) {
  1064. // Tunnel does not have a serverContext when DisableApi is set
  1065. if tunnel.serverContext == nil {
  1066. return
  1067. }
  1068. // Skip when tunnel is discarded
  1069. if tunnel.IsDiscarded() {
  1070. return
  1071. }
  1072. err := tunnel.serverContext.TryUntunneledStatusRequest(isShutdown)
  1073. if err != nil {
  1074. NoticeAlert("TryUntunneledStatusRequest failed for %s: %s", tunnel.serverEntry.IpAddress, err)
  1075. }
  1076. }
  1077. // sendClientVerification is a helper for sending a client verification request
  1078. // to the server.
  1079. func sendClientVerification(tunnel *Tunnel, clientVerificationPayload string) bool {
  1080. // Tunnel does not have a serverContext when DisableApi is set
  1081. if tunnel.serverContext == nil {
  1082. return true
  1083. }
  1084. // Skip when tunnel is discarded
  1085. if tunnel.IsDiscarded() {
  1086. return true
  1087. }
  1088. err := tunnel.serverContext.DoClientVerificationRequest(clientVerificationPayload, tunnel.serverEntry.IpAddress)
  1089. if err != nil {
  1090. NoticeAlert("DoClientVerificationRequest failed for %s: %s", tunnel.serverEntry.IpAddress, err)
  1091. }
  1092. return err == nil
  1093. }