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

ssh.go 5.2 kB

10 years ago
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. "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. "code.gitea.io/gitea/models"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/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(
  62. os.Environ(),
  63. "SSH_ORIGINAL_COMMAND="+cmdName,
  64. "SKIP_MINWINSVC=1",
  65. )
  66. stdout, err := cmd.StdoutPipe()
  67. if err != nil {
  68. log.Error(3, "SSH: StdoutPipe: %v", err)
  69. return
  70. }
  71. stderr, err := cmd.StderrPipe()
  72. if err != nil {
  73. log.Error(3, "SSH: StderrPipe: %v", err)
  74. return
  75. }
  76. input, err := cmd.StdinPipe()
  77. if err != nil {
  78. log.Error(3, "SSH: StdinPipe: %v", err)
  79. return
  80. }
  81. // FIXME: check timeout
  82. if err = cmd.Start(); err != nil {
  83. log.Error(3, "SSH: Start: %v", err)
  84. return
  85. }
  86. req.Reply(true, nil)
  87. go io.Copy(input, ch)
  88. io.Copy(ch, stdout)
  89. io.Copy(ch.Stderr(), stderr)
  90. if err = cmd.Wait(); err != nil {
  91. log.Error(3, "SSH: Wait: %v", err)
  92. return
  93. }
  94. ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
  95. return
  96. default:
  97. }
  98. }
  99. }(reqs)
  100. }
  101. }
  102. func listen(config *ssh.ServerConfig, host string, port int) {
  103. listener, err := net.Listen("tcp", host+":"+com.ToStr(port))
  104. if err != nil {
  105. log.Fatal(4, "Fail to start SSH server: %v", err)
  106. }
  107. for {
  108. // Once a ServerConfig has been configured, connections can be accepted.
  109. conn, err := listener.Accept()
  110. if err != nil {
  111. log.Error(3, "SSH: Error accepting incoming connection: %v", err)
  112. continue
  113. }
  114. // Before use, a handshake must be performed on the incoming net.Conn.
  115. // It must be handled in a separate goroutine,
  116. // otherwise one user could easily block entire loop.
  117. // For example, user could be asked to trust server key fingerprint and hangs.
  118. go func() {
  119. log.Trace("SSH: Handshaking for %s", conn.RemoteAddr())
  120. sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
  121. if err != nil {
  122. if err == io.EOF {
  123. log.Warn("SSH: Handshaking was terminated: %v", err)
  124. } else {
  125. log.Error(3, "SSH: Error on handshaking: %v", err)
  126. }
  127. return
  128. }
  129. log.Trace("SSH: Connection from %s (%s)", sConn.RemoteAddr(), sConn.ClientVersion())
  130. // The incoming Request channel must be serviced.
  131. go ssh.DiscardRequests(reqs)
  132. go handleServerConn(sConn.Permissions.Extensions["key-id"], chans)
  133. }()
  134. }
  135. }
  136. // Listen starts a SSH server listens on given port.
  137. func Listen(host string, port int) {
  138. config := &ssh.ServerConfig{
  139. PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
  140. pkey, err := models.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
  141. if err != nil {
  142. log.Error(3, "SearchPublicKeyByContent: %v", err)
  143. return nil, err
  144. }
  145. return &ssh.Permissions{Extensions: map[string]string{"key-id": com.ToStr(pkey.ID)}}, nil
  146. },
  147. }
  148. keyPath := filepath.Join(setting.AppDataPath, "ssh/gogs.rsa")
  149. if !com.IsExist(keyPath) {
  150. filePath := filepath.Dir(keyPath)
  151. if err := os.MkdirAll(filePath, os.ModePerm); err != nil {
  152. log.Error(4, "Fail to create dir %s: %v", filePath, err)
  153. }
  154. _, stderr, err := com.ExecCmd("ssh-keygen", "-f", keyPath, "-t", "rsa", "-N", "")
  155. if err != nil {
  156. panic(fmt.Sprintf("Fail to generate private key: %v - %s", err, stderr))
  157. }
  158. log.Trace("SSH: New private key is generateed: %s", keyPath)
  159. }
  160. privateBytes, err := ioutil.ReadFile(keyPath)
  161. if err != nil {
  162. panic("SSH: Fail to load private key")
  163. }
  164. private, err := ssh.ParsePrivateKey(privateBytes)
  165. if err != nil {
  166. panic("SSH: Fail to parse private key")
  167. }
  168. config.AddHostKey(private)
  169. go listen(config, host, port)
  170. }