From 01a3206e905f36df7bf7da6b5d90e497ece8a17b Mon Sep 17 00:00:00 2001 From: privacydied Date: Thu, 10 Sep 2026 23:04:42 +0100 Subject: [PATCH] fix(git): carry user safe.directory past non-interactive config isolation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `noninteractive_git_env()` blanks GIT_CONFIG_GLOBAL/SYSTEM to /dev/null so a user's config cannot hang Hermes's internal git plumbing with pagers, hooks or credential prompts. Sound intent, but it also discards `safe.directory` — and git honours that key ONLY from global/system config (it is rejected from repo-level config by design, so a hostile repo cannot self-authorise). Result: every internal git call fails on a repo whose st_uid != geteuid(): $ hermes -w ✗ Failed to create worktree: fatal: detected dubious ownership in repository at '/mnt/nas/py/repo' That hits NFS/CIFS mounts without idmapping, shared checkouts, and containers with a remapped uid. The user's own `git config --global --add safe.directory` is correctly set and their interactive git works — Hermes throws the setting away before git reads it, so the error's own suggested remedy can never fix it. There is no config or env escape hatch: the blanking is unconditional. Reproducer (any repo where the checkout uid differs from the caller's): git rev-parse HEAD # works GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null \ GIT_CONFIG_NOSYSTEM=1 git rev-parse HEAD # dubious ownership Fix: read the user's real `safe.directory` values before the isolation is applied, then re-inject them over the GIT_CONFIG_KEY_n channel, which survives GIT_CONFIG_GLOBAL=/dev/null. Isolation is unchanged — global/system config stay pointed at /dev/null and every hardening override still applies, since a later key of the same name wins in git's config order. Read-only and non-widening: only values already present in the user's own config are carried, so this grants no trust they had not granted. Ambient GIT_CONFIG_KEY_n injection is still stripped first, so a caller cannot launder an attacker-controlled path in this way — covered by a regression test. Tests: three cases in TestNoninteractiveGitEnv — entries carried past isolation, no entries injected when the user configured none, and ambient injection not trusted. All pin GIT_CONFIG_SYSTEM at an empty file, since a real /etc/gitconfig on the test host can otherwise leak entries and mask the assertions. Verified on Arch Linux, git 2.x, repo on an NFSv4 mount (uid 1024 vs caller 1000): `git worktree add` under the patched env returns rc=0 where it previously failed. 80 passed in tests/hermes_cli/test_noninteractive_git.py, tests/security/test_gitspawn_config_injection.py and tests/tools/test_checkpoint_manager.py, including the pre-existing assertions that the isolation stays in force. --- hermes_cli/_subprocess_compat.py | 54 +++++++++++++- tests/hermes_cli/test_noninteractive_git.py | 80 +++++++++++++++++++++ 2 files changed, 132 insertions(+), 2 deletions(-) diff --git a/hermes_cli/_subprocess_compat.py b/hermes_cli/_subprocess_compat.py index d55e4dec1b..6c8dea3a9e 100644 --- a/hermes_cli/_subprocess_compat.py +++ b/hermes_cli/_subprocess_compat.py @@ -232,6 +232,42 @@ _GIT_CONFIG_OVERRIDES = { } +def _user_safe_directories(base_env: "Mapping[str, str]") -> list[str]: + """The user's configured ``safe.directory`` values, read from their real global/system config. + + Read with ``git config --get-all`` under *base_env* (the caller's untouched environment) so an + explicit ``GIT_CONFIG_GLOBAL``/``GIT_CONFIG_SYSTEM`` still points at the file the user means. + Best-effort: any failure (git missing, malformed config, timeout) yields no entries and leaves + the caller exactly as it behaved before. + """ + env = dict(base_env) + # --get-all itself must not be derailed by ambient injection or an interactive prompt. + for key in list(env): + if key == "GIT_CONFIG_PARAMETERS" or key.startswith(_GIT_CONFIG_INJECT_PREFIXES): + env.pop(key, None) + env.pop("GIT_CONFIG_COUNT", None) + env["GIT_TERMINAL_PROMPT"] = "0" + values: list[str] = [] + seen: set[str] = set() + for scope in ("--global", "--system"): + try: + proc = subprocess.run( + ["git", "config", scope, "--get-all", "safe.directory"], + capture_output=True, text=True, encoding="utf-8", errors="replace", + timeout=5, stdin=subprocess.DEVNULL, env=env, check=False, + ) + except (OSError, subprocess.SubprocessError): + continue + if proc.returncode != 0: + continue + for line in proc.stdout.splitlines(): + entry = line.strip() + if entry and entry not in seen: + seen.add(entry) + values.append(entry) + return values + + def noninteractive_git_env(base: "Mapping[str, str] | None" = None) -> dict[str, str]: """Environment for *internal* git invocations that must never prompt. @@ -258,6 +294,9 @@ def noninteractive_git_env(base: "Mapping[str, str] | None" = None) -> dict[str, for input nobody can type. """ env = dict(base if base is not None else os.environ) + # Captured before the isolation below rewrites GIT_CONFIG_GLOBAL/SYSTEM to /dev/null -- + # reading after that point would resolve the user's config to an empty file. + safe_directories = _user_safe_directories(base if base is not None else os.environ) env["GIT_TERMINAL_PROMPT"] = "0" env["GCM_INTERACTIVE"] = "Never" # Drop caller-supplied config injection; the GIT_CONFIG_COUNT block is rebuilt below so @@ -272,8 +311,19 @@ def noninteractive_git_env(base: "Mapping[str, str] | None" = None) -> dict[str, env["GIT_PAGER"] = "cat" env["PAGER"] = "cat" env["GIT_EDITOR"] = "true" - env["GIT_CONFIG_COUNT"] = str(len(_GIT_CONFIG_OVERRIDES)) - for idx, (key, value) in enumerate(_GIT_CONFIG_OVERRIDES.items()): + overrides = list(_GIT_CONFIG_OVERRIDES.items()) + # safe.directory is honoured ONLY from global/system config (git rejects it from repo-level + # config so a hostile repo cannot self-authorise), and both are blanked just above. Without + # re-injection every internal git call fails "detected dubious ownership" on any repo whose + # st_uid != geteuid() -- NFS/CIFS mounts without idmapping, shared checkouts, containers with + # a remapped uid -- even though the user's own `git config --global --add safe.directory` is + # correctly set and their interactive git works fine. Carried over the GIT_CONFIG_KEY_n + # channel, which survives GIT_CONFIG_GLOBAL=/dev/null. Read-only: it never widens the set + # beyond what the user already trusts, and the hardening overrides above still win because a + # later key of the same name takes precedence in git's config order. + overrides.extend(("safe.directory", value) for value in safe_directories) + env["GIT_CONFIG_COUNT"] = str(len(overrides)) + for idx, (key, value) in enumerate(overrides): env[f"GIT_CONFIG_KEY_{idx}"] = key env[f"GIT_CONFIG_VALUE_{idx}"] = value return env diff --git a/tests/hermes_cli/test_noninteractive_git.py b/tests/hermes_cli/test_noninteractive_git.py index a3e0588965..5054c98497 100644 --- a/tests/hermes_cli/test_noninteractive_git.py +++ b/tests/hermes_cli/test_noninteractive_git.py @@ -97,6 +97,86 @@ class TestNoninteractiveGitEnv: assert values["sequence.editor"] == "true" assert values["diff.external"] == "" + def test_carries_user_safe_directory_past_config_isolation(self, tmp_path, monkeypatch): + """safe.directory survives GIT_CONFIG_GLOBAL=/dev/null (#dubious-ownership on NFS). + + git honours safe.directory only from global/system config, and both are blanked here. If + it is not re-injected, every internal git call fails "detected dubious ownership" on a + repo whose st_uid != geteuid() -- an NFS/CIFS mount without idmapping, a shared checkout, + a container with a remapped uid -- even though the user configured it correctly. + """ + gitconfig = tmp_path / "gitconfig" + gitconfig.write_text( + "[safe]\n\tdirectory = /mnt/nfs/repo\n\tdirectory = /srv/shared/other\n", + encoding="utf-8", + ) + empty_system = tmp_path / "system-gitconfig" + empty_system.write_text("", encoding="utf-8") + monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(gitconfig)) + monkeypatch.setenv("GIT_CONFIG_SYSTEM", str(empty_system)) + + env = noninteractive_git_env() + pairs = [ + (env[f"GIT_CONFIG_KEY_{idx}"], env[f"GIT_CONFIG_VALUE_{idx}"]) + for idx in range(int(env["GIT_CONFIG_COUNT"])) + ] + safe = [value for key, value in pairs if key == "safe.directory"] + + assert "/mnt/nfs/repo" in safe + assert "/srv/shared/other" in safe + # Isolation is still in force: the values ride the KEY_n channel, not the config file. + assert env["GIT_CONFIG_GLOBAL"] == os.devnull + assert env["GIT_CONFIG_SYSTEM"] == os.devnull + # And the hardening overrides are untouched by the appended entries. + assert ("core.pager", "cat") in pairs + assert ("credential.helper", "") in pairs + + def test_safe_directory_absent_when_user_configured_none(self, tmp_path, monkeypatch): + """No user entries -> no injected entries; the env is exactly as it was before.""" + gitconfig = tmp_path / "gitconfig" + gitconfig.write_text("[user]\n\tname = nobody\n", encoding="utf-8") + empty_system = tmp_path / "system-gitconfig" + empty_system.write_text("", encoding="utf-8") + monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(gitconfig)) + # Pin the system scope too: a real /etc/gitconfig on the test host may carry its own + # safe.directory entries, which would otherwise leak in and mask the assertion. + monkeypatch.setenv("GIT_CONFIG_SYSTEM", str(empty_system)) + + env = noninteractive_git_env() + keys = [env[f"GIT_CONFIG_KEY_{idx}"] for idx in range(int(env["GIT_CONFIG_COUNT"]))] + + assert "safe.directory" not in keys + + def test_ambient_safe_directory_injection_is_not_trusted(self, tmp_path, monkeypatch): + """A caller-supplied GIT_CONFIG_KEY_n=safe.directory is dropped, not laundered through. + + Only what the user's own config file says is carried; ambient injection stays stripped so + this cannot become a path-trust escalation vector. + """ + gitconfig = tmp_path / "gitconfig" + gitconfig.write_text("[safe]\n\tdirectory = /mnt/nfs/repo\n", encoding="utf-8") + empty_system = tmp_path / "system-gitconfig" + empty_system.write_text("", encoding="utf-8") + monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(gitconfig)) + monkeypatch.setenv("GIT_CONFIG_SYSTEM", str(empty_system)) + + env = noninteractive_git_env( + { + **os.environ, + "GIT_CONFIG_COUNT": "1", + "GIT_CONFIG_KEY_0": "safe.directory", + "GIT_CONFIG_VALUE_0": "/attacker/controlled", + } + ) + safe = [ + env[f"GIT_CONFIG_VALUE_{idx}"] + for idx in range(int(env["GIT_CONFIG_COUNT"])) + if env[f"GIT_CONFIG_KEY_{idx}"] == "safe.directory" + ] + + assert "/attacker/controlled" not in safe + assert "/mnt/nfs/repo" in safe + def test_ssh_host_key_prompts_fail_closed(self): """core.sshCommand is pinned to BatchMode ssh (#104591).