Files
pruefwerk/docs/features/control-mapping.md
T
sharangandClaude Opus 5.5 d406741907
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m13s
CI / Deploy Agent (push) Successful in 6m21s
feat(sast): vendored MIT semgrep packs and a guard against registry rules (#492) (#504)
Our ~35 own rules left whole languages without SAST findings. Three
permissively licensed community packs now run next to them, on the same
semgrep invocation (--metrics=off, local files only):

- GitLab sast-rules v2.10.1 (53bf5cf6): 148 rules for C#, Java,
  JavaScript/TypeScript, Python and one Go rule; only files whose header says
  "License: MIT (c) GitLab Inc.". Not vendored: c/ (every file GPL-2.0,
  generated from flawfinder), go/ apart from one file (Apache-2.0 gosec
  ports), scala/, rules/lgpl, rules/lgpl-cc (Commons Clause), rules/gitlab (EE).
- 0xdea semgrep-rules (dae50da6, MIT): 35 C/C++ rules.
- elttam semgrep-rules (24426856, MIT; its LICENSE carries the Semgrep
  template's copyright line): 34 rules for Java, Go and Struts/Spring XML.

Each pack lives in compliance-agent/rules/vendor/<source>/ with LICENSE,
NOTICE (provenance, what was left out and why) and UPSTREAM (pinned commit):
upstream/ holds the selected files unchanged with their tests, pack.yaml the
rules the agent runs, ids prefixed per source (gitlab-, 0xdea-, elttam-),
rules.json an index for the tests. scripts/vendor-semgrep-rules.py
regenerates all of it deterministically.

Provenance: every candidate rule was compared with the Semgrep registry
(semgrep/semgrep-rules, read only for the comparison). Eight GitLab Python/JS
rules with the same message or the same patterns are not vendored, nor are
elttam's Kubernetes rules (registry-derived). Also left out: elttam's
entrypoint enumerators, its ORM-leak hints, three files whose upstream
tests fail on semgrep 1.177 and a join-mode rule.

Noise budget: run over the nightly fixtures, the public samples and
FreeRTOS-Kernel, lwIP, OpenRA, eShopOnWeb, requests, express and
spring-petclinic. 15 rules that flood real code (0xdea missing-return 1514
hits, typos 989, interesting-api-calls 718, signed-unsigned-conversion 221,
suspicious-assert 176, format-string-bugs 61 ...; GitLab assert-used) are
dropped from the pack, each listed with its reason in NOTICE. CPU time of
the semgrep run roughly doubles on C-heavy trees (FreeRTOS-Kernel 70 s ->
136 s, lwIP 18 s -> 68 s), well inside the 10-minute stage timeout.

Ids stay bare (#473 logic covers the vendored ids, fingerprint() unchanged).
The control map gets one vendored semgrep binding per control, by CWE (by
rule id for the few elttam rules without one), with exactly the languages of
the rules behind it; a test checks every vendored rule maps to a control
that claims its languages.

Guard: semgrep_args() builds the one invocation; a test fails if any
--config is not a staged local pack, or is auto, p/, r/ or a URL, and
another scans the agent source, scripts, docker/, CI and Dockerfile.agent for
a registry config.

Nightly baselines with C, Python, C# or JS code change and need a bless run
after the image is deployed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-10-06 12:22:50 +00:00

18 KiB
Raw Blame History

Compliance Control Mapping

Control mapping connects the scanner's raw output — deterministic tool findings and the code itself — to the compliance controls each piece of evidence supports. A hardcoded credential stops being just "CWE-798 from semgrep" and becomes evidence for "cra-ai-8: no default passwords" and, at scale, master control mc-31761 hardcoded_secrets_detection. Findings carry those references (control_refs) into the dashboard and out over the MCP server as OSCAL, so the compliance report is built from real, grounded findings rather than a questionnaire.

The core principle: tools detect, the LLM judges

The design has one rule, borrowed from the ZeroFalse / IRIS line of research: deterministic tools are the detectors; the LLM is only ever a grounded false-positive filter, never the thing that finds the issue.

  • A tool (semgrep, gitleaks, syft/osv, the PLC linter; the DAST agents today, with Nuclei and ZAP planned as deterministic web/OT detectors underneath them — see Tools & Scanners) detects.
  • An authored, human-reviewed lookup table (control-map) maps that detection to the control(s) it's evidence for.
  • The LLM enters last, to confirm or refute the mapping against the actual code — and every surviving verdict is anchored to a verbatim snippet by the grounding gate. The judge decides the mapping, never whether a finding exists: a refuted finding is kept for a person to review, not hidden (#367).

This keeps hallucination out of detection. The LLM supplies cross-language, cross-stack pattern recognition; the surrounding machinery supplies determinism.

Coverage model

Every control lands in one of three buckets, recorded in the control-map LUT (control-map/data/cra_control_map.json) and never decided by an LLM:

Bucket Meaning
covered An existing tool's scan surfaces findings for this control
needs_tooling Code-checkable, but no off-the-shelf tool digs it out — we author a detector or use the grounded surface check
not_code_checkable A design/process property — out of static-scan scope

For the CRA framework (40 controls) the split is 21 covered · 0 needs_tooling · 19 not_code_checkable. The Semgrep registry rules are not run (their licence allows internal use only, not a service for others): every semgrep binding names our own rules or, since #492, the vendored MIT packs (GitLab, 0xdea, elttam), so a binding covers exactly the languages its rules are written for. The originally uncovered controls were resolved as a hybrid:

  • Custom semgrep detectors, shipped in the binary and matched back to controls by rule id so a broad CWE can't over-attribute:
    • for Python and JavaScript/TypeScript: cra-ai-1, 7, 10, 14 (secure-by-default, weak password hashing, insecure session cookies, weak data-at-rest ciphers), cra-ai-20 (shell commands and SQL built from variables, request input echoed into a response), cra-ai-8 (hard-coded credentials, Python) and cra-ai-15 (plain http:// requests);
    • for C and C++ firmware: cra-ai-8, 13, 16, 20 (hard-coded credentials including #define macros, broken hash/cipher, rand(), unbounded string functions and non-literal format strings), next to cppcheck for memory safety.
  • Vendored semgrep packs (GitLab, 0xdea, elttam; #492), bound by CWE like off-the-shelf tools, on a semgrep binding of their own per control whose languages are exactly those of the vendored rules under those CWEs (a test checks every vendored rule maps to a control that claims its languages). The few elttam rules without a CWE are bound by rule id. Because these bindings are semgrep bindings, a CWE they list also attaches our own semgrep findings with that CWE to the control.
  • mobsfscan for Android and iOS apps, bound by CWE (a mobsfscan binding only ever attaches mobsfscan findings): cra-ai-1 (debuggable, exported components, outdated minSdkVersion), 7, 8, 9, 13, 14, 15 (cleartext, TLS, App Transport Security), 16 and 20. Each binding lists only the languages mobsfscan has rules for under those CWEs, so cra-ai-1 covers Java and Kotlin (its manifest checks) but not Swift.
  • 8 grounded surface checks (cra-ai-6, 11, 12, 24, 27, 28, 29, 30): the absence-based controls (no rate limiting, no security logging, no update-signature check…) that have no syntactic pattern.
  • Marked not_code_checkable (cra-ai-2, 3, 4, 5, among the 19): minimal attack surface, secure architecture, least privilege, tamper protection.

Languages, and what the CRA status may claim

Each binding in the control map names the languages its rules run on (languages, empty for language-independent tools such as gitleaks, syft and osv). A test keeps these in step with the rule pack. Each scan run records the source languages it saw outside vendor code (ScanRun.languages).

The CRA status calls a covered control "no violation found" only when one of its bindings applies to those languages and no tool it relies on failed in that scan (a skipped sast, sast_c_cpp, sast_mobile or cve_lookup stage). Otherwise the control is not assessed, with the reason: not scanned yet, no rule for the languages found, a tool that did not complete, or languages unknown (a run from before they were recorded). A C-only firmware repo therefore never reads "no violation found" for controls only Python rules check (#368, #387).

At scale, the master-controls corpus (breakpilot's deduped clusters, exported as OSCAL) currently provides ~2,882 code-checkable controls (2,143 network + 739 source_code), matched semantically.

The three mapping paths

flowchart TD
    T[Deterministic tools\nsemgrep · gitleaks · syft/osv · DAST · PLC linter] --> F[Findings]
    F --> B["Stage 5b — LUT triage\ncontrols_for(tool, cwe / rule_id)"]
    F --> C["Stage 5c — Semantic\nembed region+intent → top-K master controls"]
    R[Repo source] --> D["Stage 5d — Grounded surface\nretrieve surface for absence-based controls"]
    B --> J{{Grounded LLM judge\ntemp 0 · verbatim snippet}}
    C --> J
    D --> J
    J -->|snippet grounds in region| S[Stamp control_refs]
    J -->|refuted| X[5b: finding kept as needs review\n5c/5d: nothing added]
    J -->|no verdict: model down or unreadable| U[Left as it is]

All three paths converge on the same grounded judge and the same grounding gate. They differ only in how candidate (finding/region, control) pairs are produced.

Stage 5b — deterministic LUT triage

The default path. A tool finding is matched to controls via control_map.controls_for_finding(tool, cwe, rule_id); the judge then confirms each mapped control against the code region. Outcomes:

  • Confirmed([ids]): stamp them.
  • NeedsReview: the judge refuted every mapped control it could check. The finding stays, with the status needs review ("Zu prüfen") and a rationale, for a person to decide.
  • Undecided: no verdict (the model was unreachable, its answer unreadable, or a control has no requirement text). The finding is left as it is.
  • Unmapped: keep it untagged.

The general LLM triage before it (stage 5) follows the same rule: a finding it dismisses or confirms with low confidence is kept as needs review, never deleted. Runs whenever a catalog is available — either BREAKPILOT_BASE_URL points at a breakpilot-compliance backend, or a catalog snapshot is present (see snapshot-only mode).

Stage 5c — semantic retrieval (master-controls scale)

Master controls carry no CWE, so they can't be LUT-mapped. Instead we map by similarity: embed every control's requirement text once (cached), then for each finding retrieve the top-K nearest controls and hand them to the judge. Gated behind BREAKPILOT_SEMANTIC_MAPPING (default on; off on staging and production until the master-controls catalog is shipped, see #382). See Semantic retrieval.

Stage 5d — grounded surface checks (absence-based controls)

Some controls are violated by an absence — no rate limiting on login, no security logging, no signature check on an update. There's no pattern for semgrep to match, so we deterministically retrieve the code surface the control governs (a login route, a logging setup, update/download code) by identifier/route terms, and let the judge decide whether the control holds there. Produces net-new, already-grounded findings. It reads C and C++ as well, with embedded terms (crc32, ota_, bootloader, hal_flash, secure_boot, ecdsa, syslog), and skips vendor code so the HAL and middleware don't fill its cap (#376). Gated behind BREAKPILOT_GROUNDED_CHECKS (default on).

The grounding gate

No matter the path, a verdict becomes a finding only if it survives compliance_core::control_check::ground:

  1. The judge runs at temperature 0 with a closed prompt and must quote the offending code verbatim into snippet.
  2. That snippet must appear literally in the retrieved region — otherwise the verdict is dropped.
  3. The finding's line is recomputed from the match; the model's own line number is never trusted.
  4. Verdicts are cached by content hash, so re-scans reproduce.

The model is allowed to be smart; it is never trusted.

Semantic retrieval in detail

  1. Embed the corpus once. Each control's requirement text is embedded with bge-multilingual-gemma2 (3584-dim — multilingual matters, the master controls are in German while code is English). The embedding backend caps input arrays at 25 per request, so embed() chunks at 16; the whole ControlIndex is persisted to snapshot_dir keyed by a corpus hash, so only the first scan after a catalog change pays the embedding cost.
  2. Build the query from the finding's intent, not just the code. The retrieval query is finding.title + finding.description + region, not the raw region. This is the single most important tuning: two findings in one file share overlapping windows and, on the code alone, embed alike and collapse onto the same controls. The finding's own words ("brute-force protection" vs "weak hash") carry the discriminating signal. The raw region still goes to the judge for grounding.
  3. Retrieve → judge → ground. Top-K nearest by cosine, each judged against the region, each grounded.

Worked examples

Both examples are from the live end-to-end verification (c5_semantic_live.rs) against the real ~2,882-control corpus.

Example 1 — a small auth file (the tuning story)

Two findings in one auth.py: a weak hashlib.md5(password) hash and a login endpoint with no brute-force protection.

Finding Region-only retrieval Intent-enriched retrieval
Weak md5 hash 19874, 20683, 23149, 29985 mc-23149 (eliminate weak unsalted hashes) at rank 1, + mc-21634 salted hashing
Login w/o brute-force protection identical 4, reordered newly surfaces mc-19984 brute_force_protection + mc-23186 account_lockout

Region-only retrieval gave both findings the same four password-hashing controls — the brute-force finding never found its real controls because its window is saturated with password tokens. Enriching the query with the finding's intent fixed it: the brute-force finding now pulls the correct rate-limiting / lockout controls out of the 2,882.

Example 2 — four topically distinct vulnerabilities

Finding Top matched controls Family
SQL injection (string-concat query) sql_injection_prevention, sql_injection, parameterized_queries, input_sanitization input-validation ✓
Hardcoded API credential hardcoded_secrets_detection, credential_scanning, secrets_detection credentials ✓
TLS verification disabled (verify=False) https_enforcement, configuration_verification, transport config transport-encryption ✓
Insecure deserialization (pickle.loads) deserialization, deserialization_testing, deserialization_security deserialization ✓

Every finding maps to its exact control family, with the most specific control often at the top, and the four sets are distinct.

Known limitations

  • Absence findings are weak for semantic retrieval. Similarity matches what code is about, not what it lacks; a "missing rate limiting" finding embeds like login code. This is exactly why the grounded surface path (Stage 5d) exists — it decides presence/absence at a retrieved surface rather than by embedding distance.
  • Generic catch-all controls co-occur. mc-20890 secure_development_security_code_review appears in the top-K for many code-security findings because it is semantically near almost all of them. It's harmless (the judge grounds it, and it never crowds out the specific controls — the SQLi example didn't get it) but is a candidate for future down-weighting.
  • Corpus classification noise. The master-controls verification_method classification is imperfect — e.g. a documentation control (eu_declaration_accuracy) is currently tagged source_code. That's a corpus-side data-quality issue, separate from the mapping engine.

Emitting over MCP — closing the loop

Findings don't just land in the dashboard; they flow to breakpilot-compliance as OSCAL over the scanner's MCP server, so the compliance report is assembled from real, control-tagged findings.

  • The MCP server exposes an oscal_assessment tool: given a repo_id, it emits a standard OSCAL 1.1 assessment-results document for that repo's findings — mapped findings target their controls via the stamped control_refs, and unmapped findings are reported as-is (as observations), so nothing is lost.
  • breakpilot pulls it: POST /v1/cra/oscal-from-scanner calls oscal_assessment over MCP (Streamable HTTP + bearer) and consumes the pre-computed OSCAL — rather than pulling raw findings and re-assessing.

Operational note — tenant context over HTTP. The MCP server is multi-tenant; the bearer token resolves a tenant whose per-tenant database the tools query. rmcp's Streamable HTTP transport runs each session's tool calls in a tokio::spawned task, and task_locals do not cross a spawn — so binding the tenant in a per-request middleware task_local leaves tool handlers with no context (every call fails no tenant context). The fix is to bind the tenant to the per-session server instance at creation (the factory runs in the request scope before the spawn), not to a per-request task_local. Until this was fixed, the loop silently failed over HTTP and consumers fell back to demo data.

Configuration

Variable Effect
BREAKPILOT_BASE_URL breakpilot-compliance root; enables live control ingest. Unset falls back to the catalog snapshots in BREAKPILOT_SNAPSHOT_DIR; with neither, control mapping is off and findings carry no control_refs.
BREAKPILOT_SEMANTIC_MAPPING Stage 5c (semantic master-controls mapping). Default on (validated live).
BREAKPILOT_GROUNDED_CHECKS Stage 5d (grounded surface checks). Default on (validated live).
BREAKPILOT_SNAPSHOT_DIR Where OSCAL catalog snapshots and the cached control-embedding index live.

The semantic and grounded passes default on now that both are validated live; each is still a no-op if no catalog is reachable, so they only ever add coverage.

On staging and production (platform/orca-platform service files): BREAKPILOT_BASE_URL is unset, so the agent runs in snapshot-only mode on the CRA catalog baked into the image. The LUT triage (5b) and the grounded surface checks (5d) run; BREAKPILOT_SEMANTIC_MAPPING=false, so the semantic pass (5c) does not, and PLC findings get no CRA control refs until the master-controls catalog is shipped (#281, #382).

Snapshot-only mode

The catalog loader already snapshots the exact bytes it fetches (oscal-catalog-<framework>.json under BREAKPILOT_SNAPSHOT_DIR) and falls back to that snapshot when the backend is unreachable. Snapshot-only mode is the same path without ever having been online: the agent image ships compliance-agent/controls/snapshot/oscal-catalog-cra.json (CRA Annex I, 40 controls, built by breakpilot-compliance's build_cra_catalog), and the entrypoint copies it into BREAKPILOT_SNAPSHOT_DIR if no file of that name is there yet. With BREAKPILOT_BASE_URL unset the deterministic LUT triage (5b) and the grounded surface checks (5d) therefore run and findings carry CRA control_refs, while the semantic pass (5c) stays a no-op because master-controls is DB-derived and is not shipped — set BREAKPILOT_SEMANTIC_MAPPING=false in that environment to skip its warning.

Refresh the committed snapshot from a live backend with scripts/refresh-oscal-snapshot.sh (see its header); a fetched snapshot always wins over the baked one, because the entrypoint only copies what is absent. The live verifications live in compliance-agent/tests/c5_semantic_live.rs and grounded_surface_live.rs (ignored; run with --ignored).

Appendix — the master-controls data pipeline

The master-controls corpus is produced by breakpilot-compliance and pulled as an OSCAL catalog from GET /api/compliance/v1/oscal/catalog?framework=master-controls. Two operational lessons are worth recording, because they cost real time to diagnose:

  • The catalog is served from breakpilot_db, not postgres. Diagnostics run against the wrong database will look clean while the app serves something else entirely. Confirm the app's datname (pg_stat_activity) before trusting any count or EXPLAIN.
  • A constraint-less dump triplicated the master-control tables. Restored without their PK/unique constraints, master_controls / mc_verification / master_control_members accumulated identical rows 3× (the same artifact migration 158 fixed for doc_check_controls). That inflated the catalog to ~26k dup'd controls and, with the indexes also missing, drove the export query to a >120s / 502. The fix (breakpilot migration 160) ctid-dedups each table by its natural key and restores the constraints + indexes so it can't recur; the export query was also rewritten set-based (a single windowed pass instead of a per-row correlated subquery). After dedup: 41,850 → 13,950 master controls, catalog 25,938 → 2,882 code-checkable, endpoint 502 → 200 in ~3s.