serv.go 7.4 KB

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