serv.go 9.7 KB

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