tunnelServer.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  1. /*
  2. * Copyright (c) 2016, 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 server
  20. import (
  21. "crypto/subtle"
  22. "encoding/json"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "net"
  27. "strconv"
  28. "sync"
  29. "sync/atomic"
  30. "time"
  31. "github.com/Psiphon-Inc/crypto/ssh"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  34. )
  35. const (
  36. SSH_HANDSHAKE_TIMEOUT = 30 * time.Second
  37. SSH_CONNECTION_READ_DEADLINE = 5 * time.Minute
  38. SSH_TCP_PORT_FORWARD_DIAL_TIMEOUT = 30 * time.Second
  39. SSH_TCP_PORT_FORWARD_COPY_BUFFER_SIZE = 8192
  40. )
  41. // Disallowed port forward hosts is a failsafe. The server should
  42. // be run on a host with correctly configured firewall rules, or
  43. // containerization, or both.
  44. var SSH_DISALLOWED_PORT_FORWARD_HOSTS = []string{"localhost", "127.0.0.1"}
  45. // TunnelServer is the main server that accepts Psiphon client
  46. // connections, via various obfuscation protocols, and provides
  47. // port forwarding (TCP and UDP) services to the Psiphon client.
  48. // At its core, TunnelServer is an SSH server. SSH is the base
  49. // protocol that provides port forward multiplexing, and transport
  50. // security. Layered on top of SSH, optionally, is Obfuscated SSH
  51. // and meek protocols, which provide further circumvention
  52. // capabilities.
  53. type TunnelServer struct {
  54. runWaitGroup *sync.WaitGroup
  55. listenerError chan error
  56. shutdownBroadcast <-chan struct{}
  57. sshServer *sshServer
  58. }
  59. // NewTunnelServer initializes a new tunnel server.
  60. func NewTunnelServer(
  61. support *SupportServices,
  62. shutdownBroadcast <-chan struct{}) (*TunnelServer, error) {
  63. sshServer, err := newSSHServer(support, shutdownBroadcast)
  64. if err != nil {
  65. return nil, common.ContextError(err)
  66. }
  67. return &TunnelServer{
  68. runWaitGroup: new(sync.WaitGroup),
  69. listenerError: make(chan error),
  70. shutdownBroadcast: shutdownBroadcast,
  71. sshServer: sshServer,
  72. }, nil
  73. }
  74. // Run runs the tunnel server; this function blocks while running a selection of
  75. // listeners that handle connection using various obfuscation protocols.
  76. //
  77. // Run listens on each designated tunnel port and spawns new goroutines to handle
  78. // each client connection. It halts when shutdownBroadcast is signaled. A list of active
  79. // clients is maintained, and when halting all clients are cleanly shutdown.
  80. //
  81. // Each client goroutine handles its own obfuscation (optional), SSH handshake, SSH
  82. // authentication, and then looping on client new channel requests. "direct-tcpip"
  83. // channels, dynamic port fowards, are supported. When the UDPInterceptUdpgwServerAddress
  84. // config parameter is configured, UDP port forwards over a TCP stream, following
  85. // the udpgw protocol, are handled.
  86. //
  87. // A new goroutine is spawned to handle each port forward for each client. Each port
  88. // forward tracks its bytes transferred. Overall per-client stats for connection duration,
  89. // GeoIP, number of port forwards, and bytes transferred are tracked and logged when the
  90. // client shuts down.
  91. func (server *TunnelServer) Run() error {
  92. type sshListener struct {
  93. net.Listener
  94. localAddress string
  95. tunnelProtocol string
  96. }
  97. // TODO: should TunnelServer hold its own support pointer?
  98. support := server.sshServer.support
  99. // First bind all listeners; once all are successful,
  100. // start accepting connections on each.
  101. var listeners []*sshListener
  102. for tunnelProtocol, listenPort := range support.Config.TunnelProtocolPorts {
  103. localAddress := fmt.Sprintf(
  104. "%s:%d", support.Config.ServerIPAddress, listenPort)
  105. listener, err := net.Listen("tcp", localAddress)
  106. if err != nil {
  107. for _, existingListener := range listeners {
  108. existingListener.Listener.Close()
  109. }
  110. return common.ContextError(err)
  111. }
  112. log.WithContextFields(
  113. LogFields{
  114. "localAddress": localAddress,
  115. "tunnelProtocol": tunnelProtocol,
  116. }).Info("listening")
  117. listeners = append(
  118. listeners,
  119. &sshListener{
  120. Listener: listener,
  121. localAddress: localAddress,
  122. tunnelProtocol: tunnelProtocol,
  123. })
  124. }
  125. for _, listener := range listeners {
  126. server.runWaitGroup.Add(1)
  127. go func(listener *sshListener) {
  128. defer server.runWaitGroup.Done()
  129. log.WithContextFields(
  130. LogFields{
  131. "localAddress": listener.localAddress,
  132. "tunnelProtocol": listener.tunnelProtocol,
  133. }).Info("running")
  134. server.sshServer.runListener(
  135. listener.Listener,
  136. server.listenerError,
  137. listener.tunnelProtocol)
  138. log.WithContextFields(
  139. LogFields{
  140. "localAddress": listener.localAddress,
  141. "tunnelProtocol": listener.tunnelProtocol,
  142. }).Info("stopped")
  143. }(listener)
  144. }
  145. var err error
  146. select {
  147. case <-server.shutdownBroadcast:
  148. case err = <-server.listenerError:
  149. }
  150. for _, listener := range listeners {
  151. listener.Close()
  152. }
  153. server.sshServer.stopClients()
  154. server.runWaitGroup.Wait()
  155. log.WithContext().Info("stopped")
  156. return err
  157. }
  158. // GetLoadStats returns load stats for the tunnel server. The stats are
  159. // broken down by protocol ("SSH", "OSSH", etc.) and type. Types of stats
  160. // include current connected client count, total number of current port
  161. // forwards.
  162. func (server *TunnelServer) GetLoadStats() map[string]map[string]int64 {
  163. return server.sshServer.getLoadStats()
  164. }
  165. // ResetAllClientTrafficRules resets all established client traffic rules
  166. // to use the latest server config and client state.
  167. func (server *TunnelServer) ResetAllClientTrafficRules() {
  168. server.sshServer.resetAllClientTrafficRules()
  169. }
  170. // SetClientHandshakeState sets the handshake state -- that it completed and
  171. // what paramaters were passed -- in sshClient. This state is used for allowing
  172. // port forwards and for future traffic rule selection. SetClientHandshakeState
  173. // also triggers an immediate traffic rule re-selection, as the rules selected
  174. // upon tunnel establishment may no longer apply now that handshake values are
  175. // set.
  176. func (server *TunnelServer) SetClientHandshakeState(
  177. sessionID string, state handshakeState) error {
  178. return server.sshServer.setClientHandshakeState(sessionID, state)
  179. }
  180. type sshServer struct {
  181. support *SupportServices
  182. shutdownBroadcast <-chan struct{}
  183. sshHostKey ssh.Signer
  184. clientsMutex sync.Mutex
  185. stoppingClients bool
  186. acceptedClientCounts map[string]int64
  187. clients map[string]*sshClient
  188. }
  189. func newSSHServer(
  190. support *SupportServices,
  191. shutdownBroadcast <-chan struct{}) (*sshServer, error) {
  192. privateKey, err := ssh.ParseRawPrivateKey([]byte(support.Config.SSHPrivateKey))
  193. if err != nil {
  194. return nil, common.ContextError(err)
  195. }
  196. // TODO: use cert (ssh.NewCertSigner) for anti-fingerprint?
  197. signer, err := ssh.NewSignerFromKey(privateKey)
  198. if err != nil {
  199. return nil, common.ContextError(err)
  200. }
  201. return &sshServer{
  202. support: support,
  203. shutdownBroadcast: shutdownBroadcast,
  204. sshHostKey: signer,
  205. acceptedClientCounts: make(map[string]int64),
  206. clients: make(map[string]*sshClient),
  207. }, nil
  208. }
  209. // runListener is intended to run an a goroutine; it blocks
  210. // running a particular listener. If an unrecoverable error
  211. // occurs, it will send the error to the listenerError channel.
  212. func (sshServer *sshServer) runListener(
  213. listener net.Listener,
  214. listenerError chan<- error,
  215. tunnelProtocol string) {
  216. handleClient := func(clientConn net.Conn) {
  217. // process each client connection concurrently
  218. go sshServer.handleClient(tunnelProtocol, clientConn)
  219. }
  220. // Note: when exiting due to a unrecoverable error, be sure
  221. // to try to send the error to listenerError so that the outer
  222. // TunnelServer.Run will properly shut down instead of remaining
  223. // running.
  224. if common.TunnelProtocolUsesMeekHTTP(tunnelProtocol) ||
  225. common.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  226. meekServer, err := NewMeekServer(
  227. sshServer.support,
  228. listener,
  229. common.TunnelProtocolUsesMeekHTTPS(tunnelProtocol),
  230. handleClient,
  231. sshServer.shutdownBroadcast)
  232. if err != nil {
  233. select {
  234. case listenerError <- common.ContextError(err):
  235. default:
  236. }
  237. return
  238. }
  239. meekServer.Run()
  240. } else {
  241. for {
  242. conn, err := listener.Accept()
  243. select {
  244. case <-sshServer.shutdownBroadcast:
  245. if err == nil {
  246. conn.Close()
  247. }
  248. return
  249. default:
  250. }
  251. if err != nil {
  252. if e, ok := err.(net.Error); ok && e.Temporary() {
  253. log.WithContextFields(LogFields{"error": err}).Error("accept failed")
  254. // Temporary error, keep running
  255. continue
  256. }
  257. select {
  258. case listenerError <- common.ContextError(err):
  259. default:
  260. }
  261. return
  262. }
  263. handleClient(conn)
  264. }
  265. }
  266. }
  267. // An accepted client has completed a direct TCP or meek connection and has a net.Conn. Registration
  268. // is for tracking the number of connections.
  269. func (sshServer *sshServer) registerAcceptedClient(tunnelProtocol string) {
  270. sshServer.clientsMutex.Lock()
  271. defer sshServer.clientsMutex.Unlock()
  272. sshServer.acceptedClientCounts[tunnelProtocol] += 1
  273. }
  274. func (sshServer *sshServer) unregisterAcceptedClient(tunnelProtocol string) {
  275. sshServer.clientsMutex.Lock()
  276. defer sshServer.clientsMutex.Unlock()
  277. sshServer.acceptedClientCounts[tunnelProtocol] -= 1
  278. }
  279. // An established client has completed its SSH handshake and has a ssh.Conn. Registration is
  280. // for tracking the number of fully established clients and for maintaining a list of running
  281. // clients (for stopping at shutdown time).
  282. func (sshServer *sshServer) registerEstablishedClient(client *sshClient) bool {
  283. sshServer.clientsMutex.Lock()
  284. if sshServer.stoppingClients {
  285. sshServer.clientsMutex.Unlock()
  286. return false
  287. }
  288. // In the case of a duplicate client sessionID, the previous client is closed.
  289. // - Well-behaved clients generate pick a random sessionID that should be
  290. // unique (won't accidentally conflict) and hard to guess (can't be targetted
  291. // by a malicious client).
  292. // - Clients reuse the same sessionID when a tunnel is unexpectedly disconnected
  293. // and resestablished. In this case, when the same server is selected, this logic
  294. // will be hit; closing the old, dangling client is desirable.
  295. // - Multi-tunnel clients should not normally use one server for multiple tunnels.
  296. existingClient := sshServer.clients[client.sessionID]
  297. sshServer.clients[client.sessionID] = client
  298. sshServer.clientsMutex.Unlock()
  299. // Call stop() outside the mutex to avoid deadlock.
  300. if existingClient != nil {
  301. existingClient.stop()
  302. }
  303. return true
  304. }
  305. func (sshServer *sshServer) unregisterEstablishedClient(sessionID string) {
  306. sshServer.clientsMutex.Lock()
  307. client := sshServer.clients[sessionID]
  308. delete(sshServer.clients, sessionID)
  309. sshServer.clientsMutex.Unlock()
  310. // Call stop() outside the mutex to avoid deadlock.
  311. if client != nil {
  312. client.stop()
  313. }
  314. }
  315. func (sshServer *sshServer) getLoadStats() map[string]map[string]int64 {
  316. sshServer.clientsMutex.Lock()
  317. defer sshServer.clientsMutex.Unlock()
  318. loadStats := make(map[string]map[string]int64)
  319. // Explicitly populate with zeros to get 0 counts in log messages derived from getLoadStats()
  320. for tunnelProtocol, _ := range sshServer.support.Config.TunnelProtocolPorts {
  321. loadStats[tunnelProtocol] = make(map[string]int64)
  322. loadStats[tunnelProtocol]["AcceptedClients"] = 0
  323. loadStats[tunnelProtocol]["EstablishedClients"] = 0
  324. loadStats[tunnelProtocol]["TCPPortForwards"] = 0
  325. loadStats[tunnelProtocol]["TotalTCPPortForwards"] = 0
  326. loadStats[tunnelProtocol]["UDPPortForwards"] = 0
  327. loadStats[tunnelProtocol]["TotalUDPPortForwards"] = 0
  328. }
  329. // Note: as currently tracked/counted, each established client is also an accepted client
  330. for tunnelProtocol, acceptedClientCount := range sshServer.acceptedClientCounts {
  331. loadStats[tunnelProtocol]["AcceptedClients"] = acceptedClientCount
  332. }
  333. for _, client := range sshServer.clients {
  334. // Note: can't sum trafficState.peakConcurrentPortForwardCount to get a global peak
  335. loadStats[client.tunnelProtocol]["EstablishedClients"] += 1
  336. client.Lock()
  337. loadStats[client.tunnelProtocol]["TCPPortForwards"] += client.tcpTrafficState.concurrentPortForwardCount
  338. loadStats[client.tunnelProtocol]["TotalTCPPortForwards"] += client.tcpTrafficState.totalPortForwardCount
  339. loadStats[client.tunnelProtocol]["UDPPortForwards"] += client.udpTrafficState.concurrentPortForwardCount
  340. loadStats[client.tunnelProtocol]["TotalUDPPortForwards"] += client.udpTrafficState.totalPortForwardCount
  341. client.Unlock()
  342. }
  343. // Calculate and report totals across all protocols. It's easier to do this here
  344. // than futher down the stats stack. Also useful for glancing at log files.
  345. allProtocolsStats := make(map[string]int64)
  346. for _, stats := range loadStats {
  347. for name, value := range stats {
  348. allProtocolsStats[name] += value
  349. }
  350. }
  351. loadStats["ALL"] = allProtocolsStats
  352. return loadStats
  353. }
  354. func (sshServer *sshServer) resetAllClientTrafficRules() {
  355. sshServer.clientsMutex.Lock()
  356. clients := make(map[string]*sshClient)
  357. for sessionID, client := range sshServer.clients {
  358. clients[sessionID] = client
  359. }
  360. sshServer.clientsMutex.Unlock()
  361. for _, client := range clients {
  362. client.setTrafficRules()
  363. }
  364. }
  365. func (sshServer *sshServer) setClientHandshakeState(
  366. sessionID string, state handshakeState) error {
  367. sshServer.clientsMutex.Lock()
  368. client := sshServer.clients[sessionID]
  369. sshServer.clientsMutex.Unlock()
  370. if client == nil {
  371. return common.ContextError(errors.New("unknown session ID"))
  372. }
  373. err := client.setHandshakeState(state)
  374. if err != nil {
  375. return common.ContextError(err)
  376. }
  377. client.setTrafficRules()
  378. return nil
  379. }
  380. func (sshServer *sshServer) stopClients() {
  381. sshServer.clientsMutex.Lock()
  382. sshServer.stoppingClients = true
  383. clients := sshServer.clients
  384. sshServer.clients = make(map[string]*sshClient)
  385. sshServer.clientsMutex.Unlock()
  386. for _, client := range clients {
  387. client.stop()
  388. }
  389. }
  390. func (sshServer *sshServer) handleClient(tunnelProtocol string, clientConn net.Conn) {
  391. sshServer.registerAcceptedClient(tunnelProtocol)
  392. defer sshServer.unregisterAcceptedClient(tunnelProtocol)
  393. geoIPData := sshServer.support.GeoIPService.Lookup(
  394. common.IPAddressFromAddr(clientConn.RemoteAddr()))
  395. sshClient := newSshClient(sshServer, tunnelProtocol, geoIPData)
  396. // Set initial traffic rules, pre-handshake, based on currently known info.
  397. sshClient.setTrafficRules()
  398. // Wrap the base client connection with an ActivityMonitoredConn which will
  399. // terminate the connection if no data is received before the deadline. This
  400. // timeout is in effect for the entire duration of the SSH connection. Clients
  401. // must actively use the connection or send SSH keep alive requests to keep
  402. // the connection active. Writes are not considered reliable activity indicators
  403. // due to buffering.
  404. activityConn, err := common.NewActivityMonitoredConn(
  405. clientConn,
  406. SSH_CONNECTION_READ_DEADLINE,
  407. false,
  408. nil)
  409. if err != nil {
  410. clientConn.Close()
  411. log.WithContextFields(LogFields{"error": err}).Error("NewActivityMonitoredConn failed")
  412. return
  413. }
  414. clientConn = activityConn
  415. // Further wrap the connection in a rate limiting ThrottledConn.
  416. throttledConn := common.NewThrottledConn(clientConn, sshClient.rateLimits())
  417. clientConn = throttledConn
  418. // Run the initial [obfuscated] SSH handshake in a goroutine so we can both
  419. // respect shutdownBroadcast and implement a specific handshake timeout.
  420. // The timeout is to reclaim network resources in case the handshake takes
  421. // too long.
  422. type sshNewServerConnResult struct {
  423. conn net.Conn
  424. sshConn *ssh.ServerConn
  425. channels <-chan ssh.NewChannel
  426. requests <-chan *ssh.Request
  427. err error
  428. }
  429. resultChannel := make(chan *sshNewServerConnResult, 2)
  430. if SSH_HANDSHAKE_TIMEOUT > 0 {
  431. time.AfterFunc(time.Duration(SSH_HANDSHAKE_TIMEOUT), func() {
  432. resultChannel <- &sshNewServerConnResult{err: errors.New("ssh handshake timeout")}
  433. })
  434. }
  435. go func(conn net.Conn) {
  436. sshServerConfig := &ssh.ServerConfig{
  437. PasswordCallback: sshClient.passwordCallback,
  438. AuthLogCallback: sshClient.authLogCallback,
  439. ServerVersion: sshServer.support.Config.SSHServerVersion,
  440. }
  441. sshServerConfig.AddHostKey(sshServer.sshHostKey)
  442. result := &sshNewServerConnResult{}
  443. // Wrap the connection in an SSH deobfuscator when required.
  444. if common.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  445. // Note: NewObfuscatedSshConn blocks on network I/O
  446. // TODO: ensure this won't block shutdown
  447. conn, result.err = psiphon.NewObfuscatedSshConn(
  448. psiphon.OBFUSCATION_CONN_MODE_SERVER,
  449. conn,
  450. sshServer.support.Config.ObfuscatedSSHKey)
  451. if result.err != nil {
  452. result.err = common.ContextError(result.err)
  453. }
  454. }
  455. if result.err == nil {
  456. result.sshConn, result.channels, result.requests, result.err =
  457. ssh.NewServerConn(conn, sshServerConfig)
  458. }
  459. resultChannel <- result
  460. }(clientConn)
  461. var result *sshNewServerConnResult
  462. select {
  463. case result = <-resultChannel:
  464. case <-sshServer.shutdownBroadcast:
  465. // Close() will interrupt an ongoing handshake
  466. // TODO: wait for goroutine to exit before returning?
  467. clientConn.Close()
  468. return
  469. }
  470. if result.err != nil {
  471. clientConn.Close()
  472. // This is a Debug log due to noise. The handshake often fails due to I/O
  473. // errors as clients frequently interrupt connections in progress when
  474. // client-side load balancing completes a connection to a different server.
  475. log.WithContextFields(LogFields{"error": result.err}).Debug("handshake failed")
  476. return
  477. }
  478. sshClient.Lock()
  479. sshClient.sshConn = result.sshConn
  480. sshClient.activityConn = activityConn
  481. sshClient.throttledConn = throttledConn
  482. sshClient.Unlock()
  483. if !sshServer.registerEstablishedClient(sshClient) {
  484. clientConn.Close()
  485. log.WithContext().Warning("register failed")
  486. return
  487. }
  488. defer sshServer.unregisterEstablishedClient(sshClient.sessionID)
  489. sshClient.runClient(result.channels, result.requests)
  490. // Note: sshServer.unregisterClient calls sshClient.Close(),
  491. // which also closes underlying transport Conn.
  492. }
  493. type sshClient struct {
  494. sync.Mutex
  495. sshServer *sshServer
  496. tunnelProtocol string
  497. sshConn ssh.Conn
  498. activityConn *common.ActivityMonitoredConn
  499. throttledConn *common.ThrottledConn
  500. geoIPData GeoIPData
  501. sessionID string
  502. handshakeState handshakeState
  503. udpChannel ssh.Channel
  504. trafficRules TrafficRules
  505. tcpTrafficState trafficState
  506. udpTrafficState trafficState
  507. channelHandlerWaitGroup *sync.WaitGroup
  508. tcpPortForwardLRU *common.LRUConns
  509. stopBroadcast chan struct{}
  510. }
  511. type trafficState struct {
  512. // Note: 64-bit ints used with atomic operations are at placed
  513. // at the start of struct to ensure 64-bit alignment.
  514. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  515. bytesUp int64
  516. bytesDown int64
  517. concurrentPortForwardCount int64
  518. peakConcurrentPortForwardCount int64
  519. totalPortForwardCount int64
  520. }
  521. type handshakeState struct {
  522. completed bool
  523. apiProtocol string
  524. apiParams requestJSONObject
  525. }
  526. func newSshClient(
  527. sshServer *sshServer, tunnelProtocol string, geoIPData GeoIPData) *sshClient {
  528. return &sshClient{
  529. sshServer: sshServer,
  530. tunnelProtocol: tunnelProtocol,
  531. geoIPData: geoIPData,
  532. channelHandlerWaitGroup: new(sync.WaitGroup),
  533. tcpPortForwardLRU: common.NewLRUConns(),
  534. stopBroadcast: make(chan struct{}),
  535. }
  536. }
  537. func (sshClient *sshClient) passwordCallback(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
  538. expectedSessionIDLength := 2 * common.PSIPHON_API_CLIENT_SESSION_ID_LENGTH
  539. expectedSSHPasswordLength := 2 * SSH_PASSWORD_BYTE_LENGTH
  540. var sshPasswordPayload struct {
  541. SessionId string `json:"SessionId"`
  542. SshPassword string `json:"SshPassword"`
  543. }
  544. err := json.Unmarshal(password, &sshPasswordPayload)
  545. if err != nil {
  546. // Backwards compatibility case: instead of a JSON payload, older clients
  547. // send the hex encoded session ID prepended to the SSH password.
  548. // Note: there's an even older case where clients don't send any session ID,
  549. // but that's no longer supported.
  550. if len(password) == expectedSessionIDLength+expectedSSHPasswordLength {
  551. sshPasswordPayload.SessionId = string(password[0:expectedSessionIDLength])
  552. sshPasswordPayload.SshPassword = string(password[expectedSSHPasswordLength:len(password)])
  553. } else {
  554. return nil, common.ContextError(fmt.Errorf("invalid password payload for %q", conn.User()))
  555. }
  556. }
  557. if !isHexDigits(sshClient.sshServer.support, sshPasswordPayload.SessionId) ||
  558. len(sshPasswordPayload.SessionId) != expectedSessionIDLength {
  559. return nil, common.ContextError(fmt.Errorf("invalid session ID for %q", conn.User()))
  560. }
  561. userOk := (subtle.ConstantTimeCompare(
  562. []byte(conn.User()), []byte(sshClient.sshServer.support.Config.SSHUserName)) == 1)
  563. passwordOk := (subtle.ConstantTimeCompare(
  564. []byte(sshPasswordPayload.SshPassword), []byte(sshClient.sshServer.support.Config.SSHPassword)) == 1)
  565. if !userOk || !passwordOk {
  566. return nil, common.ContextError(fmt.Errorf("invalid password for %q", conn.User()))
  567. }
  568. sessionID := sshPasswordPayload.SessionId
  569. sshClient.Lock()
  570. sshClient.sessionID = sessionID
  571. geoIPData := sshClient.geoIPData
  572. sshClient.Unlock()
  573. // Store the GeoIP data associated with the session ID. This makes the GeoIP data
  574. // available to the web server for web transport Psiphon API requests. To allow for
  575. // post-tunnel final status requests, the lifetime of cached GeoIP records exceeds
  576. // the lifetime of the sshClient, and that's why this distinct session cache exists.
  577. sshClient.sshServer.support.GeoIPService.SetSessionCache(sessionID, geoIPData)
  578. return nil, nil
  579. }
  580. func (sshClient *sshClient) authLogCallback(conn ssh.ConnMetadata, method string, err error) {
  581. if err != nil {
  582. if method == "none" && err.Error() == "no auth passed yet" {
  583. // In this case, the callback invocation is noise from auth negotiation
  584. return
  585. }
  586. // Note: here we previously logged messages for fail2ban to act on. This is no longer
  587. // done as the complexity outweighs the benefits.
  588. //
  589. // - The SSH credential is not secret -- it's in the server entry. Attackers targetting
  590. // the server likely already have the credential. On the other hand, random scanning and
  591. // brute forcing is mitigated with high entropy random passwords, rate limiting
  592. // (implemented on the host via iptables), and limited capabilities (the SSH session can
  593. // only port forward).
  594. //
  595. // - fail2ban coverage was inconsistent; in the case of an unfronted meek protocol through
  596. // an upstream proxy, the remote address is the upstream proxy, which should not be blocked.
  597. // The X-Forwarded-For header cant be used instead as it may be forged and used to get IPs
  598. // deliberately blocked; and in any case fail2ban adds iptables rules which can only block
  599. // by direct remote IP, not by original client IP. Fronted meek has the same iptables issue.
  600. //
  601. // TODO: random scanning and brute forcing of port 22 will result in log noise. To eliminate
  602. // this, and to also cover meek protocols, and bad obfuscation keys, and bad inputs to the web
  603. // server, consider implementing fail2ban-type logic directly in this server, with the ability
  604. // to use X-Forwarded-For (when trustworthy; e.g, from a CDN).
  605. log.WithContextFields(LogFields{"error": err, "method": method}).Warning("authentication failed")
  606. } else {
  607. log.WithContextFields(LogFields{"error": err, "method": method}).Debug("authentication success")
  608. }
  609. }
  610. func (sshClient *sshClient) stop() {
  611. sshClient.sshConn.Close()
  612. sshClient.sshConn.Wait()
  613. close(sshClient.stopBroadcast)
  614. sshClient.channelHandlerWaitGroup.Wait()
  615. // Note: reporting duration based on last confirmed data transfer, which
  616. // is reads for sshClient.activityConn.GetActiveDuration(), and not
  617. // connection closing is important for protocols such as meek. For
  618. // meek, the connection remains open until the HTTP session expires,
  619. // which may be some time after the tunnel has closed. (The meek
  620. // protocol has no allowance for signalling payload EOF, and even if
  621. // it did the client may not have the opportunity to send a final
  622. // request with an EOF flag set.)
  623. sshClient.Lock()
  624. logFields := getRequestLogFields(
  625. sshClient.sshServer.support,
  626. "server_tunnel",
  627. sshClient.geoIPData,
  628. sshClient.handshakeState.apiParams,
  629. baseRequestParams)
  630. // TODO: match legacy log field naming convention?
  631. logFields["HandshakeCompleted"] = sshClient.handshakeState.completed
  632. logFields["startTime"] = sshClient.activityConn.GetStartTime()
  633. logFields["Duration"] = sshClient.activityConn.GetActiveDuration()
  634. logFields["BytesUpTCP"] = sshClient.tcpTrafficState.bytesUp
  635. logFields["BytesDownTCP"] = sshClient.tcpTrafficState.bytesDown
  636. logFields["PeakConcurrentPortForwardCountTCP"] = sshClient.tcpTrafficState.peakConcurrentPortForwardCount
  637. logFields["TotalPortForwardCountTCP"] = sshClient.tcpTrafficState.totalPortForwardCount
  638. logFields["BytesUpUDP"] = sshClient.udpTrafficState.bytesUp
  639. logFields["BytesDownUDP"] = sshClient.udpTrafficState.bytesDown
  640. logFields["PeakConcurrentPortForwardCountUDP"] = sshClient.udpTrafficState.peakConcurrentPortForwardCount
  641. logFields["TotalPortForwardCountUDP"] = sshClient.udpTrafficState.totalPortForwardCount
  642. sshClient.Unlock()
  643. log.LogRawFieldsWithTimestamp(logFields)
  644. }
  645. // runClient handles/dispatches new channel and new requests from the client.
  646. // When the SSH client connection closes, both the channels and requests channels
  647. // will close and runClient will exit.
  648. func (sshClient *sshClient) runClient(
  649. channels <-chan ssh.NewChannel, requests <-chan *ssh.Request) {
  650. requestsWaitGroup := new(sync.WaitGroup)
  651. requestsWaitGroup.Add(1)
  652. go func() {
  653. defer requestsWaitGroup.Done()
  654. for request := range requests {
  655. // Requests are processed serially; API responses must be sent in request order.
  656. var responsePayload []byte
  657. var err error
  658. if request.Type == "keepalive@openssh.com" {
  659. // Keepalive requests have an empty response.
  660. } else {
  661. // All other requests are assumed to be API requests.
  662. responsePayload, err = sshAPIRequestHandler(
  663. sshClient.sshServer.support,
  664. sshClient.geoIPData,
  665. request.Type,
  666. request.Payload)
  667. }
  668. if err == nil {
  669. err = request.Reply(true, responsePayload)
  670. } else {
  671. log.WithContextFields(LogFields{"error": err}).Warning("request failed")
  672. err = request.Reply(false, nil)
  673. }
  674. if err != nil {
  675. log.WithContextFields(LogFields{"error": err}).Warning("response failed")
  676. }
  677. }
  678. }()
  679. for newChannel := range channels {
  680. if newChannel.ChannelType() != "direct-tcpip" {
  681. sshClient.rejectNewChannel(newChannel, ssh.Prohibited, "unknown or unsupported channel type")
  682. continue
  683. }
  684. // process each port forward concurrently
  685. sshClient.channelHandlerWaitGroup.Add(1)
  686. go sshClient.handleNewPortForwardChannel(newChannel)
  687. }
  688. requestsWaitGroup.Wait()
  689. }
  690. func (sshClient *sshClient) rejectNewChannel(newChannel ssh.NewChannel, reason ssh.RejectionReason, logMessage string) {
  691. log.WithContextFields(
  692. LogFields{
  693. "channelType": newChannel.ChannelType(),
  694. "logMessage": logMessage,
  695. "rejectReason": reason.String(),
  696. }).Warning("reject new channel")
  697. // Note: logMessage is internal, for logging only; just the RejectionReason is sent to the client
  698. newChannel.Reject(reason, reason.String())
  699. }
  700. func (sshClient *sshClient) handleNewPortForwardChannel(newChannel ssh.NewChannel) {
  701. defer sshClient.channelHandlerWaitGroup.Done()
  702. // http://tools.ietf.org/html/rfc4254#section-7.2
  703. var directTcpipExtraData struct {
  704. HostToConnect string
  705. PortToConnect uint32
  706. OriginatorIPAddress string
  707. OriginatorPort uint32
  708. }
  709. err := ssh.Unmarshal(newChannel.ExtraData(), &directTcpipExtraData)
  710. if err != nil {
  711. sshClient.rejectNewChannel(newChannel, ssh.Prohibited, "invalid extra data")
  712. return
  713. }
  714. // Intercept TCP port forwards to a specified udpgw server and handle directly.
  715. // TODO: also support UDP explicitly, e.g. with a custom "direct-udp" channel type?
  716. isUDPChannel := sshClient.sshServer.support.Config.UDPInterceptUdpgwServerAddress != "" &&
  717. sshClient.sshServer.support.Config.UDPInterceptUdpgwServerAddress ==
  718. net.JoinHostPort(directTcpipExtraData.HostToConnect, strconv.Itoa(int(directTcpipExtraData.PortToConnect)))
  719. if isUDPChannel {
  720. sshClient.handleUDPChannel(newChannel)
  721. } else {
  722. sshClient.handleTCPChannel(
  723. directTcpipExtraData.HostToConnect, int(directTcpipExtraData.PortToConnect), newChannel)
  724. }
  725. }
  726. // setHandshakeState records that a client has completed a handshake API request.
  727. // Some parameters from the handshake request may be used in future traffic rule
  728. // selection. Port forwards are disallowed until a handshake is complete. The
  729. // handshake parameters are included in the session summary log recorded in
  730. // sshClient.stop().
  731. func (sshClient *sshClient) setHandshakeState(state handshakeState) error {
  732. sshClient.Lock()
  733. defer sshClient.Unlock()
  734. // Client must only perform one handshake
  735. if sshClient.handshakeState.completed {
  736. return common.ContextError(errors.New("handshake already completed"))
  737. }
  738. sshClient.handshakeState = state
  739. return nil
  740. }
  741. // setTrafficRules resets the client's traffic rules based on the latest server config
  742. // and client state. As sshClient.trafficRules may be reset by a concurrent goroutine,
  743. // trafficRules must only be accessed within the sshClient mutex.
  744. func (sshClient *sshClient) setTrafficRules() {
  745. sshClient.Lock()
  746. defer sshClient.Unlock()
  747. sshClient.trafficRules = sshClient.sshServer.support.TrafficRulesSet.GetTrafficRules(
  748. sshClient.tunnelProtocol, sshClient.geoIPData, sshClient.handshakeState)
  749. }
  750. func (sshClient *sshClient) rateLimits() common.RateLimits {
  751. sshClient.Lock()
  752. defer sshClient.Unlock()
  753. return sshClient.trafficRules.RateLimits.CommonRateLimits()
  754. }
  755. func (sshClient *sshClient) idleTCPPortForwardTimeout() time.Duration {
  756. sshClient.Lock()
  757. defer sshClient.Unlock()
  758. return time.Duration(*sshClient.trafficRules.IdleTCPPortForwardTimeoutMilliseconds) * time.Millisecond
  759. }
  760. func (sshClient *sshClient) idleUDPPortForwardTimeout() time.Duration {
  761. sshClient.Lock()
  762. defer sshClient.Unlock()
  763. return time.Duration(*sshClient.trafficRules.IdleUDPPortForwardTimeoutMilliseconds) * time.Millisecond
  764. }
  765. const (
  766. portForwardTypeTCP = iota
  767. portForwardTypeUDP
  768. )
  769. func (sshClient *sshClient) isPortForwardPermitted(
  770. portForwardType int, host string, port int) bool {
  771. sshClient.Lock()
  772. defer sshClient.Unlock()
  773. if !sshClient.handshakeState.completed {
  774. return false
  775. }
  776. if common.Contains(SSH_DISALLOWED_PORT_FORWARD_HOSTS, host) {
  777. return false
  778. }
  779. var allowPorts []int
  780. if portForwardType == portForwardTypeTCP {
  781. allowPorts = sshClient.trafficRules.AllowTCPPorts
  782. } else {
  783. allowPorts = sshClient.trafficRules.AllowUDPPorts
  784. }
  785. if len(allowPorts) == 0 {
  786. return true
  787. }
  788. // TODO: faster lookup?
  789. if len(allowPorts) > 0 {
  790. for _, allowPort := range allowPorts {
  791. if port == allowPort {
  792. return true
  793. }
  794. }
  795. }
  796. // TODO: AllowSubnets won't match when host is a domain.
  797. // Callers should resolve domain host before checking
  798. // isPortForwardPermitted.
  799. if ip := net.ParseIP(host); ip != nil {
  800. for _, subnet := range sshClient.trafficRules.AllowSubnets {
  801. // Note: ignoring error as config has been validated
  802. _, network, _ := net.ParseCIDR(subnet)
  803. if network.Contains(ip) {
  804. return true
  805. }
  806. }
  807. }
  808. return false
  809. }
  810. func (sshClient *sshClient) isPortForwardLimitExceeded(
  811. portForwardType int) (int, bool) {
  812. sshClient.Lock()
  813. defer sshClient.Unlock()
  814. var maxPortForwardCount int
  815. var state *trafficState
  816. if portForwardType == portForwardTypeTCP {
  817. maxPortForwardCount = *sshClient.trafficRules.MaxTCPPortForwardCount
  818. state = &sshClient.tcpTrafficState
  819. } else {
  820. maxPortForwardCount = *sshClient.trafficRules.MaxUDPPortForwardCount
  821. state = &sshClient.udpTrafficState
  822. }
  823. if maxPortForwardCount > 0 && state.concurrentPortForwardCount >= int64(maxPortForwardCount) {
  824. return maxPortForwardCount, true
  825. }
  826. return maxPortForwardCount, false
  827. }
  828. func (sshClient *sshClient) openedPortForward(
  829. portForwardType int) {
  830. sshClient.Lock()
  831. defer sshClient.Unlock()
  832. var state *trafficState
  833. if portForwardType == portForwardTypeTCP {
  834. state = &sshClient.tcpTrafficState
  835. } else {
  836. state = &sshClient.udpTrafficState
  837. }
  838. state.concurrentPortForwardCount += 1
  839. if state.concurrentPortForwardCount > state.peakConcurrentPortForwardCount {
  840. state.peakConcurrentPortForwardCount = state.concurrentPortForwardCount
  841. }
  842. state.totalPortForwardCount += 1
  843. }
  844. func (sshClient *sshClient) closedPortForward(
  845. portForwardType int, bytesUp, bytesDown int64) {
  846. sshClient.Lock()
  847. defer sshClient.Unlock()
  848. var state *trafficState
  849. if portForwardType == portForwardTypeTCP {
  850. state = &sshClient.tcpTrafficState
  851. } else {
  852. state = &sshClient.udpTrafficState
  853. }
  854. state.concurrentPortForwardCount -= 1
  855. state.bytesUp += bytesUp
  856. state.bytesDown += bytesDown
  857. }
  858. func (sshClient *sshClient) handleTCPChannel(
  859. hostToConnect string,
  860. portToConnect int,
  861. newChannel ssh.NewChannel) {
  862. isWebServerPortForward := false
  863. config := sshClient.sshServer.support.Config
  864. if config.WebServerPortForwardAddress != "" {
  865. destination := net.JoinHostPort(hostToConnect, strconv.Itoa(portToConnect))
  866. if destination == config.WebServerPortForwardAddress {
  867. isWebServerPortForward = true
  868. if config.WebServerPortForwardRedirectAddress != "" {
  869. // Note: redirect format is validated when config is loaded
  870. host, portStr, _ := net.SplitHostPort(config.WebServerPortForwardRedirectAddress)
  871. port, _ := strconv.Atoi(portStr)
  872. hostToConnect = host
  873. portToConnect = port
  874. }
  875. }
  876. }
  877. if !isWebServerPortForward && !sshClient.isPortForwardPermitted(
  878. portForwardTypeTCP, hostToConnect, portToConnect) {
  879. sshClient.rejectNewChannel(
  880. newChannel, ssh.Prohibited, "port forward not permitted")
  881. return
  882. }
  883. var bytesUp, bytesDown int64
  884. sshClient.openedPortForward(portForwardTypeTCP)
  885. defer func() {
  886. sshClient.closedPortForward(
  887. portForwardTypeTCP, atomic.LoadInt64(&bytesUp), atomic.LoadInt64(&bytesDown))
  888. }()
  889. // TOCTOU note: important to increment the port forward count (via
  890. // openPortForward) _before_ checking isPortForwardLimitExceeded
  891. // otherwise, the client could potentially consume excess resources
  892. // by initiating many port forwards concurrently.
  893. // TODO: close LRU connection (after successful Dial) instead of
  894. // rejecting new connection?
  895. if maxCount, exceeded := sshClient.isPortForwardLimitExceeded(portForwardTypeTCP); exceeded {
  896. // Close the oldest TCP port forward. CloseOldest() closes
  897. // the conn and the port forward's goroutine will complete
  898. // the cleanup asynchronously.
  899. //
  900. // Some known limitations:
  901. //
  902. // - Since CloseOldest() closes the upstream socket but does not
  903. // clean up all resources associated with the port forward. These
  904. // include the goroutine(s) relaying traffic as well as the SSH
  905. // channel. Closing the socket will interrupt the goroutines which
  906. // will then complete the cleanup. But, since the full cleanup is
  907. // asynchronous, there exists a possibility that a client can consume
  908. // more than max port forward resources -- just not upstream sockets.
  909. //
  910. // - An LRU list entry for this port forward is not added until
  911. // after the dial completes, but the port forward is counted
  912. // towards max limits. This means many dials in progress will
  913. // put established connections in jeopardy.
  914. //
  915. // - We're closing the oldest open connection _before_ successfully
  916. // dialing the new port forward. This means we are potentially
  917. // discarding a good connection to make way for a failed connection.
  918. // We cannot simply dial first and still maintain a limit on
  919. // resources used, so to address this we'd need to add some
  920. // accounting for connections still establishing.
  921. sshClient.tcpPortForwardLRU.CloseOldest()
  922. log.WithContextFields(
  923. LogFields{
  924. "maxCount": maxCount,
  925. }).Debug("closed LRU TCP port forward")
  926. }
  927. // Dial the target remote address. This is done in a goroutine to
  928. // ensure the shutdown signal is handled immediately.
  929. remoteAddr := fmt.Sprintf("%s:%d", hostToConnect, portToConnect)
  930. log.WithContextFields(LogFields{"remoteAddr": remoteAddr}).Debug("dialing")
  931. type dialTcpResult struct {
  932. conn net.Conn
  933. err error
  934. }
  935. resultChannel := make(chan *dialTcpResult, 1)
  936. go func() {
  937. // TODO: on EADDRNOTAVAIL, temporarily suspend new clients
  938. // TODO: IPv6 support
  939. conn, err := net.DialTimeout(
  940. "tcp4", remoteAddr, SSH_TCP_PORT_FORWARD_DIAL_TIMEOUT)
  941. resultChannel <- &dialTcpResult{conn, err}
  942. }()
  943. var result *dialTcpResult
  944. select {
  945. case result = <-resultChannel:
  946. case <-sshClient.stopBroadcast:
  947. // Note: may leave dial in progress (TODO: use DialContext to cancel)
  948. return
  949. }
  950. if result.err != nil {
  951. sshClient.rejectNewChannel(newChannel, ssh.ConnectionFailed, result.err.Error())
  952. return
  953. }
  954. // The upstream TCP port forward connection has been established. Schedule
  955. // some cleanup and notify the SSH client that the channel is accepted.
  956. fwdConn := result.conn
  957. defer fwdConn.Close()
  958. fwdChannel, requests, err := newChannel.Accept()
  959. if err != nil {
  960. log.WithContextFields(LogFields{"error": err}).Warning("accept new channel failed")
  961. return
  962. }
  963. go ssh.DiscardRequests(requests)
  964. defer fwdChannel.Close()
  965. // ActivityMonitoredConn monitors the TCP port forward I/O and updates
  966. // its LRU status. ActivityMonitoredConn also times out I/O on the port
  967. // forward if both reads and writes have been idle for the specified
  968. // duration.
  969. lruEntry := sshClient.tcpPortForwardLRU.Add(fwdConn)
  970. defer lruEntry.Remove()
  971. fwdConn, err = common.NewActivityMonitoredConn(
  972. fwdConn,
  973. sshClient.idleTCPPortForwardTimeout(),
  974. true,
  975. lruEntry)
  976. if result.err != nil {
  977. log.WithContextFields(LogFields{"error": err}).Error("NewActivityMonitoredConn failed")
  978. return
  979. }
  980. // Relay channel to forwarded connection.
  981. log.WithContextFields(LogFields{"remoteAddr": remoteAddr}).Debug("relaying")
  982. // TODO: relay errors to fwdChannel.Stderr()?
  983. relayWaitGroup := new(sync.WaitGroup)
  984. relayWaitGroup.Add(1)
  985. go func() {
  986. defer relayWaitGroup.Done()
  987. // io.Copy allocates a 32K temporary buffer, and each port forward relay uses
  988. // two of these buffers; using io.CopyBuffer with a smaller buffer reduces the
  989. // overall memory footprint.
  990. bytes, err := io.CopyBuffer(
  991. fwdChannel, fwdConn, make([]byte, SSH_TCP_PORT_FORWARD_COPY_BUFFER_SIZE))
  992. atomic.AddInt64(&bytesDown, bytes)
  993. if err != nil && err != io.EOF {
  994. // Debug since errors such as "connection reset by peer" occur during normal operation
  995. log.WithContextFields(LogFields{"error": err}).Debug("downstream TCP relay failed")
  996. }
  997. // Interrupt upstream io.Copy when downstream is shutting down.
  998. // TODO: this is done to quickly cleanup the port forward when
  999. // fwdConn has a read timeout, but is it clean -- upstream may still
  1000. // be flowing?
  1001. fwdChannel.Close()
  1002. }()
  1003. bytes, err := io.CopyBuffer(
  1004. fwdConn, fwdChannel, make([]byte, SSH_TCP_PORT_FORWARD_COPY_BUFFER_SIZE))
  1005. atomic.AddInt64(&bytesUp, bytes)
  1006. if err != nil && err != io.EOF {
  1007. log.WithContextFields(LogFields{"error": err}).Debug("upstream TCP relay failed")
  1008. }
  1009. // Shutdown special case: fwdChannel will be closed and return EOF when
  1010. // the SSH connection is closed, but we need to explicitly close fwdConn
  1011. // to interrupt the downstream io.Copy, which may be blocked on a
  1012. // fwdConn.Read().
  1013. fwdConn.Close()
  1014. relayWaitGroup.Wait()
  1015. log.WithContextFields(
  1016. LogFields{
  1017. "remoteAddr": remoteAddr,
  1018. "bytesUp": atomic.LoadInt64(&bytesUp),
  1019. "bytesDown": atomic.LoadInt64(&bytesDown)}).Debug("exiting")
  1020. }