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.1KB

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