From 9b5dcaf85da5946dbf69dcd53f9edba08f760b32 Mon Sep 17 00:00:00 2001
From: Byron <sebastian.thiel@icloud.com>
Date: Sun, 2 Aug 2026 09:06:40 +0000
Subject: [PATCH] Guard read-tree index output paths

<!-- agent -->
GHSA-4gmw-gg2m-w46p reports that caller-controlled treeish arguments could
be parsed by git read-tree as --index-output and select an arbitrary output
path. A regression test showed that from_tree reached Git instead of raising
UnsafeOptionError; the same unchecked path was reachable through reset and
both merge_tree treeish positions.

Add the project-standard unsafe-option guard and explicit opt-out to
from_tree, merge_tree, and reset. Check positional and keyword candidates so
abbreviations and alternate forwarding forms are covered before read-tree
runs.

A broader audit found only two read-tree sinks in the codebase; both are now
guarded, and reset delegates to the guarded from_tree path. The only remaining
index-output use is GitPython's controlled temporary index. Git cf5497b14
confirms read-tree parses this path-taking option before tree arguments.
Focused index tests and Ruff checks pass.

Assisted-by: GPT 5.6
Co-authored-by: GPT 5.6 <codex@openai.com>
---
 git/index/base.py  | 40 +++++++++++++++++++++++++++++++++++++---
 test/test_index.py | 16 ++++++++++++++++
 2 files changed, 53 insertions(+), 3 deletions(-)

