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.

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