serv.go 9.7 KB

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