tunnelServer.go 50 KB

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