From e4b8e7d026ca6abb4cf604f8e77093432ce23c06 Mon Sep 17 00:00:00 2001
From: Byron <sebastian.thiel@icloud.com>
Date: Sat, 1 Aug 2026 04:47:40 +0200
Subject: [PATCH] Validate submodule names before filesystem operations

<!-- agent -->
Submodule names read from .gitmodules can influence the separate Git directory
path. Reject empty names, absolute or drive-qualified names, and parent
components with either path separator.

Validate before constructing module paths and before opening or mutating
existing checkouts, so a repository initialized by an older vulnerable version
cannot bypass the guard. Validate programmatic add and rename inputs before
making changes as well.

Advisory: GHSA-hmq2-w58f-27jc

Assisted-by: GPT 5.6
Co-authored-by: GPT 5.6 <codex@openai.com>
---
 git/objects/submodule/base.py | 23 +++++++++++-
 test/test_submodule.py        | 69 +++++++++++++++++++++++++++++++++++
 2 files changed, 91 insertions(+), 1 deletion(-)

Index: GitPython-3.1.34.1693646983.2a2ae77/git/objects/submodule/base.py
===================================================================
--- GitPython-3.1.34.1693646983.2a2ae77.orig/git/objects/submodule/base.py
+++ GitPython-3.1.34.1693646983.2a2ae77/git/objects/submodule/base.py
@@ -1,6 +1,7 @@
 # need a dict to set bloody .name field
 from io import BytesIO
 import logging
+import ntpath
 import os
 import stat
 import uuid
