ssh.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. log "gopkg.in/clog.v1"
  17. "github.com/gogs/gogs/models"
  18. "github.com/gogs/gogs/pkg/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, host string, port int) {
  99. listener, err := net.Listen("tcp", host+":"+com.ToStr(port))
  100. if err != nil {
  101. log.Fatal(4, "Fail to start SSH server: %v", 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(host string, port int, ciphers []string) {
  134. config := &ssh.ServerConfig{
  135. Config: ssh.Config{
  136. Ciphers: ciphers,
  137. },
  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. os.MkdirAll(filepath.Dir(keyPath), os.ModePerm)
  150. _, stderr, err := com.ExecCmd(setting.SSH.KeygenPath, "-f", keyPath, "-t", "rsa", "-m", "PEM", "-N", "")
  151. if err != nil {
  152. panic(fmt.Sprintf("Fail to generate private key: %v - %s", err, stderr))
  153. }
  154. log.Trace("SSH: New private key is generateed: %s", keyPath)
  155. }
  156. privateBytes, err := ioutil.ReadFile(keyPath)
  157. if err != nil {
  158. panic("SSH: Fail to load private key: " + err.Error())
  159. }
  160. private, err := ssh.ParsePrivateKey(privateBytes)
  161. if err != nil {
  162. panic("SSH: Fail to parse private key: " + err.Error())
  163. }
  164. config.AddHostKey(private)
  165. go listen(config, host, port)
  166. }