You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ssh.go 6.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea 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. "crypto/rand"
  8. "crypto/rsa"
  9. "crypto/x509"
  10. "encoding/pem"
  11. "io"
  12. "io/ioutil"
  13. "net"
  14. "os"
  15. "os/exec"
  16. "path/filepath"
  17. "strings"
  18. "github.com/Unknwon/com"
  19. "golang.org/x/crypto/ssh"
  20. "code.gitea.io/gitea/models"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/setting"
  23. )
  24. func cleanCommand(cmd string) string {
  25. i := strings.Index(cmd, "git")
  26. if i == -1 {
  27. return cmd
  28. }
  29. return cmd[i:]
  30. }
  31. func handleServerConn(keyID string, chans <-chan ssh.NewChannel) {
  32. for newChan := range chans {
  33. if newChan.ChannelType() != "session" {
  34. newChan.Reject(ssh.UnknownChannelType, "unknown channel type")
  35. continue
  36. }
  37. ch, reqs, err := newChan.Accept()
  38. if 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. log.Error(3, "env: %v", err)
  57. return
  58. }
  59. case "exec":
  60. cmdName := strings.TrimLeft(payload, "'()")
  61. log.Trace("SSH: Payload: %v", cmdName)
  62. args := []string{"serv", "key-" + keyID, "--config=" + setting.CustomConf}
  63. log.Trace("SSH: Arguments: %v", args)
  64. cmd := exec.Command(setting.AppPath, args...)
  65. cmd.Env = append(
  66. os.Environ(),
  67. "SSH_ORIGINAL_COMMAND="+cmdName,
  68. "SKIP_MINWINSVC=1",
  69. )
  70. stdout, err := cmd.StdoutPipe()
  71. if err != nil {
  72. log.Error(3, "SSH: StdoutPipe: %v", err)
  73. return
  74. }
  75. stderr, err := cmd.StderrPipe()
  76. if err != nil {
  77. log.Error(3, "SSH: StderrPipe: %v", err)
  78. return
  79. }
  80. input, err := cmd.StdinPipe()
  81. if 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. log.Error(3, "SSH: Start: %v", err)
  88. return
  89. }
  90. req.Reply(true, nil)
  91. go io.Copy(input, ch)
  92. io.Copy(ch, stdout)
  93. io.Copy(ch.Stderr(), stderr)
  94. if err = cmd.Wait(); err != nil {
  95. log.Error(3, "SSH: Wait: %v", err)
  96. return
  97. }
  98. ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
  99. return
  100. default:
  101. }
  102. }
  103. }(reqs)
  104. }
  105. }
  106. func listen(config *ssh.ServerConfig, host string, port int) {
  107. listener, err := net.Listen("tcp", host+":"+com.ToStr(port))
  108. if err != nil {
  109. log.Fatal(4, "Failed to start SSH server: %v", err)
  110. }
  111. for {
  112. // Once a ServerConfig has been configured, connections can be accepted.
  113. conn, err := listener.Accept()
  114. if err != nil {
  115. log.Error(3, "SSH: Error accepting incoming connection: %v", err)
  116. continue
  117. }
  118. // Before use, a handshake must be performed on the incoming net.Conn.
  119. // It must be handled in a separate goroutine,
  120. // otherwise one user could easily block entire loop.
  121. // For example, user could be asked to trust server key fingerprint and hangs.
  122. go func() {
  123. log.Trace("SSH: Handshaking for %s", conn.RemoteAddr())
  124. sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
  125. if err != nil {
  126. if err == io.EOF {
  127. log.Warn("SSH: Handshaking with %s was terminated: %v", conn.RemoteAddr(), err)
  128. } else {
  129. log.Error(3, "SSH: Error on handshaking with %s: %v", conn.RemoteAddr(), 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, keyExchanges []string, macs []string) {
  142. config := &ssh.ServerConfig{
  143. Config: ssh.Config{
  144. Ciphers: ciphers,
  145. KeyExchanges: keyExchanges,
  146. MACs: macs,
  147. },
  148. PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
  149. pkey, err := models.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
  150. if err != nil {
  151. log.Error(3, "SearchPublicKeyByContent: %v", err)
  152. return nil, err
  153. }
  154. return &ssh.Permissions{Extensions: map[string]string{"key-id": com.ToStr(pkey.ID)}}, nil
  155. },
  156. }
  157. keyPath := filepath.Join(setting.AppDataPath, "ssh/gogs.rsa")
  158. if !com.IsExist(keyPath) {
  159. filePath := filepath.Dir(keyPath)
  160. if err := os.MkdirAll(filePath, os.ModePerm); err != nil {
  161. log.Error(4, "Failed to create dir %s: %v", filePath, err)
  162. }
  163. err := GenKeyPair(keyPath)
  164. if err != nil {
  165. log.Fatal(4, "Failed to generate private key: %v", err)
  166. }
  167. log.Trace("SSH: New private key is generateed: %s", keyPath)
  168. }
  169. privateBytes, err := ioutil.ReadFile(keyPath)
  170. if err != nil {
  171. log.Fatal(4, "SSH: Failed to load private key")
  172. }
  173. private, err := ssh.ParsePrivateKey(privateBytes)
  174. if err != nil {
  175. log.Fatal(4, "SSH: Failed to parse private key")
  176. }
  177. config.AddHostKey(private)
  178. go listen(config, host, port)
  179. }
  180. // GenKeyPair make a pair of public and private keys for SSH access.
  181. // Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file.
  182. // Private Key generated is PEM encoded
  183. func GenKeyPair(keyPath string) error {
  184. privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
  185. if err != nil {
  186. return err
  187. }
  188. privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}
  189. f, err := os.OpenFile(keyPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  190. if err != nil {
  191. return err
  192. }
  193. defer f.Close()
  194. if err := pem.Encode(f, privateKeyPEM); err != nil {
  195. return err
  196. }
  197. // generate public key
  198. pub, err := ssh.NewPublicKey(&privateKey.PublicKey)
  199. if err != nil {
  200. return err
  201. }
  202. public := ssh.MarshalAuthorizedKey(pub)
  203. p, err := os.OpenFile(keyPath+".pub", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  204. if err != nil {
  205. return err
  206. }
  207. defer p.Close()
  208. _, err = p.Write(public)
  209. return err
  210. }