tunnelServer.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  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. "sync"
  28. "sync/atomic"
  29. "time"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  31. "golang.org/x/crypto/ssh"
  32. )
  33. // TunnelServer is the main server that accepts Psiphon client
  34. // connections, via various obfuscation protocols, and provides
  35. // port forwarding (TCP and UDP) services to the Psiphon client.
  36. // At its core, TunnelServer is an SSH server. SSH is the base
  37. // protocol that provides port forward multiplexing, and transport
  38. // security. Layered on top of SSH, optionally, is Obfuscated SSH
  39. // and meek protocols, which provide further circumvention
  40. // capabilities.
  41. type TunnelServer struct {
  42. config *Config
  43. runWaitGroup *sync.WaitGroup
  44. listenerError chan error
  45. shutdownBroadcast <-chan struct{}
  46. sshServer *sshServer
  47. }
  48. // NewTunnelServer initializes a new tunnel server.
  49. func NewTunnelServer(
  50. config *Config, shutdownBroadcast <-chan struct{}) (*TunnelServer, error) {
  51. sshServer, err := newSSHServer(config, shutdownBroadcast)
  52. if err != nil {
  53. return nil, psiphon.ContextError(err)
  54. }
  55. return &TunnelServer{
  56. config: config,
  57. runWaitGroup: new(sync.WaitGroup),
  58. listenerError: make(chan error),
  59. shutdownBroadcast: shutdownBroadcast,
  60. sshServer: sshServer,
  61. }, nil
  62. }
  63. // GetLoadStats returns load stats for the tunnel server. The stats are
  64. // broken down by protocol ("SSH", "OSSH", etc.) and type. Types of stats
  65. // include current connected client count, total number of current port
  66. // forwards.
  67. func (server *TunnelServer) GetLoadStats() map[string]map[string]int64 {
  68. return server.sshServer.getLoadStats()
  69. }
  70. // Run runs the tunnel server; this function blocks while running a selection of
  71. // listeners that handle connection using various obfuscation protocols.
  72. //
  73. // Run listens on each designated tunnel port and spawns new goroutines to handle
  74. // each client connection. It halts when shutdownBroadcast is signaled. A list of active
  75. // clients is maintained, and when halting all clients are cleanly shutdown.
  76. //
  77. // Each client goroutine handles its own obfuscation (optional), SSH handshake, SSH
  78. // authentication, and then looping on client new channel requests. "direct-tcpip"
  79. // channels, dynamic port fowards, are supported. When the UDPInterceptUdpgwServerAddress
  80. // config parameter is configured, UDP port forwards over a TCP stream, following
  81. // the udpgw protocol, are handled.
  82. //
  83. // A new goroutine is spawned to handle each port forward for each client. Each port
  84. // forward tracks its bytes transferred. Overall per-client stats for connection duration,
  85. // GeoIP, number of port forwards, and bytes transferred are tracked and logged when the
  86. // client shuts down.
  87. func (server *TunnelServer) Run() error {
  88. type sshListener struct {
  89. net.Listener
  90. localAddress string
  91. tunnelProtocol string
  92. }
  93. // First bind all listeners; once all are successful,
  94. // start accepting connections on each.
  95. var listeners []*sshListener
  96. for tunnelProtocol, listenPort := range server.config.TunnelProtocolPorts {
  97. localAddress := fmt.Sprintf(
  98. "%s:%d", server.config.ServerIPAddress, listenPort)
  99. listener, err := net.Listen("tcp", localAddress)
  100. if err != nil {
  101. for _, existingListener := range listeners {
  102. existingListener.Listener.Close()
  103. }
  104. return psiphon.ContextError(err)
  105. }
  106. log.WithContextFields(
  107. LogFields{
  108. "localAddress": localAddress,
  109. "tunnelProtocol": tunnelProtocol,
  110. }).Info("listening")
  111. listeners = append(
  112. listeners,
  113. &sshListener{
  114. Listener: listener,
  115. localAddress: localAddress,
  116. tunnelProtocol: tunnelProtocol,
  117. })
  118. }
  119. for _, listener := range listeners {
  120. server.runWaitGroup.Add(1)
  121. go func(listener *sshListener) {
  122. defer server.runWaitGroup.Done()
  123. log.WithContextFields(
  124. LogFields{
  125. "localAddress": listener.localAddress,
  126. "tunnelProtocol": listener.tunnelProtocol,
  127. }).Info("running")
  128. server.sshServer.runListener(
  129. listener.Listener,
  130. server.listenerError,
  131. listener.tunnelProtocol)
  132. log.WithContextFields(
  133. LogFields{
  134. "localAddress": listener.localAddress,
  135. "tunnelProtocol": listener.tunnelProtocol,
  136. }).Info("stopped")
  137. }(listener)
  138. }
  139. var err error
  140. select {
  141. case <-server.shutdownBroadcast:
  142. case err = <-server.listenerError:
  143. }
  144. for _, listener := range listeners {
  145. listener.Close()
  146. }
  147. server.sshServer.stopClients()
  148. server.runWaitGroup.Wait()
  149. log.WithContext().Info("stopped")
  150. return err
  151. }
  152. type sshClientID uint64
  153. type sshServer struct {
  154. config *Config
  155. shutdownBroadcast <-chan struct{}
  156. sshHostKey ssh.Signer
  157. nextClientID sshClientID
  158. clientsMutex sync.Mutex
  159. stoppingClients bool
  160. clients map[sshClientID]*sshClient
  161. }
  162. func newSSHServer(
  163. config *Config,
  164. shutdownBroadcast <-chan struct{}) (*sshServer, error) {
  165. privateKey, err := ssh.ParseRawPrivateKey([]byte(config.SSHPrivateKey))
  166. if err != nil {
  167. return nil, psiphon.ContextError(err)
  168. }
  169. // TODO: use cert (ssh.NewCertSigner) for anti-fingerprint?
  170. signer, err := ssh.NewSignerFromKey(privateKey)
  171. if err != nil {
  172. return nil, psiphon.ContextError(err)
  173. }
  174. return &sshServer{
  175. config: config,
  176. shutdownBroadcast: shutdownBroadcast,
  177. sshHostKey: signer,
  178. nextClientID: 1,
  179. clients: make(map[sshClientID]*sshClient),
  180. }, nil
  181. }
  182. // runListener is intended to run an a goroutine; it blocks
  183. // running a particular listener. If an unrecoverable error
  184. // occurs, it will send the error to the listenerError channel.
  185. func (sshServer *sshServer) runListener(
  186. listener net.Listener,
  187. listenerError chan<- error,
  188. tunnelProtocol string) {
  189. handleClient := func(clientConn net.Conn) {
  190. // process each client connection concurrently
  191. go sshServer.handleClient(tunnelProtocol, clientConn)
  192. }
  193. // Note: when exiting due to a unrecoverable error, be sure
  194. // to try to send the error to listenerError so that the outer
  195. // TunnelServer.Run will properly shut down instead of remaining
  196. // running.
  197. if psiphon.TunnelProtocolUsesMeekHTTP(tunnelProtocol) ||
  198. psiphon.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  199. meekServer, err := NewMeekServer(
  200. sshServer.config,
  201. listener,
  202. psiphon.TunnelProtocolUsesMeekHTTPS(tunnelProtocol),
  203. handleClient,
  204. sshServer.shutdownBroadcast)
  205. if err != nil {
  206. select {
  207. case listenerError <- psiphon.ContextError(err):
  208. default:
  209. }
  210. return
  211. }
  212. meekServer.Run()
  213. } else {
  214. for {
  215. conn, err := listener.Accept()
  216. select {
  217. case <-sshServer.shutdownBroadcast:
  218. if err == nil {
  219. conn.Close()
  220. }
  221. return
  222. default:
  223. }
  224. if err != nil {
  225. if e, ok := err.(net.Error); ok && e.Temporary() {
  226. log.WithContextFields(LogFields{"error": err}).Error("accept failed")
  227. // Temporary error, keep running
  228. continue
  229. }
  230. select {
  231. case listenerError <- psiphon.ContextError(err):
  232. default:
  233. }
  234. return
  235. }
  236. handleClient(conn)
  237. }
  238. }
  239. }
  240. func (sshServer *sshServer) registerClient(client *sshClient) (sshClientID, bool) {
  241. sshServer.clientsMutex.Lock()
  242. defer sshServer.clientsMutex.Unlock()
  243. if sshServer.stoppingClients {
  244. return 0, false
  245. }
  246. clientID := sshServer.nextClientID
  247. sshServer.nextClientID += 1
  248. sshServer.clients[clientID] = client
  249. return clientID, true
  250. }
  251. func (sshServer *sshServer) unregisterClient(clientID sshClientID) {
  252. sshServer.clientsMutex.Lock()
  253. client := sshServer.clients[clientID]
  254. delete(sshServer.clients, clientID)
  255. sshServer.clientsMutex.Unlock()
  256. if client != nil {
  257. client.stop()
  258. }
  259. }
  260. func (sshServer *sshServer) getLoadStats() map[string]map[string]int64 {
  261. sshServer.clientsMutex.Lock()
  262. defer sshServer.clientsMutex.Unlock()
  263. loadStats := make(map[string]map[string]int64)
  264. for _, client := range sshServer.clients {
  265. if loadStats[client.tunnelProtocol] == nil {
  266. loadStats[client.tunnelProtocol] = make(map[string]int64)
  267. }
  268. // Note: can't sum trafficState.peakConcurrentPortForwardCount to get a global peak
  269. loadStats[client.tunnelProtocol]["CurrentClients"] += 1
  270. client.Lock()
  271. loadStats[client.tunnelProtocol]["CurrentTCPPortForwards"] += client.tcpTrafficState.concurrentPortForwardCount
  272. loadStats[client.tunnelProtocol]["TotalTCPPortForwards"] += client.tcpTrafficState.totalPortForwardCount
  273. loadStats[client.tunnelProtocol]["CurrentUDPPortForwards"] += client.udpTrafficState.concurrentPortForwardCount
  274. loadStats[client.tunnelProtocol]["TotalUDPPortForwards"] += client.udpTrafficState.totalPortForwardCount
  275. client.Unlock()
  276. }
  277. return loadStats
  278. }
  279. func (sshServer *sshServer) stopClients() {
  280. sshServer.clientsMutex.Lock()
  281. sshServer.stoppingClients = true
  282. sshServer.clients = make(map[sshClientID]*sshClient)
  283. sshServer.clientsMutex.Unlock()
  284. for _, client := range sshServer.clients {
  285. client.stop()
  286. }
  287. }
  288. func (sshServer *sshServer) handleClient(tunnelProtocol string, clientConn net.Conn) {
  289. geoIPData := GeoIPLookup(psiphon.IPAddressFromAddr(clientConn.RemoteAddr()))
  290. sshClient := newSshClient(
  291. sshServer,
  292. tunnelProtocol,
  293. geoIPData,
  294. sshServer.config.GetTrafficRules(geoIPData.Country))
  295. // Wrap the base client connection with an ActivityMonitoredConn which will
  296. // terminate the connection if no data is received before the deadline. This
  297. // timeout is in effect for the entire duration of the SSH connection. Clients
  298. // must actively use the connection or send SSH keep alive requests to keep
  299. // the connection active.
  300. clientConn = psiphon.NewActivityMonitoredConn(
  301. clientConn,
  302. SSH_CONNECTION_READ_DEADLINE,
  303. false,
  304. nil)
  305. // Further wrap the connection in a rate limiting ThrottledConn.
  306. rateLimits := sshClient.trafficRules.GetRateLimits(tunnelProtocol)
  307. clientConn = psiphon.NewThrottledConn(
  308. clientConn,
  309. rateLimits.DownstreamUnlimitedBytes,
  310. int64(rateLimits.DownstreamBytesPerSecond),
  311. rateLimits.UpstreamUnlimitedBytes,
  312. int64(rateLimits.UpstreamBytesPerSecond))
  313. // Run the initial [obfuscated] SSH handshake in a goroutine so we can both
  314. // respect shutdownBroadcast and implement a specific handshake timeout.
  315. // The timeout is to reclaim network resources in case the handshake takes
  316. // too long.
  317. type sshNewServerConnResult struct {
  318. conn net.Conn
  319. sshConn *ssh.ServerConn
  320. channels <-chan ssh.NewChannel
  321. requests <-chan *ssh.Request
  322. err error
  323. }
  324. resultChannel := make(chan *sshNewServerConnResult, 2)
  325. if SSH_HANDSHAKE_TIMEOUT > 0 {
  326. time.AfterFunc(time.Duration(SSH_HANDSHAKE_TIMEOUT), func() {
  327. resultChannel <- &sshNewServerConnResult{err: errors.New("ssh handshake timeout")}
  328. })
  329. }
  330. go func(conn net.Conn) {
  331. sshServerConfig := &ssh.ServerConfig{
  332. PasswordCallback: sshClient.passwordCallback,
  333. AuthLogCallback: sshClient.authLogCallback,
  334. ServerVersion: sshServer.config.SSHServerVersion,
  335. }
  336. sshServerConfig.AddHostKey(sshServer.sshHostKey)
  337. result := &sshNewServerConnResult{}
  338. // Wrap the connection in an SSH deobfuscator when required.
  339. if psiphon.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  340. // Note: NewObfuscatedSshConn blocks on network I/O
  341. // TODO: ensure this won't block shutdown
  342. conn, result.err = psiphon.NewObfuscatedSshConn(
  343. psiphon.OBFUSCATION_CONN_MODE_SERVER,
  344. clientConn,
  345. sshServer.config.ObfuscatedSSHKey)
  346. if result.err != nil {
  347. result.err = psiphon.ContextError(result.err)
  348. }
  349. }
  350. if result.err == nil {
  351. result.sshConn, result.channels, result.requests, result.err =
  352. ssh.NewServerConn(conn, sshServerConfig)
  353. }
  354. resultChannel <- result
  355. }(clientConn)
  356. var result *sshNewServerConnResult
  357. select {
  358. case result = <-resultChannel:
  359. case <-sshServer.shutdownBroadcast:
  360. // Close() will interrupt an ongoing handshake
  361. // TODO: wait for goroutine to exit before returning?
  362. clientConn.Close()
  363. return
  364. }
  365. if result.err != nil {
  366. clientConn.Close()
  367. // This is a Debug log due to noise. The handshake often fails due to I/O
  368. // errors as clients frequently interrupt connections in progress when
  369. // client-side load balancing completes a connection to a different server.
  370. log.WithContextFields(LogFields{"error": result.err}).Debug("handshake failed")
  371. return
  372. }
  373. sshClient.Lock()
  374. sshClient.sshConn = result.sshConn
  375. sshClient.Unlock()
  376. clientID, ok := sshServer.registerClient(sshClient)
  377. if !ok {
  378. clientConn.Close()
  379. log.WithContext().Warning("register failed")
  380. return
  381. }
  382. defer sshServer.unregisterClient(clientID)
  383. go ssh.DiscardRequests(result.requests)
  384. sshClient.handleChannels(result.channels)
  385. // TODO: clientConn.Close()?
  386. }
  387. type sshClient struct {
  388. sync.Mutex
  389. sshServer *sshServer
  390. tunnelProtocol string
  391. sshConn ssh.Conn
  392. startTime time.Time
  393. geoIPData GeoIPData
  394. psiphonSessionID string
  395. udpChannel ssh.Channel
  396. trafficRules TrafficRules
  397. tcpTrafficState *trafficState
  398. udpTrafficState *trafficState
  399. channelHandlerWaitGroup *sync.WaitGroup
  400. tcpPortForwardLRU *psiphon.LRUConns
  401. stopBroadcast chan struct{}
  402. }
  403. type trafficState struct {
  404. bytesUp int64
  405. bytesDown int64
  406. concurrentPortForwardCount int64
  407. peakConcurrentPortForwardCount int64
  408. totalPortForwardCount int64
  409. }
  410. func newSshClient(
  411. sshServer *sshServer, tunnelProtocol string, geoIPData GeoIPData, trafficRules TrafficRules) *sshClient {
  412. return &sshClient{
  413. sshServer: sshServer,
  414. tunnelProtocol: tunnelProtocol,
  415. startTime: time.Now(),
  416. geoIPData: geoIPData,
  417. trafficRules: trafficRules,
  418. tcpTrafficState: &trafficState{},
  419. udpTrafficState: &trafficState{},
  420. channelHandlerWaitGroup: new(sync.WaitGroup),
  421. tcpPortForwardLRU: psiphon.NewLRUConns(),
  422. stopBroadcast: make(chan struct{}),
  423. }
  424. }
  425. func (sshClient *sshClient) passwordCallback(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
  426. var sshPasswordPayload struct {
  427. SessionId string `json:"SessionId"`
  428. SshPassword string `json:"SshPassword"`
  429. }
  430. err := json.Unmarshal(password, &sshPasswordPayload)
  431. if err != nil {
  432. return nil, psiphon.ContextError(fmt.Errorf("invalid password payload for %q", conn.User()))
  433. }
  434. userOk := (subtle.ConstantTimeCompare(
  435. []byte(conn.User()), []byte(sshClient.sshServer.config.SSHUserName)) == 1)
  436. passwordOk := (subtle.ConstantTimeCompare(
  437. []byte(sshPasswordPayload.SshPassword), []byte(sshClient.sshServer.config.SSHPassword)) == 1)
  438. if !userOk || !passwordOk {
  439. return nil, psiphon.ContextError(fmt.Errorf("invalid password for %q", conn.User()))
  440. }
  441. psiphonSessionID := sshPasswordPayload.SessionId
  442. sshClient.Lock()
  443. sshClient.psiphonSessionID = psiphonSessionID
  444. geoIPData := sshClient.geoIPData
  445. sshClient.Unlock()
  446. if sshClient.sshServer.config.UseRedis() {
  447. err = UpdateRedisForLegacyPsiWeb(psiphonSessionID, geoIPData)
  448. if err != nil {
  449. log.WithContextFields(LogFields{
  450. "psiphonSessionID": psiphonSessionID,
  451. "error": err}).Warning("UpdateRedisForLegacyPsiWeb failed")
  452. // Allow the connection to proceed; legacy psi_web will not get accurate GeoIP values.
  453. }
  454. }
  455. return nil, nil
  456. }
  457. func (sshClient *sshClient) authLogCallback(conn ssh.ConnMetadata, method string, err error) {
  458. if err != nil {
  459. if sshClient.sshServer.config.UseFail2Ban() {
  460. clientIPAddress := psiphon.IPAddressFromAddr(conn.RemoteAddr())
  461. if clientIPAddress != "" {
  462. LogFail2Ban(clientIPAddress)
  463. }
  464. }
  465. log.WithContextFields(LogFields{"error": err, "method": method}).Debug("authentication failed")
  466. } else {
  467. log.WithContextFields(LogFields{"error": err, "method": method}).Debug("authentication success")
  468. }
  469. }
  470. func (sshClient *sshClient) stop() {
  471. sshClient.sshConn.Close()
  472. sshClient.sshConn.Wait()
  473. close(sshClient.stopBroadcast)
  474. sshClient.channelHandlerWaitGroup.Wait()
  475. sshClient.Lock()
  476. log.WithContextFields(
  477. LogFields{
  478. "startTime": sshClient.startTime,
  479. "duration": time.Now().Sub(sshClient.startTime),
  480. "psiphonSessionID": sshClient.psiphonSessionID,
  481. "country": sshClient.geoIPData.Country,
  482. "city": sshClient.geoIPData.City,
  483. "ISP": sshClient.geoIPData.ISP,
  484. "bytesUpTCP": sshClient.tcpTrafficState.bytesUp,
  485. "bytesDownTCP": sshClient.tcpTrafficState.bytesDown,
  486. "peakConcurrentPortForwardCountTCP": sshClient.tcpTrafficState.peakConcurrentPortForwardCount,
  487. "totalPortForwardCountTCP": sshClient.tcpTrafficState.totalPortForwardCount,
  488. "bytesUpUDP": sshClient.udpTrafficState.bytesUp,
  489. "bytesDownUDP": sshClient.udpTrafficState.bytesDown,
  490. "peakConcurrentPortForwardCountUDP": sshClient.udpTrafficState.peakConcurrentPortForwardCount,
  491. "totalPortForwardCountUDP": sshClient.udpTrafficState.totalPortForwardCount,
  492. }).Info("tunnel closed")
  493. sshClient.Unlock()
  494. }
  495. func (sshClient *sshClient) handleChannels(channels <-chan ssh.NewChannel) {
  496. for newChannel := range channels {
  497. if newChannel.ChannelType() != "direct-tcpip" {
  498. sshClient.rejectNewChannel(newChannel, ssh.Prohibited, "unknown or unsupported channel type")
  499. continue
  500. }
  501. // process each port forward concurrently
  502. sshClient.channelHandlerWaitGroup.Add(1)
  503. go sshClient.handleNewPortForwardChannel(newChannel)
  504. }
  505. }
  506. func (sshClient *sshClient) rejectNewChannel(newChannel ssh.NewChannel, reason ssh.RejectionReason, message string) {
  507. // TODO: log more details?
  508. log.WithContextFields(
  509. LogFields{
  510. "channelType": newChannel.ChannelType(),
  511. "rejectMessage": message,
  512. "rejectReason": reason,
  513. }).Warning("reject new channel")
  514. newChannel.Reject(reason, message)
  515. }
  516. func (sshClient *sshClient) handleNewPortForwardChannel(newChannel ssh.NewChannel) {
  517. defer sshClient.channelHandlerWaitGroup.Done()
  518. // http://tools.ietf.org/html/rfc4254#section-7.2
  519. var directTcpipExtraData struct {
  520. HostToConnect string
  521. PortToConnect uint32
  522. OriginatorIPAddress string
  523. OriginatorPort uint32
  524. }
  525. err := ssh.Unmarshal(newChannel.ExtraData(), &directTcpipExtraData)
  526. if err != nil {
  527. sshClient.rejectNewChannel(newChannel, ssh.Prohibited, "invalid extra data")
  528. return
  529. }
  530. // Intercept TCP port forwards to a specified udpgw server and handle directly.
  531. // TODO: also support UDP explicitly, e.g. with a custom "direct-udp" channel type?
  532. isUDPChannel := sshClient.sshServer.config.UDPInterceptUdpgwServerAddress != "" &&
  533. sshClient.sshServer.config.UDPInterceptUdpgwServerAddress ==
  534. fmt.Sprintf("%s:%d",
  535. directTcpipExtraData.HostToConnect,
  536. directTcpipExtraData.PortToConnect)
  537. if isUDPChannel {
  538. sshClient.handleUDPChannel(newChannel)
  539. } else {
  540. sshClient.handleTCPChannel(
  541. directTcpipExtraData.HostToConnect, int(directTcpipExtraData.PortToConnect), newChannel)
  542. }
  543. }
  544. func (sshClient *sshClient) isPortForwardPermitted(
  545. port int, allowPorts []int, denyPorts []int) bool {
  546. // TODO: faster lookup?
  547. if len(allowPorts) > 0 {
  548. for _, allowPort := range allowPorts {
  549. if port == allowPort {
  550. return true
  551. }
  552. }
  553. return false
  554. }
  555. if len(denyPorts) > 0 {
  556. for _, denyPort := range denyPorts {
  557. if port == denyPort {
  558. return false
  559. }
  560. }
  561. }
  562. return true
  563. }
  564. func (sshClient *sshClient) isPortForwardLimitExceeded(
  565. state *trafficState, maxPortForwardCount int) bool {
  566. limitExceeded := false
  567. if maxPortForwardCount > 0 {
  568. sshClient.Lock()
  569. limitExceeded = state.concurrentPortForwardCount >= int64(maxPortForwardCount)
  570. sshClient.Unlock()
  571. }
  572. return limitExceeded
  573. }
  574. func (sshClient *sshClient) openedPortForward(
  575. state *trafficState) {
  576. sshClient.Lock()
  577. state.concurrentPortForwardCount += 1
  578. if state.concurrentPortForwardCount > state.peakConcurrentPortForwardCount {
  579. state.peakConcurrentPortForwardCount = state.concurrentPortForwardCount
  580. }
  581. state.totalPortForwardCount += 1
  582. sshClient.Unlock()
  583. }
  584. func (sshClient *sshClient) closedPortForward(
  585. state *trafficState, bytesUp, bytesDown int64) {
  586. sshClient.Lock()
  587. state.concurrentPortForwardCount -= 1
  588. state.bytesUp += bytesUp
  589. state.bytesDown += bytesDown
  590. sshClient.Unlock()
  591. }
  592. func (sshClient *sshClient) handleTCPChannel(
  593. hostToConnect string,
  594. portToConnect int,
  595. newChannel ssh.NewChannel) {
  596. if !sshClient.isPortForwardPermitted(
  597. portToConnect,
  598. sshClient.trafficRules.AllowTCPPorts,
  599. sshClient.trafficRules.DenyTCPPorts) {
  600. sshClient.rejectNewChannel(
  601. newChannel, ssh.Prohibited, "port forward not permitted")
  602. return
  603. }
  604. var bytesUp, bytesDown int64
  605. sshClient.openedPortForward(sshClient.tcpTrafficState)
  606. defer func() {
  607. sshClient.closedPortForward(
  608. sshClient.tcpTrafficState,
  609. atomic.LoadInt64(&bytesUp),
  610. atomic.LoadInt64(&bytesDown))
  611. }()
  612. // TOCTOU note: important to increment the port forward count (via
  613. // openPortForward) _before_ checking isPortForwardLimitExceeded
  614. // otherwise, the client could potentially consume excess resources
  615. // by initiating many port forwards concurrently.
  616. // TODO: close LRU connection (after successful Dial) instead of
  617. // rejecting new connection?
  618. if sshClient.isPortForwardLimitExceeded(
  619. sshClient.tcpTrafficState,
  620. sshClient.trafficRules.MaxTCPPortForwardCount) {
  621. // Close the oldest TCP port forward. CloseOldest() closes
  622. // the conn and the port forward's goroutine will complete
  623. // the cleanup asynchronously.
  624. //
  625. // Some known limitations:
  626. //
  627. // - Since CloseOldest() closes the upstream socket but does not
  628. // clean up all resources associated with the port forward. These
  629. // include the goroutine(s) relaying traffic as well as the SSH
  630. // channel. Closing the socket will interrupt the goroutines which
  631. // will then complete the cleanup. But, since the full cleanup is
  632. // asynchronous, there exists a possibility that a client can consume
  633. // more than max port forward resources -- just not upstream sockets.
  634. //
  635. // - An LRU list entry for this port forward is not added until
  636. // after the dial completes, but the port forward is counted
  637. // towards max limits. This means many dials in progress will
  638. // put established connections in jeopardy.
  639. //
  640. // - We're closing the oldest open connection _before_ successfully
  641. // dialing the new port forward. This means we are potentially
  642. // discarding a good connection to make way for a failed connection.
  643. // We cannot simply dial first and still maintain a limit on
  644. // resources used, so to address this we'd need to add some
  645. // accounting for connections still establishing.
  646. sshClient.tcpPortForwardLRU.CloseOldest()
  647. log.WithContextFields(
  648. LogFields{
  649. "maxCount": sshClient.trafficRules.MaxTCPPortForwardCount,
  650. }).Debug("closed LRU TCP port forward")
  651. }
  652. // Dial the target remote address. This is done in a goroutine to
  653. // ensure the shutdown signal is handled immediately.
  654. remoteAddr := fmt.Sprintf("%s:%d", hostToConnect, portToConnect)
  655. log.WithContextFields(LogFields{"remoteAddr": remoteAddr}).Debug("dialing")
  656. type dialTcpResult struct {
  657. conn net.Conn
  658. err error
  659. }
  660. resultChannel := make(chan *dialTcpResult, 1)
  661. go func() {
  662. // TODO: on EADDRNOTAVAIL, temporarily suspend new clients
  663. // TODO: IPv6 support
  664. conn, err := net.DialTimeout(
  665. "tcp4", remoteAddr, SSH_TCP_PORT_FORWARD_DIAL_TIMEOUT)
  666. resultChannel <- &dialTcpResult{conn, err}
  667. }()
  668. var result *dialTcpResult
  669. select {
  670. case result = <-resultChannel:
  671. case <-sshClient.stopBroadcast:
  672. // Note: may leave dial in progress
  673. return
  674. }
  675. if result.err != nil {
  676. sshClient.rejectNewChannel(newChannel, ssh.ConnectionFailed, result.err.Error())
  677. return
  678. }
  679. // The upstream TCP port forward connection has been established. Schedule
  680. // some cleanup and notify the SSH client that the channel is accepted.
  681. fwdConn := result.conn
  682. defer fwdConn.Close()
  683. lruEntry := sshClient.tcpPortForwardLRU.Add(fwdConn)
  684. defer lruEntry.Remove()
  685. // ActivityMonitoredConn monitors the TCP port forward I/O and updates
  686. // its LRU status. ActivityMonitoredConn also times out read on the port
  687. // forward if both reads and writes have been idle for the specified
  688. // duration.
  689. fwdConn = psiphon.NewActivityMonitoredConn(
  690. fwdConn,
  691. time.Duration(sshClient.trafficRules.IdleTCPPortForwardTimeoutMilliseconds)*time.Millisecond,
  692. true,
  693. lruEntry)
  694. fwdChannel, requests, err := newChannel.Accept()
  695. if err != nil {
  696. log.WithContextFields(LogFields{"error": err}).Warning("accept new channel failed")
  697. return
  698. }
  699. go ssh.DiscardRequests(requests)
  700. defer fwdChannel.Close()
  701. log.WithContextFields(LogFields{"remoteAddr": remoteAddr}).Debug("relaying")
  702. // Relay channel to forwarded connection.
  703. // TODO: relay errors to fwdChannel.Stderr()?
  704. relayWaitGroup := new(sync.WaitGroup)
  705. relayWaitGroup.Add(1)
  706. go func() {
  707. defer relayWaitGroup.Done()
  708. // io.Copy allocates a 32K temporary buffer, and each port forward relay uses
  709. // two of these buffers; using io.CopyBuffer with a smaller buffer reduces the
  710. // overall memory footprint.
  711. bytes, err := io.CopyBuffer(
  712. fwdChannel, fwdConn, make([]byte, SSH_TCP_PORT_FORWARD_COPY_BUFFER_SIZE))
  713. atomic.AddInt64(&bytesDown, bytes)
  714. if err != nil && err != io.EOF {
  715. // Debug since errors such as "connection reset by peer" occur during normal operation
  716. log.WithContextFields(LogFields{"error": err}).Debug("downstream TCP relay failed")
  717. }
  718. // Interrupt upstream io.Copy when downstream is shutting down.
  719. // TODO: this is done to quickly cleanup the port forward when
  720. // fwdConn has a read timeout, but is it clean -- upstream may still
  721. // be flowing?
  722. fwdChannel.Close()
  723. }()
  724. bytes, err := io.CopyBuffer(
  725. fwdConn, fwdChannel, make([]byte, SSH_TCP_PORT_FORWARD_COPY_BUFFER_SIZE))
  726. atomic.AddInt64(&bytesUp, bytes)
  727. if err != nil && err != io.EOF {
  728. log.WithContextFields(LogFields{"error": err}).Debug("upstream TCP relay failed")
  729. }
  730. // Shutdown special case: fwdChannel will be closed and return EOF when
  731. // the SSH connection is closed, but we need to explicitly close fwdConn
  732. // to interrupt the downstream io.Copy, which may be blocked on a
  733. // fwdConn.Read().
  734. fwdConn.Close()
  735. relayWaitGroup.Wait()
  736. log.WithContextFields(
  737. LogFields{
  738. "remoteAddr": remoteAddr,
  739. "bytesUp": atomic.LoadInt64(&bytesUp),
  740. "bytesDown": atomic.LoadInt64(&bytesDown)}).Debug("exiting")
  741. }