serv.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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/routers/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) {
  76. ss := strings.SplitN(cmd, " ", 2)
  77. if len(ss) != 2 {
  78. return "", ""
  79. }
  80. return ss[0], strings.Replace(ss[1], "'/", "'", 1)
  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. }
  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 := os.Getenv("SSH_ORIGINAL_COMMAND")
  114. if len(sshCmd) == 0 {
  115. println("Hi there, You've successfully authenticated, but Gogs does not provide shell access.")
  116. println("If this is unexpected, please log in with password and setup Gogs under another user.")
  117. return nil
  118. }
  119. verb, args := parseSSHCmd(sshCmd)
  120. repoFullName := strings.ToLower(strings.Trim(args, "'"))
  121. repoFields := strings.SplitN(repoFullName, "/", 2)
  122. if len(repoFields) != 2 {
  123. fail("Invalid repository path", "Invalid repository path: %v", args)
  124. }
  125. ownerName := strings.ToLower(repoFields[0])
  126. repoName := strings.TrimSuffix(strings.ToLower(repoFields[1]), ".git")
  127. repoName = strings.TrimSuffix(repoName, ".wiki")
  128. owner, err := models.GetUserByName(ownerName)
  129. if err != nil {
  130. if errors.IsUserNotExist(err) {
  131. fail("Repository owner does not exist", "Unregistered owner: %s", ownerName)
  132. }
  133. fail("Internal error", "Fail to get repository owner '%s': %v", ownerName, err)
  134. }
  135. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  136. if err != nil {
  137. if errors.IsRepoNotExist(err) {
  138. fail(_ACCESS_DENIED_MESSAGE, "Repository does not exist: %s/%s", owner.Name, repoName)
  139. }
  140. fail("Internal error", "Fail to get repository: %v", err)
  141. }
  142. repo.Owner = owner
  143. requestMode, ok := allowedCommands[verb]
  144. if !ok {
  145. fail("Unknown git command", "Unknown git command '%s'", verb)
  146. }
  147. // Prohibit push to mirror repositories.
  148. if requestMode > models.ACCESS_MODE_READ && repo.IsMirror {
  149. fail("Mirror repository is read-only", "")
  150. }
  151. // Allow anonymous (user is nil) clone for public repositories.
  152. var user *models.User
  153. key, err := models.GetPublicKeyByID(com.StrTo(strings.TrimPrefix(c.Args()[0], "key-")).MustInt64())
  154. if err != nil {
  155. fail("Invalid key ID", "Invalid key ID '%s': %v", c.Args()[0], err)
  156. }
  157. if requestMode == models.ACCESS_MODE_WRITE || repo.IsPrivate {
  158. // Check deploy key or user key.
  159. if key.IsDeployKey() {
  160. if key.Mode < requestMode {
  161. fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
  162. }
  163. checkDeployKey(key, repo)
  164. } else {
  165. user, err = models.GetUserByKeyID(key.ID)
  166. if err != nil {
  167. fail("Internal error", "Fail to get user by key ID '%d': %v", key.ID, err)
  168. }
  169. mode, err := models.AccessLevel(user.ID, repo)
  170. if err != nil {
  171. fail("Internal error", "Fail to check access: %v", err)
  172. }
  173. if mode < requestMode {
  174. clientMessage := _ACCESS_DENIED_MESSAGE
  175. if mode >= models.ACCESS_MODE_READ {
  176. clientMessage = "You do not have sufficient authorization for this action"
  177. }
  178. fail(clientMessage,
  179. "User '%s' does not have level '%v' access to repository '%s'",
  180. user.Name, requestMode, repoFullName)
  181. }
  182. }
  183. } else {
  184. setting.NewService()
  185. // Check if the key can access to the repository in case of it is a deploy key (a deploy keys != user key).
  186. // A deploy key doesn't represent a signed in user, so in a site with Service.RequireSignInView activated
  187. // we should give read access only in repositories where this deploy key is in use. In other case, a server
  188. // or system using an active deploy key can get read access to all the repositories in a Gogs service.
  189. if key.IsDeployKey() && setting.Service.RequireSignInView {
  190. checkDeployKey(key, repo)
  191. }
  192. }
  193. // Update user key activity.
  194. if key.ID > 0 {
  195. key, err := models.GetPublicKeyByID(key.ID)
  196. if err != nil {
  197. fail("Internal error", "GetPublicKeyByID: %v", err)
  198. }
  199. key.Updated = time.Now()
  200. if err = models.UpdatePublicKey(key); err != nil {
  201. fail("Internal error", "UpdatePublicKey: %v", err)
  202. }
  203. }
  204. // Special handle for Windows.
  205. if setting.IsWindows {
  206. verb = strings.Replace(verb, "-", " ", 1)
  207. }
  208. var gitCmd *exec.Cmd
  209. verbs := strings.Split(verb, " ")
  210. if len(verbs) == 2 {
  211. gitCmd = exec.Command(verbs[0], verbs[1], repoFullName)
  212. } else {
  213. gitCmd = exec.Command(verb, repoFullName)
  214. }
  215. if requestMode == models.ACCESS_MODE_WRITE {
  216. gitCmd.Env = append(os.Environ(), http.ComposeHookEnvs(http.ComposeHookEnvsOptions{
  217. AuthUser: user,
  218. OwnerName: owner.Name,
  219. OwnerSalt: owner.Salt,
  220. RepoID: repo.ID,
  221. RepoName: repo.Name,
  222. RepoPath: repo.RepoPath(),
  223. })...)
  224. }
  225. gitCmd.Dir = setting.RepoRootPath
  226. gitCmd.Stdout = os.Stdout
  227. gitCmd.Stdin = os.Stdin
  228. gitCmd.Stderr = os.Stderr
  229. if err = gitCmd.Run(); err != nil {
  230. fail("Internal error", "Fail to execute git command: %v", err)
  231. }
  232. return nil
  233. }