serv.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package cmd
  5. import (
  6. "fmt"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. "github.com/Unknwon/com"
  13. "github.com/urfave/cli"
  14. log "gopkg.in/clog.v1"
  15. "github.com/gogits/gogs/models"
  16. "github.com/gogits/gogs/models/errors"
  17. "github.com/gogits/gogs/pkg/setting"
  18. http "github.com/gogits/gogs/routers/repo"
  19. "syscall"
  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, "Gin:", 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 isAnnexShell(cmd string) bool {
  77. return cmd == "git-annex-shell"
  78. }
  79. func parseSSHCmd(cmd string) (string, string, []string) {
  80. ss := strings.Split(cmd, " ")
  81. if len(ss) < 2 {
  82. return "", "", nil
  83. }
  84. if isAnnexShell(ss[0]) {
  85. return ss[0], strings.Replace(ss[2], "/", "'", 1), ss
  86. } else {
  87. return ss[0], strings.Replace(ss[1], "/", "'", 1), ss
  88. }
  89. }
  90. func checkDeployKey(key *models.PublicKey, repo *models.Repository) {
  91. // Check if this deploy key belongs to current repository.
  92. if !models.HasDeployKey(key.ID, repo.ID) {
  93. fail("Key access denied", "Deploy key access denied: [key_id: %d, repo_id: %d]", key.ID, repo.ID)
  94. }
  95. // Update deploy key activity.
  96. deployKey, err := models.GetDeployKeyByRepo(key.ID, repo.ID)
  97. if err != nil {
  98. fail("Internal error", "GetDeployKey: %v", err)
  99. }
  100. deployKey.Updated = time.Now()
  101. if err = models.UpdateDeployKey(deployKey); err != nil {
  102. fail("Internal error", "UpdateDeployKey: %v", err)
  103. }
  104. }
  105. var (
  106. allowedCommands = map[string]models.AccessMode{
  107. "git-upload-pack": models.ACCESS_MODE_READ,
  108. "git-upload-archive": models.ACCESS_MODE_READ,
  109. "git-receive-pack": models.ACCESS_MODE_WRITE,
  110. "git-annex-shell": models.ACCESS_MODE_WRITE,
  111. }
  112. )
  113. func runServ(c *cli.Context) error {
  114. setup(c, "serv.log", true)
  115. if setting.SSH.Disabled {
  116. println("Gins: SSH has been disabled")
  117. return nil
  118. }
  119. if len(c.Args()) < 1 {
  120. fail("Not enough arguments", "Not enough arguments")
  121. }
  122. sshCmd := strings.Replace(os.Getenv("SSH_ORIGINAL_COMMAND"), "'", "", -1)
  123. log.Info("SSH commadn:%s", sshCmd)
  124. if len(sshCmd) == 0 {
  125. println("Hi there, You've successfully authenticated, but Gin does not provide shell access.")
  126. return nil
  127. }
  128. verb, path, args := parseSSHCmd(sshCmd)
  129. repoFullName := strings.ToLower(strings.Trim(path, "'"))
  130. repoFields := strings.SplitN(repoFullName, "/", 2)
  131. if len(repoFields) != 2 {
  132. fail("Invalid repository path", "Invalid repository path: %v", path)
  133. }
  134. ownerName := strings.ToLower(repoFields[0])
  135. repoName := strings.TrimSuffix(strings.ToLower(repoFields[1]), ".git")
  136. repoName = strings.TrimSuffix(repoName, ".wiki")
  137. owner, err := models.GetUserByName(ownerName)
  138. if err != nil {
  139. if errors.IsUserNotExist(err) {
  140. fail("Repository owner does not exist", "Unregistered owner: %s", ownerName)
  141. }
  142. fail("Internal error", "Fail to get repository owner '%s': %v", ownerName, err)
  143. }
  144. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  145. if err != nil {
  146. if errors.IsRepoNotExist(err) {
  147. fail(_ACCESS_DENIED_MESSAGE, "Repository does not exist: %s/%s", owner.Name, repoName)
  148. }
  149. fail("Internal error", "Fail to get repository: %v", err)
  150. }
  151. repo.Owner = owner
  152. requestMode, ok := allowedCommands[verb]
  153. if !ok {
  154. fail("Unknown git command", "Unknown git command '%s'", verb)
  155. }
  156. // Prohibit push to mirror repositories.
  157. if requestMode > models.ACCESS_MODE_READ && repo.IsMirror {
  158. fail("Mirror repository is read-only", "")
  159. }
  160. // Allow anonymous (user is nil) clone for public repositories.
  161. var user *models.User
  162. key, err := models.GetPublicKeyByID(com.StrTo(strings.TrimPrefix(c.Args()[0], "key-")).MustInt64())
  163. if err != nil {
  164. fail("Invalid key ID", "Invalid key ID '%s': %v", c.Args()[0], err)
  165. }
  166. if requestMode == models.ACCESS_MODE_WRITE || repo.IsPrivate {
  167. // Check deploy key or user key.
  168. if key.IsDeployKey() {
  169. if key.Mode < requestMode {
  170. fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
  171. }
  172. checkDeployKey(key, repo)
  173. } else {
  174. user, err = models.GetUserByKeyID(key.ID)
  175. if err != nil {
  176. fail("Internal error", "Fail to get user by key ID '%d': %v", key.ID, err)
  177. }
  178. mode, err := models.AccessLevel(user.ID, repo)
  179. if err != nil {
  180. fail("Internal error", "Fail to check access: %v", err)
  181. }
  182. if mode < requestMode {
  183. clientMessage := _ACCESS_DENIED_MESSAGE
  184. if mode >= models.ACCESS_MODE_READ {
  185. clientMessage = "You do not have sufficient authorization for this action"
  186. }
  187. fail(clientMessage,
  188. "User '%s' does not have level '%v' access to repository '%s'",
  189. user.Name, requestMode, repoFullName)
  190. }
  191. }
  192. } else {
  193. setting.NewService()
  194. // Check if the key can access to the repository in case of it is a deploy key (a deploy keys != user key).
  195. // A deploy key doesn't represent a signed in user, so in a site with Service.RequireSignInView activated
  196. // we should give read access only in repositories where this deploy key is in use. In other case, a server
  197. // or system using an active deploy key can get read access to all the repositories in a Gogs service.
  198. if key.IsDeployKey() && setting.Service.RequireSignInView {
  199. checkDeployKey(key, repo)
  200. }
  201. }
  202. // Update user key activity.
  203. if key.ID > 0 {
  204. key, err := models.GetPublicKeyByID(key.ID)
  205. if err != nil {
  206. fail("Internal error", "GetPublicKeyByID: %v", err)
  207. }
  208. key.Updated = time.Now()
  209. if err = models.UpdatePublicKey(key); err != nil {
  210. fail("Internal error", "UpdatePublicKey: %v", err)
  211. }
  212. }
  213. // Special handle for Windows.
  214. // Todo will break with annex
  215. if setting.IsWindows {
  216. verb = strings.Replace(verb, "-", " ", 1)
  217. }
  218. verbs := strings.Split(verb, " ")
  219. var cmd []string
  220. if len(verbs) == 2 {
  221. cmd = []string{verbs[0], verbs[1], repoFullName}
  222. } else if isAnnexShell(verb) {
  223. repoAbsPath := setting.RepoRootPath + "/" + repoFullName
  224. if err := secureGitAnnex(repoAbsPath, requestMode); err != nil {
  225. fail("Git annex failed", "Git annex failed: %s", err)
  226. }
  227. cmd = args
  228. // Setting full path to repo as git-annex-shell requires it
  229. cmd[2] = repoAbsPath
  230. } else {
  231. cmd = []string{verb, repoFullName}
  232. }
  233. runGit(cmd, requestMode, user, owner, repo)
  234. return nil
  235. }
  236. func runGit(cmd [] string, requestMode models.AccessMode, user *models.User, owner *models.User,
  237. repo *models.Repository) error {
  238. log.Info("will exectute:%s", cmd)
  239. gitCmd := exec.Command(cmd[0], cmd[1:]...)
  240. if requestMode == models.ACCESS_MODE_WRITE {
  241. gitCmd.Env = append(os.Environ(), http.ComposeHookEnvs(http.ComposeHookEnvsOptions{
  242. AuthUser: user,
  243. OwnerName: owner.Name,
  244. OwnerSalt: owner.Salt,
  245. RepoID: repo.ID,
  246. RepoName: repo.Name,
  247. RepoPath: repo.RepoPath(),
  248. })...)
  249. }
  250. gitCmd.Dir = setting.RepoRootPath
  251. gitCmd.Stdout = os.Stdout
  252. gitCmd.Stdin = os.Stdin
  253. gitCmd.Stderr = os.Stderr
  254. log.Info("args:%s", gitCmd.Args)
  255. err := gitCmd.Run()
  256. log.Info("err:%s", err)
  257. if t, ok := err.(*exec.ExitError); ok {
  258. log.Info("t:%s", t)
  259. os.Exit(t.Sys().(syscall.WaitStatus).ExitStatus())
  260. }
  261. return nil
  262. }
  263. // Make sure git-annex-shell does not make "bad" changes (refectored from repo)
  264. func secureGitAnnex(path string, requestMode models.AccessMode) error {
  265. // "If set, disallows running git-shell to handle unknown commands."
  266. err := os.Setenv("GIT_ANNEX_SHELL_LIMITED", "True")
  267. if err != nil {
  268. return fmt.Errorf("ERROR: Could set annex shell to be limited.")
  269. }
  270. // "If set, git-annex-shell will refuse to run commands
  271. // that do not operate on the specified directory."
  272. err = os.Setenv("GIT_ANNEX_SHELL_DIRECTORY", path)
  273. if err != nil {
  274. return fmt.Errorf("ERROR: Could set annex shell directory.")
  275. }
  276. if ! (requestMode > models.ACCESS_MODE_READ) {
  277. err = os.Setenv("GIT_ANNEX_SHELL_READONLY", "True")
  278. if err != nil {
  279. return fmt.Errorf("ERROR: Could set annex shell to read only.")
  280. }
  281. }
  282. return nil
  283. }