Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

ssh.go 5.1KB

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