Skip to content
GitSpawn: Scan Untrusted Repos Before Your AI Agent Does — ContentBuffer guide

GitSpawn: Scan Untrusted Repos Before Your AI Agent Does

K
Kodetra Technologies··11 min read Intermediate

Summary

A repo's .git/config can run code the moment a coding agent calls git. Build a preflight scanner.

A zip file, an AI agent, and code that runs before you type a word

Most agent security advice is about what the model might be tricked into doing. GitSpawn is different. Nobody tricks the model. The agent simply runs git status to gather context when you open a folder, and git does what the folder's own config tells it to do.

Manifold Security published the research and Adversa AI put it at the top of its October 2026 coding-agent vulnerability roundup. It covers eight findings across Claude Code, OpenAI Codex, Cursor, Goose, Qwen Code, Grok Build and Hermes Agent. In Manifold's write-up (dated 1 September), four of the eight were still unpatched, and they say each was re-confirmed on a current release before publication. That is why it keeps resurfacing now: the fix lives in every vendor's hands, but the defence you can ship today lives in yours.

In this guide you will reproduce the core mechanism safely on your own machine, then build two small tools: gitgate.py, a preflight scanner that flags program-naming settings in a repo that arrived as files, and safegit.py, a wrapper that makes the git calls your own agent harness issues immune to the most common sinks. Everything below was run and verified with git 2.43 and Python 3.

How the attack works

Some git settings name a program. The best known is core.fsmonitor, a performance setting: during an index refresh, git runs the configured helper to ask which files changed. Commands like git status and git diff trigger that refresh, so the agent's exact choice of command barely matters.

The repository's own .git/config is read by git with local authority. Agents call git in the background for context, often at startup and before any trust prompt, and those calls do not strip repo-level config. The git subprocess is spawned by the agent itself, so it runs outside the agent's sandbox, with your privileges, and without an approval prompt.

Delivery matters, and it limits the blast radius. Cloning, fetching or pulling a hostile URL does not copy the attacker's .git/config to you. The attack needs the repository to arrive as files with the .git directory included: a shared zip, a synced folder, a USB stick, a download from a drive link. Think of the 'here is my broken project, can your agent take a look' message.

AgentTrigger point (per Manifold)Status in the 1 Sep write-up
Claude Code (core.fsmonitor)git status when a folder is opened, before the trust promptPatched in 2.1.196
Claude Code (ultrareview)A second, unnamed setting on the review pathUnpatched at publication
Goosegoose review collecting the diffPatched in 1.44.0 (CVE-2026-72718)
Qwen CodeStarting qwen, before authenticationUnpatched at publication
Grok BuildFirst keystroke in a promptUnpatched at publication
Hermes AgentFirst message in a sessionUnpatched (CVE-2026-71963)
Codex, CursorSame class, different detailsPatched (Aviatrix tracks the Codex CLI case as CVE-2026-19592)

Treat that table as a snapshot, not a status page. Check each vendor's advisory for your installed version before relying on it.

Prerequisites

  • Python 3.9+ and git 2.30+ (the tests below used git 2.43.0)
  • A throwaway directory. You will create a deliberately booby-trapped repo, so never run the demo inside a project you care about
  • About 20 minutes. No API keys needed, because the point is what happens before any model call

Step 1: Reproduce the primitive safely

The payload here is a shell script that only appends a timestamp to a marker file. It proves execution without doing anything harmful.

cat > /tmp/pwn.sh <<'EOF'
#!/bin/sh
echo "ran at $(date +%s)" >> /tmp/PWNED_MARKER
EOF
chmod +x /tmp/pwn.sh

mkdir demo && cd demo && git init -q
git config user.email a@b.c && git config user.name t
echo hi > a.txt && git add . && git commit -qm init

# the "hostile" part: a repo-local setting that names a program
git config core.fsmonitor /tmp/pwn.sh
echo x >> a.txt

git status --short
cat /tmp/PWNED_MARKER

Real output from my run:

 M a.txt
ran at 1791990391

You ran one read-only command and your script executed. git diff does the same. Now see what a single override does:

rm -f /tmp/PWNED_MARKER
git -c core.fsmonitor=false status --short
cat /tmp/PWNED_MARKER   # cat: No such file or directory

That -c core.fsmonitor=false is exactly the mitigation Manifold suggests for agent vendors on background context-gathering calls. It is a good fix for one key. The trouble is that git has many keys like it.

Step 2: Know the other sinks

core.fsmonitor is the headline, not the whole class. Any setting that names a program is a candidate. I confirmed the following run attacker-chosen commands from repo-local config in my own tests: diff.external (fires on a plain git diff), plus aliases starting with ! and credential helpers by their documented behavior. These are the families worth scanning for:

