sshService.go 9.7 KB

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