tunnelServer.go 51 KB

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