sshService.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. "encoding/json"
  22. "errors"
  23. "fmt"
  24. "io"
  25. "net"
  26. "sync"
  27. "time"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  29. "golang.org/x/crypto/ssh"
  30. )
  31. func RunSSHServer(config *Config, shutdownBroadcast <-chan struct{}) error {
  32. return runSSHServer(config, false, shutdownBroadcast)
  33. }
  34. func RunObfuscatedSSHServer(config *Config, shutdownBroadcast <-chan struct{}) error {
  35. return runSSHServer(config, true, shutdownBroadcast)
  36. }
  37. type sshServer struct {
  38. config *Config
  39. useObfuscation bool
  40. shutdownBroadcast <-chan struct{}
  41. sshConfig *ssh.ServerConfig
  42. clientMutex sync.Mutex
  43. stoppingClients bool
  44. clients map[string]ssh.Conn
  45. }
  46. func runSSHServer(
  47. config *Config, useObfuscation bool, shutdownBroadcast <-chan struct{}) error {
  48. sshServer := &sshServer{
  49. config: config,
  50. useObfuscation: useObfuscation,
  51. shutdownBroadcast: shutdownBroadcast,
  52. clients: make(map[string]ssh.Conn),
  53. }
  54. sshServer.sshConfig = &ssh.ServerConfig{
  55. PasswordCallback: sshServer.passwordCallback,
  56. AuthLogCallback: sshServer.authLogCallback,
  57. ServerVersion: config.SSHServerVersion,
  58. }
  59. privateKey, err := ssh.ParseRawPrivateKey([]byte(config.SSHPrivateKey))
  60. if err != nil {
  61. return psiphon.ContextError(err)
  62. }
  63. // TODO: use cert (ssh.NewCertSigner) for anti-fingerprint?
  64. signer, err := ssh.NewSignerFromKey(privateKey)
  65. if err != nil {
  66. return psiphon.ContextError(err)
  67. }
  68. sshServer.sshConfig.AddHostKey(signer)
  69. var serverPort int
  70. if useObfuscation {
  71. serverPort = config.ObfuscatedSSHServerPort
  72. } else {
  73. serverPort = config.SSHServerPort
  74. }
  75. listener, err := net.Listen(
  76. "tcp", fmt.Sprintf("%s:%d", config.ServerIPAddress, serverPort))
  77. if err != nil {
  78. return psiphon.ContextError(err)
  79. }
  80. log.WithContextFields(
  81. LogFields{
  82. "useObfuscation": useObfuscation,
  83. "port": serverPort,
  84. }).Info("starting")
  85. err = nil
  86. errors := make(chan error)
  87. waitGroup := new(sync.WaitGroup)
  88. waitGroup.Add(1)
  89. go func() {
  90. defer waitGroup.Done()
  91. loop:
  92. for {
  93. conn, err := listener.Accept()
  94. select {
  95. case <-shutdownBroadcast:
  96. if err == nil {
  97. conn.Close()
  98. }
  99. break loop
  100. default:
  101. }
  102. if err != nil {
  103. if e, ok := err.(net.Error); ok && e.Temporary() {
  104. log.WithContextFields(LogFields{"error": err}).Error("accept failed")
  105. // Temporary error, keep running
  106. continue
  107. }
  108. select {
  109. case errors <- psiphon.ContextError(err):
  110. default:
  111. }
  112. break loop
  113. }
  114. // process each client connection concurrently
  115. go sshServer.handleClient(conn)
  116. }
  117. sshServer.stopClients()
  118. log.WithContextFields(
  119. LogFields{"useObfuscation": useObfuscation}).Info("stopped")
  120. }()
  121. select {
  122. case <-shutdownBroadcast:
  123. case err = <-errors:
  124. }
  125. listener.Close()
  126. waitGroup.Wait()
  127. log.WithContextFields(
  128. LogFields{"useObfuscation": useObfuscation}).Info("exiting")
  129. return err
  130. }
  131. func (sshServer *sshServer) passwordCallback(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
  132. var sshPasswordPayload struct {
  133. SessionId string `json:"SessionId"`
  134. SshPassword string `json:"SshPassword"`
  135. }
  136. err := json.Unmarshal(password, &sshPasswordPayload)
  137. if err != nil {
  138. return nil, psiphon.ContextError(fmt.Errorf("invalid password payload for %q", conn.User()))
  139. }
  140. if conn.User() == sshServer.config.SSHUserName &&
  141. sshPasswordPayload.SshPassword == sshServer.config.SSHPassword {
  142. return nil, nil
  143. }
  144. return nil, psiphon.ContextError(fmt.Errorf("invalid password for %q", conn.User()))
  145. }
  146. func (sshServer *sshServer) authLogCallback(conn ssh.ConnMetadata, method string, err error) {
  147. if err != nil {
  148. log.WithContextFields(LogFields{"error": err, "method": method}).Warning("authentication failed")
  149. } else {
  150. log.WithContextFields(LogFields{"error": err, "method": method}).Info("authentication success")
  151. }
  152. }
  153. func (sshServer *sshServer) registerClient(sshConn ssh.Conn) bool {
  154. sshServer.clientMutex.Lock()
  155. defer sshServer.clientMutex.Unlock()
  156. if sshServer.stoppingClients {
  157. return false
  158. }
  159. existingSshConn := sshServer.clients[string(sshConn.SessionID())]
  160. if existingSshConn != nil {
  161. log.WithContext().Warning("unexpected existing connection")
  162. existingSshConn.Close()
  163. existingSshConn.Wait()
  164. }
  165. sshServer.clients[string(sshConn.SessionID())] = sshConn
  166. return true
  167. }
  168. func (sshServer *sshServer) unregisterClient(sshConn ssh.Conn) {
  169. sshServer.clientMutex.Lock()
  170. if sshServer.stoppingClients {
  171. return
  172. }
  173. delete(sshServer.clients, string(sshConn.SessionID()))
  174. sshServer.clientMutex.Unlock()
  175. sshConn.Close()
  176. }
  177. func (sshServer *sshServer) stopClients() {
  178. sshServer.clientMutex.Lock()
  179. sshServer.stoppingClients = true
  180. sshServer.clientMutex.Unlock()
  181. for _, sshConn := range sshServer.clients {
  182. sshConn.Close()
  183. sshConn.Wait()
  184. }
  185. }
  186. func (sshServer *sshServer) handleClient(conn net.Conn) {
  187. // Run the initial [obfuscated] SSH handshake in a goroutine
  188. // so we can both respect shutdownBroadcast and implement a
  189. // handshake timeout. The timeout is to reclaim network
  190. // resources in case the handshake takes too long.
  191. type sshNewServerConnResult struct {
  192. conn net.Conn
  193. sshConn *ssh.ServerConn
  194. channels <-chan ssh.NewChannel
  195. requests <-chan *ssh.Request
  196. err error
  197. }
  198. resultChannel := make(chan *sshNewServerConnResult, 2)
  199. if SSH_HANDSHAKE_TIMEOUT > 0 {
  200. time.AfterFunc(time.Duration(SSH_HANDSHAKE_TIMEOUT), func() {
  201. resultChannel <- &sshNewServerConnResult{err: errors.New("ssh handshake timeout")}
  202. })
  203. }
  204. go func() {
  205. result := &sshNewServerConnResult{}
  206. if sshServer.useObfuscation {
  207. result.conn, result.err = psiphon.NewObfuscatedSshConn(
  208. psiphon.OBFUSCATION_CONN_MODE_SERVER, conn, sshServer.config.ObfuscatedSSHKey)
  209. } else {
  210. result.conn = conn
  211. }
  212. if result.err == nil {
  213. result.sshConn, result.channels,
  214. result.requests, result.err = ssh.NewServerConn(result.conn, sshServer.sshConfig)
  215. }
  216. resultChannel <- result
  217. }()
  218. var result *sshNewServerConnResult
  219. select {
  220. case result = <-resultChannel:
  221. case <-sshServer.shutdownBroadcast:
  222. // Close() will interrupt an ongoing handshake
  223. // TODO: wait for goroutine to exit before returning?
  224. conn.Close()
  225. return
  226. }
  227. if result.err != nil {
  228. conn.Close()
  229. log.WithContextFields(LogFields{"error": result.err}).Warning("handshake failed")
  230. return
  231. }
  232. if !sshServer.registerClient(result.sshConn) {
  233. result.sshConn.Close()
  234. log.WithContext().Warning("register failed")
  235. return
  236. }
  237. defer sshServer.unregisterClient(result.sshConn)
  238. // TODO: don't record IP; do GeoIP
  239. log.WithContextFields(
  240. LogFields{"remoteAddr": result.sshConn.RemoteAddr()}).Warning("connection accepted")
  241. go ssh.DiscardRequests(result.requests)
  242. for newChannel := range result.channels {
  243. if newChannel.ChannelType() != "direct-tcpip" {
  244. sshServer.rejectNewChannel(newChannel, ssh.Prohibited, "unknown or unsupported channel type")
  245. return
  246. }
  247. // process each port forward concurrently
  248. go sshServer.handleNewDirectTcpipChannel(newChannel)
  249. }
  250. }
  251. func (sshServer *sshServer) rejectNewChannel(newChannel ssh.NewChannel, reason ssh.RejectionReason, message string) {
  252. // TODO: log more details?
  253. log.WithContextFields(
  254. LogFields{
  255. "channelType": newChannel.ChannelType(),
  256. "rejectMessage": message,
  257. "rejectReason": reason,
  258. }).Warning("reject new channel")
  259. newChannel.Reject(reason, message)
  260. }
  261. func (sshServer *sshServer) handleNewDirectTcpipChannel(newChannel ssh.NewChannel) {
  262. // http://tools.ietf.org/html/rfc4254#section-7.2
  263. var directTcpipExtraData struct {
  264. HostToConnect string
  265. PortToConnect uint32
  266. OriginatorIPAddress string
  267. OriginatorPort uint32
  268. }
  269. err := ssh.Unmarshal(newChannel.ExtraData(), &directTcpipExtraData)
  270. if err != nil {
  271. sshServer.rejectNewChannel(newChannel, ssh.Prohibited, "invalid extra data")
  272. return
  273. }
  274. targetAddr := fmt.Sprintf("%s:%d",
  275. directTcpipExtraData.HostToConnect,
  276. directTcpipExtraData.PortToConnect)
  277. log.WithContextFields(LogFields{"target": targetAddr}).Debug("dialing")
  278. // TODO: port forward dial timeout
  279. // TODO: report ssh.ResourceShortage when appropriate
  280. fwdConn, err := net.Dial("tcp", targetAddr)
  281. if err != nil {
  282. sshServer.rejectNewChannel(newChannel, ssh.ConnectionFailed, err.Error())
  283. return
  284. }
  285. defer fwdConn.Close()
  286. fwdChannel, requests, err := newChannel.Accept()
  287. if err != nil {
  288. log.WithContextFields(LogFields{"error": err}).Warning("accept new channel failed")
  289. return
  290. }
  291. log.WithContextFields(LogFields{"target": targetAddr}).Debug("relaying")
  292. go ssh.DiscardRequests(requests)
  293. defer fwdChannel.Close()
  294. // relay channel to forwarded connection
  295. // TODO: use a low-memory io.Copy?
  296. // TODO: relay errors to fwdChannel.Stderr()?
  297. relayWaitGroup := new(sync.WaitGroup)
  298. relayWaitGroup.Add(1)
  299. go func() {
  300. defer relayWaitGroup.Done()
  301. _, err := io.Copy(fwdConn, fwdChannel)
  302. if err != nil {
  303. log.WithContextFields(LogFields{"error": err}).Warning("upstream relay failed")
  304. }
  305. }()
  306. _, err = io.Copy(fwdChannel, fwdConn)
  307. if err != nil {
  308. log.WithContextFields(LogFields{"error": err}).Warning("downstream relay failed")
  309. }
  310. fwdChannel.CloseWrite()
  311. relayWaitGroup.Wait()
  312. log.WithContextFields(LogFields{"target": targetAddr}).Debug("exiting")
  313. }