本站源代码
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.

261 lines
7.3KB

  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2016 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 cmd
  6. import (
  7. "encoding/json"
  8. "fmt"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "os/exec"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "code.gitea.io/gitea/models"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/pprof"
  19. "code.gitea.io/gitea/modules/private"
  20. "code.gitea.io/gitea/modules/setting"
  21. "github.com/dgrijalva/jwt-go"
  22. "github.com/unknwon/com"
  23. "github.com/urfave/cli"
  24. )
  25. const (
  26. lfsAuthenticateVerb = "git-lfs-authenticate"
  27. )
  28. // CmdServ represents the available serv sub-command.
  29. var CmdServ = cli.Command{
  30. Name: "serv",
  31. Usage: "This command should only be called by SSH shell",
  32. Description: `Serv provide access auth for repositories`,
  33. Action: runServ,
  34. Flags: []cli.Flag{
  35. cli.BoolFlag{
  36. Name: "enable-pprof",
  37. },
  38. },
  39. }
  40. func setup(logPath string) {
  41. _ = log.DelLogger("console")
  42. setting.NewContext()
  43. }
  44. func parseCmd(cmd string) (string, string) {
  45. ss := strings.SplitN(cmd, " ", 2)
  46. if len(ss) != 2 {
  47. return "", ""
  48. }
  49. return ss[0], strings.Replace(ss[1], "'/", "'", 1)
  50. }
  51. var (
  52. allowedCommands = map[string]models.AccessMode{
  53. "git-upload-pack": models.AccessModeRead,
  54. "git-upload-archive": models.AccessModeRead,
  55. "git-receive-pack": models.AccessModeWrite,
  56. lfsAuthenticateVerb: models.AccessModeNone,
  57. }
  58. )
  59. func fail(userMessage, logMessage string, args ...interface{}) {
  60. fmt.Fprintln(os.Stderr, "Gitea:", userMessage)
  61. if len(logMessage) > 0 {
  62. if !setting.ProdMode {
  63. fmt.Fprintf(os.Stderr, logMessage+"\n", args...)
  64. }
  65. }
  66. os.Exit(1)
  67. }
  68. func runServ(c *cli.Context) error {
  69. // FIXME: This needs to internationalised
  70. setup("serv.log")
  71. if setting.SSH.Disabled {
  72. println("Gitea: SSH has been disabled")
  73. return nil
  74. }
  75. if len(c.Args()) < 1 {
  76. if err := cli.ShowSubcommandHelp(c); err != nil {
  77. fmt.Printf("error showing subcommand help: %v\n", err)
  78. }
  79. return nil
  80. }
  81. keys := strings.Split(c.Args()[0], "-")
  82. if len(keys) != 2 || keys[0] != "key" {
  83. fail("Key ID format error", "Invalid key argument: %s", c.Args()[0])
  84. }
  85. keyID := com.StrTo(keys[1]).MustInt64()
  86. cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
  87. if len(cmd) == 0 {
  88. key, user, err := private.ServNoCommand(keyID)
  89. if err != nil {
  90. fail("Internal error", "Failed to check provided key: %v", err)
  91. }
  92. if key.Type == models.KeyTypeDeploy {
  93. println("Hi there! You've successfully authenticated with the deploy key named " + key.Name + ", but Gitea does not provide shell access.")
  94. } else {
  95. println("Hi there, " + user.Name + "! You've successfully authenticated with the key named " + key.Name + ", but Gitea does not provide shell access.")
  96. }
  97. println("If this is unexpected, please log in with password and setup Gitea under another user.")
  98. return nil
  99. }
  100. verb, args := parseCmd(cmd)
  101. var lfsVerb string
  102. if verb == lfsAuthenticateVerb {
  103. if !setting.LFS.StartServer {
  104. fail("Unknown git command", "LFS authentication request over SSH denied, LFS support is disabled")
  105. }
  106. argsSplit := strings.Split(args, " ")
  107. if len(argsSplit) >= 2 {
  108. args = strings.TrimSpace(argsSplit[0])
  109. lfsVerb = strings.TrimSpace(argsSplit[1])
  110. }
  111. }
  112. repoPath := strings.ToLower(strings.Trim(args, "'"))
  113. rr := strings.SplitN(repoPath, "/", 2)
  114. if len(rr) != 2 {
  115. fail("Invalid repository path", "Invalid repository path: %v", args)
  116. }
  117. username := strings.ToLower(rr[0])
  118. reponame := strings.ToLower(strings.TrimSuffix(rr[1], ".git"))
  119. if setting.EnablePprof || c.Bool("enable-pprof") {
  120. if err := os.MkdirAll(setting.PprofDataPath, os.ModePerm); err != nil {
  121. fail("Error while trying to create PPROF_DATA_PATH", "Error while trying to create PPROF_DATA_PATH: %v", err)
  122. }
  123. stopCPUProfiler, err := pprof.DumpCPUProfileForUsername(setting.PprofDataPath, username)
  124. if err != nil {
  125. fail("Internal Server Error", "Unable to start CPU profile: %v", err)
  126. }
  127. defer func() {
  128. stopCPUProfiler()
  129. err := pprof.DumpMemProfileForUsername(setting.PprofDataPath, username)
  130. if err != nil {
  131. fail("Internal Server Error", "Unable to dump Mem Profile: %v", err)
  132. }
  133. }()
  134. }
  135. requestedMode, has := allowedCommands[verb]
  136. if !has {
  137. fail("Unknown git command", "Unknown git command %s", verb)
  138. }
  139. if verb == lfsAuthenticateVerb {
  140. if lfsVerb == "upload" {
  141. requestedMode = models.AccessModeWrite
  142. } else if lfsVerb == "download" {
  143. requestedMode = models.AccessModeRead
  144. } else {
  145. fail("Unknown LFS verb", "Unknown lfs verb %s", lfsVerb)
  146. }
  147. }
  148. results, err := private.ServCommand(keyID, username, reponame, requestedMode, verb, lfsVerb)
  149. if err != nil {
  150. if private.IsErrServCommand(err) {
  151. errServCommand := err.(private.ErrServCommand)
  152. if errServCommand.StatusCode != http.StatusInternalServerError {
  153. fail("Unauthorized", "%s", errServCommand.Error())
  154. } else {
  155. fail("Internal Server Error", "%s", errServCommand.Error())
  156. }
  157. }
  158. fail("Internal Server Error", "%s", err.Error())
  159. }
  160. os.Setenv(models.EnvRepoIsWiki, strconv.FormatBool(results.IsWiki))
  161. os.Setenv(models.EnvRepoName, results.RepoName)
  162. os.Setenv(models.EnvRepoUsername, results.OwnerName)
  163. os.Setenv(models.EnvPusherName, results.UserName)
  164. os.Setenv(models.EnvPusherID, strconv.FormatInt(results.UserID, 10))
  165. os.Setenv(models.ProtectedBranchRepoID, strconv.FormatInt(results.RepoID, 10))
  166. os.Setenv(models.ProtectedBranchPRID, fmt.Sprintf("%d", 0))
  167. os.Setenv(models.EnvIsDeployKey, fmt.Sprintf("%t", results.IsDeployKey))
  168. os.Setenv(models.EnvKeyID, fmt.Sprintf("%d", results.KeyID))
  169. //LFS token authentication
  170. if verb == lfsAuthenticateVerb {
  171. url := fmt.Sprintf("%s%s/%s.git/info/lfs", setting.AppURL, url.PathEscape(results.OwnerName), url.PathEscape(results.RepoName))
  172. now := time.Now()
  173. claims := jwt.MapClaims{
  174. "repo": results.RepoID,
  175. "op": lfsVerb,
  176. "exp": now.Add(setting.LFS.HTTPAuthExpiry).Unix(),
  177. "nbf": now.Unix(),
  178. "user": results.UserID,
  179. }
  180. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  181. // Sign and get the complete encoded token as a string using the secret
  182. tokenString, err := token.SignedString(setting.LFS.JWTSecretBytes)
  183. if err != nil {
  184. fail("Internal error", "Failed to sign JWT token: %v", err)
  185. }
  186. tokenAuthentication := &models.LFSTokenResponse{
  187. Header: make(map[string]string),
  188. Href: url,
  189. }
  190. tokenAuthentication.Header["Authorization"] = fmt.Sprintf("Bearer %s", tokenString)
  191. enc := json.NewEncoder(os.Stdout)
  192. err = enc.Encode(tokenAuthentication)
  193. if err != nil {
  194. fail("Internal error", "Failed to encode LFS json response: %v", err)
  195. }
  196. return nil
  197. }
  198. // Special handle for Windows.
  199. if setting.IsWindows {
  200. verb = strings.Replace(verb, "-", " ", 1)
  201. }
  202. var gitcmd *exec.Cmd
  203. verbs := strings.Split(verb, " ")
  204. if len(verbs) == 2 {
  205. gitcmd = exec.Command(verbs[0], verbs[1], repoPath)
  206. } else {
  207. gitcmd = exec.Command(verb, repoPath)
  208. }
  209. gitcmd.Dir = setting.RepoRootPath
  210. gitcmd.Stdout = os.Stdout
  211. gitcmd.Stdin = os.Stdin
  212. gitcmd.Stderr = os.Stderr
  213. if err = gitcmd.Run(); err != nil {
  214. fail("Internal error", "Failed to execute git command: %v", err)
  215. }
  216. // Update user key activity.
  217. if results.KeyID > 0 {
  218. if err = private.UpdatePublicKeyInRepo(results.KeyID, results.RepoID); err != nil {
  219. fail("Internal error", "UpdatePublicKeyInRepo: %v", err)
  220. }
  221. }
  222. return nil
  223. }
上海开阖软件有限公司 沪ICP备12045867号-1