Files
AiSOC/detections
ToufiqtoufiqboandToufiqtoufiqbo 6cb8030738 feat(detections): flag AI agents reading credential files, and fix the two catalogue claims that were false (#1804)
## Summary

Adds the first community detection rule: an AI agent's file tool reading
a credential file (`~/.ssh/id_rsa`, `~/.aws/credentials`, …) —
T1552.001, which prompt-level secret scanning cannot see, because the
prompt is clean and the disclosure happens on the way out (into the
model context, a tool argument, or a second call). Writing it surfaced
three catalogue/portability bugs, all fixed here: the
`quarantine_reason` fallback asserted `enabled: false` about a rule file
the builder never opened; the marketplace, corpus-stats, truth-table,
llms and curation generators wrote the platform's line endings and
`str(Path)` separators, so their `--check` compared text that had
already translated the difference away; and `hello-hunt.md` instructed
contributors to do the one thing `detection_truth_table.py --check`
rejects.

Regenerated: the marketplace index (three copies), the corpus stats, the
detection truth table, and the llms.txt pair. The published rule counts
follow: 7408 on disk, 4442 not loaded.

## Type of change

- [x] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [x] Documentation update
- [ ] Refactor / tech debt
- [ ] CI / infra change

## Related issues

Nothing closed by this PR; no tracking issue existed for these bugs.

- Relates to #357 (detection rule contributions wanted / community
rules) — this is the first rule under
`detections/community/application/`.
- Relates to #978 and #898, which introduced and later widened the
`quarantine_reason` / executable-split surface corrected here.

## Changes

**New rule + fixtures**
- `detections/community/application/ai-agent-credential-file-read.yaml`
— `community-toufiqtoufiqbo-ai-agent-credential-file-read`, high,
`application`, T1552.001. Matches the `ai_runtime` fields the
`aisoc-ai-sdk` actually emits (`tool_name`, `resource` — both string
literals in `aisoc_ai/client.py`), excludes public-key reads (`*.pub`,
`authorized_keys`), and does not fire on model calls. It ships `enabled:
false` with a `quarantine_reason`, because the truth-table gate refuses
an enabled rule the engine never loads and nothing walks
`detections/community/` into the compiled rule set.
-
`detections/fixtures/{positive,negative}/ai-agent-credential-file-read.json`.

**Truthful `quarantine_reason`**
- `scripts/build_marketplace.py` — new `_why_not_executable()`. The old
fallback told every non-quarantined, non-executable row that it was
"disabled in the rule file (`enabled: false`)" — a claim about a file
the builder never opened, reached precisely when it had not looked. The
reason now names the real cause per tier, and the rule's own
`quarantine_reason` still wins when the file carries one.
- `apps/docs/docs/detections/hello-hunt.md` — the tutorial said
"`enabled: true` controls whether the rule runs in production. Community
rules ship as `true` by default." Both halves are false: nothing loads a
community rule, and `detection_truth_table.py --check` fails one that
claims to be enabled. It now says what the gate enforces — `enabled:
false` plus a `quarantine_reason` naming what promotion would take.
- `tests/test_marketplace_executable_split.py` —
`test_a_reason_that_names_the_rule_file_is_true_of_it` walks every
reference-only entry whose reason quotes `enabled: false` (99 today),
reads the rule file it cites, and fails if the flag disagrees. It also
fails if it ever ends up checking nothing.

**LF / POSIX artefacts, byte-level `--check`**
- `scripts/build_marketplace.py`, `scripts/curate_detections.py`,
`scripts/generate_corpus_stats.py`, `scripts/detection_truth_table.py`,
`scripts/generate_llms_txt.py` — explicit `newline="\n"` on every
artefact write; manifest `path` fields via `.as_posix()`.
- The `--check` modes now compare **bytes** and reject `b"\r"`. In text
mode the read translated CRLF away, so a CRLF file and an LF template
agreed with each other and the drift was invisible.
- `scripts/curate_detections.py` — the curated selection's `path` field
used `str(Path)`. On Windows that is 601 backslashed paths, so `pnpm
marketplace:curate --check` could never pass there and regenerating
rewrote every entry. Now `.as_posix()`, and the check passes on Windows
and Linux alike.

