# GHSA-4C7Q-GFC8-47VH: Interpretation conflict

- Database: GitHub
- Severity: high (stated by ghsa, no CVSS score)
- Published: 2026-11-23
- Modified: 2026-11-23

## Affected versions

- gix (crates.io): through 0.90.0
- gix-submodule (crates.io): through 0.36.1
- gix-config (crates.io): through 0.62.2
- gix-validate (crates.io): through 0.13.1

## Description

# Configuration Section-Trust Demotion Bypass, Unfiltered `Trust::Reduced` Accessors, and `.gitmodules` Submodule Parser Differentials (`ANT-2026-6SNS6KMP` Follow-Up)

In `GitoxideLabs/gitoxide` at `b8e1eb2a3deaf67d82bdfec0ddad43b693639d8b` (`gix 0.90.0`, `gix-submodule 0.36.1`, `gix-config 0.62.2`, `gix-validate 0.13.1`), incomplete configuration section-trust synchronization (`CWE-349` / `CWE-863`, following `GHSA-f26g-jm89-4g65` / `CVE-2026-40034` / `ANT-2026-6SNS6KMP`, `GHSA-q54r-jf2p-rfr2`, and commit `2145f39c605a7d08d829c84a453fcf50cd020236`) and two submodule/configuration parser differentials against C `git` (`CWE-436`, following `3d3aa94b70b2bda3d5a44de241acfe481458b4a9`) allow repository-local configuration that should be untrusted under `gix_sec::Trust::Reduced` to remain trusted or bypass `filter_config_section()`, and allow `.gitmodules` files containing quoted NUL subsection names (`[submodule "s.url\0"]`) to pass `git fsck --full` while resolving opposite submodule URLs in C `git` versus `gix`.

---

## 1. Affected Versions, Commit Coordinates, & Preconditions

- **Tested `HEAD`:** `b8e1eb2a3deaf67d82bdfec0ddad43b693639d8b` (`gix 0.90.0`, `gix-submodule 0.36.1`, `gix-config 0.62.2`, `gix-validate 0.13.1`)
- **Related Prior Security & Hardening Commits:**
  - `dd5c18d9e526e8de462fa40aa047acd097cfa7dc` & `c860df3659fccd800cdc0b56a0e9851227ce75b3` (`fix(gix): honor section trust when merging submodule overrides`, `GHSA-f26g-jm89-4g65` / `CVE-2026-40034` / `ANT-2026-6SNS6KMP`)
  - `743957880154aa1726b30b8b5779fd10c78a058c` (`fix(gix): respect section trust for filesystem path protections`, `GHSA-q54r-jf2p-rfr2`)
  - `2145f39c605a7d08d829c84a453fcf50cd020236` (`fix(gix): honor configuration trust for security-sensitive settings`)
  - `3d3aa94b70b2bda3d5a44de241acfe481458b4a9` (`fix(gix-config): reject extra tokens after implicit values`)
- **CWEs:**
  - `CWE-349`: Acceptance of Extraneous Untrusted Data With Trusted Data
  - `CWE-863`: Incorrect Authorization (Stale `Section::meta().trust` After Repository Trust Demotion)
  - `CWE-436`: Interpretation Conflict (`gix-submodule` / `gix-config` vs. C `git` `config.c`)
- **Preconditions by Surface:**
  - **Surface A (Worktree-Induced Trust Demotion & `safe.directory` Promotion):**
    - *Demotion bypass (security boundary):* The `git_dir` initially opens at `Trust::Full` (owned by the current user—for example an extracted archive, cached bare/split store, or linked worktree admin dir under `.git/worktrees/<id>`), while its `core.worktree` or worktree `gitdir` points to a path not owned by the current user (or missing on disk), causing `ThreadSafeRepository::open_from_paths` to demote `*git_dir_trust` to `Trust::Reduced` at `gix/src/open/repository.rs:447`.
    - *`safe.directory` promotion (companion non-security functional regression from `2145f39c6`, fixed by the same synchronization helper):* A repository not owned by the current user (`*git_dir_trust == Trust::Reduced`) is allowlisted via trusted `safe.directory` configuration in system/global config.
  - **Surface B (Direct `Trust::Reduced` Unfiltered Accessors):**
    - Any repository opened directly at `gix_sec::Trust::Reduced` (e.g. a directory owned by another user or opened with `.with_trust(gix_sec::Trust::Reduced)`), without requiring `git_dir` to start at `Trust::Full`.
  - **Surface C (`.gitmodules` & `gix-config` Parser Differentials):**
    - Triggered on any cloned repository via tracked `.gitmodules` bytes (or config bytes passed to `gix_config::File::from_bytes*`).

---

## 2. Root-Cause Analysis Across Three Surfaces

### Surface A — `ThreadSafeRepository::open_from_paths` Stale Section Trust & Stage-One Cache Desynchronization (`gix/src/open/repository.rs:310-341, 422-494, 531-554`)

1. **Component A (`open_from_paths` Trust Demotion Loop) Lowers `*git_dir_trust` Without Demoting `Kind::Repository` Sections:**
   When `git_dir` opens with `*git_dir_trust == Trust::Full`, `config::Cache::from_stage_one` (`gix/src/open/repository.rs:310`) parses `.git/config` (`Source::Local` / `Source::Worktree`, `Kind::Repository`) with `section.meta().trust == Trust::Full`. When `worktree_dir` is subsequently checked at `gix/src/open/repository.rs:422-448` and fails `is_path_owned_by_current_user` and `check_safe_directories`, line `447` sets:
   ```rust
   // This is how the worktree-trust can reduce the git-dir trust.
   *git_dir_trust = gix_sec::Trust::Reduced;
   ```
   Immediately below, the section-trust loop (`gix/src/open/repository.rs:455-492`) skips every section that already carries `Trust::Full`:
   ```rust
   let section_trusted_by_default = Safe::directory_filter(section.meta());
   if section_trusted_by_default || section.meta().trust == gix_sec::Trust::Full {
       continue;
   }
   ```
   In addition, `open_from_paths` never calls `config.reread_values_and_clear_caches()` after mutating `*git_dir_trust`.

2. **Component B (`filter_config_section()` Consumers) Trusts Per-Section Metadata Rather Than `repo.git_dir_trust()`:**
   `repo.filter_config_section()` defaults to `config::section::is_trusted` (`meta.trust == gix_sec::Trust::Full`). Because the repository-local sections retained `Trust::Full` even though `repo.git_dir_trust()` is now `Trust::Reduced`, every security-sensitive consumer gated on `filter_config_section()` accepts the untrusted `.git/config`:
   - **External filter driver registration (`gix/src/filter.rs:55, 245`):** `gix::filter::Pipeline::options(&repo)` loads repository-local `filter.<name>.clean`, `smudge`, and `process` external command drivers (reachable via `core.worktree` in `open_opts`, `WorktreeProxy::into_repo` at `gix/src/worktree/proxy.rs:105-132`, or `Submodule::open` at `gix/src/submodule/mod.rs:386-393`).
   - **External transport/credential helpers:** `core.sshCommand` (`gix/src/repository/config/mod.rs:253`) and `credential.helper` (`gix/src/config/snapshot/credential_helpers.rs:86`) remain trusted.
   - **Filesystem path protections (`GHSA-q54r-jf2p-rfr2`):** `Cache::protect_options` (`gix/src/config/cache/access.rs:333-360`) honors repository-local `core.protectNTFS = false` / `core.protectHFS = false`.
   - **Ref-namespace redirection & reduced-trust OOM guard (`2145f39c6`):** `config.refs_namespace` (`gix/src/config/cache/init.rs:84`) retains the untrusted `gitoxide.core.refsNamespace` (redirecting `HEAD` resolution into `refs/namespaces/<ns>/...`, which causes `repo.head()` to fail when that namespaced ref is absent), and `open_from_paths` (`gix/src/open/repository.rs:531-542`) honors repository-local `gitoxide.objects.allocLimitIfReducedTrust` (allowing `0` to disable the reduced-trust allocation cap or `1` to force object reads to fail).

