serv.go 7.7 KB

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