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.2KB

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