serv.go 9.5 KB

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