**Regenerated**
- `marketplace/index.json`, `apps/web/public/marketplace/index.json`,
`services/api/app/data/marketplace/index.json` — byte-identical, LF,
POSIX paths, 7582 items.
- `apps/web/src/data/corpus-stats.json` — 2966 executable, 7408 on disk,
4442 quarantined.
- `docs/detections/truth-table.md` — 7408 on disk, community 2,
`enabled: false` 229.
- `apps/docs/static/llms.txt`, `apps/docs/static/llms-full.txt` — the
gate that first caught the stale on-disk count.
- `README.md`, `apps/docs/docs/concepts/detections.md` — the published
on-disk count (7407 → 7408), the tier line (`community=1` →
`community=2`) and the not-loaded figure (4441 → 4442).

`marketplace/curated.json` and `apps/docs/docs/detections/coverage.md`
are deliberately unchanged: the curated selection is byte-identical once
paths are POSIX, so there is nothing to regenerate, and touching them
would rewrite all 601 entries for no content change.

## Testing

- [x] Unit tests added / updated
- [ ] Integration tests pass locally — see the two environment-only
failures below
- [x] Manually tested (describe steps below)

<details>
<summary>Manual test steps</summary>

All commands run in the pushed tree, with `AISOC_REPO_ROOT` set (this
machine has no `git` binary) and `PYTHONUTF8=1`.

1. Rule validator — all 7408 rules, including the new one, and its
fixtures:
   ```text
   Validated 7408 rules — 7408 passed, 0 failed, 0 fixture warnings
     Tiers: community=2, imported=6113, native=1293
     Executable (loaded by the engine): 2966; not loaded: 4442
   ```
2. Engine replay of the rule through the engine's own `_sigma_fallback`,
five cases — the fourth is a Windows path, which `pathlib` would have
normalised away before the `.as_posix()` fix:
   ```text
   PASS  positive (private key): matched=1 expected=1
   PASS  negative (benign pdf): matched=0 expected=0
   PASS  public key exclusion: matched=0 expected=0
   PASS  windows credential path: matched=1 expected=1
   PASS  model call is not a file read: matched=0 expected=0
   ```
3. Artefact gates, all four, on Windows:
   ```text
   OK: detection truth table current — 2966 executable / 7408 on disk
   marketplace index is up to date in 3 locations (7582 items).
check_marketplace_index_parity: OK — 3 identical copies, 7582 items all
carrying a digest
corpus-stats OK — 2966 executable across 7 categories, 7408 indexed on
disk (4442 quarantined), 85 plugins, 64 playbook packs
   OK: llms.txt and llms-full.txt match their sources (2 files).
   curation up to date (601 curated, 122 techniques).
   ```
4. `python -m pytest tests/test_marketplace_executable_split.py -q` →
`10 passed` (was 9; the new test is the truthfulness one).
5. `ruff format --check .` clean over the whole tree (2979 files) and
`ruff check services/ scripts/ tests/ tools/` clean — the two commands
CI runs.
6. Byte-level check of all touched paths: all LF, no `\r` anywhere,
including the three 11 MB index copies.
7. Regeneration is a no-op: every `--check` above passes immediately
after the committed artefacts, on a Windows checkout — the platform the
bugs were invisible on.

**Two pre-existing local failures, not caused by this PR:**
`tests/test_attribution_gate.py` and
`tests/test_detection_attribution_gate.py` fail on this machine because
they shell out to `git` and `bash`, neither of which exists here. They
are untouched by this diff.

</details>

## Screenshots (if UI changes)

