ssh.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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/gogits/gogs/models"
  17. "github.com/gogits/gogs/modules/log"
  18. "github.com/gogits/gogs/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("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. os.Setenv("SSH_ORIGINAL_COMMAND", cmdName)
  58. log.Trace("Payload: %v", cmdName)
  59. args := []string{"serv", "key-" + keyID, "--config=" + setting.CustomConf}
  60. log.Trace("Arguments: %v", args)
  61. cmd := exec.Command(setting.AppPath, args...)
  62. stdout, err := cmd.StdoutPipe()
  63. if err != nil {
  64. log.Error(3, "StdoutPipe: %v", err)
  65. return
  66. }
  67. stderr, err := cmd.StderrPipe()
  68. if err != nil {
  69. log.Error(3, "StderrPipe: %v", err)
  70. return
  71. }
  72. input, err := cmd.StdinPipe()
  73. if err != nil {
  74. log.Error(3, "StdinPipe: %v", err)
  75. return
  76. }
  77. // FIXME: check timeout
  78. if err = cmd.Start(); err != nil {
  79. log.Error(3, "Start: %v", err)
  80. return
  81. }
  82. go io.Copy(input, ch)
  83. io.Copy(ch, stdout)
  84. io.Copy(ch.Stderr(), stderr)
  85. if err = cmd.Wait(); err != nil {
  86. log.Error(3, "Wait: %v", err)
  87. return
  88. }
  89. ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
  90. return
  91. default:
  92. }
  93. }
  94. }(reqs)
  95. }
  96. }
  97. func listen(config *ssh.ServerConfig, port int) {
  98. listener, err := net.Listen("tcp", "0.0.0.0:"+com.ToStr(port))
  99. if err != nil {
  100. panic(err)
  101. }
  102. for {
  103. // Once a ServerConfig has been configured, connections can be accepted.
  104. conn, err := listener.Accept()
  105. if err != nil {
  106. log.Error(3, "Error accepting incoming connection: %v", err)
  107. continue
  108. }
  109. // Before use, a handshake must be performed on the incoming net.Conn.
  110. sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
  111. if err != nil {
  112. log.Error(3, "Error on handshaking: %v", err)
  113. continue
  114. }
  115. log.Trace("Connection from %s (%s)", sConn.RemoteAddr(), sConn.ClientVersion())
  116. // The incoming Request channel must be serviced.
  117. go ssh.DiscardRequests(reqs)
  118. go handleServerConn(sConn.Permissions.Extensions["key-id"], chans)
  119. }
  120. }
  121. // Listen starts a SSH server listens on given port.
  122. func Listen(port int) {
  123. config := &ssh.ServerConfig{
  124. PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
  125. pkey, err := models.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
  126. if err != nil {
  127. log.Error(3, "SearchPublicKeyByContent: %v", err)
  128. return nil, err
  129. }
  130. return &ssh.Permissions{Extensions: map[string]string{"key-id": com.ToStr(pkey.ID)}}, nil
  131. },
  132. }
  133. keyPath := filepath.Join(setting.AppDataPath, "ssh/gogs.rsa")
  134. if !com.IsExist(keyPath) {
  135. os.MkdirAll(filepath.Dir(keyPath), os.ModePerm)
  136. _, stderr, err := com.ExecCmd("ssh-keygen", "-f", keyPath, "-t", "rsa", "-N", "")
  137. if err != nil {
  138. panic(fmt.Sprintf("Fail to generate private key: %v - %s", err, stderr))
  139. }
  140. log.Trace("New private key is generateed: %s", keyPath)
  141. }
  142. privateBytes, err := ioutil.ReadFile(keyPath)
  143. if err != nil {
  144. panic("Fail to load private key")
  145. }
  146. private, err := ssh.ParsePrivateKey(privateBytes)
  147. if err != nil {
  148. panic("Fail to parse private key")
  149. }
  150. config.AddHostKey(private)
  151. go listen(config, port)
  152. }