You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

197 lines
5.3 KiB

9 years ago
  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, ciphers []string, keyExchanges []string, macs []string) {
  137. config := &ssh.ServerConfig{
  138. Config: ssh.Config{
  139. Ciphers: ciphers,
  140. KeyExchanges: keyExchanges,
  141. MACs: macs,
  142. },
  143. PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
  144. pkey, err := models.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
  145. if err != nil {
  146. log.Error(3, "SearchPublicKeyByContent: %v", err)
  147. return nil, err
  148. }
  149. return &ssh.Permissions{Extensions: map[string]string{"key-id": com.ToStr(pkey.ID)}}, nil
  150. },
  151. }
  152. keyPath := filepath.Join(setting.AppDataPath, "ssh/gogs.rsa")
  153. if !com.IsExist(keyPath) {
  154. filePath := filepath.Dir(keyPath)
  155. if err := os.MkdirAll(filePath, os.ModePerm); err != nil {
  156. log.Error(4, "Failed to create dir %s: %v", filePath, err)
  157. }
  158. _, stderr, err := com.ExecCmd("ssh-keygen", "-f", keyPath, "-t", "rsa", "-N", "")
  159. if err != nil {
  160. log.Fatal(4, "Failed to generate private key: %v - %s", err, stderr)
  161. }
  162. log.Trace("SSH: New private key is generateed: %s", keyPath)
  163. }
  164. privateBytes, err := ioutil.ReadFile(keyPath)
  165. if err != nil {
  166. log.Fatal(4, "SSH: Failed to load private key")
  167. }
  168. private, err := ssh.ParsePrivateKey(privateBytes)
  169. if err != nil {
  170. log.Fatal(4, "SSH: Failed to parse private key")
  171. }
  172. config.AddHostKey(private)
  173. go listen(config, host, port)
  174. }