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

ssh.go 6.2 kB

3 years ago
3 years ago
3 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package ssh
  5. import (
  6. "crypto/rand"
  7. "crypto/rsa"
  8. "crypto/x509"
  9. "encoding/pem"
  10. "fmt"
  11. "io"
  12. "os"
  13. "os/exec"
  14. "path/filepath"
  15. "strings"
  16. "sync"
  17. "syscall"
  18. "code.gitea.io/gitea/models"
  19. "code.gitea.io/gitea/modules/log"
  20. "code.gitea.io/gitea/modules/setting"
  21. "github.com/gliderlabs/ssh"
  22. "github.com/unknwon/com"
  23. gossh "golang.org/x/crypto/ssh"
  24. )
  25. type contextKey string
  26. const giteaKeyID = contextKey("gitea-key-id")
  27. func getExitStatusFromError(err error) int {
  28. if err == nil {
  29. return 0
  30. }
  31. exitErr, ok := err.(*exec.ExitError)
  32. if !ok {
  33. return 1
  34. }
  35. waitStatus, ok := exitErr.Sys().(syscall.WaitStatus)
  36. if !ok {
  37. // This is a fallback and should at least let us return something useful
  38. // when running on Windows, even if it isn't completely accurate.
  39. if exitErr.Success() {
  40. return 0
  41. }
  42. return 1
  43. }
  44. return waitStatus.ExitStatus()
  45. }
  46. func sessionHandler(session ssh.Session) {
  47. keyID := session.Context().Value(giteaKeyID).(int64)
  48. command := session.RawCommand()
  49. log.Trace("SSH: Payload: %v", command)
  50. args := []string{"serv", "key-" + com.ToStr(keyID), "--config=" + setting.CustomConf}
  51. log.Trace("SSH: Arguments: %v", args)
  52. cmd := exec.Command(setting.AppPath, args...)
  53. cmd.Env = append(
  54. os.Environ(),
  55. "SSH_ORIGINAL_COMMAND="+command,
  56. "SKIP_MINWINSVC=1",
  57. models.EnvRepoMaxFileSize+"="+fmt.Sprint(setting.Repository.Upload.FileMaxSize),
  58. models.EnvRepoMaxSize+"="+fmt.Sprint(setting.Repository.RepoMaxSize),
  59. models.EnvPushSizeCheckFlag+"="+fmt.Sprint(setting.Repository.Upload.ShellFlag),
  60. )
  61. if strings.HasPrefix(command, "git-receive-pack") {
  62. repo := getRepoFromCommandStr(command)
  63. if repo != nil {
  64. cmd.Env = append(cmd.Env, models.EnvRepoSize+"="+fmt.Sprint(repo.Size))
  65. }
  66. }
  67. stdout, err := cmd.StdoutPipe()
  68. if err != nil {
  69. log.Error("SSH: StdoutPipe: %v", err)
  70. return
  71. }
  72. stderr, err := cmd.StderrPipe()
  73. if err != nil {
  74. log.Error("SSH: StderrPipe: %v", err)
  75. return
  76. }
  77. stdin, err := cmd.StdinPipe()
  78. if err != nil {
  79. log.Error("SSH: StdinPipe: %v", err)
  80. return
  81. }
  82. wg := &sync.WaitGroup{}
  83. wg.Add(2)
  84. if err = cmd.Start(); err != nil {
  85. log.Error("SSH: Start: %v", err)
  86. return
  87. }
  88. go func() {
  89. defer stdin.Close()
  90. if _, err := io.Copy(stdin, session); err != nil {
  91. log.Error("Failed to write session to stdin. %s", err)
  92. }
  93. }()
  94. go func() {
  95. defer wg.Done()
  96. if _, err := io.Copy(session, stdout); err != nil {
  97. log.Error("Failed to write stdout to session. %s", err)
  98. }
  99. }()
  100. go func() {
  101. defer wg.Done()
  102. if _, err := io.Copy(session.Stderr(), stderr); err != nil {
  103. log.Error("Failed to write stderr to session. %s", err)
  104. }
  105. }()
  106. // Ensure all the output has been written before we wait on the command
  107. // to exit.
  108. wg.Wait()
  109. // Wait for the command to exit and log any errors we get
  110. err = cmd.Wait()
  111. if err != nil {
  112. log.Error("SSH: Wait: %v", err)
  113. }
  114. if err := session.Exit(getExitStatusFromError(err)); err != nil {
  115. log.Error("Session failed to exit. %s", err)
  116. }
  117. }
  118. func getRepoFromCommandStr(command string) *models.Repository {
  119. repoPath := strings.TrimPrefix(command, "git-receive-pack '")
  120. repoPath = strings.TrimSuffix(repoPath, ".git'")
  121. if repoPath != "" {
  122. nameArray := strings.Split(repoPath, "/")
  123. if len(nameArray) >= 2 {
  124. ownerName := nameArray[0]
  125. repoName := nameArray[1]
  126. if repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName); err == nil {
  127. return repo
  128. }
  129. }
  130. }
  131. return nil
  132. }
  133. func publicKeyHandler(ctx ssh.Context, key ssh.PublicKey) bool {
  134. if ctx.User() != setting.SSH.BuiltinServerUser {
  135. return false
  136. }
  137. pkey, err := models.SearchPublicKeyByContent(strings.TrimSpace(string(gossh.MarshalAuthorizedKey(key))))
  138. if err != nil {
  139. log.Error("SearchPublicKeyByContent: %v", err)
  140. return false
  141. }
  142. ctx.SetValue(giteaKeyID, pkey.ID)
  143. return true
  144. }
  145. // Listen starts a SSH server listens on given port.
  146. func Listen(host string, port int, ciphers []string, keyExchanges []string, macs []string) {
  147. // TODO: Handle ciphers, keyExchanges, and macs
  148. srv := ssh.Server{
  149. Addr: fmt.Sprintf("%s:%d", host, port),
  150. PublicKeyHandler: publicKeyHandler,
  151. Handler: sessionHandler,
  152. // We need to explicitly disable the PtyCallback so text displays
  153. // properly.
  154. PtyCallback: func(ctx ssh.Context, pty ssh.Pty) bool {
  155. return false
  156. },
  157. }
  158. keyPath := filepath.Join(setting.AppDataPath, "ssh/gogs.rsa")
  159. if !com.IsExist(keyPath) {
  160. filePath := filepath.Dir(keyPath)
  161. if err := os.MkdirAll(filePath, os.ModePerm); err != nil {
  162. log.Error("Failed to create dir %s: %v", filePath, err)
  163. }
  164. err := GenKeyPair(keyPath)
  165. if err != nil {
  166. log.Fatal("Failed to generate private key: %v", err)
  167. }
  168. log.Trace("New private key is generated: %s", keyPath)
  169. }
  170. err := srv.SetOption(ssh.HostKeyFile(keyPath))
  171. if err != nil {
  172. log.Error("Failed to set Host Key. %s", err)
  173. }
  174. go listen(&srv)
  175. }
  176. // GenKeyPair make a pair of public and private keys for SSH access.
  177. // Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file.
  178. // Private Key generated is PEM encoded
  179. func GenKeyPair(keyPath string) error {
  180. privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
  181. if err != nil {
  182. return err
  183. }
  184. privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}
  185. f, err := os.OpenFile(keyPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  186. if err != nil {
  187. return err
  188. }
  189. defer func() {
  190. if err = f.Close(); err != nil {
  191. log.Error("Close: %v", err)
  192. }
  193. }()
  194. if err := pem.Encode(f, privateKeyPEM); err != nil {
  195. return err
  196. }
  197. // generate public key
  198. pub, err := gossh.NewPublicKey(&privateKey.PublicKey)
  199. if err != nil {
  200. return err
  201. }
  202. public := gossh.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 func() {
  208. if err = p.Close(); err != nil {
  209. log.Error("Close: %v", err)
  210. }
  211. }()
  212. _, err = p.Write(public)
  213. return err
  214. }