serv.go 7.4 KB

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