3. **Companion Functional Regression on `safe.directory` Promotion (vs. `2145f39c6^`):**
   Conversely, when `git_dir` starts at `Trust::Reduced` and is promoted to `Trust::Full` via `safe.directory` at `gix/src/open/repository.rs:441-442`, `Cache::from_stage_one` (`:310`, which queries `refs_namespace` using `filter_config_section` since `2145f39c6`) and `Core::WORKTREE` (`:329-335`) have already executed while `.git/config` sections were still `Trust::Reduced`. Because promotion neither happens before `Core::WORKTREE` resolution nor invokes `config.reread_values_and_clear_caches()`, promoted `Trust::Full` repositories silently drop `core.worktree` (`repo.workdir() == None`) and `gitoxide.core.refsNamespace` (`repo.namespace() == None`)—a non-security functional regression resolved by the same bidirectional section-trust helper.

---

### Surface B — Direct `Trust::Reduced` Accessors Omitting `filter_config_section()`

Even when a repository opens directly at `gix_sec::Trust::Reduced` (where all `.git/config` sections carry `meta.trust == Trust::Reduced`), three subsystem paths read `config.resolved` without `filter_config_section`:

1. **`core.symlinks` in `Cache::fs_capabilities` (`gix/src/config/cache/access.rs:306-312`):**
   `fs_capabilities()` reads `symlink: boolean(self, "core.symlinks", &Core::SYMLINKS, true)?` using unfiltered `self.resolved.boolean(...)` instead of `boolean_filter(..., &mut self.filter_config_section.clone())`. An untrusted `.git/config` under `Trust::Reduced` can therefore override `opts.fs.symlink` in `repo.checkout_options(...)` (either flipping the `true` default to `false`, as demonstrated in `repro.rs`, or overriding a trusted system/global `core.symlinks = false` policy with `true`).
2. **Submodule Activation, Recursion, and Configured-State Queries (`gix/src/submodule/mod.rs:57-76, 134-140, 159-172, 265-273`):**
   While `c860df3659fccd800cdc0b56a0e9851227ce75b3` (`GHSA-f26g-jm89-4g65` / `ANT-2026-6SNS6KMP`) filtered `Repository::modules_from_bytes` (`gix/src/repository/submodule.rs:84-96`), `SharedState::active_state_mut` (`submodule/mod.rs:62`) and `Submodule::is_active` (`:162`) pass unfiltered `&self.repo.config.resolved` to `IsActivePlatform`, `Submodule::fetch_recurse` (`:138`) calls unfiltered `resolved.boolean("fetch.recurseSubmodules")`, and `Submodule::state_inner` (`:270`) calls unfiltered `resolved.sections_by_name("submodule")`. An untrusted `.git/config` under `Trust::Reduced` can therefore force `submodule.<name>.active = true` / `submodule.active = .`, alter `fetch.recurseSubmodules`, and set `State::superproject_configuration = true`.
3. **Global Submodule Dirty-Status Suppression (`gix/src/status/index_worktree.rs:293-298`):**
   `submodule_status` reads `diff.ignoreSubmodules` via unfiltered `repo.config_snapshot().string(config::tree::Diff::IGNORE_SUBMODULES)`. Because `diff.ignoreSubmodules` takes precedence over `.gitmodules`, an untrusted `.git/config` under `Trust::Reduced` setting `diff.ignoreSubmodules = all` hides modified/untracked content inside submodules during `repo.status(...)`.

---

### Surface C — `.gitmodules` Quoted-NUL Subsection Split & EOF Escape Quote Differential vs. C `git`

1. **`.gitmodules` Quoted NUL Subsection Split (`gix-submodule/src/lib.rs:43-61, 101-117` & `gix-validate/src/submodule.rs:31-41`):**
   `gix-config` intentionally preserves raw NUL bytes inside quoted subsection headers for lossless event round-tripping (`gix-config/src/parse/from_bytes/tests.rs:283`). However, C `git` (`config.c`) assembles `"submodule." + subsection + "." + key` inside a `strbuf` (`"submodule.s.url\0.note"`) and passes `buf->buf` as a NUL-terminated `const char *` to config callbacks—truncating the key at the first NUL byte so `note = https://beta.example/s` inside `[submodule "s.url\0"]` is parsed by C `git` as `submodule.s.url = https://beta.example/s`.
   On a repository whose `.gitmodules` contains:
   ```ini
   [submodule "s"]
       path = s
       url = https://alpha.example/s
   [submodule "s.url\0"]
       note = https://beta.example/s
   ```
   - `git fsck --full` exits `0` (`parse_submodule_params` sees `submodule.s.url` as a valid URL and does not detect the NUL-truncated suffix).
   - `git submodule init` writes `https://beta.example/s` into `.git/config` (`submodule.s.url`).
   - Unpatched `gix_submodule::File::from_bytes` (`gix::Repository::submodules()`) indexes subsections by full `BStr` (`"s"` vs. `"s.url\0"`), ignoring the second section and returning `https://alpha.example/s`—allowing a `.gitmodules` file that passes `git fsck --full` to present `alpha.example` to `gix` callers while C `git` clones from `beta.example`.
2. **Trailing-Backslash EOF Inside Unterminated Quotes (`gix-config/src/parse/from_bytes/mod.rs:349-356, 393-395`):**
   In `parse::from_bytes::value`, hitting a lone `\` at EOF (`let Some((&escaped, after_escape)) = rest.split_first() else { ... return Ok(()); }`) returns `Ok(())` at line `355` *before* reaching `if is_in_quotes { return Err(()); }` at line `393`. Input such as `[core]\n\teditor = "abc\` is rejected by `git config --file` (`fatal: bad config line`, exit `128`) but accepted by `gix-config`.

---

## 3. Cleanroom Reproduction (`< 1m`, Air-Gapped Docker Compose)

The attached cleanroom bundle builds `GitoxideLabs/gitoxide` at `b8e1eb2a3deaf67d82bdfec0ddad43b693639d8b` (`/src/head`) alongside `/src/fixed` (`HEAD` + `fix.patch`, single differential knob) and runs `9` public-API checks (`3` `[control]` negative controls + `6` `witness` checks) under unprivileged `UID 1000:1000` with `network_mode: none`:

```bash
python3 -B test_e2e.py -v
```

| Check Row | Surface | `HEAD` (`b8e1eb2a3`) | Patched (`fix.patch`) |
| :--- | :--- | :--- | :--- |
| `[control] trust_reduced_driver_protectntfs_namespace_baseline` | Baseline direct `Trust::Reduced` filter (`filter.*`, `protectNTFS`, `refsNamespace` via `head()`, `allocLimit`) | Filtered | Filtered |
| `[control] submodule_url_override_filter_baseline` | `Trust::Full` submodule overrides (`c860df365`) | Honored | Honored |
| `[control] gitmodules_clean_balanced_eof_and_raw_nul_parity` | Clean `.gitmodules`, balanced `\\\n`, & lossless `gix-config` raw NUL event | Preserved | Preserved |
| `s2.witness.worktree_demotion_core_worktree` | Surface A: `open_opts` demotion via foreign/missing `core.worktree` | **Untrusted `filter`, `protectNTFS=false`, `refsNamespace` (`head()` broken), `allocLimit` active** | **Demoted & caches cleared** |
| `s2.witness.worktree_demotion_linked_proxy` | Surface A: linked worktree (`open_path_as_is`) demotion | **Untrusted sections remain `Trust::Full`** | **Demoted & caches cleared** |
| `s2.witness.safe_directory_promotion_regression` | Surface A (functional regression): `safe.directory` promotion of `Trust::Reduced` repo | **`workdir() == None`, `namespace() == None`** | **`workdir()` & `namespace()` populated** |
| `s2.witness.reduced_trust_core_symlinks_override` | Surface B: `Cache::fs_capabilities` `core.symlinks` under `Trust::Reduced` | **Untrusted `.git/config` flips `opts.fs.symlink`** | **Filtered via `boolean_filter`** |
| `s2.witness.reduced_trust_submodule_and_status_overrides` | Surface B: `Submodule::{is_active, fetch_recurse, state}` & `status` `diff.ignoreSubmodules` | **Untrusted `.git/config` activates submodule, sets `superproject_configuration`, & suppresses dirty status** | **Filtered via `filter_config_section`** |
| `s2.witness.gitmodules_nul_subsection_and_eof_quote_split` | Surface C: `[submodule "s.url\0"]` (`git fsck` `0`) & EOF `"abc\` | **`gix` resolves `alpha.example` while `git` registers `beta.example`; EOF `"abc\` accepted** | **Both rejected consistently** |

