serv.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 Gitote. All rights reserved.
  3. //
  4. // This source code is licensed under the MIT license found in the
  5. // LICENSE file in the root directory of this source tree.
  6. package cmd
  7. import (
  8. "fmt"
  9. "gitote/gitote/models"
  10. "gitote/gitote/models/errors"
  11. "gitote/gitote/pkg/setting"
  12. "os"
  13. "os/exec"
  14. "path/filepath"
  15. "strings"
  16. "time"
  17. "github.com/Unknwon/com"
  18. "github.com/urfave/cli"
  19. log "gopkg.in/clog.v1"
  20. )
  21. const (
  22. _ACCESS_DENIED_MESSAGE = "Repository does not exist or you do not have access"
  23. )
  24. var Serv = cli.Command{
  25. Name: "serv",
  26. Usage: "This command should only be called by SSH shell",
  27. Description: `Serv provide access auth for repositories`,
  28. Action: runServ,
  29. Flags: []cli.Flag{
  30. stringFlag("config, c", "custom/conf/app.ini", "Custom configuration file path"),
  31. },
  32. }
  33. func fail(userMessage, logMessage string, args ...interface{}) {
  34. fmt.Fprintln(os.Stderr, "Gitote:", userMessage)
  35. if len(logMessage) > 0 {
  36. if !setting.ProdMode {
  37. fmt.Fprintf(os.Stderr, logMessage+"\n", args...)
  38. }
  39. log.Fatal(3, logMessage, args...)
  40. }
  41. os.Exit(1)
  42. }
  43. func setup(c *cli.Context, logPath string, connectDB bool) {
  44. if c.IsSet("config") {
  45. setting.CustomConf = c.String("config")
  46. } else if c.GlobalIsSet("config") {
  47. setting.CustomConf = c.GlobalString("config")
  48. }
  49. setting.NewContext()
  50. level := log.TRACE
  51. if setting.ProdMode {
  52. level = log.ERROR
  53. }
  54. log.New(log.FILE, log.FileConfig{
  55. Level: level,
  56. Filename: filepath.Join(setting.LogRootPath, logPath),
  57. FileRotationConfig: log.FileRotationConfig{
  58. Rotate: true,
  59. Daily: true,
  60. MaxDays: 3,
  61. },
  62. })
  63. log.Delete(log.CONSOLE) // Remove primary logger
  64. if !connectDB {
  65. return
  66. }
  67. models.LoadConfigs()
  68. if setting.UseSQLite3 {
  69. workDir, _ := setting.WorkDir()
  70. os.Chdir(workDir)
  71. }
  72. if err := models.SetEngine(); err != nil {
  73. fail("Internal error", "SetEngine: %v", err)
  74. }
  75. }
  76. func parseSSHCmd(cmd string) (string, string) {
  77. ss := strings.SplitN(cmd, " ", 2)
  78. if len(ss) != 2 {
  79. return "", ""
  80. }
  81. return ss[0], strings.Replace(ss[1], "'/", "'", 1)
  82. }
  83. func checkDeployKey(key *models.PublicKey, repo *models.Repository) {
  84. // Check if this deploy key belongs to current repository.
  85. if !models.HasDeployKey(key.ID, repo.ID) {
  86. fail("Key access denied", "Deploy key access denied: [key_id: %d, repo_id: %d]", key.ID, repo.ID)
  87. }
  88. // Update deploy key activity.
  89. deployKey, err := models.GetDeployKeyByRepo(key.ID, repo.ID)
  90. if err != nil {
  91. fail("Internal error", "GetDeployKey: %v", err)
  92. }
  93. deployKey.Updated = time.Now()
  94. if err = models.UpdateDeployKey(deployKey); err != nil {
  95. fail("Internal error", "UpdateDeployKey: %v", err)
  96. }
  97. }
  98. var (
  99. allowedCommands = map[string]models.AccessMode{
  100. "git-upload-pack": models.ACCESS_MODE_READ,
  101. "git-upload-archive": models.ACCESS_MODE_READ,
  102. "git-receive-pack": models.ACCESS_MODE_WRITE,
  103. }
  104. )
  105. func runServ(c *cli.Context) error {
  106. setup(c, "serv.log", true)
  107. if setting.SSH.Disabled {
  108. println("Gitote: SSH has been disabled")
  109. return nil
  110. }
  111. if len(c.Args()) < 1 {
  112. fail("Not enough arguments", "Not enough arguments")
  113. }
  114. sshCmd := os.Getenv("SSH_ORIGINAL_COMMAND")
  115. if len(sshCmd) == 0 {
  116. println("Hi there, You've successfully authenticated, but Gitote does not provide shell access.")
  117. println("🦄🦄🦄🦄🦄")
  118. return nil
  119. }
  120. verb, args := parseSSHCmd(sshCmd)
  121. repoFullName := strings.ToLower(strings.Trim(args, "'"))
  122. repoFields := strings.SplitN(repoFullName, "/", 2)
  123. if len(repoFields) != 2 {
  124. fail("Invalid repository path", "Invalid repository path: %v", args)
  125. }
  126. ownerName := strings.ToLower(repoFields[0])
  127. repoName := strings.TrimSuffix(strings.ToLower(repoFields[1]), ".git")
  128. repoName = strings.TrimSuffix(repoName, ".wiki")
  129. owner, err := models.GetUserByName(ownerName)
  130. if err != nil {
  131. if errors.IsUserNotExist(err) {
  132. fail("Repository owner does not exist", "Unregistered owner: %s", ownerName)
  133. }
  134. fail("Internal error", "Fail to get repository owner '%s': %v", ownerName, err)
  135. }
  136. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  137. if err != nil {
  138. if errors.IsRepoNotExist(err) {
  139. fail(_ACCESS_DENIED_MESSAGE, "Repository does not exist: %s/%s", owner.Name, repoName)
  140. }
  141. fail("Internal error", "Fail to get repository: %v", err)
  142. }
  143. repo.Owner = owner
  144. requestMode, ok := allowedCommands[verb]
  145. if !ok {
  146. fail("Unknown git command", "Unknown git command '%s'", verb)
  147. }
  148. // Prohibit push to mirror repositories.
  149. if requestMode > models.ACCESS_MODE_READ && repo.IsMirror {
  150. fail("Mirror repository is read-only", "")
  151. }
  152. // Allow anonymous (user is nil) clone for public repositories.
  153. var user *models.User
  154. key, err := models.GetPublicKeyByID(com.StrTo(strings.TrimPrefix(c.Args()[0], "key-")).MustInt64())
  155. if err != nil {
  156. fail("Invalid key ID", "Invalid key ID '%s': %v", c.Args()[0], err)
  157. }
  158. if requestMode == models.ACCESS_MODE_WRITE || repo.IsPrivate {
  159. // Check deploy key or user key.
  160. if key.IsDeployKey() {
  161. if key.Mode < requestMode {
  162. fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
  163. }
  164. checkDeployKey(key, repo)
  165. } else {
  166. user, err = models.GetUserByKeyID(key.ID)
  167. if err != nil {
  168. fail("Internal error", "Fail to get user by key ID '%d': %v", key.ID, err)
  169. }
  170. mode, err := models.AccessLevel(user.ID, repo)
  171. if err != nil {
  172. fail("Internal error", "Fail to check access: %v", err)
  173. }
  174. if mode < requestMode {
  175. clientMessage := _ACCESS_DENIED_MESSAGE
  176. if mode >= models.ACCESS_MODE_READ {
  177. clientMessage = "You do not have sufficient authorization for this action"
  178. }
  179. fail(clientMessage,
  180. "User '%s' does not have level '%v' access to repository '%s'",
  181. user.Name, requestMode, repoFullName)
  182. }
  183. }
  184. } else {
  185. setting.NewService()
  186. // Check if the key can access to the repository in case of it is a deploy key (a deploy keys != user key).
  187. // A deploy key doesn't represent a signed in user, so in a site with Service.RequireSignInView activated
  188. // we should give read access only in repositories where this deploy key is in use. In other case, a server
  189. // or system using an active deploy key can get read access to all the repositories in a Gitote service.
  190. if key.IsDeployKey() && setting.Service.RequireSignInView {
  191. checkDeployKey(key, repo)
  192. }
  193. }
  194. // Update user key activity.
  195. if key.ID > 0 {
  196. key, err := models.GetPublicKeyByID(key.ID)
  197. if err != nil {
  198. fail("Internal error", "GetPublicKeyByID: %v", err)
  199. }
  200. key.Updated = time.Now()
  201. if err = models.UpdatePublicKey(key); err != nil {
  202. fail("Internal error", "UpdatePublicKey: %v", err)
  203. }
  204. }
  205. // Special handle for Windows.
  206. if setting.IsWindows {
  207. verb = strings.Replace(verb, "-", " ", 1)
  208. }
  209. var gitCmd *exec.Cmd
  210. verbs := strings.Split(verb, " ")
  211. if len(verbs) == 2 {
  212. gitCmd = exec.Command(verbs[0], verbs[1], repoFullName)
  213. } else {
  214. gitCmd = exec.Command(verb, repoFullName)
  215. }
  216. if requestMode == models.ACCESS_MODE_WRITE {
  217. gitCmd.Env = append(os.Environ(), models.ComposeHookEnvs(models.ComposeHookEnvsOptions{
  218. AuthUser: user,
  219. OwnerName: owner.Name,
  220. OwnerSalt: owner.Salt,
  221. RepoID: repo.ID,
  222. RepoName: repo.Name,
  223. RepoPath: repo.RepoPath(),
  224. })...)
  225. }
  226. gitCmd.Dir = setting.RepoRootPath
  227. gitCmd.Stdout = os.Stdout
  228. gitCmd.Stdin = os.Stdin
  229. gitCmd.Stderr = os.Stderr
  230. if err = gitCmd.Run(); err != nil {
  231. fail("Internal error", "Fail to execute git command: %v", err)
  232. }
  233. return nil
  234. }