GHSA-8R2X-49GJ-H6RM
Protected Branch Bypass via Pull Request Merge Due to Missing Hook Environment Variables
CVSS:4.0/AV:N/AC:L/AT:N/PR:L/UI:N/VC:N/VI:H/VA:N/SC:N/SI:H/SA:N
Fuente: GitHub
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Divulgación | Publicada | GHSA-8R2X-49GJ-H6RM divulgada · CVSS 8.3 (GitHub) | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
Summary
The pull request merge operation in Gogs completely bypasses protected branch enforcement. When a pull request is merged through the web interface, the internal `git push` that writes the merge commit to the base repository runs without the `SSH_ORIGINAL_COMMAND` environment variable. The pre-receive hook checks for this variable at startup and immediately exits when it is absent, skipping all branch protection logic including whitelist enforcement, required pull request checks, and merge restrictions. Any collaborator with Write access can merge a pull request into any protected branch, regardless of whether they are in the push whitelist.
Details
The vulnerability spans three components that fail to connect properly:
1. MergePullRequest handler has no application-level protection check
The handler at `internal/route/repo/pull.go:401-431` only requires `reqRepoWriter` middleware. It never calls `GetProtectBranchOfRepoByName` to check whether the target branch is protected, nor does it verify whether the merging user is in the push whitelist:
func MergePullRequest(c *context.Context) {
issue := checkPullInfo(c)
if c.Written() { return }
if issue.IsClosed { /* error */ return }
pr := issue.PullRequest
if !pr.CanAutoMerge() || pr.HasMerged { /* error */ return }
// No protected branch check here
pr.Merge(c.User, c.Repo.GitRepo, database.MergeStyle(c.Query("merge_style")),
c.Query("commit_description"))
}2. pr.Merge() calls git.Push without environment variables
The `Merge` function at `internal/database/pull.go:194-316` performs the merge in a temporary directory, then pushes the result to the base repository at line 314:
if err = git.Push(tmpBasePath, baseGitRepo.Path(), pr.BaseBranch); err != nil {
return errors.Newf("git push: %v", err)
}This calls `git.Push` with no `PushOptions`, meaning no environment variables are passed to the git child process. Compare with the properly protected `UpdateRepoFile` function at `internal/database/repo_editor.go:226-239`, which passes `ComposeHookEnvs()` (setting `SSH_ORIGINAL_COMMAND=1` plus user/repo identification variables) to its push call.
3. The git-module Push function has no environment variable support
The `git.Push` function at `github.com/gogs/git-module@v1.8.8/repo.go:258-267`:
func Push(repoPath, remote, branch string, opts ...PushOptions) error {
var opt PushOptions
if len(opts) > 0 { opt = opts[0] }
cmd := NewCommand("push").AddOptions(opt.CommandOptions).AddArgs("--end-of-options", remote, branch)
_, err := cmd.RunInDirWithTimeout(opt.Timeout, repoPath)
return err
}The `PushOptions` struct contains only `Timeout` and `CommandOptions` fields. There is no `Envs` field, so even if the caller wanted to pass environment variables, the function cannot accept them.
4. Pre-receive hook exits immediately without SSH_ORIGINAL_COMMAND
The pre-receive hook at `cmd/gogs/hook.go:63-66`:
func runHookPreReceive(_ context.Context, cmd *cli.Command) error {
if os.Getenv("SSH_ORIGINAL_COMMAND") == "" {
return nil // Exits immediately, skipping ALL checks
}
// ... branch protection enforcement followsWhen `SSH_ORIGINAL_COMMAND` is empty (as it is during PR merge), the hook returns nil without checking protected branches, whitelists, or any other restriction.
The properly protected code paths (HTTP push via `serviceRPC` and web editor via `UpdateRepoFile`) both call `ComposeHookEnvs` at `internal/database/repo_editor.go:64-77`, which sets `SSH_ORIGINAL_COMMAND=1` along with user and repo identification. This environment reaches the hook through the git process, enabling protection enforcement. The PR merge path was missed entirely.
PoC
Tested on Gogs 0.14.3 (latest stable release), Linux.
Setup: Repository `testadmin/test-repo` with branch `main` protected (whitelist enabled, only user ID 1 `testadmin` whitelisted). User `regularuser` (ID:2) has Write access but is NOT in the whitelist.
Step 1: Confirm HTTP push to protected branch is correctly blocked
# Clone as regularuser using access token
git clone http://regularuser:<token>@TARGET:3000/testadmin/test-repo.git
cd test-repo
echo "test" > bypass.txt && git add bypass.txt
git commit -m "Direct push attempt"
git push origin mainOutput:
remote: Gogs: Branch 'main' is protected and you are not in the push whitelist
! [remote rejected] main -> main (pre-receive hook declined)HTTP push correctly enforces branch protection.
Step 2: Simulate what pr.Merge() does internally (local git push without env vars)
# Clone the bare repo locally (simulating pr.Merge temp workspace)
BASE_REPO="/data/repos/testadmin/test-repo.git"
git clone "$BASE_REPO" /tmp/merge-workspace
cd /tmp/merge-workspace
# Create merge commit as non-whitelisted user
echo "bypass" > merged-via-pr.txt && git add merged-via-pr.txt
git commit -m "Merge pull request - bypasses protection" \
--author="regularuser <regular@test.local>"
# Push directly to base repo WITHOUT SSH_ORIGINAL_COMMAND
# This is exactly what git.Push(tmpBasePath, baseGitRepo.Path(), pr.BaseBranch) does
unset SSH_ORIGINAL_COMMAND
git push "$BASE_REPO" mainOutput:
To /data/repos/testadmin/test-repo.git
0747518..2205841 main -> mainPush succeeds. The pre-receive hook exited at line 64 because `SSH_ORIGINAL_COMMAND` was empty, skipping all protection checks.
Step 3: Confirm the same push IS blocked when SSH_ORIGINAL_COMMAND is set
SSH_ORIGINAL_COMMAND=1 GOGS_AUTH_USER_ID=2 GOGS_REPO_ID=1 \
git push "$BASE_REPO" mainOutput:
remote: Gogs: Branch 'main' is protected and you are not in the push whitelist
! [remote rejected] main -> main (pre-receive hook declined)This proves the pre-receive hook works correctly when the environment variable is present. The only issue is that `pr.Merge()` never provides it.
Full attack path: A repository collaborator with Write permission but not in the protected branch whitelist creates a branch, opens a pull request targeting the protected branch, and clicks "Merge". The merge handler has no application-level protection check, and the git push it performs triggers the pre-receive hook without `SSH_ORIGINAL_COMMAND`, causing the hook to exit immediately and allow the merge.
Impact
Protected branches are a core security feature that organizations rely on to enforce code review, restrict who can write to production branches, and prevent unauthorized changes. This vulnerability completely negates that protection for the PR merge code path.
A collaborator with Write access can merge any pull request into any protected branch, even when:
- They are explicitly excluded from the push whitelist
- The branch requires pull request approval (the merge is done by the submitter, with no separate approval check)
- The branch has any form of merge restriction enabled
This allows bypassing mandatory code review workflows, merging malicious or untested code into release branches, and undermining the integrity of the software supply chain for any project hosted on the Gogs instance. The attacker only needs basic Write collaborator access, which is commonly granted to external contributors or junior developers who are intentionally excluded from direct-push privileges on critical branches.
The root cause is that `pr.Merge()` uses `git.Push()` from git-module v1.8.8, which has no mechanism to pass environment variables. The `ComposeHookEnvs` function that other code paths use to enable hook enforcement cannot be applied here. Fixing this requires either adding environment variable support to git-module's `Push` function, or adding an application-level protected branch check in the `MergePullRequest` handler before calling `pr.Merge()`.
Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.
Desglose de métricas
Rangos afectados
Estado del parche por paquete
| Paquete / producto | Estado | Corregida en | Desde divulgación | Última versión |
|---|---|---|---|---|
gogogs.io/gogs |
Sin parche | — | — | v0.13.3 afectada |
0.15.0Arsenal público
Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.
https://github.com/gogs/gogs/security/advisories/GHSA-8r2x-49gj-h6rmLas referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
