ssh.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package ssh
  5. import (
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net"
  10. "os"
  11. "os/exec"
  12. "path/filepath"
  13. "strings"
  14. "github.com/unknwon/com"
  15. "golang.org/x/crypto/ssh"
  16. log "unknwon.dev/clog/v2"
  17. "gogs.io/gogs/internal/conf"
  18. "gogs.io/gogs/internal/db"
  19. )
  20. func cleanCommand(cmd string) string {
  21. i := strings.Index(cmd, "git")
  22. if i == -1 {
  23. return cmd
  24. }
  25. return cmd[i:]
  26. }
  27. func handleServerConn(keyID string, chans <-chan ssh.NewChannel) {
  28. for newChan := range chans {
  29. if newChan.ChannelType() != "session" {
  30. _ = newChan.Reject(ssh.UnknownChannelType, "unknown channel type")
  31. continue
  32. }
  33. ch, reqs, err := newChan.Accept()
  34. if err != nil {
  35. log.Error("Error accepting channel: %v", err)
  36. continue
  37. }
  38. go func(in <-chan *ssh.Request) {
  39. defer func() {
  40. _ = ch.Close()
  41. }()
  42. for req := range in {
  43. payload := cleanCommand(string(req.Payload))
  44. switch req.Type {
  45. case "env":
  46. var env struct {
  47. Name string
  48. Value string
  49. }
  50. if err := ssh.Unmarshal(req.Payload, &env); err != nil {
  51. log.Warn("SSH: Invalid env payload %q: %v", req.Payload, err)
  52. continue
  53. }
  54. // Sometimes the client could send malformed command (i.e. missing "="),
  55. // see https://discuss.gogs.io/t/ssh/3106.
  56. if env.Name == "" || env.Value == "" {
  57. log.Warn("SSH: Invalid env arguments: %+v", env)
  58. continue
  59. }
  60. _, stderr, err := com.ExecCmd("env", fmt.Sprintf("%s=%s", env.Name, env.Value))
  61. if err != nil {
  62. log.Error("env: %v - %s", err, stderr)
  63. return
  64. }
  65. case "exec":
  66. cmdName := strings.TrimLeft(payload, "'()")
  67. log.Trace("SSH: Payload: %v", cmdName)
  68. args := []string{"serv", "key-" + keyID, "--config=" + conf.CustomConf}
  69. log.Trace("SSH: Arguments: %v", args)
  70. cmd := exec.Command(conf.AppPath(), args...)
  71. cmd.Env = append(os.Environ(), "SSH_ORIGINAL_COMMAND="+cmdName)
  72. stdout, err := cmd.StdoutPipe()
  73. if err != nil {
  74. log.Error("SSH: StdoutPipe: %v", err)
  75. return
  76. }
  77. stderr, err := cmd.StderrPipe()
  78. if err != nil {
  79. log.Error("SSH: StderrPipe: %v", err)
  80. return
  81. }
  82. input, err := cmd.StdinPipe()
  83. if err != nil {
  84. log.Error("SSH: StdinPipe: %v", err)
  85. return
  86. }
  87. // FIXME: check timeout
  88. if err = cmd.Start(); err != nil {
  89. log.Error("SSH: Start: %v", err)
  90. return
  91. }
  92. _ = req.Reply(true, nil)
  93. go func() {
  94. _, _ = io.Copy(input, ch)
  95. }()
  96. _, _ = io.Copy(ch, stdout)
  97. _, _ = io.Copy(ch.Stderr(), stderr)
  98. if err = cmd.Wait(); err != nil {
  99. log.Error("SSH: Wait: %v", err)
  100. return
  101. }
  102. _, _ = ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
  103. return
  104. default:
  105. }
  106. }
  107. }(reqs)
  108. }
  109. }
  110. func listen(config *ssh.ServerConfig, host string, port int) {
  111. listener, err := net.Listen("tcp", host+":"+com.ToStr(port))
  112. if err != nil {
  113. log.Fatal("Failed to start SSH server: %v", err)
  114. }
  115. for {
  116. // Once a ServerConfig has been configured, connections can be accepted.
  117. conn, err := listener.Accept()
  118. if err != nil {
  119. log.Error("SSH: Error accepting incoming connection: %v", err)
  120. continue
  121. }
  122. // Before use, a handshake must be performed on the incoming net.Conn.
  123. // It must be handled in a separate goroutine,
  124. // otherwise one user could easily block entire loop.
  125. // For example, user could be asked to trust server key fingerprint and hangs.
  126. go func() {
  127. log.Trace("SSH: Handshaking for %s", conn.RemoteAddr())
  128. sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
  129. if err != nil {
  130. if err == io.EOF {
  131. log.Warn("SSH: Handshaking was terminated: %v", err)
  132. } else {
  133. log.Error("SSH: Error on handshaking: %v", err)
  134. }
  135. return
  136. }
  137. log.Trace("SSH: Connection from %s (%s)", sConn.RemoteAddr(), sConn.ClientVersion())
  138. // The incoming Request channel must be serviced.
  139. go ssh.DiscardRequests(reqs)
  140. go handleServerConn(sConn.Permissions.Extensions["key-id"], chans)
  141. }()
  142. }
  143. }
  144. // Listen starts a SSH server listens on given port.
  145. func Listen(host string, port int, ciphers []string) {
  146. config := &ssh.ServerConfig{
  147. Config: ssh.Config{
  148. Ciphers: ciphers,
  149. },
  150. PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
  151. pkey, err := db.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
  152. if err != nil {
  153. log.Error("SearchPublicKeyByContent: %v", err)
  154. return nil, err
  155. }
  156. return &ssh.Permissions{Extensions: map[string]string{"key-id": com.ToStr(pkey.ID)}}, nil
  157. },
  158. }
  159. keyPath := filepath.Join(conf.Server.AppDataPath, "ssh", "gogs.rsa")
  160. if !com.IsExist(keyPath) {
  161. if err := os.MkdirAll(filepath.Dir(keyPath), os.ModePerm); err != nil {
  162. panic(err)
  163. }
  164. _, stderr, err := com.ExecCmd(conf.SSH.KeygenPath, "-f", keyPath, "-t", "rsa", "-m", "PEM", "-N", "")
  165. if err != nil {
  166. panic(fmt.Sprintf("Failed to generate private key: %v - %s", err, stderr))
  167. }
  168. log.Trace("SSH: New private key is generateed: %s", keyPath)
  169. }
  170. privateBytes, err := ioutil.ReadFile(keyPath)
  171. if err != nil {
  172. panic("SSH: Failed to load private key: " + err.Error())
  173. }
  174. private, err := ssh.ParsePrivateKey(privateBytes)
  175. if err != nil {
  176. panic("SSH: Failed to parse private key: " + err.Error())
  177. }
  178. config.AddHostKey(private)
  179. go listen(config, host, port)
  180. }