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. "net"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "strings"
  13. "github.com/unknwon/com"
  14. "golang.org/x/crypto/ssh"
  15. log "unknwon.dev/clog/v2"
  16. "gogs.io/gogs/internal/conf"
  17. "gogs.io/gogs/internal/db"
  18. )
  19. func cleanCommand(cmd string) string {
  20. i := strings.Index(cmd, "git")
  21. if i == -1 {
  22. return cmd
  23. }
  24. return cmd[i:]
  25. }
  26. func handleServerConn(keyID string, chans <-chan ssh.NewChannel) {
  27. for newChan := range chans {
  28. if newChan.ChannelType() != "session" {
  29. _ = newChan.Reject(ssh.UnknownChannelType, "unknown channel type")
  30. continue
  31. }
  32. ch, reqs, err := newChan.Accept()
  33. if err != nil {
  34. log.Error("Error accepting channel: %v", err)
  35. continue
  36. }
  37. go func(in <-chan *ssh.Request) {
  38. defer func() {
  39. _ = ch.Close()
  40. }()
  41. for req := range in {
  42. payload := cleanCommand(string(req.Payload))
  43. switch req.Type {
  44. case "env":
  45. var env struct {
  46. Name string
  47. Value string
  48. }
  49. if err := ssh.Unmarshal(req.Payload, &env); err != nil {
  50. log.Warn("SSH: Invalid env payload %q: %v", req.Payload, err)
  51. continue
  52. }
  53. // Sometimes the client could send malformed command (i.e. missing "="),
  54. // see https://discuss.gogs.io/t/ssh/3106.
  55. if env.Name == "" || env.Value == "" {
  56. log.Warn("SSH: Invalid env arguments: %+v", env)
  57. continue
  58. }
  59. _, stderr, err := com.ExecCmd("env", fmt.Sprintf("%s=%s", env.Name, env.Value))
  60. if err != nil {
  61. log.Error("env: %v - %s", err, stderr)
  62. return
  63. }
  64. case "exec":
  65. cmdName := strings.TrimLeft(payload, "'()")
  66. log.Trace("SSH: Payload: %v", cmdName)
  67. args := []string{"serv", "key-" + keyID, "--config=" + conf.CustomConf}
  68. log.Trace("SSH: Arguments: %v", args)
  69. cmd := exec.Command(conf.AppPath(), args...)
  70. cmd.Env = append(os.Environ(), "SSH_ORIGINAL_COMMAND="+cmdName)
  71. stdout, err := cmd.StdoutPipe()
  72. if err != nil {
  73. log.Error("SSH: StdoutPipe: %v", err)
  74. return
  75. }
  76. stderr, err := cmd.StderrPipe()
  77. if err != nil {
  78. log.Error("SSH: StderrPipe: %v", err)
  79. return
  80. }
  81. input, err := cmd.StdinPipe()
  82. if err != nil {
  83. log.Error("SSH: StdinPipe: %v", err)
  84. return
  85. }
  86. // FIXME: check timeout
  87. if err = cmd.Start(); err != nil {
  88. log.Error("SSH: Start: %v", err)
  89. return
  90. }
  91. _ = req.Reply(true, nil)
  92. go func() {
  93. _, _ = io.Copy(input, ch)
  94. }()
  95. _, _ = io.Copy(ch, stdout)
  96. _, _ = io.Copy(ch.Stderr(), stderr)
  97. if err = cmd.Wait(); err != nil {
  98. log.Error("SSH: Wait: %v", err)
  99. return
  100. }
  101. _, _ = ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
  102. return
  103. default:
  104. }
  105. }
  106. }(reqs)
  107. }
  108. }
  109. func listen(config *ssh.ServerConfig, host string, port int) {
  110. listener, err := net.Listen("tcp", host+":"+com.ToStr(port))
  111. if err != nil {
  112. log.Fatal("Failed to start SSH server: %v", err)
  113. }
  114. for {
  115. // Once a ServerConfig has been configured, connections can be accepted.
  116. conn, err := listener.Accept()
  117. if err != nil {
  118. log.Error("SSH: Error accepting incoming connection: %v", err)
  119. continue
  120. }
  121. // Before use, a handshake must be performed on the incoming net.Conn.
  122. // It must be handled in a separate goroutine,
  123. // otherwise one user could easily block entire loop.
  124. // For example, user could be asked to trust server key fingerprint and hangs.
  125. go func() {
  126. log.Trace("SSH: Handshaking for %s", conn.RemoteAddr())
  127. sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
  128. if err != nil {
  129. if err == io.EOF {
  130. log.Warn("SSH: Handshaking was terminated: %v", err)
  131. } else {
  132. log.Error("SSH: Error on handshaking: %v", err)
  133. }
  134. return
  135. }
  136. log.Trace("SSH: Connection from %s (%s)", sConn.RemoteAddr(), sConn.ClientVersion())
  137. // The incoming Request channel must be serviced.
  138. go ssh.DiscardRequests(reqs)
  139. go handleServerConn(sConn.Permissions.Extensions["key-id"], chans)
  140. }()
  141. }
  142. }
  143. // Listen starts a SSH server listens on given port.
  144. func Listen(host string, port int, ciphers, macs []string) {
  145. config := &ssh.ServerConfig{
  146. Config: ssh.Config{
  147. Ciphers: ciphers,
  148. MACs: macs,
  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 := os.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. }