serv.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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_READ,
  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 us, err := models.GetUserByKeyID(key.ID); err == nil {
  167. user = us
  168. } else {
  169. fail("Key Error", "Cannot find key %v", err)
  170. }
  171. if requestMode == models.ACCESS_MODE_WRITE || repo.IsPrivate {
  172. // Check deploy key or user key.
  173. if key.IsDeployKey() {
  174. if key.Mode < requestMode {
  175. fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
  176. }
  177. checkDeployKey(key, repo)
  178. } else {
  179. user, err = models.GetUserByKeyID(key.ID)
  180. if err != nil {
  181. fail("Internal error", "Fail to get user by key ID '%d': %v", key.ID, err)
  182. }
  183. mode, err := models.AccessLevel(user.ID, repo)
  184. if err != nil {
  185. fail("Internal error", "Fail to check access: %v", err)
  186. }
  187. if mode < requestMode {
  188. clientMessage := _ACCESS_DENIED_MESSAGE
  189. if mode >= models.ACCESS_MODE_READ {
  190. clientMessage = "You do not have sufficient authorization for this action"
  191. }
  192. fail(clientMessage,
  193. "User '%s' does not have level '%v' access to repository '%s'",
  194. user.Name, requestMode, repoFullName)
  195. }
  196. }
  197. } else {
  198. setting.NewService()
  199. // Check if the key can access to the repository in case of it is a deploy key (a deploy keys != user key).
  200. // A deploy key doesn't represent a signed in user, so in a site with Service.RequireSignInView activated
  201. // we should give read access only in repositories where this deploy key is in use. In other case, a server
  202. // or system using an active deploy key can get read access to all the repositories in a Gogs service.
  203. if key.IsDeployKey() && setting.Service.RequireSignInView {
  204. checkDeployKey(key, repo)
  205. }
  206. }
  207. // Update user key activity.
  208. if key.ID > 0 {
  209. key, err := models.GetPublicKeyByID(key.ID)
  210. if err != nil {
  211. fail("Internal error", "GetPublicKeyByID: %v", err)
  212. }
  213. key.Updated = time.Now()
  214. if err = models.UpdatePublicKey(key); err != nil {
  215. fail("Internal error", "UpdatePublicKey: %v", err)
  216. }
  217. }
  218. // Special handle for Windows.
  219. // Todo will break with annex
  220. if setting.IsWindows {
  221. verb = strings.Replace(verb, "-", " ", 1)
  222. }
  223. verbs := strings.Split(verb, " ")
  224. var cmd []string
  225. if len(verbs) == 2 {
  226. cmd = []string{verbs[0], verbs[1], repoFullName}
  227. } else if isAnnexShell(verb) {
  228. repoAbsPath := setting.RepoRootPath + "/" + repoFullName
  229. if err := secureGitAnnex(repoAbsPath, user, repo); err != nil {
  230. fail("Git annex failed", "Git annex failed: %s", err)
  231. }
  232. cmd = args
  233. // Setting full path to repo as git-annex-shell requires it
  234. cmd[2] = repoAbsPath
  235. } else {
  236. cmd = []string{verb, repoFullName}
  237. }
  238. runGit(cmd, requestMode, user, owner, repo)
  239. return nil
  240. }
  241. func runGit(cmd []string, requestMode models.AccessMode, user *models.User, owner *models.User,
  242. repo *models.Repository) error {
  243. log.Info("will exectute:%s", cmd)
  244. gitCmd := exec.Command(cmd[0], cmd[1:]...)
  245. if requestMode == models.ACCESS_MODE_WRITE {
  246. gitCmd.Env = append(os.Environ(), http.ComposeHookEnvs(http.ComposeHookEnvsOptions{
  247. AuthUser: user,
  248. OwnerName: owner.Name,
  249. OwnerSalt: owner.Salt,
  250. RepoID: repo.ID,
  251. RepoName: repo.Name,
  252. RepoPath: repo.RepoPath(),
  253. })...)
  254. }
  255. gitCmd.Dir = setting.RepoRootPath
  256. gitCmd.Stdout = os.Stdout
  257. gitCmd.Stdin = os.Stdin
  258. gitCmd.Stderr = os.Stderr
  259. log.Info("args:%s", gitCmd.Args)
  260. err := gitCmd.Run()
  261. log.Info("err:%s", err)
  262. if t, ok := err.(*exec.ExitError); ok {
  263. log.Info("t:%s", t)
  264. os.Exit(t.Sys().(syscall.WaitStatus).ExitStatus())
  265. }
  266. return nil
  267. }
  268. // Make sure git-annex-shell does not make "bad" changes (refectored from repo)
  269. func secureGitAnnex(path string, user *models.User, repo *models.Repository) error {
  270. // "If set, disallows running git-shell to handle unknown commands."
  271. err := os.Setenv("GIT_ANNEX_SHELL_LIMITED", "True")
  272. if err != nil {
  273. return fmt.Errorf("ERROR: Could set annex shell to be limited.")
  274. }
  275. // "If set, git-annex-shell will refuse to run commands
  276. // that do not operate on the specified directory."
  277. err = os.Setenv("GIT_ANNEX_SHELL_DIRECTORY", path)
  278. if err != nil {
  279. return fmt.Errorf("ERROR: Could set annex shell directory.")
  280. }
  281. mode := models.ACCESS_MODE_NONE
  282. if user != nil {
  283. mode, err = models.AccessLevel(user.ID, repo)
  284. if err != nil {
  285. fail("Internal error", "Fail to check access: %v", err)
  286. }
  287. }
  288. if mode < models.ACCESS_MODE_WRITE {
  289. err = os.Setenv("GIT_ANNEX_SHELL_READONLY", "True")
  290. if err != nil {
  291. return fmt.Errorf("ERROR: Could set annex shell to read only.")
  292. }
  293. }
  294. return nil
  295. }