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 8.4KB

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