Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

serv.go 8.6KB

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