---

## 4. Suggested Fix Summary (`fix.patch`)

1. **`gix/src/open/repository.rs`:** Introduce `update_repository_section_trust(...)` to synchronize `Kind::Repository` section trust in both directions (promoting sections before `Core::WORKTREE` when `git_dir` matches `safe.directory`, and demoting `Kind::Repository` sections back to `Trust::Reduced` if subsequent `worktree_dir` checks reduce `*git_dir_trust`) followed by `config.reread_values_and_clear_caches()`.
2. **`gix/src/config/cache/access.rs`, `gix/src/repository/submodule.rs`, `gix/src/submodule/mod.rs`, `gix/src/status/index_worktree.rs`:** Filter `core.symlinks` with `boolean_filter`, construct `IsActivePlatform` from `repo.trusted_submodule_config()`, and filter `fetch.recurseSubmodules`, `Submodule::state_inner`, and `diff.ignoreSubmodules` via `repo.filter_config_section()`.
3. **`gix-submodule/src/lib.rs`, `gix-validate/src/submodule.rs`, `gix-config/src/parse/from_bytes/mod.rs`:** Reject NUL bytes in submodule subsection names in `gix_submodule::File::{from_bytes, append_submodule_overrides}` and `gix_validate::submodule::name` (preserving `gix-config` lossless event parsing and non-UTF-8 submodule names), and reject `is_in_quotes` before returning `Ok(())` on trailing `\` at EOF in `gix-config`.

Upstream test suites `cargo test -p gix-validate -p gix-submodule -p gix-config` and `cargo test -p gix` (lib, integration, and doc tests) pass on the patched tree.

---

## 5. Self-Contained Cleanroom Bundle & Unified Patch

<details>
<summary><code>Dockerfile</code></summary>

```dockerfile
FROM rust:1-bookworm