None — no UI change. (`corpus-stats.json` moves the counts the landing
page reads; the numbers change, not the rendering.)

## Checklist

- [x] My code follows the style guidelines of this project (`ruff`,
`eslint`, `gofmt`)
- [x] I have performed a self-review of my own code
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] New and existing unit tests pass locally — all except the two
`git`/`bash`-dependent gates noted above
- [x] I have updated documentation as needed (README, CHANGELOG,
CONTRIBUTING)
- [x] My changes do not introduce new linter warnings
- [x] I have checked for sensitive data / credentials in my diff

## Eval harness (required for substrate / playbook / detection changes)

`python3 scripts/run_evals.py --json` on `3ec5fb1` (before) and on this
branch (after), same machine, same synthetic dataset (200 deterministic
cases). Both runs `all_passed: true`.

The new rule is catalogue-only — it lives under `detections/community/`,
which no engine path loads — so no eval input changes and the suites are
identical, as expected. No axis regressed.

<details>
<summary><strong>Before</strong> (<code>scripts/run_evals.py</code> on
<code>3ec5fb1</code>)</summary>

```text
suite                        metric                       value   target  passed
mitre_accuracy               accuracy                     0.97    >=0.8   true
alert_reduction              reduction_ratio              0.753   >=0.7   true
investigation_completeness   mean_keyword_coverage        0.9425  >=0.85  true
response_quality             mean_rubric_score            1.0     >=0.8   true
hunt_corpus                  positive_scenario_catch_rate 1.0     >=1.0   true
adversary_eval               graceful_degradation_catch   0.475   >=0.4   true
confidence_calibration       investigation_brier_score    0.0646  <=0.18  true
memory_recall                memory_recall_accuracy       1.0     >=1.0   true
override_accuracy            override_accuracy            1.0     >=1.0   true
playbook_completion_rate     completion_rate              0.735   >=0.5   true
detection_fp_rate            worst_per_rule_fp_rate       0.0031  <=0.05  true
all_passed: true
```

</details>

<details>
<summary><strong>After</strong> (<code>scripts/run_evals.py</code> on
this branch)</summary>

```text
suite                        metric                       value   target  passed
mitre_accuracy               accuracy                     0.97    >=0.8   true
alert_reduction              reduction_ratio              0.753   >=0.7   true
investigation_completeness   mean_keyword_coverage        0.9425  >=0.85  true
response_quality             mean_rubric_score            1.0     >=0.8   true
hunt_corpus                  positive_scenario_catch_rate 1.0     >=1.0   true
adversary_eval               graceful_degradation_catch   0.475   >=0.4   true
confidence_calibration       investigation_brier_score    0.0646  <=0.18  true
memory_recall                memory_recall_accuracy       1.0     >=1.0   true
override_accuracy            override_accuracy            1.0     >=1.0   true
playbook_completion_rate     completion_rate              0.735   >=0.5   true
detection_fp_rate            worst_per_rule_fp_rate       0.0031  <=0.05  true
all_passed: true
```

</details>

- [ ] Not applicable — this PR does not touch substrate, playbooks,
detections, or eval inputs
- [x] No axis regressed
- [ ] An axis regressed; rationale and follow-up are described in the
Summary above

Signed-off-by: Toufiqtoufiqbo <185284988+Toufiqtoufiqbo@users.noreply.github.com>
Co-authored-by: Toufiqtoufiqbo <185284988+Toufiqtoufiqbo@users.noreply.github.com>
2026-11-10 08:00:15 -08:00
..
2026-11-05 18:36:51 -08:00

AiSOC Detection Rules

This directory contains AiSOC detection content in a Sigma-inspired YAML format. Rules are organized into four tiers based on origin, quality bar, and what the AiSOC engine can do with them out of the box.

