tunnelServer.go 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945
  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. "context"
  22. "crypto/subtle"
  23. "encoding/json"
  24. "errors"
  25. "fmt"
  26. "io"
  27. "net"
  28. "strconv"
  29. "sync"
  30. "sync/atomic"
  31. "syscall"
  32. "time"
  33. "github.com/Psiphon-Inc/crypto/ssh"
  34. "github.com/Psiphon-Inc/goarista/monotime"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/osl"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  38. )
  39. const (
  40. SSH_HANDSHAKE_TIMEOUT = 30 * time.Second
  41. SSH_CONNECTION_READ_DEADLINE = 5 * time.Minute
  42. SSH_TCP_PORT_FORWARD_DIAL_TIMEOUT = 10 * time.Second
  43. SSH_TCP_PORT_FORWARD_COPY_BUFFER_SIZE = 8192
  44. SSH_TCP_PORT_FORWARD_QUEUE_SIZE = 1024
  45. SSH_SEND_OSL_INITIAL_RETRY_DELAY = 30 * time.Second
  46. SSH_SEND_OSL_RETRY_FACTOR = 2
  47. )
  48. // TunnelServer is the main server that accepts Psiphon client
  49. // connections, via various obfuscation protocols, and provides
  50. // port forwarding (TCP and UDP) services to the Psiphon client.
  51. // At its core, TunnelServer is an SSH server. SSH is the base
  52. // protocol that provides port forward multiplexing, and transport
  53. // security. Layered on top of SSH, optionally, is Obfuscated SSH
  54. // and meek protocols, which provide further circumvention
  55. // capabilities.
  56. type TunnelServer struct {
  57. runWaitGroup *sync.WaitGroup
  58. listenerError chan error
  59. shutdownBroadcast <-chan struct{}
  60. sshServer *sshServer
  61. }
  62. // NewTunnelServer initializes a new tunnel server.
  63. func NewTunnelServer(
  64. support *SupportServices,
  65. shutdownBroadcast <-chan struct{}) (*TunnelServer, error) {
  66. sshServer, err := newSSHServer(support, shutdownBroadcast)
  67. if err != nil {
  68. return nil, common.ContextError(err)
  69. }
  70. return &TunnelServer{
  71. runWaitGroup: new(sync.WaitGroup),
  72. listenerError: make(chan error),
  73. shutdownBroadcast: shutdownBroadcast,
  74. sshServer: sshServer,
  75. }, nil
  76. }
  77. // Run runs the tunnel server; this function blocks while running a selection of
  78. // listeners that handle connection using various obfuscation protocols.
  79. //
  80. // Run listens on each designated tunnel port and spawns new goroutines to handle
  81. // each client connection. It halts when shutdownBroadcast is signaled. A list of active
  82. // clients is maintained, and when halting all clients are cleanly shutdown.
  83. //
  84. // Each client goroutine handles its own obfuscation (optional), SSH handshake, SSH
  85. // authentication, and then looping on client new channel requests. "direct-tcpip"
  86. // channels, dynamic port fowards, are supported. When the UDPInterceptUdpgwServerAddress
  87. // config parameter is configured, UDP port forwards over a TCP stream, following
  88. // the udpgw protocol, are handled.
  89. //
  90. // A new goroutine is spawned to handle each port forward for each client. Each port
  91. // forward tracks its bytes transferred. Overall per-client stats for connection duration,
  92. // GeoIP, number of port forwards, and bytes transferred are tracked and logged when the
  93. // client shuts down.
  94. //
  95. // Note: client handler goroutines may still be shutting down after Run() returns. See
  96. // comment in sshClient.stop(). TODO: fully synchronized shutdown.
  97. func (server *TunnelServer) Run() error {
  98. type sshListener struct {
  99. net.Listener
  100. localAddress string
  101. tunnelProtocol string
  102. }
  103. // TODO: should TunnelServer hold its own support pointer?
  104. support := server.sshServer.support
  105. // First bind all listeners; once all are successful,
  106. // start accepting connections on each.
  107. var listeners []*sshListener
  108. for tunnelProtocol, listenPort := range support.Config.TunnelProtocolPorts {
  109. localAddress := fmt.Sprintf(
  110. "%s:%d", support.Config.ServerIPAddress, listenPort)
  111. listener, err := net.Listen("tcp", localAddress)
  112. if err != nil {
  113. for _, existingListener := range listeners {
  114. existingListener.Listener.Close()
  115. }
  116. return common.ContextError(err)
  117. }
  118. log.WithContextFields(
  119. LogFields{
  120. "localAddress": localAddress,
  121. "tunnelProtocol": tunnelProtocol,
  122. }).Info("listening")
  123. listeners = append(
  124. listeners,
  125. &sshListener{
  126. Listener: listener,
  127. localAddress: localAddress,
  128. tunnelProtocol: tunnelProtocol,
  129. })
  130. }
  131. for _, listener := range listeners {
  132. server.runWaitGroup.Add(1)
  133. go func(listener *sshListener) {
  134. defer server.runWaitGroup.Done()
  135. log.WithContextFields(
  136. LogFields{
  137. "localAddress": listener.localAddress,
  138. "tunnelProtocol": listener.tunnelProtocol,
  139. }).Info("running")
  140. server.sshServer.runListener(
  141. listener.Listener,
  142. server.listenerError,
  143. listener.tunnelProtocol)
  144. log.WithContextFields(
  145. LogFields{
  146. "localAddress": listener.localAddress,
  147. "tunnelProtocol": listener.tunnelProtocol,
  148. }).Info("stopped")
  149. }(listener)
  150. }
  151. var err error
  152. select {
  153. case <-server.shutdownBroadcast:
  154. case err = <-server.listenerError:
  155. }
  156. for _, listener := range listeners {
  157. listener.Close()
  158. }
  159. server.sshServer.stopClients()
  160. server.runWaitGroup.Wait()
  161. log.WithContext().Info("stopped")
  162. return err
  163. }
  164. // GetLoadStats returns load stats for the tunnel server. The stats are
  165. // broken down by protocol ("SSH", "OSSH", etc.) and type. Types of stats
  166. // include current connected client count, total number of current port
  167. // forwards.
  168. func (server *TunnelServer) GetLoadStats() map[string]interface{} {
  169. return server.sshServer.getLoadStats()
  170. }
  171. // ResetAllClientTrafficRules resets all established client traffic rules
  172. // to use the latest config and client properties. Any existing traffic
  173. // rule state is lost, including throttling state.
  174. func (server *TunnelServer) ResetAllClientTrafficRules() {
  175. server.sshServer.resetAllClientTrafficRules()
  176. }
  177. // ResetAllClientOSLConfigs resets all established client OSL state to use
  178. // the latest OSL config. Any existing OSL state is lost, including partial
  179. // progress towards SLOKs.
  180. func (server *TunnelServer) ResetAllClientOSLConfigs() {
  181. server.sshServer.resetAllClientOSLConfigs()
  182. }
  183. // SetClientHandshakeState sets the handshake state -- that it completed and
  184. // what paramaters were passed -- in sshClient. This state is used for allowing
  185. // port forwards and for future traffic rule selection. SetClientHandshakeState
  186. // also triggers an immediate traffic rule re-selection, as the rules selected
  187. // upon tunnel establishment may no longer apply now that handshake values are
  188. // set.
  189. func (server *TunnelServer) SetClientHandshakeState(
  190. sessionID string, state handshakeState) error {
  191. return server.sshServer.setClientHandshakeState(sessionID, state)
  192. }
  193. // SetEstablishTunnels sets whether new tunnels may be established or not.
  194. // When not establishing, incoming connections are immediately closed.
  195. func (server *TunnelServer) SetEstablishTunnels(establish bool) {
  196. server.sshServer.setEstablishTunnels(establish)
  197. }
  198. // GetEstablishTunnels returns whether new tunnels may be established or not.
  199. func (server *TunnelServer) GetEstablishTunnels() bool {
  200. return server.sshServer.getEstablishTunnels()
  201. }
  202. type sshServer struct {
  203. support *SupportServices
  204. establishTunnels int32
  205. shutdownBroadcast <-chan struct{}
  206. sshHostKey ssh.Signer
  207. clientsMutex sync.Mutex
  208. stoppingClients bool
  209. acceptedClientCounts map[string]map[string]int64
  210. clients map[string]*sshClient
  211. }
  212. func newSSHServer(
  213. support *SupportServices,
  214. shutdownBroadcast <-chan struct{}) (*sshServer, error) {
  215. privateKey, err := ssh.ParseRawPrivateKey([]byte(support.Config.SSHPrivateKey))
  216. if err != nil {
  217. return nil, common.ContextError(err)
  218. }
  219. // TODO: use cert (ssh.NewCertSigner) for anti-fingerprint?
  220. signer, err := ssh.NewSignerFromKey(privateKey)
  221. if err != nil {
  222. return nil, common.ContextError(err)
  223. }
  224. return &sshServer{
  225. support: support,
  226. establishTunnels: 1,
  227. shutdownBroadcast: shutdownBroadcast,
  228. sshHostKey: signer,
  229. acceptedClientCounts: make(map[string]map[string]int64),
  230. clients: make(map[string]*sshClient),
  231. }, nil
  232. }
  233. func (sshServer *sshServer) setEstablishTunnels(establish bool) {
  234. // Do nothing when the setting is already correct. This avoids
  235. // spurious log messages when setEstablishTunnels is called
  236. // periodically with the same setting.
  237. if establish == sshServer.getEstablishTunnels() {
  238. return
  239. }
  240. establishFlag := int32(1)
  241. if !establish {
  242. establishFlag = 0
  243. }
  244. atomic.StoreInt32(&sshServer.establishTunnels, establishFlag)
  245. log.WithContextFields(
  246. LogFields{"establish": establish}).Info("establishing tunnels")
  247. }
  248. func (sshServer *sshServer) getEstablishTunnels() bool {
  249. return atomic.LoadInt32(&sshServer.establishTunnels) == 1
  250. }
  251. // runListener is intended to run an a goroutine; it blocks
  252. // running a particular listener. If an unrecoverable error
  253. // occurs, it will send the error to the listenerError channel.
  254. func (sshServer *sshServer) runListener(
  255. listener net.Listener,
  256. listenerError chan<- error,
  257. tunnelProtocol string) {
  258. handleClient := func(clientConn net.Conn) {
  259. // Note: establish tunnel limiter cannot simply stop TCP
  260. // listeners in all cases (e.g., meek) since SSH tunnel can
  261. // span multiple TCP connections.
  262. if !sshServer.getEstablishTunnels() {
  263. log.WithContext().Debug("not establishing tunnels")
  264. clientConn.Close()
  265. return
  266. }
  267. // process each client connection concurrently
  268. go sshServer.handleClient(tunnelProtocol, clientConn)
  269. }
  270. // Note: when exiting due to a unrecoverable error, be sure
  271. // to try to send the error to listenerError so that the outer
  272. // TunnelServer.Run will properly shut down instead of remaining
  273. // running.
  274. if protocol.TunnelProtocolUsesMeekHTTP(tunnelProtocol) ||
  275. protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  276. meekServer, err := NewMeekServer(
  277. sshServer.support,
  278. listener,
  279. protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol),
  280. protocol.TunnelProtocolUsesObfuscatedSessionTickets(tunnelProtocol),
  281. handleClient,
  282. sshServer.shutdownBroadcast)
  283. if err != nil {
  284. select {
  285. case listenerError <- common.ContextError(err):
  286. default:
  287. }
  288. return
  289. }
  290. meekServer.Run()
  291. } else {
  292. for {
  293. conn, err := listener.Accept()
  294. select {
  295. case <-sshServer.shutdownBroadcast:
  296. if err == nil {
  297. conn.Close()
  298. }
  299. return
  300. default:
  301. }
  302. if err != nil {
  303. if e, ok := err.(net.Error); ok && e.Temporary() {
  304. log.WithContextFields(LogFields{"error": err}).Error("accept failed")
  305. // Temporary error, keep running
  306. continue
  307. }
  308. select {
  309. case listenerError <- common.ContextError(err):
  310. default:
  311. }
  312. return
  313. }
  314. handleClient(conn)
  315. }
  316. }
  317. }
  318. // An accepted client has completed a direct TCP or meek connection and has a net.Conn. Registration
  319. // is for tracking the number of connections.
  320. func (sshServer *sshServer) registerAcceptedClient(tunnelProtocol, region string) {
  321. sshServer.clientsMutex.Lock()
  322. defer sshServer.clientsMutex.Unlock()
  323. if sshServer.acceptedClientCounts[tunnelProtocol] == nil {
  324. sshServer.acceptedClientCounts[tunnelProtocol] = make(map[string]int64)
  325. }
  326. sshServer.acceptedClientCounts[tunnelProtocol][region] += 1
  327. }
  328. func (sshServer *sshServer) unregisterAcceptedClient(tunnelProtocol, region string) {
  329. sshServer.clientsMutex.Lock()
  330. defer sshServer.clientsMutex.Unlock()
  331. sshServer.acceptedClientCounts[tunnelProtocol][region] -= 1
  332. }
  333. // An established client has completed its SSH handshake and has a ssh.Conn. Registration is
  334. // for tracking the number of fully established clients and for maintaining a list of running
  335. // clients (for stopping at shutdown time).
  336. func (sshServer *sshServer) registerEstablishedClient(client *sshClient) bool {
  337. sshServer.clientsMutex.Lock()
  338. if sshServer.stoppingClients {
  339. sshServer.clientsMutex.Unlock()
  340. return false
  341. }
  342. // In the case of a duplicate client sessionID, the previous client is closed.
  343. // - Well-behaved clients generate pick a random sessionID that should be
  344. // unique (won't accidentally conflict) and hard to guess (can't be targetted
  345. // by a malicious client).
  346. // - Clients reuse the same sessionID when a tunnel is unexpectedly disconnected
  347. // and resestablished. In this case, when the same server is selected, this logic
  348. // will be hit; closing the old, dangling client is desirable.
  349. // - Multi-tunnel clients should not normally use one server for multiple tunnels.
  350. existingClient := sshServer.clients[client.sessionID]
  351. sshServer.clients[client.sessionID] = client
  352. sshServer.clientsMutex.Unlock()
  353. // Call stop() outside the mutex to avoid deadlock.
  354. if existingClient != nil {
  355. existingClient.stop()
  356. }
  357. return true
  358. }
  359. func (sshServer *sshServer) unregisterEstablishedClient(sessionID string) {
  360. sshServer.clientsMutex.Lock()
  361. client := sshServer.clients[sessionID]
  362. delete(sshServer.clients, sessionID)
  363. sshServer.clientsMutex.Unlock()
  364. // Call stop() outside the mutex to avoid deadlock.
  365. if client != nil {
  366. client.stop()
  367. }
  368. }
  369. func (sshServer *sshServer) getLoadStats() map[string]interface{} {
  370. sshServer.clientsMutex.Lock()
  371. defer sshServer.clientsMutex.Unlock()
  372. protocolStats := make(map[string]map[string]map[string]int64)
  373. // Explicitly populate with zeros to get 0 counts in log messages derived from getLoadStats()
  374. for tunnelProtocol, _ := range sshServer.support.Config.TunnelProtocolPorts {
  375. protocolStats[tunnelProtocol] = make(map[string]map[string]int64)
  376. protocolStats[tunnelProtocol]["ALL"] = make(map[string]int64)
  377. protocolStats[tunnelProtocol]["ALL"]["accepted_clients"] = 0
  378. protocolStats[tunnelProtocol]["ALL"]["established_clients"] = 0
  379. protocolStats[tunnelProtocol]["ALL"]["dialing_tcp_port_forwards"] = 0
  380. protocolStats[tunnelProtocol]["ALL"]["tcp_port_forwards"] = 0
  381. protocolStats[tunnelProtocol]["ALL"]["total_tcp_port_forwards"] = 0
  382. protocolStats[tunnelProtocol]["ALL"]["udp_port_forwards"] = 0
  383. protocolStats[tunnelProtocol]["ALL"]["total_udp_port_forwards"] = 0
  384. }
  385. // Note: as currently tracked/counted, each established client is also an accepted client
  386. for tunnelProtocol, regionAcceptedClientCounts := range sshServer.acceptedClientCounts {
  387. total := int64(0)
  388. for region, acceptedClientCount := range regionAcceptedClientCounts {
  389. if acceptedClientCount > 0 {
  390. if protocolStats[tunnelProtocol][region] == nil {
  391. protocolStats[tunnelProtocol][region] = make(map[string]int64)
  392. protocolStats[tunnelProtocol][region]["accepted_clients"] = 0
  393. protocolStats[tunnelProtocol][region]["established_clients"] = 0
  394. protocolStats[tunnelProtocol][region]["dialing_tcp_port_forwards"] = 0
  395. protocolStats[tunnelProtocol][region]["tcp_port_forwards"] = 0
  396. protocolStats[tunnelProtocol][region]["total_tcp_port_forwards"] = 0
  397. protocolStats[tunnelProtocol][region]["udp_port_forwards"] = 0
  398. protocolStats[tunnelProtocol][region]["total_udp_port_forwards"] = 0
  399. }
  400. protocolStats[tunnelProtocol][region]["accepted_clients"] = acceptedClientCount
  401. total += acceptedClientCount
  402. }
  403. }
  404. protocolStats[tunnelProtocol]["ALL"]["accepted_clients"] = total
  405. }
  406. var aggregatedQualityMetrics qualityMetrics
  407. for _, client := range sshServer.clients {
  408. client.Lock()
  409. for _, region := range []string{"ALL", client.geoIPData.Country} {
  410. if protocolStats[client.tunnelProtocol][region] == nil {
  411. protocolStats[client.tunnelProtocol][region] = make(map[string]int64)
  412. protocolStats[client.tunnelProtocol][region]["accepted_clients"] = 0
  413. protocolStats[client.tunnelProtocol][region]["established_clients"] = 0
  414. protocolStats[client.tunnelProtocol][region]["dialing_tcp_port_forwards"] = 0
  415. protocolStats[client.tunnelProtocol][region]["tcp_port_forwards"] = 0
  416. protocolStats[client.tunnelProtocol][region]["total_tcp_port_forwards"] = 0
  417. protocolStats[client.tunnelProtocol][region]["udp_port_forwards"] = 0
  418. protocolStats[client.tunnelProtocol][region]["total_udp_port_forwards"] = 0
  419. }
  420. // Note: can't sum trafficState.peakConcurrentPortForwardCount to get a global peak
  421. protocolStats[client.tunnelProtocol][region]["established_clients"] += 1
  422. protocolStats[client.tunnelProtocol][region]["dialing_tcp_port_forwards"] += client.tcpTrafficState.concurrentDialingPortForwardCount
  423. protocolStats[client.tunnelProtocol][region]["tcp_port_forwards"] += client.tcpTrafficState.concurrentPortForwardCount
  424. protocolStats[client.tunnelProtocol][region]["total_tcp_port_forwards"] += client.tcpTrafficState.totalPortForwardCount
  425. // client.udpTrafficState.concurrentDialingPortForwardCount isn't meaningful
  426. protocolStats[client.tunnelProtocol][region]["udp_port_forwards"] += client.udpTrafficState.concurrentPortForwardCount
  427. protocolStats[client.tunnelProtocol][region]["total_udp_port_forwards"] += client.udpTrafficState.totalPortForwardCount
  428. }
  429. aggregatedQualityMetrics.tcpPortForwardDialedCount += client.qualityMetrics.tcpPortForwardDialedCount
  430. aggregatedQualityMetrics.tcpPortForwardDialedDuration +=
  431. client.qualityMetrics.tcpPortForwardDialedDuration / time.Millisecond
  432. aggregatedQualityMetrics.tcpPortForwardFailedCount += client.qualityMetrics.tcpPortForwardFailedCount
  433. aggregatedQualityMetrics.tcpPortForwardFailedDuration +=
  434. client.qualityMetrics.tcpPortForwardFailedDuration / time.Millisecond
  435. aggregatedQualityMetrics.tcpPortForwardRejectedDialingLimitCount += client.qualityMetrics.tcpPortForwardRejectedDialingLimitCount
  436. client.qualityMetrics.tcpPortForwardDialedCount = 0
  437. client.qualityMetrics.tcpPortForwardDialedDuration = 0
  438. client.qualityMetrics.tcpPortForwardFailedCount = 0
  439. client.qualityMetrics.tcpPortForwardFailedDuration = 0
  440. client.qualityMetrics.tcpPortForwardRejectedDialingLimitCount = 0
  441. client.Unlock()
  442. }
  443. // Calculate and report totals across all protocols. It's easier to do this here
  444. // than futher down the stats stack. Also useful for glancing at log files.
  445. allProtocolsStats := make(map[string]int64)
  446. allProtocolsStats["accepted_clients"] = 0
  447. allProtocolsStats["established_clients"] = 0
  448. allProtocolsStats["dialing_tcp_port_forwards"] = 0
  449. allProtocolsStats["tcp_port_forwards"] = 0
  450. allProtocolsStats["total_tcp_port_forwards"] = 0
  451. allProtocolsStats["udp_port_forwards"] = 0
  452. allProtocolsStats["total_udp_port_forwards"] = 0
  453. allProtocolsStats["tcp_port_forward_dialed_count"] = aggregatedQualityMetrics.tcpPortForwardDialedCount
  454. allProtocolsStats["tcp_port_forward_dialed_duration"] = int64(aggregatedQualityMetrics.tcpPortForwardDialedDuration)
  455. allProtocolsStats["tcp_port_forward_failed_count"] = aggregatedQualityMetrics.tcpPortForwardFailedCount
  456. allProtocolsStats["tcp_port_forward_failed_duration"] = int64(aggregatedQualityMetrics.tcpPortForwardFailedDuration)
  457. allProtocolsStats["tcp_port_forward_rejected_dialing_limit_count"] = aggregatedQualityMetrics.tcpPortForwardRejectedDialingLimitCount
  458. for _, stats := range protocolStats {
  459. for name, value := range stats["ALL"] {
  460. allProtocolsStats[name] += value
  461. }
  462. }
  463. loadStats := make(map[string]interface{})
  464. loadStats["ALL"] = allProtocolsStats
  465. for tunnelProtocol, stats := range protocolStats {
  466. loadStats[tunnelProtocol] = stats
  467. }
  468. return loadStats
  469. }
  470. func (sshServer *sshServer) resetAllClientTrafficRules() {
  471. sshServer.clientsMutex.Lock()
  472. clients := make(map[string]*sshClient)
  473. for sessionID, client := range sshServer.clients {
  474. clients[sessionID] = client
  475. }
  476. sshServer.clientsMutex.Unlock()
  477. for _, client := range clients {
  478. client.setTrafficRules()
  479. }
  480. }
  481. func (sshServer *sshServer) resetAllClientOSLConfigs() {
  482. sshServer.clientsMutex.Lock()
  483. clients := make(map[string]*sshClient)
  484. for sessionID, client := range sshServer.clients {
  485. clients[sessionID] = client
  486. }
  487. sshServer.clientsMutex.Unlock()
  488. for _, client := range clients {
  489. client.setOSLConfig()
  490. }
  491. }
  492. func (sshServer *sshServer) setClientHandshakeState(
  493. sessionID string, state handshakeState) error {
  494. sshServer.clientsMutex.Lock()
  495. client := sshServer.clients[sessionID]
  496. sshServer.clientsMutex.Unlock()
  497. if client == nil {
  498. return common.ContextError(errors.New("unknown session ID"))
  499. }
  500. err := client.setHandshakeState(state)
  501. if err != nil {
  502. return common.ContextError(err)
  503. }
  504. return nil
  505. }
  506. func (sshServer *sshServer) stopClients() {
  507. sshServer.clientsMutex.Lock()
  508. sshServer.stoppingClients = true
  509. clients := sshServer.clients
  510. sshServer.clients = make(map[string]*sshClient)
  511. sshServer.clientsMutex.Unlock()
  512. for _, client := range clients {
  513. client.stop()
  514. }
  515. }
  516. func (sshServer *sshServer) handleClient(tunnelProtocol string, clientConn net.Conn) {
  517. geoIPData := sshServer.support.GeoIPService.Lookup(
  518. common.IPAddressFromAddr(clientConn.RemoteAddr()))
  519. sshServer.registerAcceptedClient(tunnelProtocol, geoIPData.Country)
  520. defer sshServer.unregisterAcceptedClient(tunnelProtocol, geoIPData.Country)
  521. sshClient := newSshClient(sshServer, tunnelProtocol, geoIPData)
  522. sshClient.run(clientConn)
  523. }
  524. func (sshServer *sshServer) monitorPortForwardDialError(err error) {
  525. // "err" is the error returned from a failed TCP or UDP port
  526. // forward dial. Certain system error codes indicate low resource
  527. // conditions: insufficient file descriptors, ephemeral ports, or
  528. // memory. For these cases, log an alert.
  529. // TODO: also temporarily suspend new clients
  530. // Note: don't log net.OpError.Error() as the full error string
  531. // may contain client destination addresses.
  532. opErr, ok := err.(*net.OpError)
  533. if ok {
  534. if opErr.Err == syscall.EADDRNOTAVAIL ||
  535. opErr.Err == syscall.EAGAIN ||
  536. opErr.Err == syscall.ENOMEM ||
  537. opErr.Err == syscall.EMFILE ||
  538. opErr.Err == syscall.ENFILE {
  539. log.WithContextFields(
  540. LogFields{"error": opErr.Err}).Error(
  541. "port forward dial failed due to unavailable resource")
  542. }
  543. }
  544. }
  545. type sshClient struct {
  546. sync.Mutex
  547. sshServer *sshServer
  548. tunnelProtocol string
  549. sshConn ssh.Conn
  550. activityConn *common.ActivityMonitoredConn
  551. throttledConn *common.ThrottledConn
  552. geoIPData GeoIPData
  553. sessionID string
  554. supportsServerRequests bool
  555. handshakeState handshakeState
  556. udpChannel ssh.Channel
  557. trafficRules TrafficRules
  558. tcpTrafficState trafficState
  559. udpTrafficState trafficState
  560. qualityMetrics qualityMetrics
  561. tcpPortForwardLRU *common.LRUConns
  562. oslClientSeedState *osl.ClientSeedState
  563. signalIssueSLOKs chan struct{}
  564. runContext context.Context
  565. stopRunning context.CancelFunc
  566. tcpPortForwardDialingAvailableSignal context.CancelFunc
  567. }
  568. type trafficState struct {
  569. bytesUp int64
  570. bytesDown int64
  571. concurrentDialingPortForwardCount int64
  572. peakConcurrentDialingPortForwardCount int64
  573. concurrentPortForwardCount int64
  574. peakConcurrentPortForwardCount int64
  575. totalPortForwardCount int64
  576. }
  577. // qualityMetrics records upstream TCP dial attempts and
  578. // elapsed time. Elapsed time includes the full TCP handshake
  579. // and, in aggregate, is a measure of the quality of the
  580. // upstream link. These stats are recorded by each sshClient
  581. // and then reported and reset in sshServer.getLoadStats().
  582. type qualityMetrics struct {
  583. tcpPortForwardDialedCount int64
  584. tcpPortForwardDialedDuration time.Duration
  585. tcpPortForwardFailedCount int64
  586. tcpPortForwardFailedDuration time.Duration
  587. tcpPortForwardRejectedDialingLimitCount int64
  588. }
  589. type handshakeState struct {
  590. completed bool
  591. apiProtocol string
  592. apiParams requestJSONObject
  593. }
  594. func newSshClient(
  595. sshServer *sshServer, tunnelProtocol string, geoIPData GeoIPData) *sshClient {
  596. runContext, stopRunning := context.WithCancel(context.Background())
  597. return &sshClient{
  598. sshServer: sshServer,
  599. tunnelProtocol: tunnelProtocol,
  600. geoIPData: geoIPData,
  601. tcpPortForwardLRU: common.NewLRUConns(),
  602. signalIssueSLOKs: make(chan struct{}, 1),
  603. runContext: runContext,
  604. stopRunning: stopRunning,
  605. }
  606. }
  607. func (sshClient *sshClient) run(clientConn net.Conn) {
  608. // Set initial traffic rules, pre-handshake, based on currently known info.
  609. sshClient.setTrafficRules()
  610. // Wrap the base client connection with an ActivityMonitoredConn which will
  611. // terminate the connection if no data is received before the deadline. This
  612. // timeout is in effect for the entire duration of the SSH connection. Clients
  613. // must actively use the connection or send SSH keep alive requests to keep
  614. // the connection active. Writes are not considered reliable activity indicators
  615. // due to buffering.
  616. activityConn, err := common.NewActivityMonitoredConn(
  617. clientConn,
  618. SSH_CONNECTION_READ_DEADLINE,
  619. false,
  620. nil,
  621. nil)
  622. if err != nil {
  623. clientConn.Close()
  624. log.WithContextFields(LogFields{"error": err}).Error("NewActivityMonitoredConn failed")
  625. return
  626. }
  627. clientConn = activityConn
  628. // Further wrap the connection in a rate limiting ThrottledConn.
  629. throttledConn := common.NewThrottledConn(clientConn, sshClient.rateLimits())
  630. clientConn = throttledConn
  631. // Run the initial [obfuscated] SSH handshake in a goroutine so we can both
  632. // respect shutdownBroadcast and implement a specific handshake timeout.
  633. // The timeout is to reclaim network resources in case the handshake takes
  634. // too long.
  635. type sshNewServerConnResult struct {
  636. conn net.Conn
  637. sshConn *ssh.ServerConn
  638. channels <-chan ssh.NewChannel
  639. requests <-chan *ssh.Request
  640. err error
  641. }
  642. resultChannel := make(chan *sshNewServerConnResult, 2)
  643. if SSH_HANDSHAKE_TIMEOUT > 0 {
  644. time.AfterFunc(time.Duration(SSH_HANDSHAKE_TIMEOUT), func() {
  645. resultChannel <- &sshNewServerConnResult{err: errors.New("ssh handshake timeout")}
  646. })
  647. }
  648. go func(conn net.Conn) {
  649. sshServerConfig := &ssh.ServerConfig{
  650. PasswordCallback: sshClient.passwordCallback,
  651. AuthLogCallback: sshClient.authLogCallback,
  652. ServerVersion: sshClient.sshServer.support.Config.SSHServerVersion,
  653. }
  654. sshServerConfig.AddHostKey(sshClient.sshServer.sshHostKey)
  655. result := &sshNewServerConnResult{}
  656. // Wrap the connection in an SSH deobfuscator when required.
  657. if protocol.TunnelProtocolUsesObfuscatedSSH(sshClient.tunnelProtocol) {
  658. // Note: NewObfuscatedSshConn blocks on network I/O
  659. // TODO: ensure this won't block shutdown
  660. conn, result.err = common.NewObfuscatedSshConn(
  661. common.OBFUSCATION_CONN_MODE_SERVER,
  662. conn,
  663. sshClient.sshServer.support.Config.ObfuscatedSSHKey)
  664. if result.err != nil {
  665. result.err = common.ContextError(result.err)
  666. }
  667. }
  668. if result.err == nil {
  669. result.sshConn, result.channels, result.requests, result.err =
  670. ssh.NewServerConn(conn, sshServerConfig)
  671. }
  672. resultChannel <- result
  673. }(clientConn)
  674. var result *sshNewServerConnResult
  675. select {
  676. case result = <-resultChannel:
  677. case <-sshClient.sshServer.shutdownBroadcast:
  678. // Close() will interrupt an ongoing handshake
  679. // TODO: wait for goroutine to exit before returning?
  680. clientConn.Close()
  681. return
  682. }
  683. if result.err != nil {
  684. clientConn.Close()
  685. // This is a Debug log due to noise. The handshake often fails due to I/O
  686. // errors as clients frequently interrupt connections in progress when
  687. // client-side load balancing completes a connection to a different server.
  688. log.WithContextFields(LogFields{"error": result.err}).Debug("handshake failed")
  689. return
  690. }
  691. sshClient.Lock()
  692. sshClient.sshConn = result.sshConn
  693. sshClient.activityConn = activityConn
  694. sshClient.throttledConn = throttledConn
  695. sshClient.Unlock()
  696. if !sshClient.sshServer.registerEstablishedClient(sshClient) {
  697. clientConn.Close()
  698. log.WithContext().Warning("register failed")
  699. return
  700. }
  701. sshClient.runTunnel(result.channels, result.requests)
  702. // Note: sshServer.unregisterEstablishedClient calls sshClient.stop(),
  703. // which also closes underlying transport Conn.
  704. sshClient.sshServer.unregisterEstablishedClient(sshClient.sessionID)
  705. sshClient.logTunnel()
  706. // Initiate cleanup of the GeoIP session cache. To allow for post-tunnel
  707. // final status requests, the lifetime of cached GeoIP records exceeds the
  708. // lifetime of the sshClient.
  709. sshClient.sshServer.support.GeoIPService.MarkSessionCacheToExpire(sshClient.sessionID)
  710. }
  711. func (sshClient *sshClient) passwordCallback(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
  712. expectedSessionIDLength := 2 * protocol.PSIPHON_API_CLIENT_SESSION_ID_LENGTH
  713. expectedSSHPasswordLength := 2 * SSH_PASSWORD_BYTE_LENGTH
  714. var sshPasswordPayload protocol.SSHPasswordPayload
  715. err := json.Unmarshal(password, &sshPasswordPayload)
  716. if err != nil {
  717. // Backwards compatibility case: instead of a JSON payload, older clients
  718. // send the hex encoded session ID prepended to the SSH password.
  719. // Note: there's an even older case where clients don't send any session ID,
  720. // but that's no longer supported.
  721. if len(password) == expectedSessionIDLength+expectedSSHPasswordLength {
  722. sshPasswordPayload.SessionId = string(password[0:expectedSessionIDLength])
  723. sshPasswordPayload.SshPassword = string(password[expectedSSHPasswordLength:len(password)])
  724. } else {
  725. return nil, common.ContextError(fmt.Errorf("invalid password payload for %q", conn.User()))
  726. }
  727. }
  728. if !isHexDigits(sshClient.sshServer.support, sshPasswordPayload.SessionId) ||
  729. len(sshPasswordPayload.SessionId) != expectedSessionIDLength {
  730. return nil, common.ContextError(fmt.Errorf("invalid session ID for %q", conn.User()))
  731. }
  732. userOk := (subtle.ConstantTimeCompare(
  733. []byte(conn.User()), []byte(sshClient.sshServer.support.Config.SSHUserName)) == 1)
  734. passwordOk := (subtle.ConstantTimeCompare(
  735. []byte(sshPasswordPayload.SshPassword), []byte(sshClient.sshServer.support.Config.SSHPassword)) == 1)
  736. if !userOk || !passwordOk {
  737. return nil, common.ContextError(fmt.Errorf("invalid password for %q", conn.User()))
  738. }
  739. sessionID := sshPasswordPayload.SessionId
  740. supportsServerRequests := common.Contains(
  741. sshPasswordPayload.ClientCapabilities, protocol.CLIENT_CAPABILITY_SERVER_REQUESTS)
  742. sshClient.Lock()
  743. sshClient.sessionID = sessionID
  744. sshClient.supportsServerRequests = supportsServerRequests
  745. geoIPData := sshClient.geoIPData
  746. sshClient.Unlock()
  747. // Store the GeoIP data associated with the session ID. This makes
  748. // the GeoIP data available to the web server for web API requests.
  749. // A cache that's distinct from the sshClient record is used to allow
  750. // for or post-tunnel final status requests.
  751. // If the client is reconnecting with the same session ID, this call
  752. // will undo the expiry set by MarkSessionCacheToExpire.
  753. sshClient.sshServer.support.GeoIPService.SetSessionCache(sessionID, geoIPData)
  754. return nil, nil
  755. }
  756. func (sshClient *sshClient) authLogCallback(conn ssh.ConnMetadata, method string, err error) {
  757. if err != nil {
  758. if method == "none" && err.Error() == "no auth passed yet" {
  759. // In this case, the callback invocation is noise from auth negotiation
  760. return
  761. }
  762. // Note: here we previously logged messages for fail2ban to act on. This is no longer
  763. // done as the complexity outweighs the benefits.
  764. //
  765. // - The SSH credential is not secret -- it's in the server entry. Attackers targetting
  766. // the server likely already have the credential. On the other hand, random scanning and
  767. // brute forcing is mitigated with high entropy random passwords, rate limiting
  768. // (implemented on the host via iptables), and limited capabilities (the SSH session can
  769. // only port forward).
  770. //
  771. // - fail2ban coverage was inconsistent; in the case of an unfronted meek protocol through
  772. // an upstream proxy, the remote address is the upstream proxy, which should not be blocked.
  773. // The X-Forwarded-For header cant be used instead as it may be forged and used to get IPs
  774. // deliberately blocked; and in any case fail2ban adds iptables rules which can only block
  775. // by direct remote IP, not by original client IP. Fronted meek has the same iptables issue.
  776. //
  777. // TODO: random scanning and brute forcing of port 22 will result in log noise. To eliminate
  778. // this, and to also cover meek protocols, and bad obfuscation keys, and bad inputs to the web
  779. // server, consider implementing fail2ban-type logic directly in this server, with the ability
  780. // to use X-Forwarded-For (when trustworthy; e.g, from a CDN).
  781. log.WithContextFields(LogFields{"error": err, "method": method}).Warning("authentication failed")
  782. } else {
  783. log.WithContextFields(LogFields{"error": err, "method": method}).Debug("authentication success")
  784. }
  785. }
  786. // stop signals the ssh connection to shutdown. After sshConn() returns,
  787. // the connection has terminated but sshClient.run() may still be
  788. // running and in the process of exiting.
  789. func (sshClient *sshClient) stop() {
  790. sshClient.sshConn.Close()
  791. sshClient.sshConn.Wait()
  792. }
  793. // runTunnel handles/dispatches new channels and new requests from the client.
  794. // When the SSH client connection closes, both the channels and requests channels
  795. // will close and runTunnel will exit.
  796. func (sshClient *sshClient) runTunnel(
  797. channels <-chan ssh.NewChannel, requests <-chan *ssh.Request) {
  798. waitGroup := new(sync.WaitGroup)
  799. // Start client SSH API request handler
  800. waitGroup.Add(1)
  801. go func() {
  802. defer waitGroup.Done()
  803. for request := range requests {
  804. // Requests are processed serially; API responses must be sent in request order.
  805. var responsePayload []byte
  806. var err error
  807. if request.Type == "[email protected]" {
  808. // Keepalive requests have an empty response.
  809. } else {
  810. // All other requests are assumed to be API requests.
  811. responsePayload, err = sshAPIRequestHandler(
  812. sshClient.sshServer.support,
  813. sshClient.geoIPData,
  814. request.Type,
  815. request.Payload)
  816. }
  817. if err == nil {
  818. err = request.Reply(true, responsePayload)
  819. } else {
  820. log.WithContextFields(LogFields{"error": err}).Warning("request failed")
  821. err = request.Reply(false, nil)
  822. }
  823. if err != nil {
  824. log.WithContextFields(LogFields{"error": err}).Warning("response failed")
  825. }
  826. }
  827. }()
  828. // Start OSL sender
  829. if sshClient.supportsServerRequests {
  830. waitGroup.Add(1)
  831. go func() {
  832. defer waitGroup.Done()
  833. sshClient.runOSLSender()
  834. }()
  835. }
  836. // Lifecycle of a TCP port forward:
  837. //
  838. // 1. A "direct-tcpip" SSH request is received from the client.
  839. //
  840. // A new TCP port forward request is enqueued. The queue delivers TCP port
  841. // forward requests to the TCP port forward manager, which enforces the TCP
  842. // port forward dial limit.
  843. //
  844. // Enqueuing new requests allows for reading further SSH requests from the
  845. // client without blocking when the dial limit is hit; this is to permit new
  846. // UDP/udpgw port forwards to be restablished without delay. The maximum size
  847. // of the queue enforces a hard cap on resources consumed by a client in the
  848. // pre-dial phase. When the queue is full, new TCP port forwards are
  849. // immediately rejected.
  850. //
  851. // 2. The TCP port forward manager dequeues the request.
  852. //
  853. // The manager calls dialingTCPPortForward(), which increments
  854. // concurrentDialingPortForwardCount, and calls
  855. // isTCPDialingPortForwardLimitExceeded() to check the concurrent dialing
  856. // count.
  857. //
  858. // The manager enforces the concurrent TCP dial limit: when at the limit, the
  859. // manager blocks waiting for the number of dials to drop below the limit before
  860. // dispatching the request to handleTCPPortForward(), which will run in its own
  861. // goroutine and will dial and relay the port forward.
  862. //
  863. // The block delays the current request and also halts dequeuing of subsequent
  864. // requests and could ultimately cause requests to be immediately rejected if
  865. // the queue fills. These actions are intended to apply back pressure when
  866. // upstream network resources are impaired.
  867. //
  868. // The time spent in the queue is deducted from the port forward's dial timeout.
  869. // The time spent blocking while at the dial limit is similarly deducted from
  870. // the dial timeout. If the dial timeout has expired before the dial begins, the
  871. // port forward is rejected and a stat is recorded.
  872. //
  873. // 3. handleTCPPortForward() performs the port forward dial and relaying.
  874. //
  875. // a. Dial the target, using the dial timeout remaining after queue and blocking
  876. // time is deducted.
  877. //
  878. // b. If the dial fails, call abortedTCPPortForward() to decrement
  879. // concurrentDialingPortForwardCount, freeing up a dial slot.
  880. //
  881. // c. If the dial succeeds, call establishedPortForward(), which decrements
  882. // concurrentDialingPortForwardCount and increments concurrentPortForwardCount,
  883. // the "established" port forward count.
  884. //
  885. // d. Check isPortForwardLimitExceeded(), which enforces the configurable limit on
  886. // concurrentPortForwardCount, the number of _established_ TCP port forwards.
  887. // If the limit is exceeded, the LRU established TCP port forward is closed and
  888. // the newly established TCP port forward proceeds. This LRU logic allows some
  889. // dangling resource consumption (e.g., TIME_WAIT) while providing a better
  890. // experience for clients.
  891. //
  892. // e. Relay data.
  893. //
  894. // f. Call closedPortForward() which decrements concurrentPortForwardCount and
  895. // records bytes transferred.
  896. // Start the TCP port forward manager
  897. type newTCPPortForward struct {
  898. enqueueTime monotime.Time
  899. hostToConnect string
  900. portToConnect int
  901. newChannel ssh.NewChannel
  902. }
  903. // The queue size is set to the traffic rules MaxTCPDPortForwardCount, which is a
  904. // reasonable indication of resource limits per client; when that value is not set,
  905. // a default is used.
  906. // A limitation: this queue size is set once and doesn't change, for this client,
  907. // when traffic rules are reloaded.
  908. queueSize := sshClient.getTCPPortForwardLimit()
  909. if queueSize == 0 {
  910. queueSize = SSH_TCP_PORT_FORWARD_QUEUE_SIZE
  911. }
  912. newTCPPortForwards := make(chan *newTCPPortForward, queueSize)
  913. waitGroup.Add(1)
  914. go func() {
  915. defer waitGroup.Done()
  916. for newPortForward := range newTCPPortForwards {
  917. remainingDialTimeout := SSH_TCP_PORT_FORWARD_DIAL_TIMEOUT - monotime.Since(newPortForward.enqueueTime)
  918. if remainingDialTimeout <= 0 {
  919. sshClient.updateQualityMetricsWithRejectedDialingLimit()
  920. sshClient.rejectNewChannel(
  921. newPortForward.newChannel, ssh.Prohibited, "TCP port forward timed out in queue")
  922. continue
  923. }
  924. // Reserve a TCP dialing slot.
  925. //
  926. // TOCTOU note: important to increment counts _before_ checking limits; otherwise,
  927. // the client could potentially consume excess resources by initiating many port
  928. // forwards concurrently.
  929. sshClient.dialingTCPPortForward()
  930. // When max dials are in progress, wait up to remainingDialTimeout for dialing
  931. // to become available. This blocks all dequeing.
  932. if sshClient.isTCPDialingPortForwardLimitExceeded() {
  933. blockStartTime := monotime.Now()
  934. ctx, cancelFunc := context.WithTimeout(sshClient.runContext, remainingDialTimeout)
  935. sshClient.setTCPPortForwardDialingAvailableSignal(cancelFunc)
  936. <-ctx.Done()
  937. sshClient.setTCPPortForwardDialingAvailableSignal(nil)
  938. remainingDialTimeout -= monotime.Since(blockStartTime)
  939. }
  940. if remainingDialTimeout <= 0 {
  941. // Release the dialing slot here since handleTCPChannel() won't be called.
  942. sshClient.abortedTCPPortForward()
  943. sshClient.updateQualityMetricsWithRejectedDialingLimit()
  944. sshClient.rejectNewChannel(
  945. newPortForward.newChannel, ssh.Prohibited, "TCP port forward timed out before dialing")
  946. continue
  947. }
  948. // Dial and relay the TCP port forward. handleTCPChannel is run in its own worker goroutine.
  949. // handleTCPChannel will release the dialing slot reserved by dialingTCPPortForward(); and
  950. // will deal with remainingDialTimeout <= 0.
  951. waitGroup.Add(1)
  952. go func(remainingDialTimeout time.Duration, newPortForward *newTCPPortForward) {
  953. defer waitGroup.Done()
  954. sshClient.handleTCPChannel(
  955. remainingDialTimeout,
  956. newPortForward.hostToConnect,
  957. newPortForward.portToConnect,
  958. newPortForward.newChannel)
  959. }(remainingDialTimeout, newPortForward)
  960. }
  961. }()
  962. // Handle new channel (port forward) requests from the client.
  963. //
  964. // udpgw client connections are dispatched immediately (clients use this for
  965. // DNS, so it's essential to not block; and only one udpgw connection is
  966. // retained at a time).
  967. //
  968. // All other TCP port forwards are dispatched via the TCP port forward
  969. // manager queue.
  970. for newChannel := range channels {
  971. if newChannel.ChannelType() != "direct-tcpip" {
  972. sshClient.rejectNewChannel(newChannel, ssh.Prohibited, "unknown or unsupported channel type")
  973. continue
  974. }
  975. // http://tools.ietf.org/html/rfc4254#section-7.2
  976. var directTcpipExtraData struct {
  977. HostToConnect string
  978. PortToConnect uint32
  979. OriginatorIPAddress string
  980. OriginatorPort uint32
  981. }
  982. err := ssh.Unmarshal(newChannel.ExtraData(), &directTcpipExtraData)
  983. if err != nil {
  984. sshClient.rejectNewChannel(newChannel, ssh.Prohibited, "invalid extra data")
  985. continue
  986. }
  987. // Intercept TCP port forwards to a specified udpgw server and handle directly.
  988. // TODO: also support UDP explicitly, e.g. with a custom "direct-udp" channel type?
  989. isUDPChannel := sshClient.sshServer.support.Config.UDPInterceptUdpgwServerAddress != "" &&
  990. sshClient.sshServer.support.Config.UDPInterceptUdpgwServerAddress ==
  991. net.JoinHostPort(directTcpipExtraData.HostToConnect, strconv.Itoa(int(directTcpipExtraData.PortToConnect)))
  992. if isUDPChannel {
  993. // Dispatch immediately. handleUDPChannel runs the udpgw protocol in its
  994. // own worker goroutine.
  995. waitGroup.Add(1)
  996. go func(channel ssh.NewChannel) {
  997. defer waitGroup.Done()
  998. sshClient.handleUDPChannel(channel)
  999. }(newChannel)
  1000. } else {
  1001. // Dispatch via TCP port forward manager. When the queue is full, the channel
  1002. // is immediately rejected.
  1003. tcpPortForward := &newTCPPortForward{
  1004. enqueueTime: monotime.Now(),
  1005. hostToConnect: directTcpipExtraData.HostToConnect,
  1006. portToConnect: int(directTcpipExtraData.PortToConnect),
  1007. newChannel: newChannel,
  1008. }
  1009. select {
  1010. case newTCPPortForwards <- tcpPortForward:
  1011. default:
  1012. sshClient.updateQualityMetricsWithRejectedDialingLimit()
  1013. sshClient.rejectNewChannel(newChannel, ssh.Prohibited, "TCP port forward dial queue full")
  1014. }
  1015. }
  1016. }
  1017. // The channel loop is interrupted by a client
  1018. // disconnect or by calling sshClient.stop().
  1019. // Stop the TCP port forward manager
  1020. close(newTCPPortForwards)
  1021. // Stop all other worker goroutines
  1022. sshClient.stopRunning()
  1023. waitGroup.Wait()
  1024. }
  1025. func (sshClient *sshClient) logTunnel() {
  1026. // Note: reporting duration based on last confirmed data transfer, which
  1027. // is reads for sshClient.activityConn.GetActiveDuration(), and not
  1028. // connection closing is important for protocols such as meek. For
  1029. // meek, the connection remains open until the HTTP session expires,
  1030. // which may be some time after the tunnel has closed. (The meek
  1031. // protocol has no allowance for signalling payload EOF, and even if
  1032. // it did the client may not have the opportunity to send a final
  1033. // request with an EOF flag set.)
  1034. sshClient.Lock()
  1035. logFields := getRequestLogFields(
  1036. sshClient.sshServer.support,
  1037. "server_tunnel",
  1038. sshClient.geoIPData,
  1039. sshClient.handshakeState.apiParams,
  1040. baseRequestParams)
  1041. logFields["handshake_completed"] = sshClient.handshakeState.completed
  1042. logFields["start_time"] = sshClient.activityConn.GetStartTime()
  1043. logFields["duration"] = sshClient.activityConn.GetActiveDuration() / time.Millisecond
  1044. logFields["bytes_up_tcp"] = sshClient.tcpTrafficState.bytesUp
  1045. logFields["bytes_down_tcp"] = sshClient.tcpTrafficState.bytesDown
  1046. logFields["peak_concurrent_dialing_port_forward_count_tcp"] = sshClient.tcpTrafficState.peakConcurrentDialingPortForwardCount
  1047. logFields["peak_concurrent_port_forward_count_tcp"] = sshClient.tcpTrafficState.peakConcurrentPortForwardCount
  1048. logFields["total_port_forward_count_tcp"] = sshClient.tcpTrafficState.totalPortForwardCount
  1049. logFields["bytes_up_udp"] = sshClient.udpTrafficState.bytesUp
  1050. logFields["bytes_down_udp"] = sshClient.udpTrafficState.bytesDown
  1051. // sshClient.udpTrafficState.peakConcurrentDialingPortForwardCount isn't meaningful
  1052. logFields["peak_concurrent_port_forward_count_udp"] = sshClient.udpTrafficState.peakConcurrentPortForwardCount
  1053. logFields["total_port_forward_count_udp"] = sshClient.udpTrafficState.totalPortForwardCount
  1054. sshClient.Unlock()
  1055. log.LogRawFieldsWithTimestamp(logFields)
  1056. }
  1057. func (sshClient *sshClient) runOSLSender() {
  1058. for {
  1059. // Await a signal that there are SLOKs to send
  1060. // TODO: use reflect.SelectCase, and optionally await timer here?
  1061. select {
  1062. case <-sshClient.signalIssueSLOKs:
  1063. case <-sshClient.runContext.Done():
  1064. return
  1065. }
  1066. retryDelay := SSH_SEND_OSL_INITIAL_RETRY_DELAY
  1067. for {
  1068. err := sshClient.sendOSLRequest()
  1069. if err == nil {
  1070. break
  1071. }
  1072. log.WithContextFields(LogFields{"error": err}).Warning("sendOSLRequest failed")
  1073. // If the request failed, retry after a delay (with exponential backoff)
  1074. // or when signaled that there are additional SLOKs to send
  1075. retryTimer := time.NewTimer(retryDelay)
  1076. select {
  1077. case <-retryTimer.C:
  1078. case <-sshClient.signalIssueSLOKs:
  1079. case <-sshClient.runContext.Done():
  1080. retryTimer.Stop()
  1081. return
  1082. }
  1083. retryTimer.Stop()
  1084. retryDelay *= SSH_SEND_OSL_RETRY_FACTOR
  1085. }
  1086. }
  1087. }
  1088. // sendOSLRequest will invoke osl.GetSeedPayload to issue SLOKs and
  1089. // generate a payload, and send an OSL request to the client when
  1090. // there are new SLOKs in the payload.
  1091. func (sshClient *sshClient) sendOSLRequest() error {
  1092. seedPayload := sshClient.getOSLSeedPayload()
  1093. // Don't send when no SLOKs. This will happen when signalIssueSLOKs
  1094. // is received but no new SLOKs are issued.
  1095. if len(seedPayload.SLOKs) == 0 {
  1096. return nil
  1097. }
  1098. oslRequest := protocol.OSLRequest{
  1099. SeedPayload: seedPayload,
  1100. }
  1101. requestPayload, err := json.Marshal(oslRequest)
  1102. if err != nil {
  1103. return common.ContextError(err)
  1104. }
  1105. ok, _, err := sshClient.sshConn.SendRequest(
  1106. protocol.PSIPHON_API_OSL_REQUEST_NAME,
  1107. true,
  1108. requestPayload)
  1109. if err != nil {
  1110. return common.ContextError(err)
  1111. }
  1112. if !ok {
  1113. return common.ContextError(errors.New("client rejected request"))
  1114. }
  1115. sshClient.clearOSLSeedPayload()
  1116. return nil
  1117. }
  1118. func (sshClient *sshClient) rejectNewChannel(newChannel ssh.NewChannel, reason ssh.RejectionReason, logMessage string) {
  1119. // Note: Debug level, as logMessage may contain user traffic destination address information
  1120. log.WithContextFields(
  1121. LogFields{
  1122. "channelType": newChannel.ChannelType(),
  1123. "logMessage": logMessage,
  1124. "rejectReason": reason.String(),
  1125. }).Debug("reject new channel")
  1126. // Note: logMessage is internal, for logging only; just the RejectionReason is sent to the client
  1127. newChannel.Reject(reason, reason.String())
  1128. }
  1129. // setHandshakeState records that a client has completed a handshake API request.
  1130. // Some parameters from the handshake request may be used in future traffic rule
  1131. // selection. Port forwards are disallowed until a handshake is complete. The
  1132. // handshake parameters are included in the session summary log recorded in
  1133. // sshClient.stop().
  1134. func (sshClient *sshClient) setHandshakeState(state handshakeState) error {
  1135. sshClient.Lock()
  1136. completed := sshClient.handshakeState.completed
  1137. if !completed {
  1138. sshClient.handshakeState = state
  1139. }
  1140. sshClient.Unlock()
  1141. // Client must only perform one handshake
  1142. if completed {
  1143. return common.ContextError(errors.New("handshake already completed"))
  1144. }
  1145. sshClient.setTrafficRules()
  1146. sshClient.setOSLConfig()
  1147. return nil
  1148. }
  1149. // setTrafficRules resets the client's traffic rules based on the latest server config
  1150. // and client properties. As sshClient.trafficRules may be reset by a concurrent
  1151. // goroutine, trafficRules must only be accessed within the sshClient mutex.
  1152. func (sshClient *sshClient) setTrafficRules() {
  1153. sshClient.Lock()
  1154. defer sshClient.Unlock()
  1155. sshClient.trafficRules = sshClient.sshServer.support.TrafficRulesSet.GetTrafficRules(
  1156. sshClient.tunnelProtocol, sshClient.geoIPData, sshClient.handshakeState)
  1157. if sshClient.throttledConn != nil {
  1158. // Any existing throttling state is reset.
  1159. sshClient.throttledConn.SetLimits(
  1160. sshClient.trafficRules.RateLimits.CommonRateLimits())
  1161. }
  1162. }
  1163. // setOSLConfig resets the client's OSL seed state based on the latest OSL config
  1164. // As sshClient.oslClientSeedState may be reset by a concurrent goroutine,
  1165. // oslClientSeedState must only be accessed within the sshClient mutex.
  1166. func (sshClient *sshClient) setOSLConfig() {
  1167. sshClient.Lock()
  1168. defer sshClient.Unlock()
  1169. propagationChannelID, err := getStringRequestParam(
  1170. sshClient.handshakeState.apiParams, "propagation_channel_id")
  1171. if err != nil {
  1172. // This should not fail as long as client has sent valid handshake
  1173. return
  1174. }
  1175. // Two limitations when setOSLConfig() is invoked due to an
  1176. // OSL config hot reload:
  1177. //
  1178. // 1. any partial progress towards SLOKs is lost.
  1179. //
  1180. // 2. all existing osl.ClientSeedPortForwards for existing
  1181. // port forwards will not send progress to the new client
  1182. // seed state.
  1183. sshClient.oslClientSeedState = sshClient.sshServer.support.OSLConfig.NewClientSeedState(
  1184. sshClient.geoIPData.Country,
  1185. propagationChannelID,
  1186. sshClient.signalIssueSLOKs)
  1187. }
  1188. // newClientSeedPortForward will return nil when no seeding is
  1189. // associated with the specified ipAddress.
  1190. func (sshClient *sshClient) newClientSeedPortForward(ipAddress net.IP) *osl.ClientSeedPortForward {
  1191. sshClient.Lock()
  1192. defer sshClient.Unlock()
  1193. // Will not be initialized before handshake.
  1194. if sshClient.oslClientSeedState == nil {
  1195. return nil
  1196. }
  1197. return sshClient.oslClientSeedState.NewClientSeedPortForward(ipAddress)
  1198. }
  1199. // getOSLSeedPayload returns a payload containing all seeded SLOKs for
  1200. // this client's session.
  1201. func (sshClient *sshClient) getOSLSeedPayload() *osl.SeedPayload {
  1202. sshClient.Lock()
  1203. defer sshClient.Unlock()
  1204. // Will not be initialized before handshake.
  1205. if sshClient.oslClientSeedState == nil {
  1206. return &osl.SeedPayload{SLOKs: make([]*osl.SLOK, 0)}
  1207. }
  1208. return sshClient.oslClientSeedState.GetSeedPayload()
  1209. }
  1210. func (sshClient *sshClient) clearOSLSeedPayload() {
  1211. sshClient.Lock()
  1212. defer sshClient.Unlock()
  1213. sshClient.oslClientSeedState.ClearSeedPayload()
  1214. }
  1215. func (sshClient *sshClient) rateLimits() common.RateLimits {
  1216. sshClient.Lock()
  1217. defer sshClient.Unlock()
  1218. return sshClient.trafficRules.RateLimits.CommonRateLimits()
  1219. }
  1220. func (sshClient *sshClient) idleTCPPortForwardTimeout() time.Duration {
  1221. sshClient.Lock()
  1222. defer sshClient.Unlock()
  1223. return time.Duration(*sshClient.trafficRules.IdleTCPPortForwardTimeoutMilliseconds) * time.Millisecond
  1224. }
  1225. func (sshClient *sshClient) idleUDPPortForwardTimeout() time.Duration {
  1226. sshClient.Lock()
  1227. defer sshClient.Unlock()
  1228. return time.Duration(*sshClient.trafficRules.IdleUDPPortForwardTimeoutMilliseconds) * time.Millisecond
  1229. }
  1230. func (sshClient *sshClient) setTCPPortForwardDialingAvailableSignal(signal context.CancelFunc) {
  1231. sshClient.Lock()
  1232. defer sshClient.Unlock()
  1233. sshClient.tcpPortForwardDialingAvailableSignal = signal
  1234. }
  1235. const (
  1236. portForwardTypeTCP = iota
  1237. portForwardTypeUDP
  1238. portForwardTypeTransparentDNS
  1239. )
  1240. func (sshClient *sshClient) isPortForwardPermitted(
  1241. portForwardType int,
  1242. isTransparentDNSForwarding bool,
  1243. remoteIP net.IP,
  1244. port int) bool {
  1245. sshClient.Lock()
  1246. defer sshClient.Unlock()
  1247. if !sshClient.handshakeState.completed {
  1248. return false
  1249. }
  1250. // Disallow connection to loopback. This is a failsafe. The server
  1251. // should be run on a host with correctly configured firewall rules.
  1252. // And exception is made in the case of tranparent DNS forwarding,
  1253. // where the remoteIP has been rewritten.
  1254. if !isTransparentDNSForwarding && remoteIP.IsLoopback() {
  1255. return false
  1256. }
  1257. var allowPorts []int
  1258. if portForwardType == portForwardTypeTCP {
  1259. allowPorts = sshClient.trafficRules.AllowTCPPorts
  1260. } else {
  1261. allowPorts = sshClient.trafficRules.AllowUDPPorts
  1262. }
  1263. if len(allowPorts) == 0 {
  1264. return true
  1265. }
  1266. // TODO: faster lookup?
  1267. if len(allowPorts) > 0 {
  1268. for _, allowPort := range allowPorts {
  1269. if port == allowPort {
  1270. return true
  1271. }
  1272. }
  1273. }
  1274. for _, subnet := range sshClient.trafficRules.AllowSubnets {
  1275. // Note: ignoring error as config has been validated
  1276. _, network, _ := net.ParseCIDR(subnet)
  1277. if network.Contains(remoteIP) {
  1278. return true
  1279. }
  1280. }
  1281. return false
  1282. }
  1283. func (sshClient *sshClient) isTCPDialingPortForwardLimitExceeded() bool {
  1284. sshClient.Lock()
  1285. defer sshClient.Unlock()
  1286. state := &sshClient.tcpTrafficState
  1287. max := *sshClient.trafficRules.MaxTCPDialingPortForwardCount
  1288. if max > 0 && state.concurrentDialingPortForwardCount >= int64(max) {
  1289. return true
  1290. }
  1291. return false
  1292. }
  1293. func (sshClient *sshClient) isPortForwardLimitExceeded(
  1294. portForwardType int) bool {
  1295. sshClient.Lock()
  1296. defer sshClient.Unlock()
  1297. var max int
  1298. var state *trafficState
  1299. if portForwardType == portForwardTypeTCP {
  1300. max = *sshClient.trafficRules.MaxTCPPortForwardCount
  1301. state = &sshClient.tcpTrafficState
  1302. } else {
  1303. max = *sshClient.trafficRules.MaxUDPPortForwardCount
  1304. state = &sshClient.udpTrafficState
  1305. }
  1306. if max > 0 && state.concurrentPortForwardCount >= int64(max) {
  1307. return true
  1308. }
  1309. return false
  1310. }
  1311. func (sshClient *sshClient) getTCPPortForwardLimit() int {
  1312. sshClient.Lock()
  1313. defer sshClient.Unlock()
  1314. return *sshClient.trafficRules.MaxTCPPortForwardCount
  1315. }
  1316. func (sshClient *sshClient) dialingTCPPortForward() {
  1317. sshClient.Lock()
  1318. defer sshClient.Unlock()
  1319. state := &sshClient.tcpTrafficState
  1320. state.concurrentDialingPortForwardCount += 1
  1321. if state.concurrentDialingPortForwardCount > state.peakConcurrentDialingPortForwardCount {
  1322. state.peakConcurrentDialingPortForwardCount = state.concurrentDialingPortForwardCount
  1323. }
  1324. }
  1325. func (sshClient *sshClient) abortedTCPPortForward() {
  1326. sshClient.Lock()
  1327. defer sshClient.Unlock()
  1328. sshClient.tcpTrafficState.concurrentDialingPortForwardCount -= 1
  1329. }
  1330. func (sshClient *sshClient) establishedPortForward(
  1331. portForwardType int) {
  1332. sshClient.Lock()
  1333. defer sshClient.Unlock()
  1334. var state *trafficState
  1335. if portForwardType == portForwardTypeTCP {
  1336. state = &sshClient.tcpTrafficState
  1337. // Assumes TCP port forwards called dialingTCPPortForward
  1338. state.concurrentDialingPortForwardCount -= 1
  1339. if sshClient.tcpPortForwardDialingAvailableSignal != nil {
  1340. max := *sshClient.trafficRules.MaxTCPDialingPortForwardCount
  1341. if max <= 0 || state.concurrentDialingPortForwardCount < int64(max) {
  1342. sshClient.tcpPortForwardDialingAvailableSignal()
  1343. }
  1344. }
  1345. } else {
  1346. state = &sshClient.udpTrafficState
  1347. }
  1348. state.concurrentPortForwardCount += 1
  1349. if state.concurrentPortForwardCount > state.peakConcurrentPortForwardCount {
  1350. state.peakConcurrentPortForwardCount = state.concurrentPortForwardCount
  1351. }
  1352. state.totalPortForwardCount += 1
  1353. }
  1354. func (sshClient *sshClient) closedPortForward(
  1355. portForwardType int, bytesUp, bytesDown int64) {
  1356. sshClient.Lock()
  1357. defer sshClient.Unlock()
  1358. var state *trafficState
  1359. if portForwardType == portForwardTypeTCP {
  1360. state = &sshClient.tcpTrafficState
  1361. } else {
  1362. state = &sshClient.udpTrafficState
  1363. }
  1364. state.concurrentPortForwardCount -= 1
  1365. state.bytesUp += bytesUp
  1366. state.bytesDown += bytesDown
  1367. }
  1368. func (sshClient *sshClient) updateQualityMetricsWithDialResult(
  1369. tcpPortForwardDialSuccess bool, dialDuration time.Duration) {
  1370. sshClient.Lock()
  1371. defer sshClient.Unlock()
  1372. if tcpPortForwardDialSuccess {
  1373. sshClient.qualityMetrics.tcpPortForwardDialedCount += 1
  1374. sshClient.qualityMetrics.tcpPortForwardDialedDuration += dialDuration
  1375. } else {
  1376. sshClient.qualityMetrics.tcpPortForwardFailedCount += 1
  1377. sshClient.qualityMetrics.tcpPortForwardFailedDuration += dialDuration
  1378. }
  1379. }
  1380. func (sshClient *sshClient) updateQualityMetricsWithRejectedDialingLimit() {
  1381. sshClient.Lock()
  1382. defer sshClient.Unlock()
  1383. sshClient.qualityMetrics.tcpPortForwardRejectedDialingLimitCount += 1
  1384. }
  1385. func (sshClient *sshClient) handleTCPChannel(
  1386. remainingDialTimeout time.Duration,
  1387. hostToConnect string,
  1388. portToConnect int,
  1389. newChannel ssh.NewChannel) {
  1390. // Assumptions:
  1391. // - sshClient.dialingTCPPortForward() has been called
  1392. // - remainingDialTimeout > 0
  1393. established := false
  1394. defer func() {
  1395. if !established {
  1396. sshClient.abortedTCPPortForward()
  1397. }
  1398. }()
  1399. // Transparently redirect web API request connections.
  1400. isWebServerPortForward := false
  1401. config := sshClient.sshServer.support.Config
  1402. if config.WebServerPortForwardAddress != "" {
  1403. destination := net.JoinHostPort(hostToConnect, strconv.Itoa(portToConnect))
  1404. if destination == config.WebServerPortForwardAddress {
  1405. isWebServerPortForward = true
  1406. if config.WebServerPortForwardRedirectAddress != "" {
  1407. // Note: redirect format is validated when config is loaded
  1408. host, portStr, _ := net.SplitHostPort(config.WebServerPortForwardRedirectAddress)
  1409. port, _ := strconv.Atoi(portStr)
  1410. hostToConnect = host
  1411. portToConnect = port
  1412. }
  1413. }
  1414. }
  1415. // Dial the remote address.
  1416. //
  1417. // Hostname resolution is performed explicitly, as a seperate step, as the target IP
  1418. // address is used for traffic rules (AllowSubnets) and OSL seed progress.
  1419. //
  1420. // Contexts are used for cancellation (via sshClient.runContext, which is cancelled
  1421. // when the client is stopping) and timeouts.
  1422. dialStartTime := monotime.Now()
  1423. log.WithContextFields(LogFields{"hostToConnect": hostToConnect}).Debug("resolving")
  1424. ctx, _ := context.WithTimeout(sshClient.runContext, remainingDialTimeout)
  1425. IPs, err := (&net.Resolver{}).LookupIPAddr(ctx, hostToConnect)
  1426. // TODO: shuffle list to try other IPs?
  1427. // TODO: IPv6 support
  1428. var IP net.IP
  1429. for _, ip := range IPs {
  1430. if ip.IP.To4() != nil {
  1431. IP = ip.IP
  1432. break
  1433. }
  1434. }
  1435. if err == nil && IP == nil {
  1436. err = errors.New("no IP address")
  1437. }
  1438. resolveElapsedTime := monotime.Since(dialStartTime)
  1439. if err != nil {
  1440. // Record a port forward failure
  1441. sshClient.updateQualityMetricsWithDialResult(true, resolveElapsedTime)
  1442. sshClient.rejectNewChannel(
  1443. newChannel, ssh.ConnectionFailed, fmt.Sprintf("LookupIP failed: %s", err))
  1444. return
  1445. }
  1446. remainingDialTimeout -= resolveElapsedTime
  1447. if remainingDialTimeout <= 0 {
  1448. sshClient.rejectNewChannel(
  1449. newChannel, ssh.Prohibited, "TCP port forward timed out resolving")
  1450. return
  1451. }
  1452. // Enforce traffic rules, using the resolved IP address.
  1453. if !isWebServerPortForward &&
  1454. !sshClient.isPortForwardPermitted(
  1455. portForwardTypeTCP,
  1456. false,
  1457. IP,
  1458. portToConnect) {
  1459. // Note: not recording a port forward failure in this case
  1460. sshClient.rejectNewChannel(
  1461. newChannel, ssh.Prohibited, "port forward not permitted")
  1462. return
  1463. }
  1464. // TCP dial.
  1465. remoteAddr := net.JoinHostPort(IP.String(), strconv.Itoa(portToConnect))
  1466. log.WithContextFields(LogFields{"remoteAddr": remoteAddr}).Debug("dialing")
  1467. ctx, _ = context.WithTimeout(sshClient.runContext, remainingDialTimeout)
  1468. fwdConn, err := (&net.Dialer{}).DialContext(ctx, "tcp", remoteAddr)
  1469. // Record port forward success or failure
  1470. sshClient.updateQualityMetricsWithDialResult(err == nil, monotime.Since(dialStartTime))
  1471. if err != nil {
  1472. // Monitor for low resource error conditions
  1473. sshClient.sshServer.monitorPortForwardDialError(err)
  1474. sshClient.rejectNewChannel(
  1475. newChannel, ssh.ConnectionFailed, fmt.Sprintf("DialTimeout failed: %s", err))
  1476. return
  1477. }
  1478. // The upstream TCP port forward connection has been established. Schedule
  1479. // some cleanup and notify the SSH client that the channel is accepted.
  1480. defer fwdConn.Close()
  1481. fwdChannel, requests, err := newChannel.Accept()
  1482. if err != nil {
  1483. log.WithContextFields(LogFields{"error": err}).Warning("accept new channel failed")
  1484. return
  1485. }
  1486. go ssh.DiscardRequests(requests)
  1487. defer fwdChannel.Close()
  1488. // Release the dialing slot and acquire an established slot.
  1489. // "established = true" cancels the deferred abortedTCPPortForward()
  1490. established = true
  1491. sshClient.establishedPortForward(portForwardTypeTCP)
  1492. var bytesUp, bytesDown int64
  1493. defer func() {
  1494. sshClient.closedPortForward(
  1495. portForwardTypeTCP, atomic.LoadInt64(&bytesUp), atomic.LoadInt64(&bytesDown))
  1496. }()
  1497. if exceeded := sshClient.isPortForwardLimitExceeded(portForwardTypeTCP); exceeded {
  1498. // Close the oldest TCP port forward. CloseOldest() closes
  1499. // the conn and the port forward's goroutines will complete
  1500. // the cleanup asynchronously.
  1501. //
  1502. // Some known limitations:
  1503. //
  1504. // - Since CloseOldest() closes the upstream socket but does not
  1505. // clean up all resources associated with the port forward. These
  1506. // include the goroutine(s) relaying traffic as well as the SSH
  1507. // channel. Closing the socket will interrupt the goroutines which
  1508. // will then complete the cleanup. But, since the full cleanup is
  1509. // asynchronous, there exists a possibility that a client can consume
  1510. // more than max port forward resources -- just not upstream sockets.
  1511. //
  1512. // - Closed sockets will enter the TIME_WAIT state, consuming some
  1513. // resources.
  1514. sshClient.tcpPortForwardLRU.CloseOldest()
  1515. log.WithContext().Debug("closed LRU TCP port forward")
  1516. }
  1517. lruEntry := sshClient.tcpPortForwardLRU.Add(fwdConn)
  1518. defer lruEntry.Remove()
  1519. // ActivityMonitoredConn monitors the TCP port forward I/O and updates
  1520. // its LRU status. ActivityMonitoredConn also times out I/O on the port
  1521. // forward if both reads and writes have been idle for the specified
  1522. // duration.
  1523. // Ensure nil interface if newClientSeedPortForward returns nil
  1524. var updater common.ActivityUpdater
  1525. seedUpdater := sshClient.newClientSeedPortForward(IP)
  1526. if seedUpdater != nil {
  1527. updater = seedUpdater
  1528. }
  1529. fwdConn, err = common.NewActivityMonitoredConn(
  1530. fwdConn,
  1531. sshClient.idleTCPPortForwardTimeout(),
  1532. true,
  1533. updater,
  1534. lruEntry)
  1535. if err != nil {
  1536. log.WithContextFields(LogFields{"error": err}).Error("NewActivityMonitoredConn failed")
  1537. return
  1538. }
  1539. // Relay channel to forwarded connection.
  1540. log.WithContextFields(LogFields{"remoteAddr": remoteAddr}).Debug("relaying")
  1541. // TODO: relay errors to fwdChannel.Stderr()?
  1542. relayWaitGroup := new(sync.WaitGroup)
  1543. relayWaitGroup.Add(1)
  1544. go func() {
  1545. defer relayWaitGroup.Done()
  1546. // io.Copy allocates a 32K temporary buffer, and each port forward relay uses
  1547. // two of these buffers; using io.CopyBuffer with a smaller buffer reduces the
  1548. // overall memory footprint.
  1549. bytes, err := io.CopyBuffer(
  1550. fwdChannel, fwdConn, make([]byte, SSH_TCP_PORT_FORWARD_COPY_BUFFER_SIZE))
  1551. atomic.AddInt64(&bytesDown, bytes)
  1552. if err != nil && err != io.EOF {
  1553. // Debug since errors such as "connection reset by peer" occur during normal operation
  1554. log.WithContextFields(LogFields{"error": err}).Debug("downstream TCP relay failed")
  1555. }
  1556. // Interrupt upstream io.Copy when downstream is shutting down.
  1557. // TODO: this is done to quickly cleanup the port forward when
  1558. // fwdConn has a read timeout, but is it clean -- upstream may still
  1559. // be flowing?
  1560. fwdChannel.Close()
  1561. }()
  1562. bytes, err := io.CopyBuffer(
  1563. fwdConn, fwdChannel, make([]byte, SSH_TCP_PORT_FORWARD_COPY_BUFFER_SIZE))
  1564. atomic.AddInt64(&bytesUp, bytes)
  1565. if err != nil && err != io.EOF {
  1566. log.WithContextFields(LogFields{"error": err}).Debug("upstream TCP relay failed")
  1567. }
  1568. // Shutdown special case: fwdChannel will be closed and return EOF when
  1569. // the SSH connection is closed, but we need to explicitly close fwdConn
  1570. // to interrupt the downstream io.Copy, which may be blocked on a
  1571. // fwdConn.Read().
  1572. fwdConn.Close()
  1573. relayWaitGroup.Wait()
  1574. log.WithContextFields(
  1575. LogFields{
  1576. "remoteAddr": remoteAddr,
  1577. "bytesUp": atomic.LoadInt64(&bytesUp),
  1578. "bytesDown": atomic.LoadInt64(&bytesDown)}).Debug("exiting")
  1579. }