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.

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