ssh.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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. log.Error(3, "Error accepting channel: %v", err)
  34. continue
  35. }
  36. go func(in <-chan *ssh.Request) {
  37. defer ch.Close()
  38. for req := range in {
  39. payload := cleanCommand(string(req.Payload))
  40. switch req.Type {
  41. case "env":
  42. args := strings.Split(strings.Replace(payload, "\x00", "", -1), "\v")
  43. if len(args) != 2 {
  44. log.Warn("SSH: Invalid env arguments: '%#v'", args)
  45. continue
  46. }
  47. args[0] = strings.TrimLeft(args[0], "\x04")
  48. _, _, err := com.ExecCmdBytes("env", args[0]+"="+args[1])
  49. if err != nil {
  50. log.Error(3, "env: %v", err)
  51. return
  52. }
  53. case "exec":
  54. cmdName := strings.TrimLeft(payload, "'()")
  55. log.Trace("SSH: Payload: %v", cmdName)
  56. args := []string{"serv", "key-" + keyID, "--config=" + setting.CustomConf}
  57. log.Trace("SSH: Arguments: %v", args)
  58. cmd := exec.Command(setting.AppPath, args...)
  59. cmd.Env = append(os.Environ(), "SSH_ORIGINAL_COMMAND="+cmdName)
  60. stdout, err := cmd.StdoutPipe()
  61. if err != nil {
  62. log.Error(3, "SSH: StdoutPipe: %v", err)
  63. return
  64. }
  65. stderr, err := cmd.StderrPipe()
  66. if err != nil {
  67. log.Error(3, "SSH: StderrPipe: %v", err)
  68. return
  69. }
  70. input, err := cmd.StdinPipe()
  71. if err != nil {
  72. log.Error(3, "SSH: StdinPipe: %v", err)
  73. return
  74. }
  75. // FIXME: check timeout
  76. if err = cmd.Start(); err != nil {
  77. log.Error(3, "SSH: Start: %v", err)
  78. return
  79. }
  80. req.Reply(true, nil)
  81. go io.Copy(input, ch)
  82. io.Copy(ch, stdout)
  83. io.Copy(ch.Stderr(), stderr)
  84. if err = cmd.Wait(); err != nil {
  85. log.Error(3, "SSH: Wait: %v", err)
  86. return
  87. }
  88. ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
  89. return
  90. default:
  91. }
  92. }
  93. }(reqs)
  94. }
  95. }
  96. func listen(config *ssh.ServerConfig, host string, port int) {
  97. listener, err := net.Listen("tcp", host+":"+com.ToStr(port))
  98. if err != nil {
  99. raven.CaptureErrorAndWait(err, nil)
  100. log.Fatal(4, "Fail to start SSH server: %v", 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, "SSH: Error accepting incoming connection: %v", err)
  107. continue
  108. }
  109. // Before use, a handshake must be performed on the incoming net.Conn.
  110. // It must be handled in a separate goroutine,
  111. // otherwise one user could easily block entire loop.
  112. // For example, user could be asked to trust server key fingerprint and hangs.
  113. go func() {
  114. log.Trace("SSH: Handshaking for %s", conn.RemoteAddr())
  115. sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
  116. if err != nil {
  117. if err == io.EOF {
  118. log.Warn("SSH: Handshaking was terminated: %v", err)
  119. } else {
  120. log.Error(3, "SSH: Error on handshaking: %v", err)
  121. }
  122. return
  123. }
  124. log.Trace("SSH: Connection from %s (%s)", sConn.RemoteAddr(), sConn.ClientVersion())
  125. // The incoming Request channel must be serviced.
  126. go ssh.DiscardRequests(reqs)
  127. go handleServerConn(sConn.Permissions.Extensions["key-id"], chans)
  128. }()
  129. }
  130. }
  131. // Listen starts a SSH server listens on given port.
  132. func Listen(host string, port int, ciphers []string) {
  133. config := &ssh.ServerConfig{
  134. Config: ssh.Config{
  135. Ciphers: ciphers,
  136. },
  137. PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
  138. pkey, err := models.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
  139. if err != nil {
  140. log.Error(3, "SearchPublicKeyByContent: %v", err)
  141. return nil, err
  142. }
  143. return &ssh.Permissions{Extensions: map[string]string{"key-id": com.ToStr(pkey.ID)}}, nil
  144. },
  145. }
  146. keyPath := filepath.Join(setting.AppDataPath, "ssh/gitote.rsa")
  147. if !com.IsExist(keyPath) {
  148. os.MkdirAll(filepath.Dir(keyPath), os.ModePerm)
  149. _, stderr, err := com.ExecCmd(setting.SSH.KeygenPath, "-f", keyPath, "-t", "rsa", "-N", "")
  150. if err != nil {
  151. panic(fmt.Sprintf("Fail to generate private key: %v - %s", err, stderr))
  152. }
  153. log.Trace("SSH: New private key is generateed: %s", keyPath)
  154. }
  155. privateBytes, err := ioutil.ReadFile(keyPath)
  156. if err != nil {
  157. panic("SSH: Fail to load private key: " + err.Error())
  158. }
  159. private, err := ssh.ParsePrivateKey(privateBytes)
  160. if err != nil {
  161. panic("SSH: Fail to parse private key: " + err.Error())
  162. }
  163. config.AddHostKey(private)
  164. go listen(config, host, port)
  165. }