serv.go 7.4 KB

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