serv.go 7.2 KB

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