Tier Where it lives Status when shipped Quality bar
Native detections/<category>/ enabled YAML schema + fixture replay + MITRE mapping
Imported detections/<source>-imports/<category>/ varies (see below) YAML schema + provenance block; fixtures optional
Quarantined detections/<source>-imports/_quarantine/<category>/ where the importer put it; see below YAML schema + provenance + a populated quarantine_reason
Community detections/community/<category>/ disabled by default YAML schema; provenance encouraged

The library holds 7,407 rules on disk, of which 2,966 execute — 1,196 native and 1,770 imported Sigma rules translated into the engine's match_when by scripts/compile_sigma_ruleset.py. Recount rather than quoting these: they move, and docs/detections/truth-table.md derives them from the ruleset the engine loads. The native tier is generated from the spec modules under scripts/detection_specs*.py. Imported tiers are populated by the importers under tools/detection_import/ and remain empty in this checkout until you run them — see tools/detection_import/README.md for the SigmaHQ, Splunk, Chronicle, and CAR pipelines and their pinned upstream commits.

What "executable" means

A rule is executable when the engine loads it, and it is only allowed into the compiled ruleset after a vendor-shaped event has been replayed through the real connector normalize() and the real DetectionEngine and that rule was seen to produce a hit — with an empty event of the same shape producing nothing. It is never inferred from a directory name, an enabled: key, or the shape of a detection: block.

The proof is known to be able to fail, which is the only reason it is worth quoting. python3 scripts/compile_sigma_ruleset.py --prove-gate reverts the Windows connector to its pre-fix behaviour — System and EventData left nested one level below the namespace the matcher reads — and requires all 1,687 Windows rules to stop firing. If any kept firing, the proof would not be measuring the thing it claims to.

What this does not claim. Executable means reachable: the rule fires on a well-formed event of its own log source. It is not evidence that the rule detects an attack, that it is tuned for your estate, or that it will be quiet. false_positives: is prose and is not machine-checked.

Why 1,362 imported rules were refused

3,132 Sigma rules were considered and 1,362 refused with a recorded reason, because a translation that is merely close changes what the rule means. Two reasons cover three quarters of them:

  • 556 — no connector emits that log source. Nothing in the product produces the telemetry the rule reads, so it could only ever be silent.
  • 464 — the negation would flip on a missing field. Sigma treats not filter as true when the field is absent, and only not_in and not_contains_any do that in the AiSOC matcher. Compiling the rest would turn "not this value" into "fires whenever the field is missing".

The remaining 342 are mechanical: Sigma modifiers with no matcher operator (|cidr, |base64, |fieldref, |all on a non-contains modifier), case-sensitive regexes against a matcher that forces IGNORECASE, dotted paths the matcher cannot traverse, and 133 that compiled but did not fire on their own proof event. Full taxonomy with an example per reason, the per-connector breakdown, and the known DRL-1.1 author-attribution gap: docs/detections/sigma-compilation.md.

Native tier (detections/<category>/)

The strict-quality, AiSOC-authored layer. Every rule has:

  • A positive fixture under detections/fixtures/positive/<slug>.json (a synthetic event that should fire it).
  • A negative fixture under detections/fixtures/negative/<slug>.json (a near-miss event that should not fire it).
  • A MITRE ATT&CK mapping in its tag list.

CI replays both fixtures on every PR using the canonical runtime matcher in scripts/generate_detections.py.

Distribution by category

Category Focus
cloud/ AWS / GCP / Azure misconfig, IAM, key-rotation, S3, CloudTrail
identity/ Auth, MFA, SSO, IdP federation, session abuse, OAuth grants
endpoint/ Process exec, persistence, LOLBAS, credential theft, ransomware
network/ C2, scanning, beaconing, DNS abuse, Tor, lateral movement
application/ Web, API, DB, secrets, supply chain, dependency abuse
data-exfil/ DLP, large transfers, archive uploads, tunneling, off-corp dest

Per-category rule counts are not written here, because every hand-typed copy of them in this tree had drifted. They are generated into apps/web/src/data/corpus-stats.json under categories — executable rules only — by python3 scripts/generate_corpus_stats.py, which reconciles the compiled ruleset, the marketplace index and the truth table against each other and fails if any two disagree. The by-tier split is in docs/detections/truth-table.md.

Native rule format

id: det-<unique-id>           # Stable identifier; native rules use det- prefix
name: Human-readable title
description: >
  What this rule detects and why it matters.
version: "1.0.0"
severity: low | medium | high | critical
tags:
  - mitre.attack.tXXXX         # MITRE ATT&CK technique ID(s)
  - tlp.white                   # Traffic Light Protocol
category: network | endpoint | cloud | identity | application | data-exfil
log_source:
  product: "syslog" | "cloudtrail" | "windows" | ...
  service: optional sub-service
detection:
  fields: [list, of, expected, fields]
  condition: PATTERN_MATCH_ANY({...}) # Human-readable serialization of match_when
false_positives:
  - Description of known benign triggers
playbook: tpl-<playbook-id>     # Optional: auto-trigger this playbook
enabled: true
author: AiSOC
created: "YYYY-MM-DD"
modified: "YYYY-MM-DD"

Native source of truth

The Python specs in scripts/detection_specs.py and scripts/detection_specs_part2.py are the canonical source of truth. The on-disk YAML files are serialized artifacts produced by scripts/generate_detections.py. Edit specs, regenerate, then commit both.

# Regenerate all native rules + fixtures from specs
python3 scripts/generate_detections.py

# Validate (matches what CI runs)
python3 scripts/validate_detections.py --strict-fixtures

Adding a new native rule

  1. Add a new spec dict to the appropriate list in scripts/detection_specs.py or scripts/detection_specs_part2.py.
  2. Required keys: slug, name, severity, mitre, log_source, fields, match_when, fp, positive, negative.
  3. Run python3 scripts/generate_detections.py to materialize the YAML and fixtures.
  4. Run python3 scripts/validate_detections.py --strict-fixtures to confirm the fixtures replay correctly.

Imported tiers (detections/<source>-imports/)

Imported rules are normalized into the AiSOC schema by the source-specific importers under tools/detection_import/. Each imported rule carries a populated provenance block so we can prove the redistribution chain.

id: <source>-<slug>-<short-sha>
name: Human-readable title (from upstream)
description: |
  Description preserved verbatim from upstream where present.
severity: low | medium | high | critical
category: network | endpoint | cloud | identity | application | data-exfil
enabled: true | false       # see "Quarantine" below
quarantine_reason: >        # required when enabled: false on import
  short reason — usually "requires manual translation to AiSOC engine"
detection:
  # tier-specific block: condition+fields for Sigma, splunk_spl for Splunk,
  # chronicle_yaral for Chronicle, native fields for CAR.
  ...
provenance:
  source: SigmaHQ/sigma | splunk/security_content | chronicle/detection-rules | mitre-attack/car
  source_id: <upstream UUID or rule key>
  source_commit: <pinned upstream sha>
  license: DRL-1.1 | Apache-2.0 | ...
  license_url: https://...
  imported_at: YYYY-MM-DD
  imported_by: tools.detection_import.<importer module>
  upstream_path: relative path to the source file in the upstream repo

provenance.license and provenance.license_url cover the legal redistribution story; the canonical attribution table for every redistributed corpus lives in .github/LICENSES.md. Without that file we cannot legally redistribute imported content.

Quarantine

The importer writes a rule into detections/<source>-imports/_quarantine/<category>/ when it parses cleanly into the AiSOC schema but the importer could not execute the upstream query as-is. That is still the whole story for Splunk SPL, Chronicle YARA-L and MITRE CAR pseudocode: this repository has no evaluator for any of those languages, so every one of those rules ships enabled: false with a quarantine_reason, indexed for coverage accounting and surfaced in the UI as "imported, requires translation" — never silently activated.