@@ -263,9 +264,20 @@ class Submodule(IndexObject, Traversable
         return SectionConstraint(parser, sm_section(self.name))
 
     @classmethod
+    def _validated_name(cls, name: str) -> str:
+        if (
+            not name
+            or name.startswith(("/", "\\"))
+            or ntpath.splitdrive(name)[0]
+            or ".." in name.replace("\\", "/").split("/")
+        ):
+            raise ValueError("Invalid submodule name %r" % name)
+        return name
+
+    @classmethod
     def _module_abspath(cls, parent_repo: "Repo", path: PathLike, name: str) -> PathLike:
         if cls._need_gitfile_submodules(parent_repo.git):
-            return osp.join(parent_repo.git_dir, "modules", name)
+            return osp.join(parent_repo.git_dir, "modules", cls._validated_name(name))
         if parent_repo.working_tree_dir:
             return osp.join(parent_repo.working_tree_dir, path)
         raise NotADirectoryError()
@@ -423,6 +435,7 @@ class Submodule(IndexObject, Traversable
             raise InvalidGitRepositoryError("Cannot add submodules to bare repositories")
         # END handle bare repos
 
+        cls._validated_name(name)
         path = cls._to_relative_path(repo, path)
 
         # assure we never put backslashes into the url, as some operating systems
@@ -608,6 +621,8 @@ class Submodule(IndexObject, Traversable
         # END init mrepo
 
         try:
+            self._validated_name(self.name)
+
             # ASSURE REPO IS PRESENT AND UPTODATE
             #####################################
             try:
@@ -859,6 +874,7 @@ class Submodule(IndexObject, Traversable
             raise ValueError("You must specify to move at least the module or the configuration of the submodule")
         # END handle input
 
+        self._validated_name(self.name)
         module_checkout_path = self._to_relative_path(self.repo, module_path)
 
         # VERIFY DESTINATION
@@ -982,6 +998,7 @@ class Submodule(IndexObject, Traversable
             raise ValueError("Need to specify to delete at least the module, or the configuration")
         # END handle parameters
 
+        self._validated_name(self.name)
         # Recursively remove children of this submodule
         nc = 0
         for csm in self.children():
@@ -1200,6 +1217,9 @@ class Submodule(IndexObject, Traversable
         if self.name == new_name:
             return self
 
+        self._validated_name(self.name)
+        self._validated_name(new_name)
+
         # .git/config
         with self.repo.config_writer() as pw:
             # As we ourselves didn't write anything about submodules into the parent .git/config,
@@ -1240,6 +1260,7 @@ class Submodule(IndexObject, Traversable
         """:return: Repo instance initialized from the repository at our submodule path
         :raise InvalidGitRepositoryError: if a repository was not available. This could
             also mean that it was not yet initialized"""
+        self._validated_name(self.name)
         # late import to workaround circular dependencies
         module_checkout_abspath = self.abspath
         try:
Index: GitPython-3.1.34.1693646983.2a2ae77/test/test_submodule.py
===================================================================
--- GitPython-3.1.34.1693646983.2a2ae77.orig/test/test_submodule.py
+++ GitPython-3.1.34.1693646983.2a2ae77/test/test_submodule.py
@@ -710,6 +710,75 @@ class TestSubmodule(TestBase):
         # end for each checkout mode
 
     @with_rw_directory
+    @_patch_git_config("protocol.file.allow", "always")
+    def test_update_rejects_parent_component_in_name(self, rwdir):
+        source = git.Repo.init(osp.join(rwdir, "source"))
+        source.git.commit(m="initial commit", allow_empty=True)
+
+        parent = git.Repo.init(osp.join(rwdir, "parent"))
+        parent.git.submodule("add", source.working_tree_dir, "module")
+        parent.index.commit("add submodule")
+        modules_file = Path(parent.working_tree_dir) / ".gitmodules"
+        modules_file.write_text(
+            modules_file.read_text().replace('submodule "module"', 'submodule "../../../escaped/module"')
+        )
+        parent.index.add([".gitmodules"])
+        parent.index.commit("change submodule name")
+
+        clone = git.Repo.clone_from(parent.working_tree_dir, osp.join(rwdir, "clone"))
+        with pytest.raises(ValueError, match="submodule name"):
+            clone.submodules[0].update(init=True)
+        assert not osp.exists(osp.join(rwdir, "escaped"))
+
+        Path(rwdir, "escaped").mkdir()
+        git.Repo.clone_from(
+            source.working_tree_dir,
+            osp.join(clone.working_tree_dir, "module"),
+            separate_git_dir=osp.join(rwdir, "escaped", "module"),
+        )
+        with pytest.raises(ValueError, match="submodule name"):
+            clone.submodules[0].update(init=True)
+
+        invalid_names = (
+            "",
+            "..",
+            "../module",
+            R"..\module",
+            "nested/../module",
+            R"nested\..\module",
+            "/module",
+            R"\module",
+            "C:module",
+            R"C:\module",
+        )
+        for name in invalid_names:
+            with pytest.raises(ValueError, match="submodule name"):
+                Submodule._module_abspath(clone, "module", name)
+
+    @with_rw_directory
+    @_patch_git_config("protocol.file.allow", "always")
+    def test_root_update_keeps_going_after_invalid_submodule_name(self, rwdir):
+        source = git.Repo.init(osp.join(rwdir, "source"))
+        source.git.commit(m="initial commit", allow_empty=True)
+
+        parent = git.Repo.init(osp.join(rwdir, "parent"))
+        parent.git.submodule("add", source.working_tree_dir, "invalid")
+        parent.git.submodule("add", source.working_tree_dir, "valid")
+        modules_file = Path(parent.working_tree_dir) / ".gitmodules"
+        modules_file.write_text(modules_file.read_text().replace('submodule "invalid"', 'submodule "../invalid"'))
+        parent.index.add([".gitmodules"])
+        parent.index.commit("add submodules")
+
+        clone = git.Repo.clone_from(parent.working_tree_dir, osp.join(rwdir, "clone"))
+        assert [sm.name for sm in clone.submodules] == ["../invalid", "valid"]
+
+        clone.submodule_update(keep_going=True)
+
+        assert os.listdir(osp.join(clone.working_tree_dir, "invalid")) == []
+        assert not clone.submodule("../invalid").module_exists()
+        assert clone.submodule("valid").module_exists()
+
+    @with_rw_directory
     def test_list_only_valid_submodules(self, rwdir):
         repo_path = osp.join(rwdir, "parent")
         repo = git.Repo.init(repo_path)
