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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. "encoding/json"
  8. "fmt"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "strings"
  13. "time"
  14. "code.gitea.io/gitea/models"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/pprof"
  17. "code.gitea.io/gitea/modules/private"
  18. "code.gitea.io/gitea/modules/setting"
  19. "github.com/Unknwon/com"
  20. "github.com/dgrijalva/jwt-go"
  21. "github.com/urfave/cli"
  22. )
  23. const (
  24. accessDenied = "Repository does not exist or you do not have access"
  25. lfsAuthenticateVerb = "git-lfs-authenticate"
  26. )
  27. // CmdServ represents the available serv sub-command.
  28. var CmdServ = cli.Command{
  29. Name: "serv",
  30. Usage: "This command should only be called by SSH shell",
  31. Description: `Serv provide access auth for repositories`,
  32. Action: runServ,
  33. Flags: []cli.Flag{
  34. cli.StringFlag{
  35. Name: "config, c",
  36. Value: "custom/conf/app.ini",
  37. Usage: "Custom configuration file path",
  38. },
  39. cli.BoolFlag{
  40. Name: "enable-pprof",
  41. },
  42. },
  43. }
  44. func setup(logPath string) {
  45. setting.NewContext()
  46. log.NewGitLogger(filepath.Join(setting.LogRootPath, logPath))
  47. }
  48. func parseCmd(cmd string) (string, string) {
  49. ss := strings.SplitN(cmd, " ", 2)
  50. if len(ss) != 2 {
  51. return "", ""
  52. }
  53. return ss[0], strings.Replace(ss[1], "'/", "'", 1)
  54. }
  55. var (
  56. allowedCommands = map[string]models.AccessMode{
  57. "git-upload-pack": models.AccessModeRead,
  58. "git-upload-archive": models.AccessModeRead,
  59. "git-receive-pack": models.AccessModeWrite,
  60. lfsAuthenticateVerb: models.AccessModeNone,
  61. }
  62. )
  63. func fail(userMessage, logMessage string, args ...interface{}) {
  64. fmt.Fprintln(os.Stderr, "Gitea:", userMessage)
  65. if len(logMessage) > 0 {
  66. if !setting.ProdMode {
  67. fmt.Fprintf(os.Stderr, logMessage+"\n", args...)
  68. }
  69. log.GitLogger.Fatal(3, logMessage, args...)
  70. return
  71. }
  72. log.GitLogger.Close()
  73. os.Exit(1)
  74. }
  75. func runServ(c *cli.Context) error {
  76. if c.IsSet("config") {
  77. setting.CustomConf = c.String("config")
  78. }
  79. setup("serv.log")
  80. if setting.SSH.Disabled {
  81. println("Gitea: SSH has been disabled")
  82. return nil
  83. }
  84. if len(c.Args()) < 1 {
  85. cli.ShowSubcommandHelp(c)
  86. return nil
  87. }
  88. cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
  89. if len(cmd) == 0 {
  90. println("Hi there, You've successfully authenticated, but Gitea does not provide shell access.")
  91. println("If this is unexpected, please log in with password and setup Gitea under another user.")
  92. return nil
  93. }
  94. verb, args := parseCmd(cmd)
  95. var lfsVerb string
  96. if verb == lfsAuthenticateVerb {
  97. if !setting.LFS.StartServer {
  98. fail("Unknown git command", "LFS authentication request over SSH denied, LFS support is disabled")
  99. }
  100. argsSplit := strings.Split(args, " ")
  101. if len(argsSplit) >= 2 {
  102. args = strings.TrimSpace(argsSplit[0])
  103. lfsVerb = strings.TrimSpace(argsSplit[1])
  104. }
  105. }
  106. repoPath := strings.ToLower(strings.Trim(args, "'"))
  107. rr := strings.SplitN(repoPath, "/", 2)
  108. if len(rr) != 2 {
  109. fail("Invalid repository path", "Invalid repository path: %v", args)
  110. }
  111. username := strings.ToLower(rr[0])
  112. reponame := strings.ToLower(strings.TrimSuffix(rr[1], ".git"))
  113. if setting.EnablePprof || c.Bool("enable-pprof") {
  114. if err := os.MkdirAll(setting.PprofDataPath, os.ModePerm); err != nil {
  115. fail("Error while trying to create PPROF_DATA_PATH", "Error while trying to create PPROF_DATA_PATH: %v", err)
  116. }
  117. stopCPUProfiler := pprof.DumpCPUProfileForUsername(setting.PprofDataPath, username)
  118. defer func() {
  119. stopCPUProfiler()
  120. pprof.DumpMemProfileForUsername(setting.PprofDataPath, username)
  121. }()
  122. }
  123. isWiki := false
  124. unitType := models.UnitTypeCode
  125. if strings.HasSuffix(reponame, ".wiki") {
  126. isWiki = true
  127. unitType = models.UnitTypeWiki
  128. reponame = reponame[:len(reponame)-5]
  129. }
  130. os.Setenv(models.EnvRepoUsername, username)
  131. if isWiki {
  132. os.Setenv(models.EnvRepoIsWiki, "true")
  133. } else {
  134. os.Setenv(models.EnvRepoIsWiki, "false")
  135. }
  136. os.Setenv(models.EnvRepoName, reponame)
  137. repo, err := private.GetRepositoryByOwnerAndName(username, reponame)
  138. if err != nil {
  139. if strings.Contains(err.Error(), "Failed to get repository: repository does not exist") {
  140. fail(accessDenied, "Repository does not exist: %s/%s", username, reponame)
  141. }
  142. fail("Internal error", "Failed to get repository: %v", err)
  143. }
  144. requestedMode, has := allowedCommands[verb]
  145. if !has {
  146. fail("Unknown git command", "Unknown git command %s", verb)
  147. }
  148. if verb == lfsAuthenticateVerb {
  149. if lfsVerb == "upload" {
  150. requestedMode = models.AccessModeWrite
  151. } else if lfsVerb == "download" {
  152. requestedMode = models.AccessModeRead
  153. } else {
  154. fail("Unknown LFS verb", "Unknown lfs verb %s", lfsVerb)
  155. }
  156. }
  157. // Prohibit push to mirror repositories.
  158. if requestedMode > models.AccessModeRead && repo.IsMirror {
  159. fail("mirror repository is read-only", "")
  160. }
  161. // Allow anonymous clone for public repositories.
  162. var (
  163. keyID int64
  164. user *models.User
  165. )
  166. if requestedMode == models.AccessModeWrite || repo.IsPrivate {
  167. keys := strings.Split(c.Args()[0], "-")
  168. if len(keys) != 2 {
  169. fail("Key ID format error", "Invalid key argument: %s", c.Args()[0])
  170. }
  171. key, err := private.GetPublicKeyByID(com.StrTo(keys[1]).MustInt64())
  172. if err != nil {
  173. fail("Invalid key ID", "Invalid key ID[%s]: %v", c.Args()[0], err)
  174. }
  175. keyID = key.ID
  176. // Check deploy key or user key.
  177. if key.Type == models.KeyTypeDeploy {
  178. if key.Mode < requestedMode {
  179. fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
  180. }
  181. // Check if this deploy key belongs to current repository.
  182. has, err := private.HasDeployKey(key.ID, repo.ID)
  183. if err != nil {
  184. fail("Key access denied", "Failed to access internal api: [key_id: %d, repo_id: %d]", key.ID, repo.ID)
  185. }
  186. if !has {
  187. fail("Key access denied", "Deploy key access denied: [key_id: %d, repo_id: %d]", key.ID, repo.ID)
  188. }
  189. // Update deploy key activity.
  190. if err = private.UpdateDeployKeyUpdated(key.ID, repo.ID); err != nil {
  191. fail("Internal error", "UpdateDeployKey: %v", err)
  192. }
  193. } else {
  194. user, err = private.GetUserByKeyID(key.ID)
  195. if err != nil {
  196. fail("internal error", "Failed to get user by key ID(%d): %v", keyID, err)
  197. }
  198. if !user.IsActive || user.ProhibitLogin {
  199. fail("Your account is not active or has been disabled by Administrator",
  200. "User %s is disabled and have no access to repository %s",
  201. user.Name, repoPath)
  202. }
  203. mode, err := private.AccessLevel(user.ID, repo.ID)
  204. if err != nil {
  205. fail("Internal error", "Failed to check access: %v", err)
  206. } else if *mode < requestedMode {
  207. clientMessage := accessDenied
  208. if *mode >= models.AccessModeRead {
  209. clientMessage = "You do not have sufficient authorization for this action"
  210. }
  211. fail(clientMessage,
  212. "User %s does not have level %v access to repository %s",
  213. user.Name, requestedMode, repoPath)
  214. }
  215. check, err := private.CheckUnitUser(user.ID, repo.ID, user.IsAdmin, unitType)
  216. if err != nil {
  217. fail("You do not have allowed for this action", "Failed to access internal api: [user.Name: %s, repoPath: %s]", user.Name, repoPath)
  218. }
  219. if !check {
  220. fail("You do not have allowed for this action",
  221. "User %s does not have allowed access to repository %s 's code",
  222. user.Name, repoPath)
  223. }
  224. os.Setenv(models.EnvPusherName, user.Name)
  225. os.Setenv(models.EnvPusherID, fmt.Sprintf("%d", user.ID))
  226. }
  227. }
  228. //LFS token authentication
  229. if verb == lfsAuthenticateVerb {
  230. url := fmt.Sprintf("%s%s/%s.git/info/lfs", setting.AppURL, username, repo.Name)
  231. now := time.Now()
  232. claims := jwt.MapClaims{
  233. "repo": repo.ID,
  234. "op": lfsVerb,
  235. "exp": now.Add(setting.LFS.HTTPAuthExpiry).Unix(),
  236. "nbf": now.Unix(),
  237. }
  238. if user != nil {
  239. claims["user"] = user.ID
  240. }
  241. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  242. // Sign and get the complete encoded token as a string using the secret
  243. tokenString, err := token.SignedString(setting.LFS.JWTSecretBytes)
  244. if err != nil {
  245. fail("Internal error", "Failed to sign JWT token: %v", err)
  246. }
  247. tokenAuthentication := &models.LFSTokenResponse{
  248. Header: make(map[string]string),
  249. Href: url,
  250. }
  251. tokenAuthentication.Header["Authorization"] = fmt.Sprintf("Bearer %s", tokenString)
  252. enc := json.NewEncoder(os.Stdout)
  253. err = enc.Encode(tokenAuthentication)
  254. if err != nil {
  255. fail("Internal error", "Failed to encode LFS json response: %v", err)
  256. }
  257. return nil
  258. }
  259. // Special handle for Windows.
  260. if setting.IsWindows {
  261. verb = strings.Replace(verb, "-", " ", 1)
  262. }
  263. var gitcmd *exec.Cmd
  264. verbs := strings.Split(verb, " ")
  265. if len(verbs) == 2 {
  266. gitcmd = exec.Command(verbs[0], verbs[1], repoPath)
  267. } else {
  268. gitcmd = exec.Command(verb, repoPath)
  269. }
  270. if isWiki {
  271. if err = repo.InitWiki(); err != nil {
  272. fail("Internal error", "Failed to init wiki repo: %v", err)
  273. }
  274. }
  275. os.Setenv(models.ProtectedBranchRepoID, fmt.Sprintf("%d", repo.ID))
  276. gitcmd.Dir = setting.RepoRootPath
  277. gitcmd.Stdout = os.Stdout
  278. gitcmd.Stdin = os.Stdin
  279. gitcmd.Stderr = os.Stderr
  280. if err = gitcmd.Run(); err != nil {
  281. fail("Internal error", "Failed to execute git command: %v", err)
  282. }
  283. // Update user key activity.
  284. if keyID > 0 {
  285. if err = private.UpdatePublicKeyUpdated(keyID); err != nil {
  286. fail("Internal error", "UpdatePublicKey: %v", err)
  287. }
  288. }
  289. return nil
  290. }