serv.go 7.4 KB

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