tunnelServer.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  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. defer sshServer.clientsMutex.Unlock()
  285. if sshServer.stoppingClients {
  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. if existingClient != nil {
  298. existingClient.stop()
  299. }
  300. sshServer.clients[client.sessionID] = client
  301. return true
  302. }
  303. func (sshServer *sshServer) unregisterEstablishedClient(sessionID string) {
  304. sshServer.clientsMutex.Lock()
  305. client := sshServer.clients[sessionID]
  306. delete(sshServer.clients, sessionID)
  307. sshServer.clientsMutex.Unlock()
  308. if client != nil {
  309. client.stop()
  310. }
  311. }
  312. func (sshServer *sshServer) getLoadStats() map[string]map[string]int64 {
  313. sshServer.clientsMutex.Lock()
  314. defer sshServer.clientsMutex.Unlock()
  315. loadStats := make(map[string]map[string]int64)
  316. // Explicitly populate with zeros to get 0 counts in log messages derived from getLoadStats()
  317. for tunnelProtocol, _ := range sshServer.support.Config.TunnelProtocolPorts {
  318. loadStats[tunnelProtocol] = make(map[string]int64)
  319. loadStats[tunnelProtocol]["AcceptedClients"] = 0
  320. loadStats[tunnelProtocol]["EstablishedClients"] = 0
  321. loadStats[tunnelProtocol]["TCPPortForwards"] = 0
  322. loadStats[tunnelProtocol]["TotalTCPPortForwards"] = 0
  323. loadStats[tunnelProtocol]["UDPPortForwards"] = 0
  324. loadStats[tunnelProtocol]["TotalUDPPortForwards"] = 0
  325. }
  326. // Note: as currently tracked/counted, each established client is also an accepted client
  327. for tunnelProtocol, acceptedClientCount := range sshServer.acceptedClientCounts {
  328. loadStats[tunnelProtocol]["AcceptedClients"] = acceptedClientCount
  329. }
  330. for _, client := range sshServer.clients {
  331. // Note: can't sum trafficState.peakConcurrentPortForwardCount to get a global peak
  332. loadStats[client.tunnelProtocol]["EstablishedClients"] += 1
  333. client.Lock()
  334. loadStats[client.tunnelProtocol]["TCPPortForwards"] += client.tcpTrafficState.concurrentPortForwardCount
  335. loadStats[client.tunnelProtocol]["TotalTCPPortForwards"] += client.tcpTrafficState.totalPortForwardCount
  336. loadStats[client.tunnelProtocol]["UDPPortForwards"] += client.udpTrafficState.concurrentPortForwardCount
  337. loadStats[client.tunnelProtocol]["TotalUDPPortForwards"] += client.udpTrafficState.totalPortForwardCount
  338. client.Unlock()
  339. }
  340. // Calculate and report totals across all protocols. It's easier to do this here
  341. // than futher down the stats stack. Also useful for glancing at log files.
  342. allProtocolsStats := make(map[string]int64)
  343. for _, stats := range loadStats {
  344. for name, value := range stats {
  345. allProtocolsStats[name] += value
  346. }
  347. }
  348. loadStats["ALL"] = allProtocolsStats
  349. return loadStats
  350. }
  351. func (sshServer *sshServer) resetAllClientTrafficRules() {
  352. sshServer.clientsMutex.Lock()
  353. clients := make(map[string]*sshClient)
  354. for sessionID, client := range sshServer.clients {
  355. clients[sessionID] = client
  356. }
  357. sshServer.clientsMutex.Unlock()
  358. for _, client := range clients {
  359. client.setTrafficRules()
  360. }
  361. }
  362. func (sshServer *sshServer) setClientHandshakeState(
  363. sessionID string, state handshakeState) error {
  364. sshServer.clientsMutex.Lock()
  365. client := sshServer.clients[sessionID]
  366. sshServer.clientsMutex.Unlock()
  367. if client == nil {
  368. return common.ContextError(errors.New("unknown session ID"))
  369. }
  370. err := client.setHandshakeState(state)
  371. if err != nil {
  372. return common.ContextError(err)
  373. }
  374. client.setTrafficRules()
  375. return nil
  376. }
  377. func (sshServer *sshServer) stopClients() {
  378. sshServer.clientsMutex.Lock()
  379. sshServer.stoppingClients = true
  380. clients := sshServer.clients
  381. sshServer.clients = make(map[string]*sshClient)
  382. sshServer.clientsMutex.Unlock()
  383. for _, client := range clients {
  384. client.stop()
  385. }
  386. }
  387. func (sshServer *sshServer) handleClient(tunnelProtocol string, clientConn net.Conn) {
  388. sshServer.registerAcceptedClient(tunnelProtocol)
  389. defer sshServer.unregisterAcceptedClient(tunnelProtocol)
  390. geoIPData := sshServer.support.GeoIPService.Lookup(
  391. common.IPAddressFromAddr(clientConn.RemoteAddr()))
  392. sshClient := newSshClient(sshServer, tunnelProtocol, geoIPData)
  393. // Set initial traffic rules, pre-handshake, based on currently known info.
  394. sshClient.setTrafficRules()
  395. // Wrap the base client connection with an ActivityMonitoredConn which will
  396. // terminate the connection if no data is received before the deadline. This
  397. // timeout is in effect for the entire duration of the SSH connection. Clients
  398. // must actively use the connection or send SSH keep alive requests to keep
  399. // the connection active. Writes are not considered reliable activity indicators
  400. // due to buffering.
  401. activityConn, err := common.NewActivityMonitoredConn(
  402. clientConn,
  403. SSH_CONNECTION_READ_DEADLINE,
  404. false,
  405. nil)
  406. if err != nil {
  407. clientConn.Close()
  408. log.WithContextFields(LogFields{"error": err}).Error("NewActivityMonitoredConn failed")
  409. return
  410. }
  411. clientConn = activityConn
  412. // Further wrap the connection in a rate limiting ThrottledConn.
  413. throttledConn := common.NewThrottledConn(clientConn, sshClient.rateLimits())
  414. clientConn = throttledConn
  415. // Run the initial [obfuscated] SSH handshake in a goroutine so we can both
  416. // respect shutdownBroadcast and implement a specific handshake timeout.
  417. // The timeout is to reclaim network resources in case the handshake takes
  418. // too long.
  419. type sshNewServerConnResult struct {
  420. conn net.Conn
  421. sshConn *ssh.ServerConn
  422. channels <-chan ssh.NewChannel
  423. requests <-chan *ssh.Request
  424. err error
  425. }
  426. resultChannel := make(chan *sshNewServerConnResult, 2)
  427. if SSH_HANDSHAKE_TIMEOUT > 0 {
  428. time.AfterFunc(time.Duration(SSH_HANDSHAKE_TIMEOUT), func() {
  429. resultChannel <- &sshNewServerConnResult{err: errors.New("ssh handshake timeout")}
  430. })
  431. }
  432. go func(conn net.Conn) {
  433. sshServerConfig := &ssh.ServerConfig{
  434. PasswordCallback: sshClient.passwordCallback,
  435. AuthLogCallback: sshClient.authLogCallback,
  436. ServerVersion: sshServer.support.Config.SSHServerVersion,
  437. }
  438. sshServerConfig.AddHostKey(sshServer.sshHostKey)
  439. result := &sshNewServerConnResult{}
  440. // Wrap the connection in an SSH deobfuscator when required.
  441. if common.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  442. // Note: NewObfuscatedSshConn blocks on network I/O
  443. // TODO: ensure this won't block shutdown
  444. conn, result.err = psiphon.NewObfuscatedSshConn(
  445. psiphon.OBFUSCATION_CONN_MODE_SERVER,
  446. conn,
  447. sshServer.support.Config.ObfuscatedSSHKey)
  448. if result.err != nil {
  449. result.err = common.ContextError(result.err)
  450. }
  451. }
  452. if result.err == nil {
  453. result.sshConn, result.channels, result.requests, result.err =
  454. ssh.NewServerConn(conn, sshServerConfig)
  455. }
  456. resultChannel <- result
  457. }(clientConn)
  458. var result *sshNewServerConnResult
  459. select {
  460. case result = <-resultChannel:
  461. case <-sshServer.shutdownBroadcast:
  462. // Close() will interrupt an ongoing handshake
  463. // TODO: wait for goroutine to exit before returning?
  464. clientConn.Close()
  465. return
  466. }
  467. if result.err != nil {
  468. clientConn.Close()
  469. // This is a Debug log due to noise. The handshake often fails due to I/O
  470. // errors as clients frequently interrupt connections in progress when
  471. // client-side load balancing completes a connection to a different server.
  472. log.WithContextFields(LogFields{"error": result.err}).Debug("handshake failed")
  473. return
  474. }
  475. sshClient.Lock()
  476. sshClient.sshConn = result.sshConn
  477. sshClient.activityConn = activityConn
  478. sshClient.throttledConn = throttledConn
  479. sshClient.Unlock()
  480. if !sshServer.registerEstablishedClient(sshClient) {
  481. clientConn.Close()
  482. log.WithContext().Warning("register failed")
  483. return
  484. }
  485. defer sshServer.unregisterEstablishedClient(sshClient.sessionID)
  486. sshClient.runClient(result.channels, result.requests)
  487. // Note: sshServer.unregisterClient calls sshClient.Close(),
  488. // which also closes underlying transport Conn.
  489. }
  490. type sshClient struct {
  491. sync.Mutex
  492. sshServer *sshServer
  493. tunnelProtocol string
  494. sshConn ssh.Conn
  495. activityConn *common.ActivityMonitoredConn
  496. throttledConn *common.ThrottledConn
  497. geoIPData GeoIPData
  498. sessionID string
  499. handshakeState handshakeState
  500. udpChannel ssh.Channel
  501. trafficRules TrafficRules
  502. tcpTrafficState trafficState
  503. udpTrafficState trafficState
  504. channelHandlerWaitGroup *sync.WaitGroup
  505. tcpPortForwardLRU *common.LRUConns
  506. stopBroadcast chan struct{}
  507. }
  508. type trafficState struct {
  509. // Note: 64-bit ints used with atomic operations are at placed
  510. // at the start of struct to ensure 64-bit alignment.
  511. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  512. bytesUp int64
  513. bytesDown int64
  514. concurrentPortForwardCount int64
  515. peakConcurrentPortForwardCount int64
  516. totalPortForwardCount int64
  517. }
  518. type handshakeState struct {
  519. completed bool
  520. apiProtocol string
  521. apiParams requestJSONObject
  522. }
  523. func newSshClient(
  524. sshServer *sshServer, tunnelProtocol string, geoIPData GeoIPData) *sshClient {
  525. return &sshClient{
  526. sshServer: sshServer,
  527. tunnelProtocol: tunnelProtocol,
  528. geoIPData: geoIPData,
  529. channelHandlerWaitGroup: new(sync.WaitGroup),
  530. tcpPortForwardLRU: common.NewLRUConns(),
  531. stopBroadcast: make(chan struct{}),
  532. }
  533. }
  534. func (sshClient *sshClient) passwordCallback(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
  535. expectedSessionIDLength := 2 * common.PSIPHON_API_CLIENT_SESSION_ID_LENGTH
  536. expectedSSHPasswordLength := 2 * SSH_PASSWORD_BYTE_LENGTH
  537. var sshPasswordPayload struct {
  538. SessionId string `json:"SessionId"`
  539. SshPassword string `json:"SshPassword"`
  540. }
  541. err := json.Unmarshal(password, &sshPasswordPayload)
  542. if err != nil {
  543. // Backwards compatibility case: instead of a JSON payload, older clients
  544. // send the hex encoded session ID prepended to the SSH password.
  545. // Note: there's an even older case where clients don't send any session ID,
  546. // but that's no longer supported.
  547. if len(password) == expectedSessionIDLength+expectedSSHPasswordLength {
  548. sshPasswordPayload.SessionId = string(password[0:expectedSessionIDLength])
  549. sshPasswordPayload.SshPassword = string(password[expectedSSHPasswordLength:len(password)])
  550. } else {
  551. return nil, common.ContextError(fmt.Errorf("invalid password payload for %q", conn.User()))
  552. }
  553. }
  554. if !isHexDigits(sshClient.sshServer.support, sshPasswordPayload.SessionId) ||
  555. len(sshPasswordPayload.SessionId) != expectedSessionIDLength {
  556. return nil, common.ContextError(fmt.Errorf("invalid session ID for %q", conn.User()))
  557. }
  558. userOk := (subtle.ConstantTimeCompare(
  559. []byte(conn.User()), []byte(sshClient.sshServer.support.Config.SSHUserName)) == 1)
  560. passwordOk := (subtle.ConstantTimeCompare(
  561. []byte(sshPasswordPayload.SshPassword), []byte(sshClient.sshServer.support.Config.SSHPassword)) == 1)
  562. if !userOk || !passwordOk {
  563. return nil, common.ContextError(fmt.Errorf("invalid password for %q", conn.User()))
  564. }
  565. sessionID := sshPasswordPayload.SessionId
  566. sshClient.Lock()
  567. sshClient.sessionID = sessionID
  568. geoIPData := sshClient.geoIPData
  569. sshClient.Unlock()
  570. // Store the GeoIP data associated with the session ID. This makes the GeoIP data
  571. // available to the web server for web transport Psiphon API requests. To allow for
  572. // post-tunnel final status requests, the lifetime of cached GeoIP records exceeds
  573. // the lifetime of the sshClient, and that's why this distinct session cache exists.
  574. sshClient.sshServer.support.GeoIPService.SetSessionCache(sessionID, geoIPData)
  575. return nil, nil
  576. }
  577. func (sshClient *sshClient) authLogCallback(conn ssh.ConnMetadata, method string, err error) {
  578. if err != nil {
  579. if method == "none" && err.Error() == "no auth passed yet" {
  580. // In this case, the callback invocation is noise from auth negotiation
  581. return
  582. }
  583. // Note: here we previously logged messages for fail2ban to act on. This is no longer
  584. // done as the complexity outweighs the benefits.
  585. //
  586. // - The SSH credential is not secret -- it's in the server entry. Attackers targetting
  587. // the server likely already have the credential. On the other hand, random scanning and
  588. // brute forcing is mitigated with high entropy random passwords, rate limiting
  589. // (implemented on the host via iptables), and limited capabilities (the SSH session can
  590. // only port forward).
  591. //
  592. // - fail2ban coverage was inconsistent; in the case of an unfronted meek protocol through
  593. // an upstream proxy, the remote address is the upstream proxy, which should not be blocked.
  594. // The X-Forwarded-For header cant be used instead as it may be forged and used to get IPs
  595. // deliberately blocked; and in any case fail2ban adds iptables rules which can only block
  596. // by direct remote IP, not by original client IP. Fronted meek has the same iptables issue.
  597. //
  598. // TODO: random scanning and brute forcing of port 22 will result in log noise. To eliminate
  599. // this, and to also cover meek protocols, and bad obfuscation keys, and bad inputs to the web
  600. // server, consider implementing fail2ban-type logic directly in this server, with the ability
  601. // to use X-Forwarded-For (when trustworthy; e.g, from a CDN).
  602. log.WithContextFields(LogFields{"error": err, "method": method}).Warning("authentication failed")
  603. } else {
  604. log.WithContextFields(LogFields{"error": err, "method": method}).Debug("authentication success")
  605. }
  606. }
  607. func (sshClient *sshClient) stop() {
  608. sshClient.sshConn.Close()
  609. sshClient.sshConn.Wait()
  610. close(sshClient.stopBroadcast)
  611. sshClient.channelHandlerWaitGroup.Wait()
  612. // Note: reporting duration based on last confirmed data transfer, which
  613. // is reads for sshClient.activityConn.GetActiveDuration(), and not
  614. // connection closing is important for protocols such as meek. For
  615. // meek, the connection remains open until the HTTP session expires,
  616. // which may be some time after the tunnel has closed. (The meek
  617. // protocol has no allowance for signalling payload EOF, and even if
  618. // it did the client may not have the opportunity to send a final
  619. // request with an EOF flag set.)
  620. sshClient.Lock()
  621. logFields := getRequestLogFields(
  622. sshClient.sshServer.support,
  623. "server_tunnel",
  624. sshClient.geoIPData,
  625. sshClient.handshakeState.apiParams,
  626. baseRequestParams)
  627. // TODO: match legacy log field naming convention?
  628. logFields["HandshakeCompleted"] = sshClient.handshakeState.completed
  629. logFields["startTime"] = sshClient.activityConn.GetStartTime()
  630. logFields["Duration"] = sshClient.activityConn.GetActiveDuration()
  631. logFields["BytesUpTCP"] = sshClient.tcpTrafficState.bytesUp
  632. logFields["BytesDownTCP"] = sshClient.tcpTrafficState.bytesDown
  633. logFields["PeakConcurrentPortForwardCountTCP"] = sshClient.tcpTrafficState.peakConcurrentPortForwardCount
  634. logFields["TotalPortForwardCountTCP"] = sshClient.tcpTrafficState.totalPortForwardCount
  635. logFields["BytesUpUDP"] = sshClient.udpTrafficState.bytesUp
  636. logFields["BytesDownUDP"] = sshClient.udpTrafficState.bytesDown
  637. logFields["PeakConcurrentPortForwardCountUDP"] = sshClient.udpTrafficState.peakConcurrentPortForwardCount
  638. logFields["TotalPortForwardCountUDP"] = sshClient.udpTrafficState.totalPortForwardCount
  639. sshClient.Unlock()
  640. log.LogRawFieldsWithTimestamp(logFields)
  641. }
  642. // runClient handles/dispatches new channel and new requests from the client.
  643. // When the SSH client connection closes, both the channels and requests channels
  644. // will close and runClient will exit.
  645. func (sshClient *sshClient) runClient(
  646. channels <-chan ssh.NewChannel, requests <-chan *ssh.Request) {
  647. requestsWaitGroup := new(sync.WaitGroup)
  648. requestsWaitGroup.Add(1)
  649. go func() {
  650. defer requestsWaitGroup.Done()
  651. for request := range requests {
  652. // Requests are processed serially; API responses must be sent in request order.
  653. var responsePayload []byte
  654. var err error
  655. if request.Type == "keepalive@openssh.com" {
  656. // Keepalive requests have an empty response.
  657. } else {
  658. // All other requests are assumed to be API requests.
  659. responsePayload, err = sshAPIRequestHandler(
  660. sshClient.sshServer.support,
  661. sshClient.geoIPData,
  662. request.Type,
  663. request.Payload)
  664. }
  665. if err == nil {
  666. err = request.Reply(true, responsePayload)
  667. } else {
  668. log.WithContextFields(LogFields{"error": err}).Warning("request failed")
  669. err = request.Reply(false, nil)
  670. }
  671. if err != nil {
  672. log.WithContextFields(LogFields{"error": err}).Warning("response failed")
  673. }
  674. }
  675. }()
  676. for newChannel := range channels {
  677. if newChannel.ChannelType() != "direct-tcpip" {
  678. sshClient.rejectNewChannel(newChannel, ssh.Prohibited, "unknown or unsupported channel type")
  679. continue
  680. }
  681. // process each port forward concurrently
  682. sshClient.channelHandlerWaitGroup.Add(1)
  683. go sshClient.handleNewPortForwardChannel(newChannel)
  684. }
  685. requestsWaitGroup.Wait()
  686. }
  687. func (sshClient *sshClient) rejectNewChannel(newChannel ssh.NewChannel, reason ssh.RejectionReason, logMessage string) {
  688. log.WithContextFields(
  689. LogFields{
  690. "channelType": newChannel.ChannelType(),
  691. "logMessage": logMessage,
  692. "rejectReason": reason.String(),
  693. }).Warning("reject new channel")
  694. // Note: logMessage is internal, for logging only; just the RejectionReason is sent to the client
  695. newChannel.Reject(reason, reason.String())
  696. }
  697. func (sshClient *sshClient) handleNewPortForwardChannel(newChannel ssh.NewChannel) {
  698. defer sshClient.channelHandlerWaitGroup.Done()
  699. // http://tools.ietf.org/html/rfc4254#section-7.2
  700. var directTcpipExtraData struct {
  701. HostToConnect string
  702. PortToConnect uint32
  703. OriginatorIPAddress string
  704. OriginatorPort uint32
  705. }
  706. err := ssh.Unmarshal(newChannel.ExtraData(), &directTcpipExtraData)
  707. if err != nil {
  708. sshClient.rejectNewChannel(newChannel, ssh.Prohibited, "invalid extra data")
  709. return
  710. }
  711. // Intercept TCP port forwards to a specified udpgw server and handle directly.
  712. // TODO: also support UDP explicitly, e.g. with a custom "direct-udp" channel type?
  713. isUDPChannel := sshClient.sshServer.support.Config.UDPInterceptUdpgwServerAddress != "" &&
  714. sshClient.sshServer.support.Config.UDPInterceptUdpgwServerAddress ==
  715. net.JoinHostPort(directTcpipExtraData.HostToConnect, strconv.Itoa(int(directTcpipExtraData.PortToConnect)))
  716. if isUDPChannel {
  717. sshClient.handleUDPChannel(newChannel)
  718. } else {
  719. sshClient.handleTCPChannel(
  720. directTcpipExtraData.HostToConnect, int(directTcpipExtraData.PortToConnect), newChannel)
  721. }
  722. }
  723. // setHandshakeState records that a client has completed a handshake API request.
  724. // Some parameters from the handshake request may be used in future traffic rule
  725. // selection. Port forwards are disallowed until a handshake is complete. The
  726. // handshake parameters are included in the session summary log recorded in
  727. // sshClient.stop().
  728. func (sshClient *sshClient) setHandshakeState(state handshakeState) error {
  729. sshClient.Lock()
  730. defer sshClient.Unlock()
  731. // Client must only perform one handshake
  732. if sshClient.handshakeState.completed {
  733. return common.ContextError(errors.New("handshake already completed"))
  734. }
  735. sshClient.handshakeState = state
  736. return nil
  737. }
  738. // setTrafficRules resets the client's traffic rules based on the latest server config
  739. // and client state. As sshClient.trafficRules may be reset by a concurrent goroutine,
  740. // trafficRules must only be accessed within the sshClient mutex.
  741. func (sshClient *sshClient) setTrafficRules() {
  742. sshClient.Lock()
  743. defer sshClient.Unlock()
  744. sshClient.trafficRules = sshClient.sshServer.support.TrafficRulesSet.GetTrafficRules(
  745. sshClient.tunnelProtocol, sshClient.geoIPData, sshClient.handshakeState)
  746. }
  747. func (sshClient *sshClient) rateLimits() common.RateLimits {
  748. sshClient.Lock()
  749. defer sshClient.Unlock()
  750. return sshClient.trafficRules.RateLimits.CommonRateLimits()
  751. }
  752. func (sshClient *sshClient) idleTCPPortForwardTimeout() time.Duration {
  753. sshClient.Lock()
  754. defer sshClient.Unlock()
  755. return time.Duration(*sshClient.trafficRules.IdleTCPPortForwardTimeoutMilliseconds) * time.Millisecond
  756. }
  757. func (sshClient *sshClient) idleUDPPortForwardTimeout() time.Duration {
  758. sshClient.Lock()
  759. defer sshClient.Unlock()
  760. return time.Duration(*sshClient.trafficRules.IdleUDPPortForwardTimeoutMilliseconds) * time.Millisecond
  761. }
  762. const (
  763. portForwardTypeTCP = iota
  764. portForwardTypeUDP
  765. )
  766. func (sshClient *sshClient) isPortForwardPermitted(
  767. portForwardType int, host string, port int) bool {
  768. sshClient.Lock()
  769. defer sshClient.Unlock()
  770. if !sshClient.handshakeState.completed {
  771. return false
  772. }
  773. if common.Contains(SSH_DISALLOWED_PORT_FORWARD_HOSTS, host) {
  774. return false
  775. }
  776. var allowPorts, denyPorts []int
  777. if portForwardType == portForwardTypeTCP {
  778. allowPorts = sshClient.trafficRules.AllowTCPPorts
  779. denyPorts = sshClient.trafficRules.AllowTCPPorts
  780. } else {
  781. allowPorts = sshClient.trafficRules.AllowUDPPorts
  782. denyPorts = sshClient.trafficRules.AllowUDPPorts
  783. }
  784. // TODO: faster lookup?
  785. if len(allowPorts) > 0 {
  786. for _, allowPort := range allowPorts {
  787. if port == allowPort {
  788. return true
  789. }
  790. }
  791. return false
  792. }
  793. if len(denyPorts) > 0 {
  794. for _, denyPort := range denyPorts {
  795. if port == denyPort {
  796. return false
  797. }
  798. }
  799. }
  800. return true
  801. }
  802. func (sshClient *sshClient) isPortForwardLimitExceeded(
  803. portForwardType int) (int, bool) {
  804. sshClient.Lock()
  805. defer sshClient.Unlock()
  806. var maxPortForwardCount int
  807. var state *trafficState
  808. if portForwardType == portForwardTypeTCP {
  809. maxPortForwardCount = *sshClient.trafficRules.MaxTCPPortForwardCount
  810. state = &sshClient.tcpTrafficState
  811. } else {
  812. maxPortForwardCount = *sshClient.trafficRules.MaxUDPPortForwardCount
  813. state = &sshClient.udpTrafficState
  814. }
  815. if maxPortForwardCount > 0 && state.concurrentPortForwardCount >= int64(maxPortForwardCount) {
  816. return maxPortForwardCount, true
  817. }
  818. return maxPortForwardCount, false
  819. }
  820. func (sshClient *sshClient) openedPortForward(
  821. portForwardType int) {
  822. sshClient.Lock()
  823. defer sshClient.Unlock()
  824. var state *trafficState
  825. if portForwardType == portForwardTypeTCP {
  826. state = &sshClient.tcpTrafficState
  827. } else {
  828. state = &sshClient.udpTrafficState
  829. }
  830. state.concurrentPortForwardCount += 1
  831. if state.concurrentPortForwardCount > state.peakConcurrentPortForwardCount {
  832. state.peakConcurrentPortForwardCount = state.concurrentPortForwardCount
  833. }
  834. state.totalPortForwardCount += 1
  835. }
  836. func (sshClient *sshClient) closedPortForward(
  837. portForwardType int, bytesUp, bytesDown int64) {
  838. sshClient.Lock()
  839. defer sshClient.Unlock()
  840. var state *trafficState
  841. if portForwardType == portForwardTypeTCP {
  842. state = &sshClient.tcpTrafficState
  843. } else {
  844. state = &sshClient.udpTrafficState
  845. }
  846. state.concurrentPortForwardCount -= 1
  847. state.bytesUp += bytesUp
  848. state.bytesDown += bytesDown
  849. }
  850. func (sshClient *sshClient) handleTCPChannel(
  851. hostToConnect string,
  852. portToConnect int,
  853. newChannel ssh.NewChannel) {
  854. isWebServerPortForward := false
  855. config := sshClient.sshServer.support.Config
  856. if config.WebServerPortForwardAddress != "" {
  857. destination := net.JoinHostPort(hostToConnect, strconv.Itoa(portToConnect))
  858. if destination == config.WebServerPortForwardAddress {
  859. isWebServerPortForward = true
  860. if config.WebServerPortForwardRedirectAddress != "" {
  861. // Note: redirect format is validated when config is loaded
  862. host, portStr, _ := net.SplitHostPort(config.WebServerPortForwardRedirectAddress)
  863. port, _ := strconv.Atoi(portStr)
  864. hostToConnect = host
  865. portToConnect = port
  866. }
  867. }
  868. }
  869. if !isWebServerPortForward && !sshClient.isPortForwardPermitted(
  870. portForwardTypeTCP, hostToConnect, portToConnect) {
  871. sshClient.rejectNewChannel(
  872. newChannel, ssh.Prohibited, "port forward not permitted")
  873. return
  874. }
  875. var bytesUp, bytesDown int64
  876. sshClient.openedPortForward(portForwardTypeTCP)
  877. defer func() {
  878. sshClient.closedPortForward(
  879. portForwardTypeTCP, atomic.LoadInt64(&bytesUp), atomic.LoadInt64(&bytesDown))
  880. }()
  881. // TOCTOU note: important to increment the port forward count (via
  882. // openPortForward) _before_ checking isPortForwardLimitExceeded
  883. // otherwise, the client could potentially consume excess resources
  884. // by initiating many port forwards concurrently.
  885. // TODO: close LRU connection (after successful Dial) instead of
  886. // rejecting new connection?
  887. if maxCount, exceeded := sshClient.isPortForwardLimitExceeded(portForwardTypeTCP); exceeded {
  888. // Close the oldest TCP port forward. CloseOldest() closes
  889. // the conn and the port forward's goroutine will complete
  890. // the cleanup asynchronously.
  891. //
  892. // Some known limitations:
  893. //
  894. // - Since CloseOldest() closes the upstream socket but does not
  895. // clean up all resources associated with the port forward. These
  896. // include the goroutine(s) relaying traffic as well as the SSH
  897. // channel. Closing the socket will interrupt the goroutines which
  898. // will then complete the cleanup. But, since the full cleanup is
  899. // asynchronous, there exists a possibility that a client can consume
  900. // more than max port forward resources -- just not upstream sockets.
  901. //
  902. // - An LRU list entry for this port forward is not added until
  903. // after the dial completes, but the port forward is counted
  904. // towards max limits. This means many dials in progress will
  905. // put established connections in jeopardy.
  906. //
  907. // - We're closing the oldest open connection _before_ successfully
  908. // dialing the new port forward. This means we are potentially
  909. // discarding a good connection to make way for a failed connection.
  910. // We cannot simply dial first and still maintain a limit on
  911. // resources used, so to address this we'd need to add some
  912. // accounting for connections still establishing.
  913. sshClient.tcpPortForwardLRU.CloseOldest()
  914. log.WithContextFields(
  915. LogFields{
  916. "maxCount": maxCount,
  917. }).Debug("closed LRU TCP port forward")
  918. }
  919. // Dial the target remote address. This is done in a goroutine to
  920. // ensure the shutdown signal is handled immediately.
  921. remoteAddr := fmt.Sprintf("%s:%d", hostToConnect, portToConnect)
  922. log.WithContextFields(LogFields{"remoteAddr": remoteAddr}).Debug("dialing")
  923. type dialTcpResult struct {
  924. conn net.Conn
  925. err error
  926. }
  927. resultChannel := make(chan *dialTcpResult, 1)
  928. go func() {
  929. // TODO: on EADDRNOTAVAIL, temporarily suspend new clients
  930. // TODO: IPv6 support
  931. conn, err := net.DialTimeout(
  932. "tcp4", remoteAddr, SSH_TCP_PORT_FORWARD_DIAL_TIMEOUT)
  933. resultChannel <- &dialTcpResult{conn, err}
  934. }()
  935. var result *dialTcpResult
  936. select {
  937. case result = <-resultChannel:
  938. case <-sshClient.stopBroadcast:
  939. // Note: may leave dial in progress
  940. return
  941. }
  942. if result.err != nil {
  943. sshClient.rejectNewChannel(newChannel, ssh.ConnectionFailed, result.err.Error())
  944. return
  945. }
  946. // The upstream TCP port forward connection has been established. Schedule
  947. // some cleanup and notify the SSH client that the channel is accepted.
  948. fwdConn := result.conn
  949. defer fwdConn.Close()
  950. fwdChannel, requests, err := newChannel.Accept()
  951. if err != nil {
  952. log.WithContextFields(LogFields{"error": err}).Warning("accept new channel failed")
  953. return
  954. }
  955. go ssh.DiscardRequests(requests)
  956. defer fwdChannel.Close()
  957. // ActivityMonitoredConn monitors the TCP port forward I/O and updates
  958. // its LRU status. ActivityMonitoredConn also times out I/O on the port
  959. // forward if both reads and writes have been idle for the specified
  960. // duration.
  961. lruEntry := sshClient.tcpPortForwardLRU.Add(fwdConn)
  962. defer lruEntry.Remove()
  963. fwdConn, err = common.NewActivityMonitoredConn(
  964. fwdConn,
  965. sshClient.idleTCPPortForwardTimeout(),
  966. true,
  967. lruEntry)
  968. if result.err != nil {
  969. log.WithContextFields(LogFields{"error": err}).Error("NewActivityMonitoredConn failed")
  970. return
  971. }
  972. // Relay channel to forwarded connection.
  973. log.WithContextFields(LogFields{"remoteAddr": remoteAddr}).Debug("relaying")
  974. // TODO: relay errors to fwdChannel.Stderr()?
  975. relayWaitGroup := new(sync.WaitGroup)
  976. relayWaitGroup.Add(1)
  977. go func() {
  978. defer relayWaitGroup.Done()
  979. // io.Copy allocates a 32K temporary buffer, and each port forward relay uses
  980. // two of these buffers; using io.CopyBuffer with a smaller buffer reduces the
  981. // overall memory footprint.
  982. bytes, err := io.CopyBuffer(
  983. fwdChannel, fwdConn, make([]byte, SSH_TCP_PORT_FORWARD_COPY_BUFFER_SIZE))
  984. atomic.AddInt64(&bytesDown, bytes)
  985. if err != nil && err != io.EOF {
  986. // Debug since errors such as "connection reset by peer" occur during normal operation
  987. log.WithContextFields(LogFields{"error": err}).Debug("downstream TCP relay failed")
  988. }
  989. // Interrupt upstream io.Copy when downstream is shutting down.
  990. // TODO: this is done to quickly cleanup the port forward when
  991. // fwdConn has a read timeout, but is it clean -- upstream may still
  992. // be flowing?
  993. fwdChannel.Close()
  994. }()
  995. bytes, err := io.CopyBuffer(
  996. fwdConn, fwdChannel, make([]byte, SSH_TCP_PORT_FORWARD_COPY_BUFFER_SIZE))
  997. atomic.AddInt64(&bytesUp, bytes)
  998. if err != nil && err != io.EOF {
  999. log.WithContextFields(LogFields{"error": err}).Debug("upstream TCP relay failed")
  1000. }
  1001. // Shutdown special case: fwdChannel will be closed and return EOF when
  1002. // the SSH connection is closed, but we need to explicitly close fwdConn
  1003. // to interrupt the downstream io.Copy, which may be blocked on a
  1004. // fwdConn.Read().
  1005. fwdConn.Close()
  1006. relayWaitGroup.Wait()
  1007. log.WithContextFields(
  1008. LogFields{
  1009. "remoteAddr": remoteAddr,
  1010. "bytesUp": atomic.LoadInt64(&bytesUp),
  1011. "bytesDown": atomic.LoadInt64(&bytesDown)}).Debug("exiting")
  1012. }