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.

serv.go 11KB

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