serv.go 7.9 KB

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