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 9.9KB

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