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.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. err := newChan.Reject(ssh.UnknownChannelType, "unknown channel type")
  35. if err != nil {
  36. log.Error("Error rejecting channel: %v", err)
  37. }
  38. continue
  39. }
  40. ch, reqs, err := newChan.Accept()
  41. if err != nil {
  42. log.Error("Error accepting channel: %v", err)
  43. continue
  44. }
  45. go func(in <-chan *ssh.Request) {
  46. defer func() {
  47. if err = ch.Close(); err != nil {
  48. log.Error("Close: %v", err)
  49. }
  50. }()
  51. for req := range in {
  52. payload := cleanCommand(string(req.Payload))
  53. switch req.Type {
  54. case "exec":
  55. cmdName := strings.TrimLeft(payload, "'()")
  56. log.Trace("SSH: Payload: %v", cmdName)
  57. args := []string{"serv", "key-" + keyID, "--config=" + setting.CustomConf}
  58. log.Trace("SSH: Arguments: %v", args)
  59. cmd := exec.Command(setting.AppPath, args...)
  60. cmd.Env = append(
  61. os.Environ(),
  62. "SSH_ORIGINAL_COMMAND="+cmdName,
  63. "SKIP_MINWINSVC=1",
  64. )
  65. stdout, err := cmd.StdoutPipe()
  66. if err != nil {
  67. log.Error("SSH: StdoutPipe: %v", err)
  68. return
  69. }
  70. stderr, err := cmd.StderrPipe()
  71. if err != nil {
  72. log.Error("SSH: StderrPipe: %v", err)
  73. return
  74. }
  75. input, err := cmd.StdinPipe()
  76. if err != nil {
  77. log.Error("SSH: StdinPipe: %v", err)
  78. return
  79. }
  80. // FIXME: check timeout
  81. if err = cmd.Start(); err != nil {
  82. log.Error("SSH: Start: %v", err)
  83. return
  84. }
  85. err = req.Reply(true, nil)
  86. if err != nil {
  87. log.Error("SSH: Reply: %v", err)
  88. }
  89. go func() {
  90. _, err = io.Copy(input, ch)
  91. if err != nil {
  92. log.Error("SSH: Copy: %v", err)
  93. }
  94. }()
  95. _, err = io.Copy(ch, stdout)
  96. if err != nil {
  97. log.Error("SSH: Copy: %v", err)
  98. }
  99. _, err = io.Copy(ch.Stderr(), stderr)
  100. if err != nil {
  101. log.Error("SSH: Copy: %v", err)
  102. }
  103. if err = cmd.Wait(); err != nil {
  104. log.Error("SSH: Wait: %v", err)
  105. return
  106. }
  107. _, err = ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
  108. if err != nil {
  109. log.Error("SSH: SendRequest: %v", err)
  110. }
  111. return
  112. default:
  113. }
  114. }
  115. }(reqs)
  116. }
  117. }
  118. func listen(config *ssh.ServerConfig, host string, port int) {
  119. listener, err := net.Listen("tcp", host+":"+com.ToStr(port))
  120. if err != nil {
  121. log.Fatal("Failed to start SSH server: %v", err)
  122. }
  123. for {
  124. // Once a ServerConfig has been configured, connections can be accepted.
  125. conn, err := listener.Accept()
  126. if err != nil {
  127. log.Error("SSH: Error accepting incoming connection: %v", err)
  128. continue
  129. }
  130. // Before use, a handshake must be performed on the incoming net.Conn.
  131. // It must be handled in a separate goroutine,
  132. // otherwise one user could easily block entire loop.
  133. // For example, user could be asked to trust server key fingerprint and hangs.
  134. go func() {
  135. log.Trace("SSH: Handshaking for %s", conn.RemoteAddr())
  136. sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
  137. if err != nil {
  138. if err == io.EOF {
  139. log.Warn("SSH: Handshaking with %s was terminated: %v", conn.RemoteAddr(), err)
  140. } else {
  141. log.Error("SSH: Error on handshaking with %s: %v", conn.RemoteAddr(), err)
  142. }
  143. return
  144. }
  145. log.Trace("SSH: Connection from %s (%s)", sConn.RemoteAddr(), sConn.ClientVersion())
  146. // The incoming Request channel must be serviced.
  147. go ssh.DiscardRequests(reqs)
  148. go handleServerConn(sConn.Permissions.Extensions["key-id"], chans)
  149. }()
  150. }
  151. }
  152. // Listen starts a SSH server listens on given port.
  153. func Listen(host string, port int, ciphers []string, keyExchanges []string, macs []string) {
  154. config := &ssh.ServerConfig{
  155. Config: ssh.Config{
  156. Ciphers: ciphers,
  157. KeyExchanges: keyExchanges,
  158. MACs: macs,
  159. },
  160. PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
  161. pkey, err := models.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
  162. if err != nil {
  163. log.Error("SearchPublicKeyByContent: %v", err)
  164. return nil, err
  165. }
  166. return &ssh.Permissions{Extensions: map[string]string{"key-id": com.ToStr(pkey.ID)}}, nil
  167. },
  168. }
  169. keyPath := filepath.Join(setting.AppDataPath, "ssh/gogs.rsa")
  170. if !com.IsExist(keyPath) {
  171. filePath := filepath.Dir(keyPath)
  172. if err := os.MkdirAll(filePath, os.ModePerm); err != nil {
  173. log.Error("Failed to create dir %s: %v", filePath, err)
  174. }
  175. err := GenKeyPair(keyPath)
  176. if err != nil {
  177. log.Fatal("Failed to generate private key: %v", err)
  178. }
  179. log.Trace("SSH: New private key is generateed: %s", keyPath)
  180. }
  181. privateBytes, err := ioutil.ReadFile(keyPath)
  182. if err != nil {
  183. log.Fatal("SSH: Failed to load private key")
  184. }
  185. private, err := ssh.ParsePrivateKey(privateBytes)
  186. if err != nil {
  187. log.Fatal("SSH: Failed to parse private key")
  188. }
  189. config.AddHostKey(private)
  190. go listen(config, host, port)
  191. }
  192. // GenKeyPair make a pair of public and private keys for SSH access.
  193. // Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file.
  194. // Private Key generated is PEM encoded
  195. func GenKeyPair(keyPath string) error {
  196. privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
  197. if err != nil {
  198. return err
  199. }
  200. privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}
  201. f, err := os.OpenFile(keyPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  202. if err != nil {
  203. return err
  204. }
  205. defer func() {
  206. if err = f.Close(); err != nil {
  207. log.Error("Close: %v", err)
  208. }
  209. }()
  210. if err := pem.Encode(f, privateKeyPEM); err != nil {
  211. return err
  212. }
  213. // generate public key
  214. pub, err := ssh.NewPublicKey(&privateKey.PublicKey)
  215. if err != nil {
  216. return err
  217. }
  218. public := ssh.MarshalAuthorizedKey(pub)
  219. p, err := os.OpenFile(keyPath+".pub", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  220. if err != nil {
  221. return err
  222. }
  223. defer func() {
  224. if err = p.Close(); err != nil {
  225. log.Error("Close: %v", err)
  226. }
  227. }()
  228. _, err = p.Write(public)
  229. return err
  230. }