serv.go 9.4 KB

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