Technical Deep-Dive14 min read

Gitleaks or Semgrep Clean Scan: Hash Every Policy Input

Gitleaks and Semgrep read config and ignore files from repo or environment, so a clean report can hide a weak policy. Hash inputs before and after the scan.

tl;dr Gitleaks and Semgrep take config, rules and ignore files from the repository being scanned or from the environment, so a clean report from a weakened policy looks the same as a real pass. Hash every policy input (config, extensions, ignore file, environment, scanner binary) before and after the scan, write the report outside the scanned repository, and downgrade a clean result to indeterminate when that binding cannot be resolved or changes mid-scan. A resolved binding makes a weak config visible, because its byte hash differs from a known good one. It does not judge the rules.

A scanner that reads its rules from the repository it is scanning can be told what to look for by that repository. If you run Gitleaks (a secret scanner) or Semgrep (a static analyzer) over code you do not fully control and file the clean report as evidence, this post gives you a way to bind that report to the config, ignore files, environment and scanner binary observed around the scan, and to refuse to call it clean when that binding fails.

When no --config flag is passed, Gitleaks picks its config from an environment variable naming a file, a second environment variable holding the TOML config text itself, a .gitleaks.toml at the target root, or its embedded defaults, in that order. It also honours a root .gitleaksignore. Semgrep has its own selectors and its own ignore sources, including .semgrepignore. Every one of those inputs can live inside the scanned tree or in the environment the scan inherits.

So a repository can ship a .gitleaks.toml whose rules match nothing, or a .gitleaksignore that suppresses everything, and the Gitleaks scan exits 0 with an empty findings list. That report has the same shape as a real pass. Before the fix described here, the audit tooling I maintain recorded both with the same policy_hash. That hash covered the command line the tooling ran and whether the check was blocking or advisory. It did not cover which config, ignore file or binary the scanner was pointed at.

The relevant part of that tooling is a scanner adapter. It wraps Gitleaks, Semgrep and Syft, normalises their output into evidence rows, and fails closed when a required gate cannot be measured. Three changes merged on the same day. Together they narrow the gap: a clean Gitleaks or Semgrep result now carries a hash of its policy inputs, and it cannot pass when those inputs cannot be pinned down. None of them judges whether the policy is any good, which the validation section comes back to. The first of the three started as a separate bug.

The bug that came first: a report named -

The Gitleaks adapter used to ask for the JSON report on stdout with --report-path -. Some Gitleaks versions treat - as a filename. Those versions can leave a file literally named - in the audited repository, and the adapter then rejects the run because stdout holds no JSON.

That is two defects at once. The audit writes into its subject (the repository being audited), and a clean scan becomes an operational error. The change’s own record lists three behavioural failures when new file-report fixtures ran against the old adapter: clean reports were rejected, findings reports were rejected, and a missing report with stdout [] incorrectly passed. That last one is the dangerous direction. In that fixture, absent evidence read as a clean result. Empty Is Not Clean: Five Fail-Open Bugs in an AI Agent catalogues the same direction in a different codebase.

The fix writes the report to a private temporary directory outside the subject and reads only that file. Stdout is never a fallback. Here is the capture, from scripts/scan.py:

