ssh.go 5.1 KB

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