ssh.go 5.3 KB

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