RUN apt-get update -qq \
 && apt-get install -y -qq --no-install-recommends git ca-certificates \
 && rm -rf /var/lib/apt/lists/*

# Pinned public clone of GitoxideLabs/gitoxide; SHA is asserted so the measured tree cannot drift.
RUN git clone https://github.com/GitoxideLabs/gitoxide.git /src/head \
 && cd /src/head \
 && git checkout b8e1eb2a3deaf67d82bdfec0ddad43b693639d8b \
 && test "$(git rev-parse HEAD)" = "b8e1eb2a3deaf67d82bdfec0ddad43b693639d8b"

COPY fix.patch /src/fix.patch

# /src/fixed differs from /src/head by fix.patch only, isolating fix.patch as the single knob.
RUN cp -a /src/head /src/fixed \
 && cd /src/fixed \
 && git apply /src/fix.patch \
 && git diff --stat

COPY Cargo.toml repro.rs /driver/head/
RUN cp -a /driver/head /driver/fixed \
 && sed -i 's|/src/head|/src/fixed|g' /driver/fixed/Cargo.toml \
 && CARGO_TARGET_DIR=/cargo-target cargo build --manifest-path /driver/head/Cargo.toml --bin repro \
 && cp /cargo-target/debug/repro /usr/local/bin/repro-head \
 && CARGO_TARGET_DIR=/cargo-target cargo build --manifest-path /driver/fixed/Cargo.toml --bin repro \
 && cp /cargo-target/debug/repro /usr/local/bin/repro-fixed \
 && rm -rf /cargo-target

USER 1000:1000
CMD ["/usr/local/bin/repro-head"]
```
</details>

<details>
<summary><code>compose.yaml</code></summary>

```yaml
services:
  repro:
    build:
      context: .
      dockerfile: Dockerfile
    image: cleanroom/gitoxide-config-trust-repro:local
    network_mode: none
    user: "1000:1000"
    command: ["/usr/local/bin/repro-head"]
```
</details>

<details>
<summary><code>Cargo.toml</code></summary>

```toml
[package]
name = "gitoxide-config-trust-repro"
version = "0.1.0"
edition = "2024"

[[bin]]
name = "repro"
path = "repro.rs"

[dependencies]
gix = { path = "/src/head/gix", default-features = false, features = ["basic", "attributes", "worktree-mutation", "status", "sha1"] }
gix-config = { path = "/src/head/gix-config" }
gix-sec = { path = "/src/head/gix-sec" }
gix-worktree = { path = "/src/head/gix-worktree" }
gix-hash = { path = "/src/head/gix-hash", features = ["sha1"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tempfile = "3"
```
</details>

<details>
<summary><code>repro.rs</code></summary>

```rust
//! Public-API driver for the configuration-trust fix.
//! With no arguments it runs `repro-head --probe` and `repro-fixed --probe` (JSON over stdout),
//! compares both measurements and prints nine PASS/FAIL rows plus a summary.
//! With `--probe` it only prints its own measurements; no gix private internals are used.
use std::path::{Path, PathBuf};
use std::process::Command;

use gix::bstr::ByteSlice;
use serde_json::{Map, Value, json};

const FIXED: &str = "/usr/local/bin/repro-fixed";
const MODULES: &str = "[submodule \"s\"]\n\tpath = s\n\turl = https://alpha.example/s\n";
/// Configuration a foreign checkout would like to be honoured: filter driver, filesystem-safety
/// switches, ref namespace and a tiny allocation limit.
const UNTRUSTED_CFG: &str = "\tbare = false\n\tsymlinks = false\n\tprotectNTFS = false\n[filter \"custom\"]\n\tsmudge = cat\n\trequired = true\n[gitoxide \"core\"]\n\trefsNamespace = ns1\n[gitoxide \"objects\"]\n\tallocLimitIfReducedTrust = 1\n";

fn git(dir: &Path, args: &[&str]) -> (i32, String) {
    let out = Command::new("git")
        .args(args)
        .current_dir(dir)
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_SYSTEM", "/dev/null")
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .env("GIT_AUTHOR_NAME", "a")
        .env("GIT_AUTHOR_EMAIL", "a@example.com")
        .env("GIT_COMMITTER_NAME", "a")
        .env("GIT_COMMITTER_EMAIL", "a@example.com")
        .output()
        .expect("spawn git");
    (out.status.code().unwrap_or(-1), String::from_utf8_lossy(&out.stdout).into_owned())
}

fn write(path: &Path, content: &str) {
    std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
    std::fs::write(path, content).expect("write");
}

fn append(path: &Path, content: &str) {
    let mut old = std::fs::read_to_string(path).unwrap_or_default();
    old.push_str(content);
    std::fs::write(path, old).expect("append");
}

fn open(path: &Path, trust: Option<gix_sec::Trust>, overrides: Vec<String>, as_is: bool) -> Option<gix::Repository> {
    let mut opts = gix::open::Options::default().open_path_as_is(as_is).config_overrides(overrides);
    if let Some(trust) = trust {
        opts = opts.with_trust(trust);
    }
    gix::open_opts(path, opts).ok()
}

/// A repository whose worktree is `work` and whose git directory is `store`.
fn split_repo(root: &Path, extra_config: &str, modules: Option<&str>) -> PathBuf {
    let work = root.join("work");
    std::fs::create_dir_all(&work).expect("work dir");
    let store = root.join("store");
    git(root, &["init", "-q", "-b", "main", "work"]);
    std::fs::rename(work.join(".git"), &store).expect("move git dir");
    write(&work.join(".git"), &format!("gitdir: {}\n", store.display()));
    append(&store.join("config"), extra_config);
    write(&store.join("refs/heads/main"), "0123456789012345678901234567890123456789\n");
    if let Some(modules) = modules {
        write(&work.join(".gitmodules"), modules);
        git(&work, &["update-index", "--add", "--cacheinfo", "160000,0123456789012345678901234567890123456789,s"]);
    }
    work
}

/// `(untrusted filter driver active, protectNTFS off, symlinks off, HEAD broken, allocation rejected)`.
fn violations(repo: &gix::Repository, blob: Option<gix::ObjectId>) -> [bool; 5] {
    let drivers = gix::filter::Pipeline::options(repo)
        .map(|opts| opts.drivers.iter().any(|d| &*d.name.to_str_lossy() == "custom"))
        .unwrap_or(true);
    let source = gix_worktree::stack::state::attributes::Source::IdMapping;
    let (protect_ntfs, symlink) = match repo.checkout_options(source) {
        Ok(opts) => (opts.validate.protect_ntfs, opts.fs.symlink),
        Err(_) => (false, false),
    };
    let alloc_rejected = blob.is_some_and(|id| repo.find_object(id).is_err());
    [
        drivers,
        !protect_ntfs,
        !symlink,
        repo.head().is_err(),
        alloc_rejected,
    ]
}

fn submodule_state(dir: &Path, trust: Option<gix_sec::Trust>) -> Option<(String, bool, String, String)> {
    let repo = open(dir, trust, Vec::new(), false)?;
    let mut subs = repo.submodules().ok()??;
    let sm = subs.find(|sm| &*sm.name().to_str_lossy() == "s")?;
    Some((
        format!("{:?}", sm.url().ok()?),
        sm.is_active().ok()?,
        format!("{:?}", sm.fetch_recurse().ok().flatten()),
        format!("{:?}", sm.ignore().ok().flatten()),
    ))
}

/// `Submodule::state().superproject_configuration`, i.e. whether `[submodule "s"]` was seen in `.git/config`.
fn submodule_configured(dir: &Path, trust: Option<gix_sec::Trust>) -> Option<bool> {
    let repo = open(dir, trust, Vec::new(), false)?;
    let mut subs = repo.submodules().ok()??;
    let sm = subs.find(|sm| &*sm.name().to_str_lossy() == "s")?;
    sm.state().ok().map(|state| state.superproject_configuration)
}

/// A superproject with a real, dirty submodule checkout at `s`. Only `.git/config` hides submodule
/// changes, via `[diff] ignoreSubmodules = all`; neither `.gitmodules` nor `submodule.s.ignore` repeats it.
fn dirty_submodule_repo(root: &Path) -> PathBuf {
    let src = root.join("src");
    std::fs::create_dir_all(&src).expect("submodule source");
    git(&src, &["init", "-q", "-b", "main"]);
    write(&src.join("tracked"), "one\n");
    git(&src, &["add", "tracked"]);
    git(&src, &["commit", "-q", "-m", "one"]);

    let work = root.join("work");
    std::fs::create_dir_all(&work).expect("superproject work");
    git(&work, &["init", "-q", "-b", "main"]);
    write(&work.join("file"), "one\n");
    git(&work, &["add", "file"]);
    git(&work, &["commit", "-q", "-m", "superproject"]);
    git(
        &work,
        &[
            "-c",
            "protocol.file.allow=always",
            "submodule",
            "add",
            "-q",
            src.to_str().expect("utf8"),
            "s",
        ],
    );
    git(&work, &["commit", "-q", "-m", "submodule"]);
    // The checkout is dirty; rewriting the recorded URL keeps the fixture free of host paths.
    write(&work.join(".gitmodules"), MODULES);
    append(&work.join("s/tracked"), "two\n");
    append(&work.join(".git/config"), "[diff]\n\tignoreSubmodules = all\n");
    work
}

/// Number of `status` items for the submodule path `s` under `mode`, or `None` if status failed.
fn dirty_submodule_items(dir: &Path, trust: gix_sec::Trust, mode: gix::status::Submodule) -> Option<u64> {
    let repo = open(dir, Some(trust), Vec::new(), false)?;
    let items = repo
        .status(gix::progress::Discard)
        .ok()?
        .untracked_files(gix::status::UntrackedFiles::None)
        .index_worktree_submodules(mode)
        .into_iter(None::<gix::bstr::BString>)
        .ok()?;
    let count = items
        .filter_map(Result::ok)
        .filter(|item| match item {
            gix::status::Item::IndexWorktree(gix::status::index_worktree::Item::Modification { rela_path, .. }) => {
                rela_path.as_bytes() == b"s"
            }
            _ => false,
        })
        .count();
    Some(count as u64)
}

fn config_ok(bytes: &[u8]) -> bool {
    gix_config::File::from_bytes_no_includes(bytes, gix_config::file::Metadata::default(), Default::default()).is_ok()
}

fn nul_lossless() -> bool {
    match gix_config::File::from_bytes_no_includes(
        b"[submodule \"s.url\0\"]\n\tnote = x\n".as_slice(),
        gix_config::file::Metadata::default(),
        Default::default(),
    ) {
        Ok(file) => file
            .sections_by_name("submodule")
            .and_then(|mut it| it.next())
            .and_then(|section| section.header().subsection_name().map(ToOwned::to_owned))
            .is_some_and(|name| name == b"s.url\0"),
        Err(_) => false,
    }
}

fn probe() -> Value {
    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path();
    let mut m = Map::new();
    let payload = root.join("payload.bin");
    write(&payload, &"x".repeat(64));

    // Trust demotion caused by `core.worktree` pointing at a checkout we do not own.
    let demote = root.join("demote");
    let _ = split_repo(&demote, &format!("\tworktree = ../missing-worktree\n{UNTRUSTED_CFG}"), None);
    let blob = git(
        &demote.join("store"),
        &["--git-dir", "store", "hash-object", "-w", payload.to_str().expect("utf8")],
    )
    .1;
    let blob = gix::ObjectId::from_hex(blob.trim().as_bytes()).ok();
    if let Some(repo) = open(&demote.join("work"), None, Vec::new(), false) {
        m.insert("demote_violations".into(), json!(violations(&repo, blob)));
    }

    // The same untrusted keys, reached through a linked-worktree proxy whose checkout is gone.
    let linked = root.join("linked");
    let _ = split_repo(&linked, UNTRUSTED_CFG, None);
    let proxy = linked.join("store/worktrees/linked");
    write(&proxy.join("commondir"), "../..\n");
    write(&proxy.join("gitdir"), &format!("{}\n", linked.join("gone/.git").display()));
    write(&proxy.join("HEAD"), "ref: refs/heads/main\n");
    if let Some(repo) = open(&proxy, None, Vec::new(), true) {
        m.insert("linked_violations".into(), json!(violations(&repo, None)));
    }

    // `safe.directory` promotion of a reduced-trust git directory must still honour `core.worktree` and `refsNamespace`.
    let promo = root.join("promo");
    let _ = split_repo(
        &promo,
        "\tbare = false\n\tworktree = sub\n\tprotectNTFS = false\n[gitoxide \"core\"]\n\trefsNamespace = trusted-ns\n",
        None,
    );
    std::fs::create_dir_all(promo.join("store/sub")).expect("sub");
    let sys_cfg = promo.join("system.gitconfig");
    write(&sys_cfg, "[safe]\n\tdirectory = *\n");
    let mut perms = gix::open::Permissions::isolated();
    perms.config.system = true;
    if let Ok(repo) = gix::open_opts(
        &promo.join("store"),
        gix::open::Options::isolated()
            .open_path_as_is(true)
            .with_trust(gix_sec::Trust::Reduced)
            .permissions(perms)
            .system_config_path(&sys_cfg),
    ) {
        let source = gix_worktree::stack::state::attributes::Source::IdMapping;
        let ntfs = repo
            .checkout_options(source)
            .map(|opts| opts.validate.protect_ntfs)
            .ok();
        m.insert(
            "promo_workdir".into(),
            json!(repo.workdir().map(|p| p.display().to_string())),
        );
        m.insert(
            "promo_namespace".into(),
            json!(repo.namespace().map(|n| n.as_bstr().to_string())),
        );
        m.insert("promo_protect_ntfs".into(), json!(ntfs));
    }

    // Control 1: reduced trust never honours the foreign keys.
    let baseline = root.join("baseline");
    let _ = split_repo(&baseline, UNTRUSTED_CFG, None);
    if let Some(repo) = open(&baseline.join("work"), Some(gix_sec::Trust::Reduced), Vec::new(), false) {
        m.insert("ctl_baseline_violations".into(), json!(violations(&repo, None)));
    }
    // Control/witness for `core.symlinks`: honoured while trusted, ignored while untrusted.
    for (key, trust) in [
        ("symlink_trusted", gix_sec::Trust::Full),
        ("symlink_reduced", gix_sec::Trust::Reduced),
    ] {
        if let Some(repo) = open(&baseline.join("work"), Some(trust), Vec::new(), false) {
            let source = gix_worktree::stack::state::attributes::Source::IdMapping;
            let symlink = repo.checkout_options(source).map(|o| o.fs.symlink).unwrap_or(false);
            m.insert(key.into(), json!(symlink));
        }
    }

    // Controls 2/3: trusted overrides are applied, a clean `.gitmodules` is understood.
    let over = root.join("over");
    let over_work = split_repo(
        &over,
        &format!(
            "{UNTRUSTED_CFG}\tworktree = ../missing-override-wt\n[submodule \"s\"]\n\turl = https://beta.example/s\n\tactive = true\n\tignore = all\n[fetch]\n\trecurseSubmodules = no\n[diff]\n\tignoreSubmodules = all\n"
        ),
        Some(MODULES),
    );
    if let Some(state) = submodule_state(&over_work, None) {
        m.insert("ctl_override".into(), json!(state));
    }
    if let Some(state) = submodule_state(&over_work, Some(gix_sec::Trust::Reduced)) {
        m.insert("reduced_override".into(), json!(state));
    }
    // `Submodule::state()` and `status::Submodule::AsConfigured { check_dirty: true }` must ignore
    // `[submodule "s"]` and `[diff] ignoreSubmodules` from an untrusted `.git/config`.
    m.insert("subcfg_full".into(), json!(submodule_configured(&over_work, None)));
    m.insert(
        "subcfg_reduced".into(),
        json!(submodule_configured(&over_work, Some(gix_sec::Trust::Reduced))),
    );
    let dirty_work = dirty_submodule_repo(&root.join("dirty_sub"));
    let dirty = |trust, mode| dirty_submodule_items(&dirty_work, trust, mode);
    let as_configured = gix::status::Submodule::AsConfigured { check_dirty: true };
    let forced = gix::status::Submodule::Given {
        ignore: gix::submodule::config::Ignore::None,
        check_dirty: true,
    };
    m.insert("subcfg_dirty_full".into(), json!(submodule_configured(&dirty_work, None)));
    m.insert(
        "subcfg_dirty_reduced".into(),
        json!(submodule_configured(&dirty_work, Some(gix_sec::Trust::Reduced))),
    );
    m.insert(
        "dirty_full".into(),
        json!(dirty(gix_sec::Trust::Full, as_configured)),
    );
    m.insert(
        "dirty_reduced".into(),
        json!(dirty(gix_sec::Trust::Reduced, as_configured)),
    );
    // Vacuity guard: with the submodule's own `ignore` forced off, the checkout is dirty on both sides.
    m.insert("dirty_forced".into(), json!(dirty(gix_sec::Trust::Reduced, forced)));
    let clean_work = split_repo(&root.join("clean"), "", Some(MODULES));
    m.insert("ctl_clean".into(), json!(submodule_state(&clean_work, None)));
    m.insert(
        "balanced_eof_ok".into(),
        json!(config_ok(b"[submodule \"b\"]\n\tpath = b\n\turl = \"https://gamma.example/g\\\n\tp\"")),
    );
    m.insert("nul_lossless".into(), json!(nul_lossless()));

    // `.gitmodules` with a raw NUL in a subsection name, compared against `git`.
    let nul_mod = root.join("nul_mod");
    let nul_work = split_repo(&nul_mod, "", None);
    std::fs::remove_file(nul_mod.join("store/refs/heads/main")).expect("drop unborn ref");
    write(
        &nul_work.join(".gitmodules"),
        &format!("{MODULES}[submodule \"s.url\0\"]\n\tnote = https://beta.example/s\n"),
    );
    let (fsck_rc, _) = git(&nul_work, &["fsck", "--full"]);
    git(&nul_work, &["update-index", "--add", "--cacheinfo", "160000,0123456789012345678901234567890123456789,s"]);
    let modules_ok = open(&nul_work, None, Vec::new(), false).is_some_and(|repo| repo.open_modules_file().is_ok());
    m.insert("gix_nul_rejects".into(), json!(!modules_ok));
    m.insert("gix_nul_state".into(), json!(submodule_state(&nul_work, None)));
    let (init_rc, _) = git(&nul_work, &["submodule", "init"]);
    let (_, url) = git(&nul_work, &["config", "--local", "--get", "submodule.s.url"]);
    m.insert("git_fsck_ok".into(), json!(fsck_rc == 0));
    m.insert("git_init_ok".into(), json!(init_rc == 0));
    m.insert("git_registered_url".into(), json!(url.trim()));

    // An EOF-split quote inside a quoted value.
    let eof_work = split_repo(&root.join("eof"), "", None);
    write(&eof_work.join("quote.cfg"), "[core]\n\teditor = \"abc\\");
    let (git_eof_rc, _) = git(&eof_work, &["config", "--file", "quote.cfg", "--list"]);
    m.insert("git_eof_quote_ok".into(), json!(git_eof_rc == 0));
    m.insert("gix_eof_quote_ok".into(), json!(config_ok(b"[core]\n\teditor = \"abc\\")));

    Value::Object(m)
}

fn b(v: &Value, key: &str) -> bool {
    v.get(key).and_then(Value::as_bool).unwrap_or(false)
}

fn no_violation(v: &Value, key: &str) -> bool {
    v.get(key)
        .and_then(Value::as_array)
        .is_some_and(|a| a.iter().all(|x| x.as_bool() == Some(false)))
}

/// Reduced-trust baseline: no foreign driver, `protectNTFS` intact, HEAD readable, no size limit.
/// `core.symlinks` is excluded here because it is the subject of its own witness row.
fn baseline_clean(v: &Value, key: &str) -> bool {
    v.get(key)
        .and_then(Value::as_array)
        .is_some_and(|a| {
            [0, 1, 3, 4]
                .iter()
                .all(|i| a.get(*i).and_then(Value::as_bool) == Some(false))
        })
}

fn any_violation(v: &Value, key: &str) -> bool {
    v.get(key)
        .and_then(Value::as_array)
        .is_some_and(|a| a.iter().any(|x| x.as_bool() == Some(true)))
}

fn state(v: &Value, key: &str) -> Option<(String, bool, String, String)> {
    let mut parts = v.get(key)?.as_array()?.iter().map(move |x| x.clone());
    let url = parts.next()?.as_str()?.to_owned();
    let active = parts.next()?.as_bool()?;
    let fetch = parts.next()?.as_str()?.to_owned();
    let ignore = parts.next()?.as_str()?.to_owned();
    Some((url, active, fetch, ignore))
}

fn main() {
    if std::env::args().skip(1).any(|a| a == "--probe") {
        println!("{}", serde_json::to_string(&probe()).expect("json"));
        return;
    }
    let me = std::env::current_exe().expect("current exe");
    let head = probe_of(&me);
    let fixed = probe_of(Path::new(FIXED));
    let trusted_override = |v: &Value| {
        state(v, "ctl_override").is_some_and(|(url, active, fetch, ignore)| {
            url.contains("beta.example") && active && fetch == "Some(Never)" && ignore == "Some(All)"
        })
    };
    let clean_modules = |v: &Value| {
        state(v, "ctl_clean").is_some_and(|(url, ..)| url.contains("alpha.example"))
            && b(v, "balanced_eof_ok")
            && b(v, "nul_lossless")
    };
    // `Submodule::state()` must not see `.git/config [submodule "s"]`, and `repo.status(..)` must not
    // honour `.git/config [diff] ignoreSubmodules = all`, once trust is reduced. `dirty_forced` drops the
    // ignore setting on both builds to prove the checkout really is dirty, so a `0` count cannot be vacuous.
    let reduced_submodule_sites = |v: &Value, head_side: bool| {
        let reported = |key: &str| v.get(key).and_then(Value::as_u64).is_some_and(|n| n >= 1);
        b(v, "subcfg_full")
            && b(v, "subcfg_dirty_full")
            && b(v, "subcfg_reduced") == head_side
            && b(v, "subcfg_dirty_reduced") == head_side
            && v.get("dirty_full").and_then(Value::as_u64) == Some(0)
            && reported("dirty_forced")
            && if head_side {
                v.get("dirty_reduced").and_then(Value::as_u64) == Some(0)
            } else {
                reported("dirty_reduced")
            }
    };
    let rows: Vec<(&str, bool)> = vec![
        (
            "[control] trust_reduced_driver_protectntfs_namespace_baseline",
            baseline_clean(&head, "ctl_baseline_violations") && baseline_clean(&fixed, "ctl_baseline_violations"),
        ),
        (
            "[control] submodule_url_override_filter_baseline",
            trusted_override(&head) && trusted_override(&fixed),
        ),
        (
            "[control] gitmodules_clean_balanced_eof_and_raw_nul_parity",
            clean_modules(&head) && clean_modules(&fixed),
        ),
        (
            "s2.witness.worktree_demotion_core_worktree",
            any_violation(&head, "demote_violations") && no_violation(&fixed, "demote_violations"),
        ),
        (
            "s2.witness.worktree_demotion_linked_proxy",
            any_violation(&head, "linked_violations") && no_violation(&fixed, "linked_violations"),
        ),
        (
            "s2.witness.safe_directory_promotion_regression",
            head.get("promo_workdir") == Some(&Value::Null)
                && head.get("promo_namespace") == Some(&Value::Null)
                && head.get("promo_protect_ntfs") == Some(&Value::Bool(false))
                && fixed.get("promo_workdir").and_then(Value::as_str).is_some()
                && fixed.get("promo_namespace").and_then(Value::as_str) == Some("refs/namespaces/trusted-ns/")
                && fixed.get("promo_protect_ntfs") == Some(&Value::Bool(false)),
        ),
        (
            "s2.witness.reduced_trust_core_symlinks_override",
            !b(&head, "symlink_trusted")
                && !b(&fixed, "symlink_trusted")
                && !b(&head, "symlink_reduced")
                && b(&fixed, "symlink_reduced"),
        ),
        (
            "s2.witness.reduced_trust_submodule_and_status_overrides",
            state(&head, "reduced_override").is_some_and(|(url, active, fetch, ignore)| {
                url.contains("alpha.example") && active && fetch == "Some(Never)" && ignore == "None"
            }) && state(&fixed, "reduced_override").is_some_and(|(url, active, fetch, ignore)| {
                url.contains("alpha.example") && !active && fetch == "None" && ignore == "None"
            }) && reduced_submodule_sites(&head, true)
                && reduced_submodule_sites(&fixed, false),
        ),
        (
            "s2.witness.gitmodules_nul_subsection_and_eof_quote_split",
            !b(&head, "gix_nul_rejects")
                && state(&head, "gix_nul_state").is_some_and(|(url, ..)| url.contains("alpha.example"))
                && b(&fixed, "gix_nul_rejects")
                && b(&fixed, "git_fsck_ok")
                && b(&fixed, "git_init_ok")
                && fixed.get("git_registered_url").and_then(Value::as_str) == Some("https://beta.example/s")
                && b(&head, "gix_eof_quote_ok")
                && !b(&fixed, "gix_eof_quote_ok")
                && !b(&fixed, "git_eof_quote_ok"),
        ),
    ];
    let mut failures = 0;
    for (name, ok) in &rows {
        if !ok {
            failures += 1;
        }
        println!("{} {name}", if *ok { "PASS" } else { "FAIL" });
    }
    if std::env::var_os("REPRO_DUMP").is_some() {
        println!("head={head}");
        println!("fixed={fixed}");
    }
    println!("== summary: checks={} failures={failures} ==", rows.len());
    if failures > 0 {
        std::process::exit(1);
    }
}

fn probe_of(bin: &Path) -> Value {
    let out = Command::new(bin)
        .arg("--probe")
        .output()
        .unwrap_or_else(|err| panic!("cannot run {}: {err}", bin.display()));
    assert!(out.status.success(), "{} --probe failed", bin.display());
    serde_json::from_slice(&out.stdout).unwrap_or_else(|err| panic!("{} emitted invalid JSON: {err}", bin.display()))
}
```
</details>

<details>
<summary><code>test_e2e.py</code></summary>

```python
#!/usr/bin/env python3
"""Host-side cleanroom runner: builds pinned /src/head vs /src/fixed, runs offline under UID 1000, tears down."""
import os
import subprocess
import sys
import unittest

sys.dont_write_bytecode = True

BUNDLE = os.path.dirname(os.path.abspath(__file__))
ENV = dict(os.environ, COMPOSE_PROJECT_NAME="gitoxide-w12-config-trust")


def compose(*args):
    return subprocess.run(
        ["docker", "compose", *args],
        cwd=BUNDLE,
        env=ENV,
        capture_output=True,
        text=True,
    )


class GitoxideConfigTrustBypassE2E(unittest.TestCase):
    def test_repro_passes(self):
        up = compose("up", "--build", "--abort-on-container-exit", "--exit-code-from", "repro")
        print(up.stdout)
        print(up.stderr, file=sys.stderr)
        self.assertEqual(up.returncode, 0, "compose run did not exit 0")
        self.assertIn("== summary: checks=9 failures=0 ==", up.stdout)
        self.assertIn("s2.witness.worktree_demotion_core_worktree", up.stdout)
        self.assertIn("s2.witness.reduced_trust_core_symlinks_override", up.stdout)
        self.assertIn("s2.witness.reduced_trust_submodule_and_status_overrides", up.stdout)
        self.assertIn("s2.witness.gitmodules_nul_subsection_and_eof_quote_split", up.stdout)
        self.assertNotIn("FAIL ", up.stdout)


if __name__ == "__main__":
    try:
        unittest.main(verbosity=2)
    finally:
        compose("down", "-v", "--remove-orphans")
```
</details>

<details>
<summary><code>fix.patch</code></summary>

```diff
diff --git a/gix-config/src/parse/from_bytes/mod.rs b/gix-config/src/parse/from_bytes/mod.rs
index 6a148789c..c1a15840d 100644
--- a/gix-config/src/parse/from_bytes/mod.rs
+++ b/gix-config/src/parse/from_bytes/mod.rs
@@ -348,6 +348,9 @@ fn value(backing: &[u8], i: &mut &[u8], dispatch: &mut dyn FnMut(Event)) -> Pars
             b';' | b'#' if !is_in_quotes => break,
             b'\\' => {
                 let Some((&escaped, after_escape)) = rest.split_first() else {
+                    if is_in_quotes {
+                        return Err(());
+                    }
                     let value = value_start[..value_start.len() - remaining.len()].as_bstr();
                     dispatch(Event::ValueNotDone(Span::new(backing, value)));
                     dispatch(Event::ValueDone(Span::default()));
diff --git a/gix-config/src/parse/from_bytes/tests.rs b/gix-config/src/parse/from_bytes/tests.rs
index f98e1f74d..f27cd9d65 100644
--- a/gix-config/src/parse/from_bytes/tests.rs
+++ b/gix-config/src/parse/from_bytes/tests.rs
@@ -1302,6 +1302,8 @@ mod value {
     #[test]
     fn unterminated_quote_is_rejected() {
         assert!(parse(br#""hello"#).is_err());
+        assert!(parse(br#""hello\"#).is_err());
+        assert!(parse(br#"hello"\"#).is_err());
     }
 }
 
diff --git a/gix-submodule/src/lib.rs b/gix-submodule/src/lib.rs
index f47edf8eb..e463585b8 100644
--- a/gix-submodule/src/lib.rs
+++ b/gix-submodule/src/lib.rs
@@ -3,7 +3,7 @@
 #![forbid(unsafe_code)]
 
 use bstr::ByteSlice;
-use gix_error::Result;
+use gix_error::{Result, bail, validation};
 
 /// All relevant information about a git module, typically from `.gitmodules` files.
 ///
@@ -48,6 +48,9 @@ impl File {
             .flatten()
             .filter_map(|s| s.header().subsection_name().map(|n| (n, s)))
         {
+            if module_name.contains(&0) {
+                bail!(validation("Submodule names must not contain null bytes"));
+            }
             let values = ["url", "fetchRecurseSubmodules", "ignore", "update", "branch"]
                 .map(|field| (field, section.value(field)));
             if values.iter().all(|(_, value)| value.is_none()) {
@@ -69,7 +72,7 @@ impl File {
 
 ///
 pub mod init {
-    use gix_error::{Result, validation};
+    use gix_error::{Result, bail, validation};
     use std::path::PathBuf;
 
     use gix_error::ResultExt;
@@ -109,6 +112,14 @@ pub mod init {
                     .or_raise(|| validation("Could not parse submodule configuration"))?,
                 metadata,
             );
+            if modules
+                .sections_by_name("submodule")
+                .into_iter()
+                .flatten()
+                .any(|section| section.header().subsection_name().is_some_and(|name| name.contains(&0)))
+            {
+                bail!(validation("Submodule names must not contain null bytes"));
+            }
 
             let mut res = Self { config: modules };
             res.append_submodule_overrides(config)
diff --git a/gix-submodule/tests/file/mod.rs b/gix-submodule/tests/file/mod.rs
index 69af94b28..a3717f1f5 100644
--- a/gix-submodule/tests/file/mod.rs
+++ b/gix-submodule/tests/file/mod.rs
@@ -710,3 +710,22 @@ url = ../override
     );
     Ok(())
 }
+
+#[test]
+fn null_bytes_in_submodule_names_are_rejected() -> TestResult {
+    let bytes = b"[submodule \"s\"]\npath = s\nurl = https://alpha.example/s\n[submodule \"s.url\0\"]\nnote = https://beta.example/s\n";
+    assert!(gix_submodule::File::from_bytes(bytes, None, &Default::default()).is_err());
+
+    let mut clean = gix_submodule::File::from_bytes(
+        b"[submodule \"s\"]\npath = s\nurl = https://alpha.example/s\n",
+        None,
+        &Default::default(),
+    )?;
+    let override_with_nul = gix_config::File::from_bytes_no_includes(
+        b"[submodule \"s.url\0\"]\nurl = https://beta.example/s\n",
+        gix_config::file::Metadata::default(),
+        Default::default(),
+    )?;
+    assert!(clean.append_submodule_overrides(&override_with_nul).is_err());
+    Ok(())
+}
diff --git a/gix-validate/src/submodule.rs b/gix-validate/src/submodule.rs
index 639a3c4b7..93cde230c 100644
--- a/gix-validate/src/submodule.rs
+++ b/gix-validate/src/submodule.rs
@@ -8,6 +8,7 @@ pub mod name {
     #[non_exhaustive]
     pub enum Error {
         Empty,
+        NullByte,
         ParentComponent,
     }
 
@@ -15,6 +16,7 @@ pub mod name {
         fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
             match self {
                 Error::Empty => write!(f, "Submodule names cannot be empty"),
+                Error::NullByte => write!(f, "Submodule names must not contain null bytes"),
                 Error::ParentComponent => write!(f, "Submodules names must not contains '..'"),
             }
         }
@@ -32,6 +34,9 @@ pub fn name(name: &BStr) -> Result<&BStr, name::Error> {
     if name.is_empty() {
         return Err(name::Error::Empty);
     }
+    if name.contains(&0) {
+        return Err(name::Error::NullByte);
+    }
     for component in name.as_bytes().split(|b| *b == b'/' || *b == b'\\') {
         if component == b".." {
             return Err(name::Error::ParentComponent);
diff --git a/gix/src/config/cache/access.rs b/gix/src/config/cache/access.rs
index bb60c2514..426788f29 100644
--- a/gix/src/config/cache/access.rs
+++ b/gix/src/config/cache/access.rs
@@ -308,7 +308,13 @@ impl Cache {
             precompose_unicode: boolean(self, "core.precomposeUnicode", &Core::PRECOMPOSE_UNICODE, false)?,
             ignore_case: boolean(self, "core.ignoreCase", &Core::IGNORE_CASE, false)?,
             executable_bit: boolean(self, "core.fileMode", &Core::FILE_MODE, true)?,
-            symlink: boolean(self, "core.symlinks", &Core::SYMLINKS, true)?,
+            symlink: Core::SYMLINKS
+                .enrich_error(
+                    self.resolved
+                        .boolean_filter("core.symlinks", &mut self.filter_config_section.clone()),
+                )
+                .with_lenient_default_value(self.lenient_config, Some(true))?
+                .unwrap_or(true),
         })
     }
 
diff --git a/gix/src/open/repository.rs b/gix/src/open/repository.rs
index 228939a5e..ee9a0475b 100644
--- a/gix/src/open/repository.rs
+++ b/gix/src/open/repository.rs
@@ -325,6 +325,39 @@ impl ThreadSafeRepository {
             use_repository_local_environment,
         )
         .or_raise(|| message("Repository configuration could not be loaded"))?;
+        let safe_dirs_from = |resolved: &gix_config::File| -> Vec<BString> {
+            resolved
+                .strings_filter(Safe::DIRECTORY, &mut Safe::directory_filter)
+                .unwrap_or_default()
+                .into_iter()
+                .collect()
+        };
+        if *git_dir_trust != gix_sec::Trust::Full && worktree_dir.is_none() {
+            let safe_dirs = safe_dirs_from(&config.resolved);
+            if check_safe_directories(
+                git_dir.as_path(),
+                git_install_dir.as_deref(),
+                current_dir,
+                home.as_deref(),
+                &safe_dirs,
+            )
+            .is_ok()
+            {
+                *git_dir_trust = gix_sec::Trust::Full;
+                update_repository_section_trust(
+                    &mut config,
+                    *git_dir_trust,
+                    git_dir.as_path(),
+                    &git_dir,
+                    common_dir_ref,
+                    git_install_dir.as_deref(),
+                    current_dir,
+                    home.as_deref(),
+                    &safe_dirs,
+                )?;
+            }
+        }
+
         // Git's precedence is: GIT_WORK_TREE, core.bare, core.worktree, inferred worktree.
         let configured_worktree = config
             .resolved
@@ -424,12 +457,7 @@ impl ThreadSafeRepository {
                 .as_deref()
                 .is_some_and(|wd| !gix_sec::identity::is_path_owned_by_current_user(wd).unwrap_or(false))
         {
-            let safe_dirs: Vec<BString> = config
-                .resolved
-                .strings_filter(Safe::DIRECTORY, &mut Safe::directory_filter)
-                .unwrap_or_default()
-                .into_iter()
-                .collect();
+            let safe_dirs = safe_dirs_from(&config.resolved);
             let test_dir = worktree_dir.as_deref().unwrap_or(git_dir.as_path());
             let res = check_safe_directories(
                 test_dir,
@@ -447,50 +475,17 @@ impl ThreadSafeRepository {
                 *git_dir_trust = gix_sec::Trust::Reduced;
             }
 
-            let Ok(mut resolved) = gix_parallel::OwnShared::try_unwrap(config.resolved) else {
-                unreachable!("Shared ownership was just established, with one reference")
-            };
-            let section_ids: Vec<_> = resolved.section_ids().collect();
-            let mut is_valid_by_path = BTreeMap::new();
-            for id in section_ids {
-                let Some(mut section) = resolved.section_mut_by_id(id) else {
-                    continue;
-                };
-                let section_trusted_by_default = Safe::directory_filter(section.meta());
-                if section_trusted_by_default || section.meta().trust == gix_sec::Trust::Full {
-                    continue;
-                }
-                let Some(meta_path) = section.meta().path.as_deref() else {
-                    continue;
-                };
-                match is_valid_by_path.entry(meta_path.to_owned()) {
-                    Entry::Occupied(entry) => {
-                        if *entry.get() {
-                            section.set_trust(gix_sec::Trust::Full);
-                        } else {
-                            continue;
-                        }
-                    }
-                    Entry::Vacant(entry) => {
-                        let config_file_is_safe = (meta_path.strip_prefix(test_dir).is_ok()
-                            && *git_dir_trust == gix_sec::Trust::Full)
-                            || check_safe_directories(
-                                meta_path,
-                                git_install_dir.as_deref(),
-                                current_dir,
-                                home.as_deref(),
-                                &safe_dirs,
-                            )
-                            .is_ok();
-
-                        entry.insert(config_file_is_safe);
-                        if config_file_is_safe {
-                            section.set_trust(gix_sec::Trust::Full);
-                        }
-                    }
-                }
-            }
-            config.resolved = resolved.into();
+            update_repository_section_trust(
+                &mut config,
+                *git_dir_trust,
+                test_dir,
+                &git_dir,
+                common_dir_ref,
+                git_install_dir.as_deref(),
+                current_dir,
+                home.as_deref(),
+                &safe_dirs,
+            )?;
         }
 
         // Trust promotion and trusted overrides are only available after configuration is resolved.
@@ -714,6 +709,59 @@ fn replacement_objects_refs_prefix(
     Ok(Some(ref_base))
 }
 
+#[expect(clippy::too_many_arguments)]
+fn update_repository_section_trust(
+    config: &mut config::Cache,
+    git_dir_trust: gix_sec::Trust,
+    test_dir: &Path,
+    git_dir: &Path,
+    common_dir: &Path,
+    git_install_dir: Option<&Path>,
+    current_dir: &Path,
+    home: Option<&Path>,
+    safe_dirs: &[BString],
+) -> Result<()> {
+    let resolved = std::mem::replace(
+        &mut config.resolved,
+        gix_config::File::default().into(),
+    );
+    let Ok(mut resolved) = gix_parallel::OwnShared::try_unwrap(resolved) else {
+        unreachable!("Shared ownership was just established, with one reference")
+    };
+    let section_ids: Vec<_> = resolved.section_ids().collect();
+    let mut is_valid_by_path = BTreeMap::new();
+    for id in section_ids {
+        let Some(mut section) = resolved.section_mut_by_id(id) else {
+            continue;
+        };
+        if section.meta().source.kind() != gix_config::source::Kind::Repository {
+            continue;
+        }
+        let Some(meta_path) = section.meta().path.as_deref() else {
+            section.set_trust(git_dir_trust);
+            continue;
+        };
+        let config_file_is_safe = match is_valid_by_path.entry(meta_path.to_owned()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let belongs_to_this_repo = meta_path.strip_prefix(test_dir).is_ok()
+                    || meta_path.strip_prefix(git_dir).is_ok()
+                    || meta_path.strip_prefix(common_dir).is_ok();
+                let is_safe = (belongs_to_this_repo && git_dir_trust == gix_sec::Trust::Full)
+                    || check_safe_directories(meta_path, git_install_dir, current_dir, home, safe_dirs).is_ok();
+                *entry.insert(is_safe)
+            }
+        };
+        section.set_trust(if config_file_is_safe {
+            gix_sec::Trust::Full
+        } else {
+            gix_sec::Trust::Reduced
+        });
+    }
+    config.resolved = resolved.into();
+    config.reread_values_and_clear_caches()
+}
+
 fn check_safe_directories(
     path_to_test: &std::path::Path,
     git_install_dir: Option<&std::path::Path>,
diff --git a/gix/src/repository/submodule.rs b/gix/src/repository/submodule.rs
index 486c334c3..50358911d 100644
--- a/gix/src/repository/submodule.rs
+++ b/gix/src/repository/submodule.rs
@@ -81,7 +81,7 @@ impl Repository {
         }
     }
 
-    fn modules_from_bytes(&self, bytes: &[u8], path: Option<std::path::PathBuf>) -> Result<gix_submodule::File> {
+    pub(crate) fn trusted_submodule_config(&self) -> Result<gix_config::File> {
         let mut overrides = gix_config::File::new(self.config.resolved.meta_owned());
         for section in self
             .config
@@ -92,6 +92,11 @@ impl Repository {
         {
             overrides.push_section(section.to_owned())?;
         }
+        Ok(overrides)
+    }
+
+    fn modules_from_bytes(&self, bytes: &[u8], path: Option<std::path::PathBuf>) -> Result<gix_submodule::File> {
+        let overrides = self.trusted_submodule_config()?;
         gix_submodule::File::from_bytes(bytes, path, &overrides)
     }
 
diff --git a/gix/src/status/index_worktree.rs b/gix/src/status/index_worktree.rs
index 5c19d7524..b716ad672 100644
--- a/gix/src/status/index_worktree.rs
+++ b/gix/src/status/index_worktree.rs
@@ -291,8 +291,12 @@ mod submodule_status {
                 Submodule::AsConfigured { check_dirty } => {
                     // diff.ignoreSubmodules is the global setting, and if it exists, it overrides the submodule's own ignore setting.
                     let global_ignore = repo
-                        .config_snapshot()
-                        .string(config::tree::Diff::IGNORE_SUBMODULES)
+                        .config
+                        .resolved
+                        .string_filter(
+                            config::tree::Diff::IGNORE_SUBMODULES,
+                            &mut repo.filter_config_section(),
+                        )
                         .map(|value| config::tree::Diff::IGNORE_SUBMODULES.try_into_ignore(value))
                         .transpose()
                         .with_leniency(repo.config.lenient_config)?;
diff --git a/gix/src/submodule/mod.rs b/gix/src/submodule/mod.rs
index f7f6f8410..ca585d766 100644
--- a/gix/src/submodule/mod.rs
+++ b/gix/src/submodule/mod.rs
@@ -54,12 +54,13 @@ impl<'repo> SharedState<'repo> {
         }))
     }
 
-    fn active_state_mut(&self) -> Result<(RefMut<'_, IsActivePlatform>, RefMut<'_, gix_worktree::Stack>)> {
+    fn active_state_mut(&self) -> Result<RefMut<'_, IsActiveState>> {
         let mut state = self.is_active.borrow_mut();
         if state.is_none() {
+            let config = self.repo.trusted_submodule_config()?;
             let platform = self
                 .modules
-                .is_active_platform(&self.repo.config.resolved, self.repo.config.pathspec_defaults()?)?;
+                .is_active_platform(&config, self.repo.config.pathspec_defaults()?)?;
             let index = self.index()?;
             let attributes = self
                 .repo
@@ -69,17 +70,19 @@ impl<'repo> SharedState<'repo> {
                         .adjust_for_bare(self.repo.is_bare()),
                 )?
                 .detach();
-            *state = Some(IsActiveState { platform, attributes });
+            *state = Some(IsActiveState {
+                platform,
+                config,
+                attributes,
+            });
         }
-        Ok(RefMut::map_split(state, |opt| {
-            let state = opt.as_mut().expect("populated above");
-            (&mut state.platform, &mut state.attributes)
-        }))
+        Ok(RefMut::map(state, |opt| opt.as_mut().expect("populated above")))
     }
 }
 
 struct IsActiveState {
     platform: IsActivePlatform,
+    config: gix_config::File,
     attributes: gix_worktree::Stack,
 }
 
@@ -134,8 +137,13 @@ impl Submodule<'_> {
     pub fn fetch_recurse(&self) -> Result<Option<config::FetchRecurse>> {
         Ok(match self.state.modules.fetch_recurse(self.name())? {
             Some(val) => Some(val),
-            None => crate::config::tree::Fetch::RECURSE_SUBMODULES
-                .try_into_recurse_submodules(self.state.repo.config.resolved.boolean("fetch.recurseSubmodules"))?,
+            None => crate::config::tree::Fetch::RECURSE_SUBMODULES.try_into_recurse_submodules(
+                self.state
+                    .repo
+                    .config
+                    .resolved
+                    .boolean_filter("fetch.recurseSubmodules", &mut self.state.repo.filter_config_section()),
+            )?,
         })
     }
 
@@ -157,12 +165,13 @@ impl Submodule<'_> {
     ///
     /// Please see the [plumbing crate documentation](gix_submodule::IsActivePlatform::is_active()) for details.
     pub fn is_active(&self) -> Result<bool> {
-        let (mut platform, mut attributes) = self.state.active_state_mut()?;
-        let is_active = platform.is_active(
-            &self.state.repo.config.resolved,
+        let state = &mut *self.state.active_state_mut()?;
+        let is_active = state.platform.is_active(
+            &state.config,
             self.name.as_ref(),
             &mut |relative_path, case, is_dir, out| {
-                attributes
+                state
+                    .attributes
                     .set_case(case)
                     .at_entry(relative_path, Some(is_dir_to_mode(is_dir)), &self.state.repo.objects)
                     .is_ok_and(|platform| platform.matching_attributes(out))
@@ -267,7 +276,7 @@ impl Submodule<'_> {
             .repo
             .config
             .resolved
-            .sections_by_name("submodule")
+            .sections_by_name_and_filter("submodule", self.state.repo.filter_config_section())
             .into_iter()
             .flatten()
             .any(|section| section.header().subsection_name() == Some(self.name.as_ref()));
```
</details>

## References

- https://github.com/GitoxideLabs/gitoxide/security/advisories/GHSA-4c7q-gfc8-47vh

Page: https://cve.now/GHSA-4C7Q-GFC8-47VH

Wrong or missing data? Send feedback: POST https://cve.now/api/v1/feedback (see https://cve.now/agents#feedback).
