serv.go 7.6 KB

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