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.

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