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