tunnelServer.go 65 KB

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