tunnel.go 46 KB

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