ssh.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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. "context"
  7. "fmt"
  8. "io"
  9. "net"
  10. "os"
  11. "os/exec"
  12. "path/filepath"
  13. "strings"
  14. "syscall"
  15. "github.com/pkg/errors"
  16. "github.com/sourcegraph/run"
  17. "github.com/unknwon/com"
  18. "golang.org/x/crypto/ssh"
  19. log "unknwon.dev/clog/v2"
  20. "gogs.io/gogs/internal/conf"
  21. "gogs.io/gogs/internal/db"
  22. "gogs.io/gogs/internal/osutil"
  23. )
  24. func cleanCommand(cmd string) string {
  25. i := strings.Index(cmd, "git")
  26. if i == -1 {
  27. return cmd
  28. }
  29. return cmd[i:]
  30. }
  31. func handleServerConn(keyID string, chans <-chan ssh.NewChannel) {
  32. for newChan := range chans {
  33. if newChan.ChannelType() != "session" {
  34. _ = newChan.Reject(ssh.UnknownChannelType, "unknown channel type")
  35. continue
  36. }
  37. ch, reqs, err := newChan.Accept()
  38. if err != nil {
  39. log.Error("Error accepting channel: %v", err)
  40. continue
  41. }
  42. go func(in <-chan *ssh.Request) {
  43. defer func() {
  44. _ = ch.Close()
  45. }()
  46. for req := range in {
  47. payload := cleanCommand(string(req.Payload))
  48. switch req.Type {
  49. case "env":
  50. var env struct {
  51. Name string
  52. Value string
  53. }
  54. if err := ssh.Unmarshal(req.Payload, &env); err != nil {
  55. log.Warn("SSH: Invalid env payload %q: %v", req.Payload, err)
  56. continue
  57. }
  58. // Sometimes the client could send malformed command (i.e. missing "="),
  59. // see https://discuss.gogs.io/t/ssh/3106.
  60. if env.Name == "" || env.Value == "" {
  61. log.Warn("SSH: Invalid env arguments: %+v", env)
  62. continue
  63. }
  64. _, stderr, err := com.ExecCmd("env", fmt.Sprintf("%s=%s", env.Name, env.Value))
  65. if err != nil {
  66. log.Error("env: %v - %s", err, stderr)
  67. return
  68. }
  69. case "exec":
  70. cmdName := strings.TrimLeft(payload, "'()")
  71. log.Trace("SSH: Payload: %v", cmdName)
  72. args := []string{"serv", "key-" + keyID, "--config=" + conf.CustomConf}
  73. log.Trace("SSH: Arguments: %v", args)
  74. cmd := exec.Command(conf.AppPath(), args...)
  75. cmd.Env = append(os.Environ(), "SSH_ORIGINAL_COMMAND="+cmdName)
  76. stdout, err := cmd.StdoutPipe()
  77. if err != nil {
  78. log.Error("SSH: StdoutPipe: %v", err)
  79. return
  80. }
  81. stderr, err := cmd.StderrPipe()
  82. if err != nil {
  83. log.Error("SSH: StderrPipe: %v", err)
  84. return
  85. }
  86. input, err := cmd.StdinPipe()
  87. if err != nil {
  88. log.Error("SSH: StdinPipe: %v", err)
  89. return
  90. }
  91. // FIXME: check timeout
  92. if err = cmd.Start(); err != nil {
  93. log.Error("SSH: Start: %v", err)
  94. return
  95. }
  96. _ = req.Reply(true, nil)
  97. go func() {
  98. _, _ = io.Copy(input, ch)
  99. }()
  100. _, _ = io.Copy(ch, stdout)
  101. _, _ = io.Copy(ch.Stderr(), stderr)
  102. if err = cmd.Wait(); err != nil {
  103. log.Error("SSH: Wait: %v", err)
  104. return
  105. }
  106. _, _ = ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
  107. return
  108. default:
  109. }
  110. }
  111. }(reqs)
  112. }
  113. }
  114. func listen(config *ssh.ServerConfig, host string, port int) {
  115. listener, err := net.Listen("tcp", host+":"+com.ToStr(port))
  116. if err != nil {
  117. log.Fatal("Failed to start SSH server: %v", err)
  118. }
  119. for {
  120. // Once a ServerConfig has been configured, connections can be accepted.
  121. conn, err := listener.Accept()
  122. if err != nil {
  123. log.Error("SSH: Error accepting incoming connection: %v", err)
  124. continue
  125. }
  126. // Before use, a handshake must be performed on the incoming net.Conn.
  127. // It must be handled in a separate goroutine,
  128. // otherwise one user could easily block entire loop.
  129. // For example, user could be asked to trust server key fingerprint and hangs.
  130. go func() {
  131. log.Trace("SSH: Handshaking for %s", conn.RemoteAddr())
  132. sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
  133. if err != nil {
  134. if err == io.EOF || errors.Is(err, syscall.ECONNRESET) {
  135. log.Trace("SSH: Handshaking was terminated: %v", err)
  136. } else {
  137. log.Error("SSH: Error on handshaking: %v", err)
  138. }
  139. return
  140. }
  141. log.Trace("SSH: Connection from %s (%s)", sConn.RemoteAddr(), sConn.ClientVersion())
  142. // The incoming Request channel must be serviced.
  143. go ssh.DiscardRequests(reqs)
  144. go handleServerConn(sConn.Permissions.Extensions["key-id"], chans)
  145. }()
  146. }
  147. }
  148. // Listen starts a SSH server listens on given port.
  149. func Listen(opts conf.SSHOpts, appDataPath string) {
  150. config := &ssh.ServerConfig{
  151. Config: ssh.Config{
  152. Ciphers: opts.ServerCiphers,
  153. MACs: opts.ServerMACs,
  154. },
  155. PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
  156. pkey, err := db.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
  157. if err != nil {
  158. log.Error("SearchPublicKeyByContent: %v", err)
  159. return nil, err
  160. }
  161. return &ssh.Permissions{Extensions: map[string]string{"key-id": com.ToStr(pkey.ID)}}, nil
  162. },
  163. }
  164. keys, err := setupHostKeys(appDataPath, opts.ServerAlgorithms)
  165. if err != nil {
  166. log.Fatal("SSH: Failed to setup host keys: %v", err)
  167. }
  168. for _, key := range keys {
  169. config.AddHostKey(key)
  170. }
  171. go listen(config, opts.ListenHost, opts.ListenPort)
  172. }
  173. func setupHostKeys(appDataPath string, algorithms []string) ([]ssh.Signer, error) {
  174. dir := filepath.Join(appDataPath, "ssh")
  175. err := os.MkdirAll(dir, os.ModePerm)
  176. if err != nil {
  177. return nil, errors.Wrapf(err, "create host key directory")
  178. }
  179. var hostKeys []ssh.Signer
  180. for _, algo := range algorithms {
  181. keyPath := filepath.Join(dir, "gogs."+algo)
  182. if !osutil.IsExist(keyPath) {
  183. args := []string{
  184. conf.SSH.KeygenPath,
  185. "-t", algo,
  186. "-f", keyPath,
  187. "-m", "PEM",
  188. "-N", run.Arg(""),
  189. }
  190. err = run.Cmd(context.Background(), args...).Run().Wait()
  191. if err != nil {
  192. return nil, errors.Wrapf(err, "generate host key with args %v", args)
  193. }
  194. log.Trace("SSH: New private key is generated: %s", keyPath)
  195. }
  196. keyData, err := os.ReadFile(keyPath)
  197. if err != nil {
  198. return nil, errors.Wrapf(err, "read host key %q", keyPath)
  199. }
  200. signer, err := ssh.ParsePrivateKey(keyData)
  201. if err != nil {
  202. return nil, errors.Wrapf(err, "parse host key %q", keyPath)
  203. }
  204. hostKeys = append(hostKeys, signer)
  205. }
  206. return hostKeys, nil
  207. }