def run_gitleaks(argv, repo, environment=None):
    temporary_root = os.path.realpath(tempfile.gettempdir())
    try:
        inside_subject = os.path.commonpath((temporary_root, os.path.realpath(repo))) == os.path.realpath(repo)
    except ValueError:
        inside_subject = False  # different Windows drives cannot overlap
    if inside_subject:
        raise ValueError("report temporary directory is inside subject")
    with tempfile.TemporaryDirectory(prefix="audit-harness-gitleaks-", dir=temporary_root) as directory:
        report_path = os.path.join(directory, "report.json")
        command = [*argv[:-1], report_path]
        proc = subprocess.run(command, cwd=repo, env=environment, capture_output=True, timeout=300)
        if proc.returncode not in (0, 10):
            return proc, b""
        fd = os.open(report_path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
        with os.fdopen(fd, "rb") as report:
            info = os.fstat(report.fileno())
            named = os.lstat(report_path)
            if (not stat.S_ISREG(info.st_mode) or not stat.S_ISREG(named.st_mode)
                    or info.st_nlink != 1 or (info.st_dev, info.st_ino) != (named.st_dev, named.st_ino)):
                raise ValueError("report is not a regular single-link file")
            if info.st_size > SECURITY_REPORT_LIMIT:
                raise OverflowError("report too large")
            payload = report.read(SECURITY_REPORT_LIMIT + 1)
        return proc, payload

Three details matter. First, the temp root is checked against the subject before anything is created, so a TMPDIR pointed inside the repo refuses instead of writing there. Second, the file is opened with O_NOFOLLOW, and the open descriptor’s device and inode must match the name’s lstat, with a single link and a regular file. A report swapped for a symlink or a hard link to something else does not get read. Third, exit code 10 is the adapter’s chosen finding code (--exit-code 10), because Gitleaks’ default exit code 1 also means “error.”

The evidence row records the command with <private-report> in place of the temp path, so the recorded command is stable across runs. The temporary directory is removed after success and after refusal. At that point the suite held 17 scanner contract tests, all passing. They are fake scanner contracts, not a run of a historical Gitleaks binary, and I am not claiming otherwise.

That fix made the report trustworthy as a file. It did nothing about the rules that produced it. Where the report came from and which policy produced it are separate questions, and a clean result needs an answer to both.

Why not pin a trusted Gitleaks config?

The obvious fix is to pin the config: pass --config /trusted/gitleaks.toml and stop caring what the repo ships. For an operator who controls the invocation that is a valid control. The adapter exposes no flag for it, but the same pin is available through the environment: setting GITLEAKS_CONFIG to a trusted file selects that file, and the binding records the selection like any other. The adapter does not add a pin of its own, for two reasons.

First, its contract is to measure the scanner as the operator configured it. It does not add a configuration flag or select replacement rules. Choosing rules inside the adapter would change what “clean” means for every consumer at once.

Second, a pin covers one input. The ignore file, the rest of the environment and the binary would still be unbound. So would the pin: a trusted path can hold different bytes next month, and the clean result would look the same. A pinned config still needs a hash beside it.

The adapter cannot infer a config on the scanner’s behalf either. For Semgrep, hashing a presumed .semgrep.yml does not establish what the command ran. Selection differs by version, and current upstream Semgrep defaults unspecified rules to auto, which it rejects with metrics disabled. Guessing the config and hashing the guess produces a confident number about the wrong thing.

So the approach is narrower. Work out which inputs the scanner’s documented selection rules point at, hash them, hash them again after the scan, and when the selection cannot be determined, say so.

The policy binding manifest: hashing config and ignore files

The second change adds metadata.policy_binding to the Gitleaks and Semgrep rows for scans that run. It is a scanner-policy-binding/v1 manifest: a list of source records, each holding a kind code, a hash of the selector label and a hash of the bytes. No config values, environment names or values, or filesystem paths are copied in.

Here is the Gitleaks branch of capture_policy in scripts/scanner_policy.py, which follows the same precedence Gitleaks does:

    # inside capture_policy(tool, repo, executable, environment)
    if tool == "gitleaks":
        if environment.get("GITLEAKS_CONFIG"):
            selector = "env-path"
            data = read(repo / environment["GITLEAKS_CONFIG"])
        elif environment.get("GITLEAKS_CONFIG_TOML"):
            selector = "env-toml"
            data = environment["GITLEAKS_CONFIG_TOML"].encode("utf-8", errors="surrogateescape")
            if len(data) > LIMIT:
                reasons.add("dependency-limit")
                data = None
            else:
                record("inline-config", selector, data)
        else:
            selector = "target-or-builtin"
            data = read(repo / ".gitleaks.toml", optional=True)
        gitleaks_config(data)
        read(repo / ".gitleaksignore", optional=True)
    # ... semgrep branch ...
    return {"schema": "scanner-policy-binding/v1", "status": "unresolved" if reasons else "resolved",
            "selector": selector, "reasons": sorted(reasons),
            "sources": sorted(entries, key=lambda e: (e["kind"], e["selector_hash"], e["bytes_hash"]))}

Every read records a missing file as its own absent kind, and optional=True only stops that absence from marking the binding unresolved. A missing .gitleaksignore is a fact in the manifest, so adding one later changes the hash. When no target config exists, the selected executable stands in for the embedded defaults.

gitleaks_config then walks extend.path dependencies, at most two levels deep. It refuses any spelling it cannot be sure Gitleaks reads the same way. Gitleaks loads config through Viper, which can normalise key case and delimiters differently from Python’s tomllib, so a key like Extend, a quoted top-level key named "extend.path" or Path inside the extend table marks the binding unsupported-config rather than risk missing a file Gitleaks would load.

This is where a crash showed up. A 3,003-byte deeply nested TOML fixture reproduced a RecursionError before the bounded parser refusal was corrected. In the merged version that error is caught with the others, so pathological nesting lands as unsupported-config instead of crashing the adapter:

        # the handler that closes gitleaks_config's try block
        except (ValueError, UnicodeError, RecursionError):
            reasons.add("unsupported-config")

Reads are bounded throughout: regular files only, symlinks refused, at most 256 source records, 1 MiB per file and 4 MiB of configuration bytes in total. A read whose stat witness changes during the read is refused as unstable.

Hash the scanner binary before and after the scan

The manifest is captured twice. The executable is resolved first, and that needed care: exec searches relative PATH entries after changing into the child’s cwd. When PATH holds relative entries, resolving with the parent’s shutil.which could hash a different binary than the one that runs.

def security_executable(tool, repo, environment):
    # exec searches relative PATH entries after chdir(cwd=repo). Resolve that
    # same selection before hashing it; parent-cwd shutil.which would disagree.
    search = os.pathsep.join(os.path.abspath(os.path.join(repo, part))
                             for part in environment.get("PATH", os.defpath).split(os.pathsep))
    return shutil.which(tool, path=search)

The adapter invokes that resolved path with the captured environment, hashes the file’s bytes separately (128 MiB maximum), and folds the manifest into policy_hash. The whole inherited environment is hashed too, which means unrelated environment changes also move the policy identity. I accepted that noise over guessing which variables matter. The aggregate also moves with the checkout location, because the selector hash of each file record is taken over that file’s absolute path. So policy_hash is comparable only within one environment, and the environment record does not travel at all. The portable parts are the bytes_hash values of the config, extension and ignore-file records, which depend only on those files’ bytes. The manifest does not label which file record is which, so a check across environments is set membership: the byte hash expected for the config is either present in the manifest or it is not.

After the report is parsed and validated, the adapter captures the manifest again and compares:

    # inside run_security_tool, after the report is parsed and validated
    if binding is not None:
        after_environment = dict(os.environ)
        after = capture_policy(tool, repo, security_executable(tool, repo, after_environment), after_environment)
        if binding != after:
            metadata["policy_binding"] = dict(binding, status="unresolved", reasons=["policy-drift"])
            metadata["policy_binding_after_hash"] = sha256_str(json.dumps(after, sort_keys=True))
            if not findings:
                return unavailable("policy-drift", "scanner policy inputs changed during measurement")
        if binding["status"] != "resolved" and not findings:
            return unavailable("policy-unresolved", "effective scanner policy could not be bound")

The two not findings conditions only bite on a clean result. Findings are real regardless of the policy that produced them, so a run with findings keeps its count and severity and records the unresolved binding beside them. It does not count as a complete policy scan. A clean run with an unresolved or drifted binding cannot become PASS. It becomes an indeterminate advisory, or FAIL when the gate is required under --fail-closed.

Semgrep: supported narrowly, unresolved by default

Semgrep binding is deliberately smaller. It resolves only when SEMGREP_RULES names an existing local rules file, or a directory whose .yaml/.yml files get bound, by absolute path or explicit ./ or ../, the subject has an explicit root .semgrepignore, and the subject is not inside a Git checkout. Bare selectors stay unresolved even when a same-named local file exists. So do auto, registry selectors, remote URLs, nested ignore files, :include directives, other SEMGREP_* settings and any GIT_* override.

That last condition is the costly one. Ordinary Git checkouts stay unresolved, including a subject below an ancestor Git root. That is a real limitation: under this contract a clean Semgrep run over an ordinary Git checkout reports indeterminate, not clean. I would rather merge that than a green result that cannot say which policy inputs it was bound to.

The third change came out of a late review finding on the second one. The Git check looked for .git in the lexical ancestry of the subject path. A symlinked subject directory, or a symlink above it, can point into a subdirectory of a real Git checkout while its lexical parents show no .git. The scanner’s cwd follows the alias; the check did not. Through such an alias, a clean fake-scanner report could establish a resolved binding and PASS. The fix adds an alias check beside the lexical one:

        # semgrep branch of capture_policy; repo is Path(repo).absolute()
        try:
            if repo.resolve(strict=True) != repo:
                reasons.add("subject-alias-unresolved")
        except (OSError, RuntimeError):
            reasons.add("subject-path-unresolved")

Comparing the physical and lexical paths now leaves any aliased subject unresolved. It does not change the scanner cwd and does not claim race-proof custody of the directory.

What the validation actually shows

The numbers here are the ones recorded in the three changes’ own descriptions. The second change records a focused scanner suite of 36 tests: 22 CLI and report contracts (the earlier 17 had grown) and 14 policy-binding controls, all against fake scanners and private fixtures. The alias fix added one test to each group, for 38. The second change also records an offline installer suite, separate from the scanner suite, passing 22 tests, including an isolated installed import that leaves the subject free of Python bytecode writes. And it records an old-source counterfactual with two intended failures: a clean result with unresolved policy and a clean result with policy drift.

The limits of that evidence are plain. The tests never ran a real Gitleaks or Semgrep binary, they certify compatibility with zero scanner versions, and this source version is not tagged or released as a package. The published package is still 2.0.0. The repository, intent-audit-harness (an in-repo package of deterministic test-quality checks), is public.

The documented limits are where this breaks. Hashes are not confidentiality: someone who already knows a candidate value can confirm it by dictionary. The executable hash identifies the launcher, not a full interpreter or package install. Before and after observation is a check, not an atomic snapshot, so a concurrent writer that restores bytes between the two reads goes undetected. Source suppression comments and Git history remain subject inputs, outside this contract. Syft is not bound at all.

A resolved binding also does not judge the policy. A .gitleaks.toml whose rules match nothing still resolves, and a clean scan under it still passes. What changed is that its bytes_hash in the manifest differs from a real config’s, so the weak policy is visible where before it was indistinguishable. Someone still has to check that the byte hash expected for the config is the one in the manifest. The binding covers the inputs the scanner’s documented precedence points at, as the adapter reads them. It does not observe what the scanner loaded, validate rules or replace Gitleaks’ parser.

Use this

  • Hash every input your scanner’s selection rules point at (config, extension files, ignore file, inherited environment, resolved binary) and store those hashes next to the result. Before trusting a clean result, check that the byte hashes you expect for the config and ignore files are present. An aggregate that folds in the environment and absolute paths only matches within one environment.
  • Capture those inputs again after the scan and treat any clean result as indeterminate when the two captures differ or a selector cannot be resolved.
  • Write scanner reports to a temp directory outside the scanned tree, open them with O_NOFOLLOW, and never fall back to stdout when the file is missing.

The full contract, including every unresolved case, is in the scanner documentation.

FAQ

How does Gitleaks choose its config file?

When no –config flag is passed, Gitleaks picks its config from an environment variable naming a file, a second environment variable holding the config text, a .gitleaks.toml at the target root, or its embedded defaults, in that order. It also honours a root .gitleaksignore.

Can a repository disable Gitleaks rules with its own .gitleaks.toml or .gitleaksignore?

Yes. When the config is not set by flag or environment, Gitleaks reads .gitleaks.toml from the repository being scanned, and a root .gitleaksignore is honoured either way. So a repository can ship a .gitleaks.toml whose rules match nothing, or a .gitleaksignore that suppresses everything. The scan then exits 0 with an empty findings list, and that report has the same shape as a real pass.

How do you tie a clean scan to the scanner config behind it?

Hash every input the scanner’s selection rules point at (config, extension files, ignore file, inherited environment, resolved binary) before the scan, capture those inputs again after it, and write the report outside the scanned tree. If the two captures differ or a selector cannot be resolved, treat the clean result as indeterminate rather than PASS. The hash identifies the policy and does not judge its rules. Before and after observation is a check, not an atomic snapshot, so a concurrent writer that restores bytes between the two reads goes undetected.

Related Posts: