ssh.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. args := strings.Split(strings.Replace(payload, "\x00", "", -1), "\v")
  47. if len(args) != 2 {
  48. log.Warn("SSH: Invalid env arguments: '%#v'", args)
  49. continue
  50. }
  51. args[0] = strings.TrimLeft(args[0], "\x04")
  52. // Sometimes the client could send malformed command (i.e. missing "="),
  53. // see https://discuss.gogs.io/t/ssh/3106.
  54. if args[0] == "" {
  55. continue
  56. }
  57. _, stderr, err := com.ExecCmd("env", args[0]+"="+args[1])
  58. if err != nil {
  59. log.Error("env: %v - %s", err, stderr)
  60. return
  61. }
  62. case "exec":
  63. cmdName := strings.TrimLeft(payload, "'()")
  64. log.Trace("SSH: Payload: %v", cmdName)
  65. args := []string{"serv", "key-" + keyID, "--config=" + conf.CustomConf}
  66. log.Trace("SSH: Arguments: %v", args)
  67. cmd := exec.Command(conf.AppPath(), args...)
  68. cmd.Env = append(os.Environ(), "SSH_ORIGINAL_COMMAND="+cmdName)
  69. stdout, err := cmd.StdoutPipe()
  70. if err != nil {
  71. log.Error("SSH: StdoutPipe: %v", err)
  72. return
  73. }
  74. stderr, err := cmd.StderrPipe()
  75. if err != nil {
  76. log.Error("SSH: StderrPipe: %v", err)
  77. return
  78. }
  79. input, err := cmd.StdinPipe()
  80. if err != nil {
  81. log.Error("SSH: StdinPipe: %v", err)
  82. return
  83. }
  84. // FIXME: check timeout
  85. if err = cmd.Start(); err != nil {
  86. log.Error("SSH: Start: %v", err)
  87. return
  88. }
  89. _ = req.Reply(true, nil)
  90. go func() {
  91. _, _ = io.Copy(input, ch)
  92. }()
  93. _, _ = io.Copy(ch, stdout)
  94. _, _ = io.Copy(ch.Stderr(), stderr)
  95. if err = cmd.Wait(); err != nil {
  96. log.Error("SSH: Wait: %v", err)
  97. return
  98. }
  99. _, _ = ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
  100. return
  101. default:
  102. }
  103. }
  104. }(reqs)
  105. }
  106. }
  107. func listen(config *ssh.ServerConfig, host string, port int) {
  108. listener, err := net.Listen("tcp", host+":"+com.ToStr(port))
  109. if err != nil {
  110. log.Fatal("Failed to start SSH server: %v", err)
  111. }
  112. for {
  113. // Once a ServerConfig has been configured, connections can be accepted.
  114. conn, err := listener.Accept()
  115. if err != nil {
  116. log.Error("SSH: Error accepting incoming connection: %v", err)
  117. continue
  118. }
  119. // Before use, a handshake must be performed on the incoming net.Conn.
  120. // It must be handled in a separate goroutine,
  121. // otherwise one user could easily block entire loop.
  122. // For example, user could be asked to trust server key fingerprint and hangs.
  123. go func() {
  124. log.Trace("SSH: Handshaking for %s", conn.RemoteAddr())
  125. sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
  126. if err != nil {
  127. if err == io.EOF {
  128. log.Warn("SSH: Handshaking was terminated: %v", err)
  129. } else {
  130. log.Error("SSH: Error on handshaking: %v", err)
  131. }
  132. return
  133. }
  134. log.Trace("SSH: Connection from %s (%s)", sConn.RemoteAddr(), sConn.ClientVersion())
  135. // The incoming Request channel must be serviced.
  136. go ssh.DiscardRequests(reqs)
  137. go handleServerConn(sConn.Permissions.Extensions["key-id"], chans)
  138. }()
  139. }
  140. }
  141. // Listen starts a SSH server listens on given port.
  142. func Listen(host string, port int, ciphers []string) {
  143. config := &ssh.ServerConfig{
  144. Config: ssh.Config{
  145. Ciphers: ciphers,
  146. },
  147. PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
  148. pkey, err := db.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
  149. if err != nil {
  150. log.Error("SearchPublicKeyByContent: %v", err)
  151. return nil, err
  152. }
  153. return &ssh.Permissions{Extensions: map[string]string{"key-id": com.ToStr(pkey.ID)}}, nil
  154. },
  155. }
  156. keyPath := filepath.Join(conf.Server.AppDataPath, "ssh", "gogs.rsa")
  157. if !com.IsExist(keyPath) {
  158. if err := os.MkdirAll(filepath.Dir(keyPath), os.ModePerm); err != nil {
  159. panic(err)
  160. }
  161. _, stderr, err := com.ExecCmd(conf.SSH.KeygenPath, "-f", keyPath, "-t", "rsa", "-m", "PEM", "-N", "")
  162. if err != nil {
  163. panic(fmt.Sprintf("Failed to generate private key: %v - %s", err, stderr))
  164. }
  165. log.Trace("SSH: New private key is generateed: %s", keyPath)
  166. }
  167. privateBytes, err := ioutil.ReadFile(keyPath)
  168. if err != nil {
  169. panic("SSH: Failed to load private key: " + err.Error())
  170. }
  171. private, err := ssh.ParsePrivateKey(privateBytes)
  172. if err != nil {
  173. panic("SSH: Failed to parse private key: " + err.Error())
  174. }
  175. config.AddHostKey(private)
  176. go listen(config, host, port)
  177. }