serv.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. os.Exit(1)
  42. }
  43. func setup(c *cli.Context, logPath string, connectDB bool) {
  44. conf.HookMode = true
  45. var customConf string
  46. if c.IsSet("config") {
  47. customConf = c.String("config")
  48. } else if c.GlobalIsSet("config") {
  49. customConf = c.GlobalString("config")
  50. }
  51. err := conf.Init(customConf)
  52. if err != nil {
  53. fail("Internal error", "Failed to init configuration: %v", err)
  54. }
  55. conf.InitLogging(true)
  56. level := log.LevelTrace
  57. if conf.IsProdMode() {
  58. level = log.LevelError
  59. }
  60. err = log.NewFile(log.FileConfig{
  61. Level: level,
  62. Filename: filepath.Join(conf.Log.RootPath, logPath),
  63. FileRotationConfig: log.FileRotationConfig{
  64. Rotate: true,
  65. Daily: true,
  66. MaxDays: 3,
  67. },
  68. })
  69. if err != nil {
  70. fail("Internal error", "Failed to init file logger: %v", err)
  71. }
  72. log.Remove(log.DefaultConsoleName) // Remove the primary logger
  73. if !connectDB {
  74. return
  75. }
  76. if conf.UseSQLite3 {
  77. _ = os.Chdir(conf.WorkDir())
  78. }
  79. if err := db.SetEngine(); err != nil {
  80. fail("Internal error", "Failed to set database engine: %v", err)
  81. }
  82. }
  83. func parseSSHCmd(cmd string) (string, string) {
  84. ss := strings.SplitN(cmd, " ", 2)
  85. if len(ss) != 2 {
  86. return "", ""
  87. }
  88. return ss[0], strings.Replace(ss[1], "'/", "'", 1)
  89. }
  90. func checkDeployKey(key *db.PublicKey, repo *db.Repository) {
  91. // Check if this deploy key belongs to current repository.
  92. if !db.HasDeployKey(key.ID, repo.ID) {
  93. fail("Key access denied", "Deploy key access denied: [key_id: %d, repo_id: %d]", key.ID, repo.ID)
  94. }
  95. // Update deploy key activity.
  96. deployKey, err := db.GetDeployKeyByRepo(key.ID, repo.ID)
  97. if err != nil {
  98. fail("Internal error", "GetDeployKey: %v", err)
  99. }
  100. deployKey.Updated = time.Now()
  101. if err = db.UpdateDeployKey(deployKey); err != nil {
  102. fail("Internal error", "UpdateDeployKey: %v", err)
  103. }
  104. }
  105. var (
  106. allowedCommands = map[string]db.AccessMode{
  107. "git-upload-pack": db.ACCESS_MODE_READ,
  108. "git-upload-archive": db.ACCESS_MODE_READ,
  109. "git-receive-pack": db.ACCESS_MODE_WRITE,
  110. }
  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 len(sshCmd) == 0 {
  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.ACCESS_MODE_READ && 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.ACCESS_MODE_WRITE || 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, err := db.UserAccessMode(user.ID, repo)
  178. if err != nil {
  179. fail("Internal error", "Failed to check access: %v", err)
  180. }
  181. if mode < requestMode {
  182. clientMessage := _ACCESS_DENIED_MESSAGE
  183. if mode >= db.ACCESS_MODE_READ {
  184. clientMessage = "You do not have sufficient authorization for this action"
  185. }
  186. fail(clientMessage,
  187. "User '%s' does not have level '%v' access to repository '%s'",
  188. user.Name, requestMode, repoFullName)
  189. }
  190. }
  191. } else {
  192. // Check if the key can access to the repository in case of it is a deploy key (a deploy keys != user key).
  193. // A deploy key doesn't represent a signed in user, so in a site with Auth.RequireSignInView enabled,
  194. // we should give read access only in repositories where this deploy key is in use. In other cases,
  195. // a server or system using an active deploy key can get read access to all repositories on a Gogs instace.
  196. if key.IsDeployKey() && conf.Auth.RequireSigninView {
  197. checkDeployKey(key, repo)
  198. }
  199. }
  200. // Update user key activity.
  201. if key.ID > 0 {
  202. key, err := db.GetPublicKeyByID(key.ID)
  203. if err != nil {
  204. fail("Internal error", "GetPublicKeyByID: %v", err)
  205. }
  206. key.Updated = time.Now()
  207. if err = db.UpdatePublicKey(key); err != nil {
  208. fail("Internal error", "UpdatePublicKey: %v", err)
  209. }
  210. }
  211. // Special handle for Windows.
  212. if conf.IsWindowsRuntime() {
  213. verb = strings.Replace(verb, "-", " ", 1)
  214. }
  215. var gitCmd *exec.Cmd
  216. verbs := strings.Split(verb, " ")
  217. if len(verbs) == 2 {
  218. gitCmd = exec.Command(verbs[0], verbs[1], repoFullName)
  219. } else {
  220. gitCmd = exec.Command(verb, repoFullName)
  221. }
  222. if requestMode == db.ACCESS_MODE_WRITE {
  223. gitCmd.Env = append(os.Environ(), db.ComposeHookEnvs(db.ComposeHookEnvsOptions{
  224. AuthUser: user,
  225. OwnerName: owner.Name,
  226. OwnerSalt: owner.Salt,
  227. RepoID: repo.ID,
  228. RepoName: repo.Name,
  229. RepoPath: repo.RepoPath(),
  230. })...)
  231. }
  232. gitCmd.Dir = conf.Repository.Root
  233. gitCmd.Stdout = os.Stdout
  234. gitCmd.Stdin = os.Stdin
  235. gitCmd.Stderr = os.Stderr
  236. if err = gitCmd.Run(); err != nil {
  237. fail("Internal error", "Failed to execute git command: %v", err)
  238. }
  239. return nil
  240. }