Sigma is the exception, and the reason the directory name is no longer a verdict. compile_sigma_ruleset.py translates rules in place rather than moving them, so 1,724 files under _quarantine/ are compiled, proven to fire and loaded by the engine today. The directory records where the importer put a rule; the compiled ruleset records whether it runs. Every tool that reports on the corpus — the truth table, the validator, the marketplace builder, the coverage curator — reads the ruleset, which is why they agree. Anything that classifies by path will report a figure roughly 1,700 too high.

Importing rules

Each importer is invoked through the orchestrator with a pinned upstream SHA:

# Run all four importers
python3 -m tools.detection_import.import_orchestrator

# Run a single source
python3 -m tools.detection_import.import_orchestrator --source sigmahq

See tools/detection_import/README.md for per-source notes on yield, dedup strategy, and what cannot be auto-translated.

Community tier (detections/community/)

External contributions live here. Validation is permissive — det-/<source>- prefixes are not required and the provenance block is encouraged but not enforced. Community rules ship with enabled: false by default; operators opt in per-tenant.

Validation

The validator at scripts/validate_detections.py classifies every rule by tier from its on-disk path and applies the right rules:

  • Native: det- ID prefix, fixture replay (positive must match, negative must not), category match against the directory name. CI runs with --strict-fixtures, which promotes missing-fixture warnings into hard fails.
  • Imported: source-specific ID prefix (sigmahq-sigma-, mitre-car-, splunk-security-content-, chronicle-detection-rules-), required provenance block, no fixtures required.
  • Community: schema check only.

The validator's summary line includes a per-tier count and how many of those rules the engine loads, so a green CI run looks like:

Validated 6991 rules — 6991 passed, 0 failed, 44 fixture warnings
  Tiers: community=1, imported=6113, native=877
  Executable (loaded by the engine): 2529; not loaded: 4462

The executable figure is read from the compiled ruleset, the same artefact detection_truth_table.py reads, so the two cannot publish different numbers about the same tree.

Counts shift as importers refresh upstream sources; the line above is a sample, not a hard target.

CI integration lives in .github/workflows/validate-detections.yml.

MITRE coverage

The marketplace builder at scripts/build_marketplace.py walks every tier and emits per-technique coverage counts to marketplace/index.json::mitre_coverage. The web UI at apps/web/src/app/(app)/detection/coverage/ renders this as a tactic × technique matrix so operators can see exactly which techniques are covered today and at what tier (native vs imported vs quarantined).

File layout

detections/
├── cloud/                            # native
├── identity/                         # native
├── endpoint/                         # native
├── network/                          # native
├── application/                      # native
├── data-exfil/                       # native
├── fixtures/
│   ├── positive/                     # one .json per native rule — should match
│   └── negative/                     # one .json per native rule — should NOT match
├── playbooks/                        # response playbooks, not detection rules —
│                                     # indexed in the marketplace as playbooks
├── sigma-imports/                    # populated by tools/detection_import/sigma_importer
│   └── _quarantine/                  # where the importer wrote them; the Sigma
│                                     # compiler translates in place, so many are loaded
├── splunk-imports/                   # populated by splunk_importer (SPL)
│   └── _quarantine/                  # always: no SPL evaluator in this repo
├── chronicle-imports/                # populated by chronicle_importer (YARA-L)
│   └── _quarantine/                  # always: no YARA-L evaluator in this repo
├── car-imports/                      # populated by car_importer (CAR pseudocode)
│   └── _quarantine/                  # always: pseudocode → engine syntax
└── community/                        # third-party / contributed rules

Two directories here hold no rules. detections/playbooks/ has 25 response playbooks — trigger: and steps:, no detection: block — and detections/sigma-correlations/ has 6 multi-document Sigma correlation files that compile into the windowed ruleset rather than the stateless one. They are the entire difference between the 7,438 YAML files under this tree and the 7,407 rules every count in this repository publishes.