serv.go 9.5 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/G-Node/gogs/models"
  16. "github.com/G-Node/gogs/models/errors"
  17. "github.com/G-Node/gogs/pkg/setting"
  18. http "github.com/G-Node/gogs/routes/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. log.New(log.FILE, log.FileConfig{
  52. Level: level,
  53. Filename: filepath.Join(setting.LogRootPath, logPath),
  54. FileRotationConfig: log.FileRotationConfig{
  55. Rotate: true,
  56. Daily: true,
  57. MaxDays: 3,
  58. },
  59. })
  60. log.Delete(log.CONSOLE) // Remove primary logger
  61. if !connectDB {
  62. return
  63. }
  64. models.LoadConfigs()
  65. if setting.UseSQLite3 {
  66. workDir, _ := setting.WorkDir()
  67. os.Chdir(workDir)
  68. }
  69. if err := models.SetEngine(); err != nil {
  70. fail("Internal error", "SetEngine: %v", err)
  71. }
  72. }
  73. func isAnnexShell(cmd string) bool {
  74. return cmd == "git-annex-shell"
  75. }
  76. func parseSSHCmd(cmd string) (string, string, []string) {
  77. ss := strings.Split(cmd, " ")
  78. if len(ss) < 2 {
  79. return "", "", nil
  80. }
  81. if isAnnexShell(ss[0]) {
  82. return ss[0], strings.Replace(ss[2], "/", "'", 1), ss
  83. } else {
  84. return ss[0], strings.Replace(ss[1], "/", "'", 1), ss
  85. }
  86. }
  87. func checkDeployKey(key *models.PublicKey, repo *models.Repository) {
  88. // Check if this deploy key belongs to current repository.
  89. if !models.HasDeployKey(key.ID, repo.ID) {
  90. fail("Key access denied", "Deploy key access denied: [key_id: %d, repo_id: %d]", key.ID, repo.ID)
  91. }
  92. // Update deploy key activity.
  93. deployKey, err := models.GetDeployKeyByRepo(key.ID, repo.ID)
  94. if err != nil {
  95. fail("Internal error", "GetDeployKey: %v", err)
  96. }
  97. deployKey.Updated = time.Now()
  98. if err = models.UpdateDeployKey(deployKey); err != nil {
  99. fail("Internal error", "UpdateDeployKey: %v", err)
  100. }
  101. }
  102. var (
  103. allowedCommands = map[string]models.AccessMode{
  104. "git-upload-pack": models.ACCESS_MODE_READ,
  105. "git-upload-archive": models.ACCESS_MODE_READ,
  106. "git-receive-pack": models.ACCESS_MODE_WRITE,
  107. "git-annex-shell": models.ACCESS_MODE_READ,
  108. }
  109. )
  110. func runServ(c *cli.Context) error {
  111. setup(c, "serv.log", true)
  112. if setting.SSH.Disabled {
  113. println("Gins: SSH has been disabled")
  114. return nil
  115. }
  116. if len(c.Args()) < 1 {
  117. fail("Not enough arguments", "Not enough arguments")
  118. }
  119. sshCmd := strings.Replace(os.Getenv("SSH_ORIGINAL_COMMAND"), "'", "", -1)
  120. log.Info("SSH commadn:%s", sshCmd)
  121. if len(sshCmd) == 0 {
  122. println("Hi there, You've successfully authenticated, but Gin does not provide shell access.")
  123. return nil
  124. }
  125. verb, path, args := parseSSHCmd(sshCmd)
  126. repoFullName := strings.ToLower(strings.Trim(path, "'"))
  127. repoFields := strings.SplitN(repoFullName, "/", 2)
  128. if len(repoFields) != 2 {
  129. fail("Invalid repository path", "Invalid repository path: %v", path)
  130. }
  131. ownerName := strings.ToLower(repoFields[0])
  132. repoName := strings.TrimSuffix(strings.ToLower(repoFields[1]), ".git")
  133. repoName = strings.TrimSuffix(repoName, ".wiki")
  134. owner, err := models.GetUserByName(ownerName)
  135. if err != nil {
  136. if errors.IsUserNotExist(err) {
  137. fail("Repository owner does not exist", "Unregistered owner: %s", ownerName)
  138. }
  139. fail("Internal error", "Fail to get repository owner '%s': %v", ownerName, err)
  140. }
  141. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  142. if err != nil {
  143. if errors.IsRepoNotExist(err) {
  144. fail(_ACCESS_DENIED_MESSAGE, "Repository does not exist: %s/%s", owner.Name, repoName)
  145. }
  146. fail("Internal error", "Fail to get repository: %v", err)
  147. }
  148. repo.Owner = owner
  149. requestMode, ok := allowedCommands[verb]
  150. if !ok {
  151. fail("Unknown git command", "Unknown git command '%s'", verb)
  152. }
  153. // Prohibit push to mirror repositories.
  154. if requestMode > models.ACCESS_MODE_READ && repo.IsMirror {
  155. fail("Mirror repository is read-only", "")
  156. }
  157. // Allow anonymous (user is nil) clone for public repositories.
  158. var user *models.User
  159. key, err := models.GetPublicKeyByID(com.StrTo(strings.TrimPrefix(c.Args()[0], "key-")).MustInt64())
  160. if err != nil {
  161. fail("Invalid key ID", "Invalid key ID '%s': %v", c.Args()[0], err)
  162. }
  163. if us, err := models.GetUserByKeyID(key.ID); err == nil {
  164. user = us
  165. } else {
  166. fail("Key Error", "Cannot find key %v", err)
  167. }
  168. if requestMode == models.ACCESS_MODE_WRITE || repo.IsPrivate {
  169. // Check deploy key or user key.
  170. if key.IsDeployKey() {
  171. if key.Mode < requestMode {
  172. fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
  173. }
  174. checkDeployKey(key, repo)
  175. } else {
  176. user, err = models.GetUserByKeyID(key.ID)
  177. if err != nil {
  178. fail("Internal error", "Fail to get user by key ID '%d': %v", key.ID, err)
  179. }
  180. mode, err := models.AccessLevel(user.ID, repo)
  181. if err != nil {
  182. fail("Internal error", "Fail to check access: %v", err)
  183. }
  184. if mode < requestMode {
  185. clientMessage := _ACCESS_DENIED_MESSAGE
  186. if mode >= models.ACCESS_MODE_READ {
  187. clientMessage = "You do not have sufficient authorization for this action"
  188. }
  189. fail(clientMessage,
  190. "User '%s' does not have level '%v' access to repository '%s'",
  191. user.Name, requestMode, repoFullName)
  192. }
  193. }
  194. } else {
  195. setting.NewService()
  196. // Check if the key can access to the repository in case of it is a deploy key (a deploy keys != user key).
  197. // A deploy key doesn't represent a signed in user, so in a site with Service.RequireSignInView activated
  198. // we should give read access only in repositories where this deploy key is in use. In other case, a server
  199. // or system using an active deploy key can get read access to all the repositories in a Gogs service.
  200. if key.IsDeployKey() && setting.Service.RequireSignInView {
  201. checkDeployKey(key, repo)
  202. }
  203. }
  204. // Update user key activity.
  205. if key.ID > 0 {
  206. key, err := models.GetPublicKeyByID(key.ID)
  207. if err != nil {
  208. fail("Internal error", "GetPublicKeyByID: %v", err)
  209. }
  210. key.Updated = time.Now()
  211. if err = models.UpdatePublicKey(key); err != nil {
  212. fail("Internal error", "UpdatePublicKey: %v", err)
  213. }
  214. }
  215. // Special handle for Windows.
  216. // Todo will break with annex
  217. if setting.IsWindows {
  218. verb = strings.Replace(verb, "-", " ", 1)
  219. }
  220. verbs := strings.Split(verb, " ")
  221. var cmd []string
  222. if len(verbs) == 2 {
  223. cmd = []string{verbs[0], verbs[1], repoFullName}
  224. } else if isAnnexShell(verb) {
  225. repoAbsPath := setting.RepoRootPath + "/" + repoFullName
  226. if err := secureGitAnnex(repoAbsPath, user, repo); err != nil {
  227. fail("Git annex failed", "Git annex failed: %s", err)
  228. }
  229. cmd = args
  230. // Setting full path to repo as git-annex-shell requires it
  231. cmd[2] = repoAbsPath
  232. } else {
  233. cmd = []string{verb, repoFullName}
  234. }
  235. runGit(cmd, requestMode, user, owner, repo)
  236. if setting.Search.Do && (requestMode == models.ACCESS_MODE_WRITE) {
  237. models.StartIndexing(user, owner, repo)
  238. }
  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. }