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. "syscall"
  16. "github.com/G-Node/gogs/models"
  17. "github.com/G-Node/gogs/models/errors"
  18. "github.com/G-Node/gogs/pkg/setting"
  19. )
  20. const (
  21. _ACCESS_DENIED_MESSAGE = "Repository does not exist or you do not have access"
  22. )
  23. var Serv = cli.Command{
  24. Name: "serv",
  25. Usage: "This command should only be called by SSH shell",
  26. Description: `Serv provide access auth for repositories`,
  27. Action: runServ,
  28. Flags: []cli.Flag{
  29. stringFlag("config, c", "custom/conf/app.ini", "Custom configuration file path"),
  30. },
  31. }
  32. func fail(userMessage, logMessage string, args ...interface{}) {
  33. fmt.Fprintln(os.Stderr, "GIN:", userMessage)
  34. if len(logMessage) > 0 {
  35. if !setting.ProdMode {
  36. fmt.Fprintf(os.Stderr, logMessage+"\n", args...)
  37. }
  38. log.Fatal(3, logMessage, args...)
  39. }
  40. os.Exit(1)
  41. }
  42. func setup(c *cli.Context, logPath string, connectDB bool) {
  43. if c.IsSet("config") {
  44. setting.CustomConf = c.String("config")
  45. } else if c.GlobalIsSet("config") {
  46. setting.CustomConf = c.GlobalString("config")
  47. }
  48. setting.NewContext()
  49. level := log.TRACE
  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 isAnnexShell(cmd string) bool {
  73. return cmd == "git-annex-shell"
  74. }
  75. func parseSSHCmd(cmd string) (string, string, []string) {
  76. ss := strings.Split(cmd, " ")
  77. if len(ss) < 2 {
  78. return "", "", nil
  79. }
  80. if isAnnexShell(ss[0]) {
  81. return ss[0], strings.Replace(ss[2], "/", "'", 1), ss
  82. } else {
  83. return ss[0], strings.Replace(ss[1], "/", "'", 1), ss
  84. }
  85. }
  86. func checkDeployKey(key *models.PublicKey, repo *models.Repository) {
  87. // Check if this deploy key belongs to current repository.
  88. if !models.HasDeployKey(key.ID, repo.ID) {
  89. fail("Key access denied", "Deploy key access denied: [key_id: %d, repo_id: %d]", key.ID, repo.ID)
  90. }
  91. // Update deploy key activity.
  92. deployKey, err := models.GetDeployKeyByRepo(key.ID, repo.ID)
  93. if err != nil {
  94. fail("Internal error", "GetDeployKey: %v", err)
  95. }
  96. deployKey.Updated = time.Now()
  97. if err = models.UpdateDeployKey(deployKey); err != nil {
  98. fail("Internal error", "UpdateDeployKey: %v", err)
  99. }
  100. }
  101. var (
  102. allowedCommands = map[string]models.AccessMode{
  103. "git-upload-pack": models.ACCESS_MODE_READ,
  104. "git-upload-archive": models.ACCESS_MODE_READ,
  105. "git-receive-pack": models.ACCESS_MODE_WRITE,
  106. "git-annex-shell": models.ACCESS_MODE_READ,
  107. }
  108. )
  109. func runServ(c *cli.Context) error {
  110. setup(c, "serv.log", true)
  111. if setting.SSH.Disabled {
  112. println("GIN: SSH has been disabled")
  113. return nil
  114. }
  115. if len(c.Args()) < 1 {
  116. fail("Not enough arguments", "Not enough arguments")
  117. }
  118. sshCmd := strings.Replace(os.Getenv("SSH_ORIGINAL_COMMAND"), "'", "", -1)
  119. log.Info("SSH commadn:%s", sshCmd)
  120. if len(sshCmd) == 0 {
  121. println("Hi there, You've successfully authenticated, but GIN does not provide shell access.")
  122. return nil
  123. }
  124. verb, path, args := parseSSHCmd(sshCmd)
  125. repoFullName := strings.ToLower(strings.Trim(path, "'"))
  126. repoFields := strings.SplitN(repoFullName, "/", 2)
  127. if len(repoFields) != 2 {
  128. fail("Invalid repository path", "Invalid repository path: %v", path)
  129. }
  130. ownerName := strings.ToLower(repoFields[0])
  131. repoName := strings.TrimSuffix(strings.ToLower(repoFields[1]), ".git")
  132. repoName = strings.TrimSuffix(repoName, ".wiki")
  133. owner, err := models.GetUserByName(ownerName)
  134. if err != nil {
  135. if errors.IsUserNotExist(err) {
  136. fail("Repository owner does not exist", "Unregistered owner: %s", ownerName)
  137. }
  138. fail("Internal error", "Fail to get repository owner '%s': %v", ownerName, err)
  139. }
  140. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  141. if err != nil {
  142. if errors.IsRepoNotExist(err) {
  143. fail(_ACCESS_DENIED_MESSAGE, "Repository does not exist: %s/%s", owner.Name, repoName)
  144. }
  145. fail("Internal error", "Fail to get repository: %v", err)
  146. }
  147. repo.Owner = owner
  148. requestMode, ok := allowedCommands[verb]
  149. if !ok {
  150. fail("Unknown git command", "Unknown git command '%s'", verb)
  151. }
  152. // Prohibit push to mirror repositories.
  153. if requestMode > models.ACCESS_MODE_READ && repo.IsMirror {
  154. fail("Mirror repository is read-only", "")
  155. }
  156. // Allow anonymous (user is nil) clone for public repositories.
  157. var user *models.User
  158. key, err := models.GetPublicKeyByID(com.StrTo(strings.TrimPrefix(c.Args()[0], "key-")).MustInt64())
  159. if err != nil {
  160. fail("Invalid key ID", "Invalid key ID '%s': %v", c.Args()[0], err)
  161. }
  162. if us, err := models.GetUserByKeyID(key.ID); err == nil {
  163. user = us
  164. } else {
  165. fail("Key Error", "Cannot find key %v", err)
  166. }
  167. if requestMode == models.ACCESS_MODE_WRITE || repo.IsPrivate {
  168. // Check deploy key or user key.
  169. if key.IsDeployKey() {
  170. if key.Mode < requestMode {
  171. fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
  172. }
  173. checkDeployKey(key, repo)
  174. } else {
  175. user, err = models.GetUserByKeyID(key.ID)
  176. if err != nil {
  177. fail("Internal error", "Fail to get user by key ID '%d': %v", key.ID, err)
  178. }
  179. mode, err := models.UserAccessMode(user.ID, repo)
  180. if err != nil {
  181. fail("Internal error", "Fail to check access: %v", err)
  182. }
  183. if mode < requestMode {
  184. clientMessage := _ACCESS_DENIED_MESSAGE
  185. if mode >= models.ACCESS_MODE_READ {
  186. clientMessage = "You do not have sufficient authorization for this action"
  187. }
  188. fail(clientMessage,
  189. "User '%s' does not have level '%v' access to repository '%s'",
  190. user.Name, requestMode, repoFullName)
  191. }
  192. }
  193. } else {
  194. setting.NewService()
  195. // Check if the key can access to the repository in case of it is a deploy key (a deploy keys != user key).
  196. // A deploy key doesn't represent a signed in user, so in a site with Service.RequireSignInView activated
  197. // we should give read access only in repositories where this deploy key is in use. In other case, a server
  198. // or system using an active deploy key can get read access to all the repositories in a Gogs service.
  199. if key.IsDeployKey() && setting.Service.RequireSignInView {
  200. checkDeployKey(key, repo)
  201. }
  202. }
  203. // Update user key activity.
  204. if key.ID > 0 {
  205. key, err := models.GetPublicKeyByID(key.ID)
  206. if err != nil {
  207. fail("Internal error", "GetPublicKeyByID: %v", err)
  208. }
  209. key.Updated = time.Now()
  210. if err = models.UpdatePublicKey(key); err != nil {
  211. fail("Internal error", "UpdatePublicKey: %v", err)
  212. }
  213. }
  214. // Special handle for Windows.
  215. // Todo will break with annex
  216. if setting.IsWindows {
  217. verb = strings.Replace(verb, "-", " ", 1)
  218. }
  219. verbs := strings.Split(verb, " ")
  220. var cmd []string
  221. if len(verbs) == 2 {
  222. cmd = []string{verbs[0], verbs[1], repoFullName}
  223. } else if isAnnexShell(verb) {
  224. repoAbsPath := setting.RepoRootPath + "/" + repoFullName
  225. if err := secureGitAnnex(repoAbsPath, user, repo); err != nil {
  226. fail("Git annex failed", "Git annex failed: %s", err)
  227. }
  228. cmd = args
  229. // Setting full path to repo as git-annex-shell requires it
  230. cmd[2] = repoAbsPath
  231. } else {
  232. cmd = []string{verb, repoFullName}
  233. }
  234. runGit(cmd, requestMode, user, owner, repo)
  235. if requestMode == models.ACCESS_MODE_WRITE {
  236. models.StartIndexing(*repo)
  237. }
  238. return nil
  239. }
  240. func runGit(cmd []string, requestMode models.AccessMode, user *models.User, owner *models.User,
  241. repo *models.Repository) error {
  242. log.Info("will exectute:%s", cmd)
  243. gitCmd := exec.Command(cmd[0], cmd[1:]...)
  244. if requestMode == models.ACCESS_MODE_WRITE {
  245. gitCmd.Env = append(os.Environ(), models.ComposeHookEnvs(models.ComposeHookEnvsOptions{
  246. AuthUser: user,
  247. OwnerName: owner.Name,
  248. OwnerSalt: owner.Salt,
  249. RepoID: repo.ID,
  250. RepoName: repo.Name,
  251. RepoPath: repo.RepoPath(),
  252. })...)
  253. }
  254. gitCmd.Dir = setting.RepoRootPath
  255. gitCmd.Stdout = os.Stdout
  256. gitCmd.Stdin = os.Stdin
  257. gitCmd.Stderr = os.Stderr
  258. log.Info("args:%s", gitCmd.Args)
  259. err := gitCmd.Run()
  260. log.Info("err:%s", err)
  261. if t, ok := err.(*exec.ExitError); ok {
  262. log.Info("t:%s", t)
  263. os.Exit(t.Sys().(syscall.WaitStatus).ExitStatus())
  264. }
  265. return nil
  266. }
  267. // Make sure git-annex-shell does not make "bad" changes (refectored from repo)
  268. func secureGitAnnex(path string, user *models.User, repo *models.Repository) error {
  269. // "If set, disallows running git-shell to handle unknown commands."
  270. err := os.Setenv("GIT_ANNEX_SHELL_LIMITED", "True")
  271. if err != nil {
  272. return fmt.Errorf("ERROR: Could set annex shell to be limited.")
  273. }
  274. // "If set, git-annex-shell will refuse to run commands
  275. // that do not operate on the specified directory."
  276. err = os.Setenv("GIT_ANNEX_SHELL_DIRECTORY", path)
  277. if err != nil {
  278. return fmt.Errorf("ERROR: Could set annex shell directory.")
  279. }
  280. mode := models.ACCESS_MODE_NONE
  281. if user != nil {
  282. mode, err = models.UserAccessMode(user.ID, repo)
  283. if err != nil {
  284. fail("Internal error", "Fail to check access: %v", err)
  285. }
  286. }
  287. if mode < models.ACCESS_MODE_WRITE {
  288. err = os.Setenv("GIT_ANNEX_SHELL_READONLY", "True")
  289. if err != nil {
  290. return fmt.Errorf("ERROR: Could set annex shell to read only.")
  291. }
  292. }
  293. return nil
  294. }