serv.go 7.4 KB

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