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

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