Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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