serv.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. "github.com/G-Node/gogs/internal/conf"
  16. "github.com/G-Node/gogs/internal/db"
  17. "github.com/G-Node/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, "GIN:", 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 isAnnexShell(cmd string) bool {
  81. return cmd == "git-annex-shell"
  82. }
  83. func parseSSHCmd(cmd string) (string, string, []string) {
  84. // TODO: Check if extra arg (compared to upstream) is necessary
  85. ss := strings.Split(cmd, " ")
  86. if len(ss) < 2 {
  87. return "", "", nil
  88. }
  89. if isAnnexShell(ss[0]) {
  90. return ss[0], strings.Replace(ss[2], "/", "'", 1), ss
  91. }
  92. return ss[0], strings.Replace(ss[1], "/", "'", 1), ss
  93. }
  94. func checkDeployKey(key *db.PublicKey, repo *db.Repository) {
  95. // Check if this deploy key belongs to current repository.
  96. if !db.HasDeployKey(key.ID, repo.ID) {
  97. fail("Key access denied", "Deploy key access denied: [key_id: %d, repo_id: %d]", key.ID, repo.ID)
  98. }
  99. // Update deploy key activity.
  100. deployKey, err := db.GetDeployKeyByRepo(key.ID, repo.ID)
  101. if err != nil {
  102. fail("Internal error", "GetDeployKey: %v", err)
  103. }
  104. deployKey.Updated = time.Now()
  105. if err = db.UpdateDeployKey(deployKey); err != nil {
  106. fail("Internal error", "UpdateDeployKey: %v", err)
  107. }
  108. }
  109. var (
  110. allowedCommands = map[string]db.AccessMode{
  111. "git-upload-pack": db.ACCESS_MODE_READ,
  112. "git-upload-archive": db.ACCESS_MODE_READ,
  113. "git-receive-pack": db.ACCESS_MODE_WRITE,
  114. "git-annex-shell": db.ACCESS_MODE_READ,
  115. }
  116. )
  117. func runServ(c *cli.Context) error {
  118. setup(c, "serv.log", true)
  119. if conf.SSH.Disabled {
  120. println("GIN: SSH has been disabled")
  121. return nil
  122. }
  123. if len(c.Args()) < 1 {
  124. fail("Not enough arguments", "Not enough arguments")
  125. }
  126. sshCmd := strings.Replace(os.Getenv("SSH_ORIGINAL_COMMAND"), "'", "", -1)
  127. log.Info("SSH commadn:%s", sshCmd)
  128. if len(sshCmd) == 0 {
  129. println("Hi there, You've successfully authenticated, but GIN does not provide shell access.")
  130. return nil
  131. }
  132. verb, path, args := parseSSHCmd(sshCmd)
  133. repoFullName := strings.ToLower(strings.Trim(path, "'"))
  134. repoFields := strings.SplitN(repoFullName, "/", 2)
  135. if len(repoFields) != 2 {
  136. fail("Invalid repository path", "Invalid repository path: %v", path)
  137. }
  138. ownerName := strings.ToLower(repoFields[0])
  139. repoName := strings.TrimSuffix(strings.ToLower(repoFields[1]), ".git")
  140. repoName = strings.TrimSuffix(repoName, ".wiki")
  141. owner, err := db.GetUserByName(ownerName)
  142. if err != nil {
  143. if errors.IsUserNotExist(err) {
  144. fail("Repository owner does not exist", "Unregistered owner: %s", ownerName)
  145. }
  146. fail("Internal error", "Failed to get repository owner '%s': %v", ownerName, err)
  147. }
  148. repo, err := db.GetRepositoryByName(owner.ID, repoName)
  149. if err != nil {
  150. if errors.IsRepoNotExist(err) {
  151. fail(_ACCESS_DENIED_MESSAGE, "Repository does not exist: %s/%s", owner.Name, repoName)
  152. }
  153. fail("Internal error", "Failed to get repository: %v", err)
  154. }
  155. repo.Owner = owner
  156. requestMode, ok := allowedCommands[verb]
  157. if !ok {
  158. fail("Unknown git command", "Unknown git command '%s'", verb)
  159. }
  160. // Prohibit push to mirror repositories.
  161. if requestMode > db.ACCESS_MODE_READ && repo.IsMirror {
  162. fail("Mirror repository is read-only", "")
  163. }
  164. // Allow anonymous (user is nil) clone for public repositories.
  165. var user *db.User
  166. key, err := db.GetPublicKeyByID(com.StrTo(strings.TrimPrefix(c.Args()[0], "key-")).MustInt64())
  167. if err != nil {
  168. fail("Invalid key ID", "Invalid key ID '%s': %v", c.Args()[0], err)
  169. }
  170. if us, err := db.GetUserByKeyID(key.ID); err == nil {
  171. user = us
  172. } else {
  173. fail("Key Error", "Cannot find key %v", err)
  174. }
  175. if requestMode == db.ACCESS_MODE_WRITE || repo.IsPrivate {
  176. // Check deploy key or user key.
  177. if key.IsDeployKey() {
  178. if key.Mode < requestMode {
  179. fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
  180. }
  181. checkDeployKey(key, repo)
  182. } else {
  183. user, err = db.GetUserByKeyID(key.ID)
  184. if err != nil {
  185. fail("Internal error", "Failed to get user by key ID '%d': %v", key.ID, err)
  186. }
  187. mode, err := db.UserAccessMode(user.ID, repo)
  188. if err != nil {
  189. fail("Internal error", "Failed to check access: %v", err)
  190. }
  191. if mode < requestMode {
  192. clientMessage := _ACCESS_DENIED_MESSAGE
  193. if mode >= db.ACCESS_MODE_READ {
  194. clientMessage = "You do not have sufficient authorization for this action"
  195. }
  196. fail(clientMessage,
  197. "User '%s' does not have level '%v' access to repository '%s'",
  198. user.Name, requestMode, repoFullName)
  199. }
  200. }
  201. } else {
  202. conf.NewService()
  203. // Check if the key can access to the repository in case of it is a deploy key (a deploy keys != user key).
  204. // A deploy key doesn't represent a signed in user, so in a site with Service.RequireSignInView activated
  205. // we should give read access only in repositories where this deploy key is in use. In other case, a server
  206. // or system using an active deploy key can get read access to all the repositories in a Gogs service.
  207. if key.IsDeployKey() && conf.Service.RequireSignInView {
  208. checkDeployKey(key, repo)
  209. }
  210. }
  211. // Update user key activity.
  212. if key.ID > 0 {
  213. key, err := db.GetPublicKeyByID(key.ID)
  214. if err != nil {
  215. fail("Internal error", "GetPublicKeyByID: %v", err)
  216. }
  217. key.Updated = time.Now()
  218. if err = db.UpdatePublicKey(key); err != nil {
  219. fail("Internal error", "UpdatePublicKey: %v", err)
  220. }
  221. }
  222. // Special handle for Windows.
  223. // Todo will break with annex
  224. if conf.IsWindowsRuntime() {
  225. verb = strings.Replace(verb, "-", " ", 1)
  226. }
  227. verbs := strings.Split(verb, " ")
  228. var cmd []string
  229. if len(verbs) == 2 {
  230. cmd = []string{verbs[0], verbs[1], repoFullName}
  231. } else if isAnnexShell(verb) {
  232. repoAbsPath := conf.RepoRootPath + "/" + repoFullName
  233. if err := secureGitAnnex(repoAbsPath, user, repo); err != nil {
  234. fail("Git annex failed", "Git annex failed: %s", err)
  235. }
  236. cmd = args
  237. // Setting full path to repo as git-annex-shell requires it
  238. cmd[2] = repoAbsPath
  239. } else {
  240. cmd = []string{verb, repoFullName}
  241. }
  242. runGit(cmd, requestMode, user, owner, repo)
  243. if requestMode == db.ACCESS_MODE_WRITE {
  244. db.StartIndexing(*repo)
  245. }
  246. return nil
  247. }
  248. func runGit(cmd []string, requestMode db.AccessMode, user *db.User, owner *db.User,
  249. repo *db.Repository) error {
  250. log.Info("Running %q", cmd)
  251. gitCmd := exec.Command(cmd[0], cmd[1:]...)
  252. if requestMode == db.ACCESS_MODE_WRITE {
  253. gitCmd.Env = append(os.Environ(), db.ComposeHookEnvs(db.ComposeHookEnvsOptions{
  254. AuthUser: user,
  255. OwnerName: owner.Name,
  256. OwnerSalt: owner.Salt,
  257. RepoID: repo.ID,
  258. RepoName: repo.Name,
  259. RepoPath: repo.RepoPath(),
  260. })...)
  261. }
  262. gitCmd.Dir = conf.RepoRootPath
  263. gitCmd.Stdout = os.Stdout
  264. gitCmd.Stdin = os.Stdin
  265. gitCmd.Stderr = os.Stderr
  266. if err := gitCmd.Run(); err != nil {
  267. fail("Internal error", "Failed to execute git command: %v", err)
  268. }
  269. return nil
  270. }
  271. // Make sure git-annex-shell does not make "bad" changes (refectored from repo)
  272. func secureGitAnnex(path string, user *db.User, repo *db.Repository) error {
  273. // "If set, disallows running git-shell to handle unknown commands."
  274. err := os.Setenv("GIT_ANNEX_SHELL_LIMITED", "True")
  275. if err != nil {
  276. return fmt.Errorf("ERROR: Could set annex shell to be limited.")
  277. }
  278. // "If set, git-annex-shell will refuse to run commands
  279. // that do not operate on the specified directory."
  280. err = os.Setenv("GIT_ANNEX_SHELL_DIRECTORY", path)
  281. if err != nil {
  282. return fmt.Errorf("ERROR: Could set annex shell directory.")
  283. }
  284. mode := db.ACCESS_MODE_NONE
  285. if user != nil {
  286. mode, err = db.UserAccessMode(user.ID, repo)
  287. if err != nil {
  288. fail("Internal error", "Fail to check access: %v", err)
  289. }
  290. }
  291. if mode < db.ACCESS_MODE_WRITE {
  292. err = os.Setenv("GIT_ANNEX_SHELL_READONLY", "True")
  293. if err != nil {
  294. return fmt.Errorf("ERROR: Could set annex shell to read only.")
  295. }
  296. }
  297. return nil
  298. }