ssh.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. // +build go1.4
  2. // Copyright 2014 The Gogs Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package ssh
  6. import (
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net"
  11. "os"
  12. "os/exec"
  13. "path/filepath"
  14. "strings"
  15. "github.com/Unknwon/com"
  16. "golang.org/x/crypto/ssh"
  17. "github.com/gogits/gogs/models"
  18. "github.com/gogits/gogs/modules/log"
  19. "github.com/gogits/gogs/modules/setting"
  20. )
  21. func cleanCommand(cmd string) string {
  22. i := strings.Index(cmd, "git")
  23. if i == -1 {
  24. return cmd
  25. }
  26. return cmd[i:]
  27. }
  28. func handleServerConn(keyID string, chans <-chan ssh.NewChannel) {
  29. for newChan := range chans {
  30. if newChan.ChannelType() != "session" {
  31. newChan.Reject(ssh.UnknownChannelType, "unknown channel type")
  32. continue
  33. }
  34. ch, reqs, err := newChan.Accept()
  35. if err != nil {
  36. log.Error(3, "Error accepting channel: %v", err)
  37. continue
  38. }
  39. go func(in <-chan *ssh.Request) {
  40. defer ch.Close()
  41. for req := range in {
  42. payload := cleanCommand(string(req.Payload))
  43. switch req.Type {
  44. case "env":
  45. args := strings.Split(strings.Replace(payload, "\x00", "", -1), "\v")
  46. if len(args) != 2 {
  47. return
  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. }