Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. "context"
  8. "fmt"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "os/exec"
  13. "regexp"
  14. "strconv"
  15. "strings"
  16. "time"
  17. asymkey_model "code.gitea.io/gitea/models/asymkey"
  18. git_model "code.gitea.io/gitea/models/git"
  19. "code.gitea.io/gitea/models/perm"
  20. "code.gitea.io/gitea/modules/git"
  21. "code.gitea.io/gitea/modules/json"
  22. "code.gitea.io/gitea/modules/log"
  23. "code.gitea.io/gitea/modules/pprof"
  24. "code.gitea.io/gitea/modules/private"
  25. "code.gitea.io/gitea/modules/process"
  26. repo_module "code.gitea.io/gitea/modules/repository"
  27. "code.gitea.io/gitea/modules/setting"
  28. "code.gitea.io/gitea/services/lfs"
  29. "github.com/golang-jwt/jwt/v4"
  30. "github.com/kballard/go-shellquote"
  31. "github.com/urfave/cli"
  32. )
  33. const (
  34. lfsAuthenticateVerb = "git-lfs-authenticate"
  35. )
  36. // CmdServ represents the available serv sub-command.
  37. var CmdServ = cli.Command{
  38. Name: "serv",
  39. Usage: "This command should only be called by SSH shell",
  40. Description: `Serv provide access auth for repositories`,
  41. Action: runServ,
  42. Flags: []cli.Flag{
  43. cli.BoolFlag{
  44. Name: "enable-pprof",
  45. },
  46. cli.BoolFlag{
  47. Name: "debug",
  48. },
  49. },
  50. }
  51. func setup(logPath string, debug bool) {
  52. _ = log.DelLogger("console")
  53. if debug {
  54. _ = log.NewLogger(1000, "console", "console", `{"level":"trace","stacktracelevel":"NONE","stderr":true}`)
  55. } else {
  56. _ = log.NewLogger(1000, "console", "console", `{"level":"fatal","stacktracelevel":"NONE","stderr":true}`)
  57. }
  58. setting.LoadFromExisting()
  59. if debug {
  60. setting.RunMode = "dev"
  61. }
  62. // Check if setting.RepoRootPath exists. It could be the case that it doesn't exist, this can happen when
  63. // `[repository]` `ROOT` is a relative path and $GITEA_WORK_DIR isn't passed to the SSH connection.
  64. if _, err := os.Stat(setting.RepoRootPath); err != nil {
  65. if os.IsNotExist(err) {
  66. _ = fail("Incorrect configuration, no repository directory.", "Directory `[repository].ROOT` %q was not found, please check if $GITEA_WORK_DIR is passed to the SSH connection or make `[repository].ROOT` an absolute value.", setting.RepoRootPath)
  67. } else {
  68. _ = fail("Incorrect configuration, repository directory is inaccessible", "Directory `[repository].ROOT` %q is inaccessible. err: %v", setting.RepoRootPath, err)
  69. }
  70. return
  71. }
  72. if err := git.InitSimple(context.Background()); err != nil {
  73. _ = fail("Failed to init git", "Failed to init git, err: %v", err)
  74. }
  75. }
  76. var (
  77. allowedCommands = map[string]perm.AccessMode{
  78. "git-upload-pack": perm.AccessModeRead,
  79. "git-upload-archive": perm.AccessModeRead,
  80. "git-receive-pack": perm.AccessModeWrite,
  81. lfsAuthenticateVerb: perm.AccessModeNone,
  82. }
  83. alphaDashDotPattern = regexp.MustCompile(`[^\w-\.]`)
  84. )
  85. func fail(userMessage, logMessage string, args ...interface{}) error {
  86. // There appears to be a chance to cause a zombie process and failure to read the Exit status
  87. // if nothing is outputted on stdout.
  88. _, _ = fmt.Fprintln(os.Stdout, "")
  89. _, _ = fmt.Fprintln(os.Stderr, "Gitea:", userMessage)
  90. if len(logMessage) > 0 {
  91. if !setting.IsProd {
  92. _, _ = fmt.Fprintf(os.Stderr, logMessage+"\n", args...)
  93. }
  94. }
  95. ctx, cancel := installSignals()
  96. defer cancel()
  97. if len(logMessage) > 0 {
  98. _ = private.SSHLog(ctx, true, fmt.Sprintf(logMessage+": ", args...))
  99. }
  100. return cli.NewExitError("", 1)
  101. }
  102. func runServ(c *cli.Context) error {
  103. ctx, cancel := installSignals()
  104. defer cancel()
  105. // FIXME: This needs to internationalised
  106. setup("serv.log", c.Bool("debug"))
  107. if setting.SSH.Disabled {
  108. println("Gitea: SSH has been disabled")
  109. return nil
  110. }
  111. if len(c.Args()) < 1 {
  112. if err := cli.ShowSubcommandHelp(c); err != nil {
  113. fmt.Printf("error showing subcommand help: %v\n", err)
  114. }
  115. return nil
  116. }
  117. keys := strings.Split(c.Args()[0], "-")
  118. if len(keys) != 2 || keys[0] != "key" {
  119. return fail("Key ID format error", "Invalid key argument: %s", c.Args()[0])
  120. }
  121. keyID, err := strconv.ParseInt(keys[1], 10, 64)
  122. if err != nil {
  123. return fail("Key ID format error", "Invalid key argument: %s", c.Args()[1])
  124. }
  125. cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
  126. if len(cmd) == 0 {
  127. key, user, err := private.ServNoCommand(ctx, keyID)
  128. if err != nil {
  129. return fail("Internal error", "Failed to check provided key: %v", err)
  130. }
  131. switch key.Type {
  132. case asymkey_model.KeyTypeDeploy:
  133. println("Hi there! You've successfully authenticated with the deploy key named " + key.Name + ", but Gitea does not provide shell access.")
  134. case asymkey_model.KeyTypePrincipal:
  135. println("Hi there! You've successfully authenticated with the principal " + key.Content + ", but Gitea does not provide shell access.")
  136. default:
  137. println("Hi there, " + user.Name + "! You've successfully authenticated with the key named " + key.Name + ", but Gitea does not provide shell access.")
  138. }
  139. println("If this is unexpected, please log in with password and setup Gitea under another user.")
  140. return nil
  141. } else if c.Bool("debug") {
  142. log.Debug("SSH_ORIGINAL_COMMAND: %s", os.Getenv("SSH_ORIGINAL_COMMAND"))
  143. }
  144. words, err := shellquote.Split(cmd)
  145. if err != nil {
  146. return fail("Error parsing arguments", "Failed to parse arguments: %v", err)
  147. }
  148. if len(words) < 2 {
  149. if git.CheckGitVersionAtLeast("2.29") == nil {
  150. // for AGit Flow
  151. if cmd == "ssh_info" {
  152. fmt.Print(`{"type":"gitea","version":1}`)
  153. return nil
  154. }
  155. }
  156. return fail("Too few arguments", "Too few arguments in cmd: %s", cmd)
  157. }
  158. verb := words[0]
  159. repoPath := words[1]
  160. if repoPath[0] == '/' {
  161. repoPath = repoPath[1:]
  162. }
  163. var lfsVerb string
  164. if verb == lfsAuthenticateVerb {
  165. if !setting.LFS.StartServer {
  166. return fail("Unknown git command", "LFS authentication request over SSH denied, LFS support is disabled")
  167. }
  168. if len(words) > 2 {
  169. lfsVerb = words[2]
  170. }
  171. }
  172. // LowerCase and trim the repoPath as that's how they are stored.
  173. repoPath = strings.ToLower(strings.TrimSpace(repoPath))
  174. rr := strings.SplitN(repoPath, "/", 2)
  175. if len(rr) != 2 {
  176. return fail("Invalid repository path", "Invalid repository path: %v", repoPath)
  177. }
  178. username := strings.ToLower(rr[0])
  179. reponame := strings.ToLower(strings.TrimSuffix(rr[1], ".git"))
  180. if alphaDashDotPattern.MatchString(reponame) {
  181. return fail("Invalid repo name", "Invalid repo name: %s", reponame)
  182. }
  183. if c.Bool("enable-pprof") {
  184. if err := os.MkdirAll(setting.PprofDataPath, os.ModePerm); err != nil {
  185. return fail("Error while trying to create PPROF_DATA_PATH", "Error while trying to create PPROF_DATA_PATH: %v", err)
  186. }
  187. stopCPUProfiler, err := pprof.DumpCPUProfileForUsername(setting.PprofDataPath, username)
  188. if err != nil {
  189. return fail("Internal Server Error", "Unable to start CPU profile: %v", err)
  190. }
  191. defer func() {
  192. stopCPUProfiler()
  193. err := pprof.DumpMemProfileForUsername(setting.PprofDataPath, username)
  194. if err != nil {
  195. _ = fail("Internal Server Error", "Unable to dump Mem Profile: %v", err)
  196. }
  197. }()
  198. }
  199. requestedMode, has := allowedCommands[verb]
  200. if !has {
  201. return fail("Unknown git command", "Unknown git command %s", verb)
  202. }
  203. if verb == lfsAuthenticateVerb {
  204. if lfsVerb == "upload" {
  205. requestedMode = perm.AccessModeWrite
  206. } else if lfsVerb == "download" {
  207. requestedMode = perm.AccessModeRead
  208. } else {
  209. return fail("Unknown LFS verb", "Unknown lfs verb %s", lfsVerb)
  210. }
  211. }
  212. results, err := private.ServCommand(ctx, keyID, username, reponame, requestedMode, verb, lfsVerb)
  213. if err != nil {
  214. if private.IsErrServCommand(err) {
  215. errServCommand := err.(private.ErrServCommand)
  216. if errServCommand.StatusCode != http.StatusInternalServerError {
  217. return fail("Unauthorized", "%s", errServCommand.Error())
  218. }
  219. return fail("Internal Server Error", "%s", errServCommand.Error())
  220. }
  221. return fail("Internal Server Error", "%s", err.Error())
  222. }
  223. // LFS token authentication
  224. if verb == lfsAuthenticateVerb {
  225. url := fmt.Sprintf("%s%s/%s.git/info/lfs", setting.AppURL, url.PathEscape(results.OwnerName), url.PathEscape(results.RepoName))
  226. now := time.Now()
  227. claims := lfs.Claims{
  228. RegisteredClaims: jwt.RegisteredClaims{
  229. ExpiresAt: jwt.NewNumericDate(now.Add(setting.LFS.HTTPAuthExpiry)),
  230. NotBefore: jwt.NewNumericDate(now),
  231. },
  232. RepoID: results.RepoID,
  233. Op: lfsVerb,
  234. UserID: results.UserID,
  235. }
  236. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  237. // Sign and get the complete encoded token as a string using the secret
  238. tokenString, err := token.SignedString(setting.LFS.JWTSecretBytes)
  239. if err != nil {
  240. return fail("Internal error", "Failed to sign JWT token: %v", err)
  241. }
  242. tokenAuthentication := &git_model.LFSTokenResponse{
  243. Header: make(map[string]string),
  244. Href: url,
  245. }
  246. tokenAuthentication.Header["Authorization"] = fmt.Sprintf("Bearer %s", tokenString)
  247. enc := json.NewEncoder(os.Stdout)
  248. err = enc.Encode(tokenAuthentication)
  249. if err != nil {
  250. return fail("Internal error", "Failed to encode LFS json response: %v", err)
  251. }
  252. return nil
  253. }
  254. // Special handle for Windows.
  255. if setting.IsWindows {
  256. verb = strings.Replace(verb, "-", " ", 1)
  257. }
  258. var gitcmd *exec.Cmd
  259. verbs := strings.Split(verb, " ")
  260. if len(verbs) == 2 {
  261. gitcmd = exec.CommandContext(ctx, verbs[0], verbs[1], repoPath)
  262. } else {
  263. gitcmd = exec.CommandContext(ctx, verb, repoPath)
  264. }
  265. process.SetSysProcAttribute(gitcmd)
  266. gitcmd.Dir = setting.RepoRootPath
  267. gitcmd.Stdout = os.Stdout
  268. gitcmd.Stdin = os.Stdin
  269. gitcmd.Stderr = os.Stderr
  270. gitcmd.Env = append(gitcmd.Env, os.Environ()...)
  271. gitcmd.Env = append(gitcmd.Env,
  272. repo_module.EnvRepoIsWiki+"="+strconv.FormatBool(results.IsWiki),
  273. repo_module.EnvRepoName+"="+results.RepoName,
  274. repo_module.EnvRepoUsername+"="+results.OwnerName,
  275. repo_module.EnvPusherName+"="+results.UserName,
  276. repo_module.EnvPusherEmail+"="+results.UserEmail,
  277. repo_module.EnvPusherID+"="+strconv.FormatInt(results.UserID, 10),
  278. repo_module.EnvRepoID+"="+strconv.FormatInt(results.RepoID, 10),
  279. repo_module.EnvPRID+"="+fmt.Sprintf("%d", 0),
  280. repo_module.EnvDeployKeyID+"="+fmt.Sprintf("%d", results.DeployKeyID),
  281. repo_module.EnvKeyID+"="+fmt.Sprintf("%d", results.KeyID),
  282. repo_module.EnvAppURL+"="+setting.AppURL,
  283. )
  284. // to avoid breaking, here only use the minimal environment variables for the "gitea serv" command.
  285. // it could be re-considered whether to use the same git.CommonGitCmdEnvs() as "git" command later.
  286. gitcmd.Env = append(gitcmd.Env, git.CommonCmdServEnvs()...)
  287. if err = gitcmd.Run(); err != nil {
  288. return fail("Internal error", "Failed to execute git command: %v", err)
  289. }
  290. // Update user key activity.
  291. if results.KeyID > 0 {
  292. if err = private.UpdatePublicKeyInRepo(ctx, results.KeyID, results.RepoID); err != nil {
  293. return fail("Internal error", "UpdatePublicKeyInRepo: %v", err)
  294. }
  295. }
  296. return nil
  297. }