FamilyExample keysWhen it fires
Index refreshcore.fsmonitorgit status, git diff, most porcelain
Diff and merge driversdiff.external, diff.*.textconv, merge.*.drivergit diff, git log -p, merges
Clean/smudge filtersfilter.*.clean, filter.*.smudge, filter.*.processStaging and checkout, when .gitattributes maps paths to the filter
Hookscore.hooksPath, .git/hooks/*commit, checkout, merge, push
Transport and authcore.sshCommand, credential.helper, core.askPassfetch, push, clone over those transports
Pagers and editorscore.pager, core.editor, sequence.editorInteractive terminals
Indirectioninclude.path, includeIf.*.path, a .git file pointing to another gitdirLoads config you did not inspect

A hook or filter needs a particular command to trigger it, so those are less of a startup risk than fsmonitor. They still matter the moment your agent commits, stages or checks out, which agents do constantly.

Step 3: Build the preflight scanner

The scanner reads the repo's config and config.worktree using git itself (git config --file ... --list -z), so quoting and escaping match what git would see. It uses glob patterns for keys that have a user-chosen middle segment, and it follows .git pointer files.

#!/usr/bin/env python3
"""gitgate: inspect a repo that arrived as files (zip, share, USB) BEFORE an AI
coding agent runs git in it. Exit 0 = clean, 1 = review, 2 = program-naming config found."""
import fnmatch, json, os, re, subprocess, sys
from pathlib import Path

# Keys where git treats the value as a program/command line to execute.
EXEC_KEYS = [
    "core.fsmonitor", "core.sshcommand", "core.pager", "core.editor", "core.askpass",
    "core.gitproxy", "core.hookspath", "core.alternaterefscommand",
    "credential.helper", "credential.*.helper", "diff.external", "diff.*.command",
    "diff.*.textconv", "filter.*.clean", "filter.*.smudge", "filter.*.process",
    "merge.*.driver", "mergetool.*.cmd", "difftool.*.cmd", "gpg.program",
    "gpg.*.program", "sequence.editor", "sendemail.smtpserver", "web.browser",
    "browser.*.cmd", "http.cookiefile", "remote.*.vcs", "remote.*.receivepack",
    "remote.*.uploadpack", "protocol.ext.allow", "uploadpack.packobjectshook",
    "include.path", "includeif.*.path",
]
BENIGN_FSMONITOR = {"false", "0", "no", "off", ""}

def git_dir(repo: Path):
    dot = repo / ".git"
    if dot.is_file():                      # "gitdir: ../elsewhere" pointer files
        m = re.match(r"gitdir:\s*(.+)", dot.read_text().strip())
        if not m: raise SystemExit(f"unreadable .git file in {repo}")
        return (repo / m.group(1)).resolve(), True
    return dot, False

def read_config(path: Path):
    if not path.exists(): return []
    out = subprocess.run(["git", "config", "--file", str(path), "--list", "-z"],
                         capture_output=True, text=True, env={**os.environ, "GIT_CONFIG_NOSYSTEM": "1"})
    items = []
    for rec in out.stdout.split("\0"):
        if "\n" in rec: k, v = rec.split("\n", 1)
        elif rec: k, v = rec, ""
        else: continue
        items.append((k.lower(), v))
    return items

def is_exec_key(key: str):
    return any(fnmatch.fnmatchcase(key, pat) for pat in EXEC_KEYS) or key.startswith("alias.") 

def scan(repo: Path):
    findings = []
    gd, pointer = git_dir(repo)
    if pointer:
        findings.append(("review", ".git", f"gitdir pointer file -> {gd}"))
    for cfg in (gd / "config", gd / "config.worktree"):
        for key, val in read_config(cfg):
            if key == "core.fsmonitor" and val.strip().lower() in BENIGN_FSMONITOR:
                continue
            if key.startswith("alias.") and not val.startswith("!"):
                continue
            if is_exec_key(key):
                findings.append(("high", cfg.name, f"{key} = {val!r}"))
    hooks = gd / "hooks"
    if hooks.is_dir():
        for h in sorted(hooks.iterdir()):
            if h.is_file() and not h.name.endswith(".sample") and os.access(h, os.X_OK):
                findings.append(("review", "hooks", f"executable hook {h.name}"))
    ga = repo / ".gitattributes"
    if ga.exists() and re.search(r"\b(filter|diff|merge)=", ga.read_text(errors="ignore")):
        findings.append(("review", ".gitattributes", "maps paths to filter/diff/merge drivers"))
    return findings

if __name__ == "__main__":
    repo = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
    f = scan(repo)
    print(json.dumps([{"level": l, "where": w, "detail": d} for l, w, d in f], indent=2))
    sys.exit(2 if any(l == "high" for l, *_ in f) else 1 if f else 0)

Run it on a clean repo and on the booby-trapped one:

$ python3 gitgate.py clean; echo "exit=$?"
[]
exit=0

$ python3 gitgate.py demo; echo "exit=$?"
[
  {
    "level": "high",
    "where": "config",
    "detail": "core.fsmonitor = '/tmp/pwn.sh'"
  }
]
exit=2

Then the real scenario. Zip the hostile repo, unzip it somewhere else like a victim would, and scan before opening anything:

$ zip -qr proj.zip project && unzip -q proj.zip -d out
$ python3 gitgate.py out/project; echo "exit=$?"
[ { "level": "high", "where": "config", "detail": "core.fsmonitor = '/tmp/pwn.sh'" } ]
exit=2

The zip round trip preserved the setting, which is the whole point. Note one more subtlety I hit: after extraction the files belong to you, so git's 'dubious ownership' safeguard does not complain. That check protects against repos owned by someone else, not against a repo you just unpacked yourself.

Add more findings to see the other sinks light up. After setting diff.external, a clean filter, a ! alias, a credential helper and an include.path, the scanner printed:

high diff.external = '/tmp/pwn.sh'
high filter.x.clean = '/tmp/pwn.sh'
high alias.st = '!/tmp/pwn.sh'
high credential.helper = '!/tmp/pwn.sh'
high include.path = '/tmp/x.cfg'

And a .git file containing gitdir: ../elsewhere produced a review finding with the resolved target path, exit code 1.

Step 4: Harden the git calls your own harness makes

If you build agents (or wrap one), you control the subprocess. Git lets you inject config at command scope through environment variables, and command scope outranks the repo's .git/config. That gives you one place to neutralise many keys without a per-command flag.

"""Run git for an agent with program-naming settings neutralised."""
import os, subprocess

HARDEN = {
    "core.fsmonitor": "false",
    "core.hooksPath": "/dev/null",
    "core.pager": "cat",
    "core.sshCommand": "false",
    "core.askPass": "",
    "credential.helper": "",
    "protocol.ext.allow": "never",
}

def hardened_env(base=None):
    env = dict(base or os.environ)
    env["GIT_CONFIG_COUNT"] = str(len(HARDEN))
    for i, (k, v) in enumerate(HARDEN.items()):
        env[f"GIT_CONFIG_KEY_{i}"] = k
        env[f"GIT_CONFIG_VALUE_{i}"] = v
    env["GIT_TERMINAL_PROMPT"] = "0"
    env["GIT_PAGER"] = "cat"
    return env

def git(repo, *args):
    # --no-ext-diff / --no-textconv cover diff.external and diff.*.textconv
    extra = ["--no-ext-diff", "--no-textconv"] if args and args[0] in ("diff", "show", "log") else []
    cmd = ["git", "-C", repo, args[0], *extra, *args[1:]]
    return subprocess.run(cmd, env=hardened_env(), capture_output=True, text=True, timeout=30)

The wrapper also adds --no-ext-diff and --no-textconv to diff-like commands, which switch off diff.external and textconv drivers at the call site. Verification against the same trapped repos:

# demo: core.fsmonitor -> /tmp/pwn.sh
r = git('.', 'status', '--short')   #  M a.txt
os.path.exists('/tmp/PWNED_MARKER') # False

# evil: diff.external -> /tmp/pwn.sh (plain `git diff` created the marker)
git('.', 'diff')
os.path.exists('/tmp/PWNED_MARKER') # False

I also confirmed the GIT_CONFIG_COUNT route alone (no -c flag) blocks the fsmonitor marker. That matters because it works even for tools that shell out to git in places you cannot easily edit, as long as you launch them with the environment set.

Step 5: Wire it into a real workflow

Here is a small launcher that refuses to start an agent in a repo that has high findings, and otherwise starts it with the hardened environment. Replace the claude command with whichever agent you use.

#!/usr/bin/env python3
# safe_open.py <dir> [agent-command...]
import os, subprocess, sys
from pathlib import Path
from gitgate import scan
from safegit import hardened_env

repo = Path(sys.argv[1]).resolve()
findings = scan(repo) if (repo / ".git").exists() else []
high = [f for f in findings if f[0] == "high"]
for lvl, where, detail in findings:
    print(f"[{lvl}] {where}: {detail}", file=sys.stderr)
if high:
    sys.exit("refusing to start agent: repo config names programs. Inspect .git/config first.")
cmd = sys.argv[2:] or ["claude"]
os.execvpe(cmd[0], cmd, hardened_env())  # cwd must be the repo

Two practical notes. First, os.execvpe does not change directory, so cd into the repo (or add os.chdir(repo)) before the exec. Second, the environment trick covers git calls the agent makes, but it cannot protect you from sinks inside the agent's own code paths. The unnamed second key on Claude Code's ultrareview path is a good example: you cannot neutralise a key you have not identified, which is why the scanner flags every program-naming key rather than a short blocklist.

A worked example: the 'can you debug my project' zip

A colleague (or someone pretending to be one) sends checkout-service.zip. Your habit is to unzip it and ask the agent why a test fails.

$ unzip -q checkout-service.zip -d ~/triage
$ python3 safe_open.py ~/triage/checkout-service
[high] config: core.fsmonitor = '/opt/.cache/helper.sh'
refusing to start agent: repo config names programs. Inspect .git/config first.

Now you read the file the scanner pointed at, which takes seconds, instead of finding out afterwards. If the repo is legitimate and the setting is something you recognise, edit it out or copy the working tree without .git and run git init yourself. For source you only need to read, git archive from a trusted clone, or just the files without the .git directory, sidesteps the whole class.

Common pitfalls and gotchas

  • Blocklists age badly. Fixing only core.fsmonitor leaves diff drivers, filters and whatever the next researcher finds. The scanner's pattern list is a floor, so extend it and prefer the allowlist mindset: a normal .git/config contains core basics, remote and branch sections, and little else.
  • fsmonitor can be a boolean. core.fsmonitor=true enables git's built-in daemon rather than an arbitrary command. My scanner still flags anything except false-like values for human review, which is the safer default.
  • Global config is a different trust boundary. The scanner reads only the repo's own files. Your ~/.gitconfig is yours and is trusted by design. Do not point the scanner at it.
  • The sandbox does not help here. The git subprocess is launched by the agent process outside the sandbox boundary, and no approval prompt fires. Do not assume 'read-only mode' or 'ask before running commands' covers background context gathering.
  • Clone is not the vector. Do not tell your team to stop cloning. The risky path is repos handed over as files with .git included. Teach people to be suspicious of zips of working directories specifically.
  • Hooks are a separate trap. Executable files under .git/hooks run on events such as commit. The scanner reports them as review items, and the wrapper points core.hooksPath at /dev/null. Do that only for agent sessions, since it will silently disable your own legitimate hooks.
  • Exit codes are part of the interface. If you call the scanner from CI or a launcher, treat exit 2 as a hard stop and exit 1 as 'a human must look'. Do not collapse them into a single 'warning'.
  • Status tables go stale in days. Re-check vendor advisories rather than trusting the patched/unpatched labels in any blog post, including this one.

Quick reference

TaskCommand or setting
Run a one-off git call with fsmonitor offgit -c core.fsmonitor=false status
Harden every git call in a processGIT_CONFIG_COUNT / GIT_CONFIG_KEY_n / GIT_CONFIG_VALUE_n env vars
Disable external diff and textconvgit diff --no-ext-diff --no-textconv
Disable repo hooks for a sessioncore.hooksPath=/dev/null
Inspect a repo's config safelygit config --file .git/config --list
Scan before openingpython3 gitgate.py (exit 0 clean, 1 review, 2 high)
Safest way to share code for reviewA clone from a trusted remote, or a tree without .git

Next steps

  • Add the scanner to your team's 'received a zip' checklist, and to any internal bot that unpacks user uploads before handing them to an agent.
  • Extend EXEC_KEYS using the list of settings in the git-config documentation whose values are commands, and add a test per key like the marker-file test above.
  • Read Manifold's original GitSpawn post and Adversa's October 2026 roundup (which also lists related issues such as trojanized hook updates and in-repo agent configs) to see how this class overlaps with trusting a repo's own agent settings.
  • Run your agent under a container or VM with no host credentials when opening unfamiliar projects. The scanner reduces risk. Isolation limits what a miss can do.

Sources: Manifold Security, 'GitSpawn: A Single Flaw Lets Untrusted Repos Run Code in Claude Code, Codex, Cursor, and Grok'; Adversa AI, 'AI coding agent vulnerabilities, October 2026'; Aviatrix threat research on CVE-2026-19592; git documentation for core.fsmonitor. All code above was executed locally against git 2.43.0.

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,617 newsletter subscribers.

Also get