ssh.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. // Copyright 2015 - Present, The Gogs Authors. All rights reserved.
  2. // Copyright 2018 - Present, Gitote. All rights reserved.
  3. //
  4. // This source code is licensed under the MIT license found in the
  5. // LICENSE file in the root directory of this source tree.
  6. package ssh
  7. import (
  8. "fmt"
  9. "gitote/gitote/models"
  10. "gitote/gitote/pkg/setting"
  11. "io"
  12. "io/ioutil"
  13. "net"
  14. "os"
  15. "os/exec"
  16. "path/filepath"
  17. "strings"
  18. raven "github.com/getsentry/raven-go"
  19. "gitlab.com/gitote/com"
  20. "golang.org/x/crypto/ssh"
  21. log "gopkg.in/clog.v1"
  22. )
  23. func cleanCommand(cmd string) string {
  24. i := strings.Index(cmd, "git")
  25. if i == -1 {
  26. return cmd
  27. }
  28. return cmd[i:]
  29. }
  30. func handleServerConn(keyID string, chans <-chan ssh.NewChannel) {
  31. for newChan := range chans {
  32. if newChan.ChannelType() != "session" {
  33. newChan.Reject(ssh.UnknownChannelType, "unknown channel type")
  34. continue
  35. }
  36. ch, reqs, err := newChan.Accept()
  37. if err != nil {
  38. raven.CaptureErrorAndWait(err, nil)
  39. log.Error(3, "Error accepting channel: %v", err)
  40. continue
  41. }
  42. go func(in <-chan *ssh.Request) {
  43. defer ch.Close()
  44. for req := range in {
  45. payload := cleanCommand(string(req.Payload))
  46. switch req.Type {
  47. case "env":
  48. args := strings.Split(strings.Replace(payload, "\x00", "", -1), "\v")
  49. if len(args) != 2 {
  50. log.Warn("SSH: Invalid env arguments: '%#v'", args)
  51. continue
  52. }
  53. args[0] = strings.TrimLeft(args[0], "\x04")
  54. _, _, err := com.ExecCmdBytes("env", args[0]+"="+args[1])
  55. if err != nil {
  56. raven.CaptureErrorAndWait(err, nil)
  57. log.Error(3, "env: %v", err)
  58. return
  59. }
  60. case "exec":
  61. cmdName := strings.TrimLeft(payload, "'()")
  62. log.Trace("SSH: Payload: %v", cmdName)
  63. args := []string{"serv", "key-" + keyID, "--config=" + setting.CustomConf}
  64. log.Trace("SSH: Arguments: %v", args)
  65. cmd := exec.Command(setting.AppPath, args...)
  66. cmd.Env = append(os.Environ(), "SSH_ORIGINAL_COMMAND="+cmdName)
  67. stdout, err := cmd.StdoutPipe()
  68. if err != nil {
  69. raven.CaptureErrorAndWait(err, nil)
  70. log.Error(3, "SSH: StdoutPipe: %v", err)
  71. return
  72. }
  73. stderr, err := cmd.StderrPipe()
  74. if err != nil {
  75. raven.CaptureErrorAndWait(err, nil)
  76. log.Error(3, "SSH: StderrPipe: %v", err)
  77. return
  78. }
  79. input, err := cmd.StdinPipe()
  80. if err != nil {
  81. raven.CaptureErrorAndWait(err, nil)
  82. log.Error(3, "SSH: StdinPipe: %v", err)
  83. return
  84. }
  85. // FIXME: check timeout
  86. if err = cmd.Start(); err != nil {
  87. raven.CaptureErrorAndWait(err, nil)
  88. log.Error(3, "SSH: Start: %v", err)
  89. return
  90. }
  91. req.Reply(true, nil)
  92. go io.Copy(input, ch)
  93. io.Copy(ch, stdout)
  94. io.Copy(ch.Stderr(), stderr)
  95. if err = cmd.Wait(); err != nil {
  96. raven.CaptureErrorAndWait(err, nil)
  97. log.Error(3, "SSH: Wait: %v", err)
  98. return
  99. }
  100. ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
  101. return
  102. default:
  103. }
  104. }
  105. }(reqs)
  106. }
  107. }
  108. func listen(config *ssh.ServerConfig, host string, port int) {
  109. listener, err := net.Listen("tcp", host+":"+com.ToStr(port))
  110. if err != nil {
  111. raven.CaptureErrorAndWait(err, nil)
  112. log.Fatal(4, "Fail to start SSH server: %v", err)
  113. }
  114. for {
  115. // Once a ServerConfig has been configured, connections can be accepted.
  116. conn, err := listener.Accept()
  117. if err != nil {
  118. raven.CaptureErrorAndWait(err, nil)
  119. log.Error(3, "SSH: Error accepting incoming connection: %v", err)
  120. continue
  121. }
  122. // Before use, a handshake must be performed on the incoming net.Conn.
  123. // It must be handled in a separate goroutine,
  124. // otherwise one user could easily block entire loop.
  125. // For example, user could be asked to trust server key fingerprint and hangs.
  126. go func() {
  127. log.Trace("SSH: Handshaking for %s", conn.RemoteAddr())
  128. sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
  129. if err != nil {
  130. if err == io.EOF {
  131. log.Warn("SSH: Handshaking was terminated: %v", err)
  132. } else {
  133. raven.CaptureErrorAndWait(err, nil)
  134. log.Error(3, "SSH: Error on handshaking: %v", err)
  135. }
  136. return
  137. }
  138. log.Trace("SSH: Connection from %s (%s)", sConn.RemoteAddr(), sConn.ClientVersion())
  139. // The incoming Request channel must be serviced.
  140. go ssh.DiscardRequests(reqs)
  141. go handleServerConn(sConn.Permissions.Extensions["key-id"], chans)
  142. }()
  143. }
  144. }
  145. // Listen starts a SSH server listens on given port.
  146. func Listen(host string, port int, ciphers []string) {
  147. config := &ssh.ServerConfig{
  148. Config: ssh.Config{
  149. Ciphers: ciphers,
  150. },
  151. PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
  152. pkey, err := models.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
  153. if err != nil {
  154. raven.CaptureErrorAndWait(err, nil)
  155. log.Error(3, "SearchPublicKeyByContent: %v", err)
  156. return nil, err
  157. }
  158. return &ssh.Permissions{Extensions: map[string]string{"key-id": com.ToStr(pkey.ID)}}, nil
  159. },
  160. }
  161. keyPath := filepath.Join(setting.AppDataPath, "ssh/gitote.rsa")
  162. if !com.IsExist(keyPath) {
  163. os.MkdirAll(filepath.Dir(keyPath), os.ModePerm)
  164. _, stderr, err := com.ExecCmd(setting.SSH.KeygenPath, "-f", keyPath, "-t", "rsa", "-m", "PEM", "-N", "")
  165. if err != nil {
  166. panic(fmt.Sprintf("Fail to generate private key: %v - %s", err, stderr))
  167. }
  168. log.Trace("SSH: New private key is generateed: %s", keyPath)
  169. }
  170. privateBytes, err := ioutil.ReadFile(keyPath)
  171. if err != nil {
  172. panic("SSH: Fail to load private key: " + err.Error())
  173. }
  174. private, err := ssh.ParsePrivateKey(privateBytes)
  175. if err != nil {
  176. panic("SSH: Fail to parse private key: " + err.Error())
  177. }
  178. config.AddHostKey(private)
  179. go listen(config, host, port)
  180. }