Index: GitPython-3.1.34.1693646983.2a2ae77/git/index/base.py
===================================================================
--- GitPython-3.1.34.1693646983.2a2ae77.orig/git/index/base.py
+++ GitPython-3.1.34.1693646983.2a2ae77/git/index/base.py
@@ -119,6 +119,7 @@ class IndexFile(LazyMixin, git_diff.Diff
     before operating on it using the git command"""
 
     unsafe_git_checkout_index_options = ["--prefix"]
+    unsafe_git_read_tree_options = ["--index-output"]
 
     __slots__ = ("repo", "version", "entries", "_extension_data", "_file_path")
     _VERSION = 2  # latest version we support
@@ -243,7 +244,12 @@ class IndexFile(LazyMixin, git_diff.Diff
 
     @post_clear_cache
     @default_index
-    def merge_tree(self, rhs: Treeish, base: Union[None, Treeish] = None) -> "IndexFile":
+        def merge_tree(
+        self,
+        rhs: Treeish,
+        base: Union[None, Treeish] = None,
+        allow_unsafe_options: bool = False,
+    ) -> "IndexFile":
         """Merge the given rhs treeish into the current index, possibly taking
         a common base treeish into account.
 
@@ -257,6 +263,9 @@ class IndexFile(LazyMixin, git_diff.Diff
             optional treeish reference pointing to the common base of 'rhs' and
             this index which equals lhs
 
+        :param allow_unsafe_options:
+            Allow options that may write to arbitrary paths.
+
         :return:
             self ( containing the merge and possibly unmerged entries in case of
             conflicts )
@@ -267,6 +276,12 @@ class IndexFile(LazyMixin, git_diff.Diff
             merge resolution to be done by yourself, you have to commit the changed
             index ( or make a valid tree from it ) and retry with a three-way
             index.from_tree call."""
+        if not allow_unsafe_options:
+            Git.check_unsafe_options(
+                options=Git._option_candidates([base, rhs]),
+                unsafe_options=self.unsafe_git_read_tree_options,
+            )
+
         # -i : ignore working tree status
         # --aggressive : handle more merge cases
         # -m : do an actual merge
@@ -308,7 +323,13 @@ class IndexFile(LazyMixin, git_diff.Diff
         return inst
 
     @classmethod
-    def from_tree(cls, repo: "Repo", *treeish: Treeish, **kwargs: Any) -> "IndexFile":
+        def from_tree(
+        cls,
+        repo: "Repo",
+        *treeish: Treeish,
+        allow_unsafe_options: bool = False,
+        **kwargs: Any,
+    ) -> "IndexFile":
         """Merge the given treeish revisions into a new index which is returned.
         The original index will remain unaltered
 
@@ -329,6 +350,9 @@ class IndexFile(LazyMixin, git_diff.Diff
         :param kwargs:
             Additional arguments passed to git-read-tree
 
+        :param allow_unsafe_options:
+            Allow options that may write to arbitrary paths.
+
         :return:
             New IndexFile instance. It will point to a temporary index location which
             does not exist anymore. If you intend to write such a merged Index, supply
@@ -345,6 +369,12 @@ class IndexFile(LazyMixin, git_diff.Diff
         if len(treeish) == 0 or len(treeish) > 3:
             raise ValueError("Please specify between 1 and 3 treeish, got %i" % len(treeish))
 
+        if not allow_unsafe_options:
+            Git.check_unsafe_options(
+                options=Git._option_candidates(treeish, kwargs),
+                unsafe_options=cls.unsafe_git_read_tree_options,
+            )
+
         arg_list: List[Union[Treeish, str]] = []
         # ignore that working tree and index possibly are out of date
         if len(treeish) > 1:
@@ -1294,6 +1324,7 @@ class IndexFile(LazyMixin, git_diff.Diff
         working_tree: bool = False,
         paths: Union[None, Iterable[PathLike]] = None,
         head: bool = False,
+        allow_unsafe_options: bool = False,
         **kwargs: Any,
     ) -> "IndexFile":
         """Reset the index to reflect the tree at the given commit. This will not
@@ -1319,6 +1350,9 @@ class IndexFile(LazyMixin, git_diff.Diff
             The paths need to exist at the commit, otherwise an exception will be
             raised.
 
+        :param allow_unsafe_options:
+            Allow options that may write to arbitrary paths.
+
         :param kwargs:
             Additional keyword arguments passed to git-reset
 
@@ -1330,7 +1364,7 @@ class IndexFile(LazyMixin, git_diff.Diff
         :return: self"""
         # what we actually want to do is to merge the tree into our existing
         # index, which is what git-read-tree does
-        new_inst = type(self).from_tree(self.repo, commit)
+        new_inst = type(self).from_tree(self.repo, commit, allow_unsafe_options=allow_unsafe_options)
         if not paths:
             self.entries = new_inst.entries
         else:
Index: GitPython-3.1.34.1693646983.2a2ae77/test/test_index.py
===================================================================
--- GitPython-3.1.34.1693646983.2a2ae77.orig/test/test_index.py
+++ GitPython-3.1.34.1693646983.2a2ae77/test/test_index.py
@@ -184,6 +184,22 @@ class TestIndex(TestBase):
             assert "index.lock' could not be obtained" not in str(ex)
 
     @with_rw_repo("0.1.6")
+    def test_read_tree_methods_reject_index_output(self, rw_repo):
+        output_path = (Path(rw_repo.working_tree_dir) / "alternate-index").as_posix()
+        unsafe_option = f"--index-output={output_path}"
+
+        with pytest.raises(UnsafeOptionError):
+            IndexFile.from_tree(rw_repo, unsafe_option)
+        with pytest.raises(UnsafeOptionError):
+            IndexFile.from_tree(rw_repo, "HEAD", index_output=output_path)
+        with pytest.raises(UnsafeOptionError):
+            rw_repo.index.reset(unsafe_option)
+        with pytest.raises(UnsafeOptionError):
+            rw_repo.index.merge_tree(unsafe_option)
+        with pytest.raises(UnsafeOptionError):
+            rw_repo.index.merge_tree("HEAD", base=unsafe_option)
+
+    @with_rw_repo("0.1.6")
     def test_index_file_from_tree(self, rw_repo):
         common_ancestor_sha = "5117c9c8a4d3af19a9958677e45cda9269de1541"
         cur_sha = "4b43ca7ff72d5f535134241e7c797ddc9c7a3573"
