serv.go 8.0 KB

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