sshService.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. "fmt"
  23. "io"
  24. "net"
  25. "sync"
  26. log "github.com/Psiphon-Inc/logrus"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  28. "golang.org/x/crypto/ssh"
  29. )
  30. type sshServer struct {
  31. config *Config
  32. sshConfig *ssh.ServerConfig
  33. clientMutex sync.Mutex
  34. stoppingClients bool
  35. clients map[string]ssh.Conn
  36. }
  37. func RunSSHServer(config *Config, shutdownBroadcast <-chan struct{}) error {
  38. sshServer := &sshServer{
  39. config: config,
  40. clients: make(map[string]ssh.Conn),
  41. }
  42. sshServer.sshConfig = &ssh.ServerConfig{
  43. PasswordCallback: sshServer.passwordCallback,
  44. AuthLogCallback: sshServer.authLogCallback,
  45. ServerVersion: config.SSHServerVersion,
  46. }
  47. privateKey, err := ssh.ParseRawPrivateKey([]byte(config.SSHPrivateKey))
  48. if err != nil {
  49. return psiphon.ContextError(err)
  50. }
  51. // TODO: use cert (ssh.NewCertSigner) for anti-fingerprint?
  52. signer, err := ssh.NewSignerFromKey(privateKey)
  53. if err != nil {
  54. return psiphon.ContextError(err)
  55. }
  56. sshServer.sshConfig.AddHostKey(signer)
  57. listener, err := net.Listen(
  58. "tcp", fmt.Sprintf("%s:%d", config.ServerIPAddress, config.SSHPort))
  59. if err != nil {
  60. return psiphon.ContextError(err)
  61. }
  62. log.Info("RunSSH: starting server")
  63. err = nil
  64. errors := make(chan error)
  65. waitGroup := new(sync.WaitGroup)
  66. waitGroup.Add(1)
  67. go func() {
  68. defer waitGroup.Done()
  69. loop:
  70. for {
  71. conn, err := listener.Accept()
  72. select {
  73. case <-shutdownBroadcast:
  74. break loop
  75. default:
  76. }
  77. if err != nil {
  78. if e, ok := err.(net.Error); ok && e.Temporary() {
  79. log.Warning("RunSSH accept error: %s", err)
  80. // Temporary error, keep running
  81. continue
  82. }
  83. select {
  84. case errors <- psiphon.ContextError(err):
  85. default:
  86. }
  87. break loop
  88. }
  89. // process each client connection concurrently
  90. go sshServer.handleClient(conn)
  91. }
  92. sshServer.stopClients()
  93. log.Info("RunSSH: server stopped")
  94. }()
  95. select {
  96. case <-shutdownBroadcast:
  97. case err = <-errors:
  98. }
  99. listener.Close()
  100. waitGroup.Wait()
  101. log.Info("RunSSH: exiting")
  102. return err
  103. }
  104. func (sshServer *sshServer) passwordCallback(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
  105. var sshPasswordPayload struct {
  106. SessionId string `json:"SessionId"`
  107. SshPassword string `json:"SshPassword"`
  108. }
  109. err := json.Unmarshal(password, &sshPasswordPayload)
  110. if err != nil {
  111. return nil, psiphon.ContextError(fmt.Errorf("invalid password payload for %q", conn.User()))
  112. }
  113. if conn.User() == sshServer.config.SSHUserName &&
  114. sshPasswordPayload.SshPassword == sshServer.config.SSHPassword {
  115. return nil, nil
  116. }
  117. return nil, psiphon.ContextError(fmt.Errorf("invalid password for %q", conn.User()))
  118. }
  119. func (sshServer *sshServer) authLogCallback(conn ssh.ConnMetadata, method string, err error) {
  120. if err != nil {
  121. log.Warning("ssh: %s authentication failed %s", method, err)
  122. } else {
  123. log.Info("ssh: %s authentication success %s", method)
  124. }
  125. }
  126. func (sshServer *sshServer) registerClient(sshConn ssh.Conn) bool {
  127. sshServer.clientMutex.Lock()
  128. defer sshServer.clientMutex.Unlock()
  129. if sshServer.stoppingClients {
  130. return false
  131. }
  132. existingSshConn := sshServer.clients[string(sshConn.SessionID())]
  133. if existingSshConn != nil {
  134. log.Warning("sshServer.registerClient: unexpected existing connection")
  135. existingSshConn.Close()
  136. existingSshConn.Wait()
  137. }
  138. sshServer.clients[string(sshConn.SessionID())] = sshConn
  139. return true
  140. }
  141. func (sshServer *sshServer) unregisterClient(sshConn ssh.Conn) {
  142. sshServer.clientMutex.Lock()
  143. if sshServer.stoppingClients {
  144. return
  145. }
  146. delete(sshServer.clients, string(sshConn.SessionID()))
  147. sshServer.clientMutex.Unlock()
  148. sshConn.Close()
  149. }
  150. func (sshServer *sshServer) stopClients() {
  151. sshServer.clientMutex.Lock()
  152. sshServer.stoppingClients = true
  153. sshServer.clientMutex.Unlock()
  154. for _, sshConn := range sshServer.clients {
  155. sshConn.Close()
  156. sshConn.Wait()
  157. }
  158. }
  159. func (sshServer *sshServer) handleClient(conn net.Conn) {
  160. // TODO: does this block on SSH handshake (so should be in goroutine)?
  161. sshConn, channels, requests, err := ssh.NewServerConn(conn, sshServer.sshConfig)
  162. if err != nil {
  163. conn.Close()
  164. log.Error("sshServer.handleClient: ssh establish connection failed: %s", err)
  165. return
  166. }
  167. if !sshServer.registerClient(sshConn) {
  168. sshConn.Close()
  169. log.Error("sshServer.handleClient: failed to register client")
  170. return
  171. }
  172. defer sshServer.unregisterClient(sshConn)
  173. // TODO: don't record IP; do GeoIP
  174. log.Info("connection from %s", sshConn.RemoteAddr())
  175. go ssh.DiscardRequests(requests)
  176. for newChannel := range channels {
  177. if newChannel.ChannelType() != "direct-tcpip" {
  178. sshServer.rejectNewChannel(newChannel, ssh.Prohibited, "unknown or unsupported channel type")
  179. return
  180. }
  181. // process each port forward concurrently
  182. go sshServer.handleNewDirectTcpipChannel(newChannel)
  183. }
  184. }
  185. func (sshServer *sshServer) rejectNewChannel(newChannel ssh.NewChannel, reason ssh.RejectionReason, message string) {
  186. // TODO: log more details?
  187. log.Warning("ssh reject new channel: %s: %d: %s", newChannel.ChannelType(), reason, message)
  188. newChannel.Reject(reason, message)
  189. }
  190. func (sshServer *sshServer) handleNewDirectTcpipChannel(newChannel ssh.NewChannel) {
  191. // http://tools.ietf.org/html/rfc4254#section-7.2
  192. var directTcpipExtraData struct {
  193. HostToConnect string
  194. PortToConnect uint32
  195. OriginatorIPAddress string
  196. OriginatorPort uint32
  197. }
  198. err := ssh.Unmarshal(newChannel.ExtraData(), &directTcpipExtraData)
  199. if err != nil {
  200. sshServer.rejectNewChannel(newChannel, ssh.Prohibited, "invalid extra data")
  201. return
  202. }
  203. targetAddr := fmt.Sprintf("%s:%d",
  204. directTcpipExtraData.HostToConnect,
  205. directTcpipExtraData.PortToConnect)
  206. log.Debug("sshServer.handleNewDirectTcpipChannel: dialing %s", targetAddr)
  207. // TODO: port forward dial timeout
  208. // TODO: report ssh.ResourceShortage when appropriate
  209. fwdConn, err := net.Dial("tcp", targetAddr)
  210. if err != nil {
  211. sshServer.rejectNewChannel(newChannel, ssh.ConnectionFailed, err.Error())
  212. return
  213. }
  214. defer fwdConn.Close()
  215. fwdChannel, requests, err := newChannel.Accept()
  216. if err != nil {
  217. log.Warning("sshServer.handleNewDirectTcpipChannel: accept new channel failed: %s", err)
  218. return
  219. }
  220. log.Debug("sshServer.handleNewDirectTcpipChannel: relaying %s", targetAddr)
  221. go ssh.DiscardRequests(requests)
  222. defer fwdChannel.Close()
  223. // relay channel to forwarded connection
  224. // TODO: use a low-memory io.Copy?
  225. // TODO: relay errors to fwdChannel.Stderr()?
  226. relayWaitGroup := new(sync.WaitGroup)
  227. relayWaitGroup.Add(1)
  228. go func() {
  229. defer relayWaitGroup.Done()
  230. _, err := io.Copy(fwdConn, fwdChannel)
  231. if err != nil {
  232. log.Warning("sshServer.handleNewDirectTcpipChannel: upstream relay failed: %s", err)
  233. }
  234. }()
  235. _, err = io.Copy(fwdChannel, fwdConn)
  236. if err != nil {
  237. log.Warning("sshServer.handleNewDirectTcpipChannel: downstream relay failed: %s", err)
  238. }
  239. fwdChannel.CloseWrite()
  240. relayWaitGroup.Wait()
  241. log.Info("sshServer.handleNewDirectTcpipChannel: exiting %s", targetAddr)
  242. }