serv.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "path/filepath"
  8. "strings"
  9. "time"
  10. "github.com/unknwon/com"
  11. "github.com/urfave/cli"
  12. log "unknwon.dev/clog/v2"
  13. "gogs.io/gogs/internal/conf"
  14. "gogs.io/gogs/internal/database"
  15. )
  16. const (
  17. accessDeniedMessage = "Repository does not exist or you do not have access"
  18. )
  19. var Serv = cli.Command{
  20. Name: "serv",
  21. Usage: "This command should only be called by SSH shell",
  22. Description: `Serv provide access auth for repositories`,
  23. Action: runServ,
  24. Flags: []cli.Flag{
  25. stringFlag("config, c", "", "Custom configuration file path"),
  26. },
  27. }
  28. // fail prints user message to the Git client (i.e. os.Stderr) and
  29. // logs error message on the server side. When not in "prod" mode,
  30. // error message is also printed to the client for easier debugging.
  31. func fail(userMessage, errMessage string, args ...any) {
  32. _, _ = fmt.Fprintln(os.Stderr, "Gogs:", userMessage)
  33. if len(errMessage) > 0 {
  34. if !conf.IsProdMode() {
  35. fmt.Fprintf(os.Stderr, errMessage+"\n", args...)
  36. }
  37. log.Error(errMessage, args...)
  38. }
  39. log.Stop()
  40. os.Exit(1)
  41. }
  42. func setup(c *cli.Context, logFile string, connectDB bool) {
  43. conf.HookMode = true
  44. var customConf string
  45. if c.IsSet("config") {
  46. customConf = c.String("config")
  47. } else if c.GlobalIsSet("config") {
  48. customConf = c.GlobalString("config")
  49. }
  50. err := conf.Init(customConf)
  51. if err != nil {
  52. fail("Internal error", "Failed to init configuration: %v", err)
  53. }
  54. conf.InitLogging(true)
  55. level := log.LevelTrace
  56. if conf.IsProdMode() {
  57. level = log.LevelError
  58. }
  59. err = log.NewFile(log.FileConfig{
  60. Level: level,
  61. Filename: filepath.Join(conf.Log.RootPath, "hooks", logFile),
  62. FileRotationConfig: log.FileRotationConfig{
  63. Rotate: true,
  64. Daily: true,
  65. MaxDays: 3,
  66. },
  67. })
  68. if err != nil {
  69. fail("Internal error", "Failed to init file logger: %v", err)
  70. }
  71. log.Remove(log.DefaultConsoleName) // Remove the primary logger
  72. if !connectDB {
  73. return
  74. }
  75. if conf.UseSQLite3 {
  76. _ = os.Chdir(conf.WorkDir())
  77. }
  78. if _, err := database.SetEngine(); err != nil {
  79. fail("Internal error", "Failed to set database engine: %v", err)
  80. }
  81. }
  82. func parseSSHCmd(cmd string) (string, string) {
  83. ss := strings.SplitN(cmd, " ", 2)
  84. if len(ss) != 2 {
  85. return "", ""
  86. }
  87. return ss[0], strings.Replace(ss[1], "'/", "'", 1)
  88. }
  89. func checkDeployKey(key *database.PublicKey, repo *database.Repository) {
  90. // Check if this deploy key belongs to current repository.
  91. if !database.HasDeployKey(key.ID, repo.ID) {
  92. fail("Key access denied", "Deploy key access denied: [key_id: %d, repo_id: %d]", key.ID, repo.ID)
  93. }
  94. // Update deploy key activity.
  95. deployKey, err := database.GetDeployKeyByRepo(key.ID, repo.ID)
  96. if err != nil {
  97. fail("Internal error", "GetDeployKey: %v", err)
  98. }
  99. deployKey.Updated = time.Now()
  100. if err = database.UpdateDeployKey(deployKey); err != nil {
  101. fail("Internal error", "UpdateDeployKey: %v", err)
  102. }
  103. }
  104. var allowedCommands = map[string]database.AccessMode{
  105. "git-upload-pack": database.AccessModeRead,
  106. "git-upload-archive": database.AccessModeRead,
  107. "git-receive-pack": database.AccessModeWrite,
  108. }
  109. func runServ(c *cli.Context) error {
  110. ctx := context.Background()
  111. setup(c, "serv.log", true)
  112. if conf.SSH.Disabled {
  113. println("Gogs: SSH has been disabled")
  114. return nil
  115. }
  116. if len(c.Args()) < 1 {
  117. fail("Not enough arguments", "Not enough arguments")
  118. }
  119. sshCmd := os.Getenv("SSH_ORIGINAL_COMMAND")
  120. if sshCmd == "" {
  121. println("Hi there, You've successfully authenticated, but Gogs does not provide shell access.")
  122. println("If this is unexpected, please log in with password and setup Gogs under another user.")
  123. return nil
  124. }
  125. verb, args := parseSSHCmd(sshCmd)
  126. repoFullName := strings.ToLower(strings.Trim(args, "'"))
  127. repoFields := strings.SplitN(repoFullName, "/", 2)
  128. if len(repoFields) != 2 {
  129. fail("Invalid repository path", "Invalid repository path: %v", args)
  130. }
  131. ownerName := strings.ToLower(repoFields[0])
  132. repoName := strings.TrimSuffix(strings.ToLower(repoFields[1]), ".git")
  133. repoName = strings.TrimSuffix(repoName, ".wiki")
  134. owner, err := database.Handle.Users().GetByUsername(ctx, ownerName)
  135. if err != nil {
  136. if database.IsErrUserNotExist(err) {
  137. fail("Repository owner does not exist", "Unregistered owner: %s", ownerName)
  138. }
  139. fail("Internal error", "Failed to get repository owner '%s': %v", ownerName, err)
  140. }
  141. repo, err := database.GetRepositoryByName(owner.ID, repoName)
  142. if err != nil {
  143. if database.IsErrRepoNotExist(err) {
  144. fail(accessDeniedMessage, "Repository does not exist: %s/%s", owner.Name, repoName)
  145. }
  146. fail("Internal error", "Failed to get repository: %v", err)
  147. }
  148. repo.Owner = owner
  149. requestMode, ok := allowedCommands[verb]
  150. if !ok {
  151. fail("Unknown git command", "Unknown git command '%s'", verb)
  152. }
  153. // Prohibit push to mirror repositories.
  154. if requestMode > database.AccessModeRead && repo.IsMirror {
  155. fail("Mirror repository is read-only", "")
  156. }
  157. // Allow anonymous (user is nil) clone for public repositories.
  158. var user *database.User
  159. key, err := database.GetPublicKeyByID(com.StrTo(strings.TrimPrefix(c.Args()[0], "key-")).MustInt64())
  160. if err != nil {
  161. fail("Invalid key ID", "Invalid key ID '%s': %v", c.Args()[0], err)
  162. }
  163. if requestMode == database.AccessModeWrite || repo.IsPrivate {
  164. // Check deploy key or user key.
  165. if key.IsDeployKey() {
  166. if key.Mode < requestMode {
  167. fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
  168. }
  169. checkDeployKey(key, repo)
  170. } else {
  171. user, err = database.Handle.Users().GetByKeyID(ctx, key.ID)
  172. if err != nil {
  173. fail("Internal error", "Failed to get user by key ID '%d': %v", key.ID, err)
  174. }
  175. mode := database.Handle.Permissions().AccessMode(ctx, user.ID, repo.ID,
  176. database.AccessModeOptions{
  177. OwnerID: repo.OwnerID,
  178. Private: repo.IsPrivate,
  179. },
  180. )
  181. if mode < requestMode {
  182. clientMessage := accessDeniedMessage
  183. if mode >= database.AccessModeRead {
  184. clientMessage = "You do not have sufficient authorization for this action"
  185. }
  186. fail(clientMessage,
  187. "User '%s' does not have level '%v' access to repository '%s'",
  188. user.Name, requestMode, repoFullName)
  189. }
  190. }
  191. } else {
  192. // Check if the key can access to the repository in case of it is a deploy key (a deploy keys != user key).
  193. // A deploy key doesn't represent a signed in user, so in a site with Auth.RequireSignInView enabled,
  194. // we should give read access only in repositories where this deploy key is in use. In other cases,
  195. // a server or system using an active deploy key can get read access to all repositories on a Gogs instance.
  196. if key.IsDeployKey() && conf.Auth.RequireSigninView {
  197. checkDeployKey(key, repo)
  198. }
  199. }
  200. // Update user key activity.
  201. if key.ID > 0 {
  202. key, err := database.GetPublicKeyByID(key.ID)
  203. if err != nil {
  204. fail("Internal error", "GetPublicKeyByID: %v", err)
  205. }
  206. key.Updated = time.Now()
  207. if err = database.UpdatePublicKey(key); err != nil {
  208. fail("Internal error", "UpdatePublicKey: %v", err)
  209. }
  210. }
  211. // Special handle for Windows.
  212. if conf.IsWindowsRuntime() {
  213. verb = strings.Replace(verb, "-", " ", 1)
  214. }
  215. var gitCmd *exec.Cmd
  216. verbs := strings.Split(verb, " ")
  217. if len(verbs) == 2 {
  218. gitCmd = exec.Command(verbs[0], verbs[1], repoFullName)
  219. } else {
  220. gitCmd = exec.Command(verb, repoFullName)
  221. }
  222. if requestMode == database.AccessModeWrite {
  223. gitCmd.Env = append(os.Environ(), database.ComposeHookEnvs(database.ComposeHookEnvsOptions{
  224. AuthUser: user,
  225. OwnerName: owner.Name,
  226. OwnerSalt: owner.Salt,
  227. RepoID: repo.ID,
  228. RepoName: repo.Name,
  229. RepoPath: repo.RepoPath(),
  230. })...)
  231. }
  232. gitCmd.Dir = conf.Repository.Root
  233. gitCmd.Stdout = os.Stdout
  234. gitCmd.Stdin = os.Stdin
  235. gitCmd.Stderr = os.Stderr
  236. if err = gitCmd.Run(); err != nil {
  237. fail("Internal error", "Failed to execute git command: %v", err)
  238. }
  239. return nil
  240. }