Detection as Code and the Detection Lifecycle
A SOC with 400 rules edited by hand in a SIEM console cannot answer simple questions: who changed this rule last month, and why did it stop firing? Which rules have never been tested? Which ones cover credential dumping? Detection as code treats detections like software: rules live as text files in a version-controlled repository, every change is reviewed, tested automatically and deployed by a pipeline, and each rule carries the documentation an analyst needs at 03:00. This lesson describes the practice, the lifecycle of a detection from idea to retirement, and lints a small rule repository in Python.
The practice
detections/
rules/
windows/proc_office_spawns_shell.yml the rule (Sigma or the SIEM's own format) + metadata
identity/auth_bruteforce_then_success.yml
tests/
proc_office_spawns_shell/positive.jsonl events that MUST alert
proc_office_spawns_shell/negative.jsonl look-alikes that must NOT alert
docs/
proc_office_spawns_shell.md goal, blind spots, false positives, response
pipelines/ field mappings per SIEM
ci.yml lint -> convert -> test -> deployThe pipeline on every change: lint (format, required metadata), convert (Sigma to the SIEM's query language with the right field mapping, see Sigma Rules), test (run the rule on its positive and negative fixtures, see Testing Detections), review by a second engineer, deploy through the SIEM's API, and monitor the rule's alert volume after deployment. The benefits are the ordinary ones of software engineering: history (git log shows who changed what and why), review, rollback, reuse across environments, and a single source of truth that coverage reports can be generated from.
The detection lifecycle
| Stage | What happens | Exit criterion |
|---|---|---|
| Idea / requirement | From threat intel, a hunt, an incident, a purple-team gap, or coverage analysis | A written goal and the data source it needs |
| Research | Understand the technique: how it works, what telemetry it leaves, how admins do the same thing legitimately | Example true-positive events (from the lab or a purple-team test) |
| Development | Write the rule and its tests | Tests pass |
| Testing / staging | Run against historical production data in "silent" mode: alerts are recorded, nobody is paged | Expected volume and precision known |
| Production | Enabled, with a severity, a playbook and an owner | |
| Tuning | False positives handled narrowly; thresholds reviewed | Precision above the agreed floor |
| Review | At a fixed interval (e.g. every 6–12 months) and after incidents: still needed? still working? | Re-approved or changed |
| Retirement | Data source gone, technique obsolete, replaced by a better rule | Removed with a note, tests kept for history |
Stages are recorded in the rule's metadata (status: experimental | test | stable | deprecated | unsupported in Sigma), so dashboards can count rules per stage and flag rules stuck in testing.
Documentation an analyst can use
Each rule needs a short document. A widely used template is Palantir's Alerting and Detection Strategy (ADS) framework: goal, categorisation (ATT&CK technique), strategy abstract, technical context, blind spots and assumptions, false positives, validation (how to produce a true positive in the lab), priority and response. The two sections most often skipped are the most useful: blind spots (what variants the rule does not catch, so hunters know where to look) and validation (so anyone can check that the rule still fires after a SIEM upgrade).
Linting a rule repository
The program lints the metadata of five synthetic rules against the house rules of a detection team: required fields, a valid ATT&CK technique ID, a known status, an owner, test fixtures present, and a review date not in the past.
import re
from datetime import date
TODAY = date(2026, 1, 15)
REQUIRED = ["id", "title", "status", "level", "owner", "attack", "logsource", "review_by"]
STATUSES = {"experimental", "test", "stable", "deprecated"}
rules = [
{"id": "d-001", "title": "Office application spawns a shell", "status": "stable", "level": "high", "owner": "det-eng/anh",
"attack": ["T1204.002", "T1059.001"], "logsource": "windows/process_creation", "review_by": date(2026, 6, 1), "tests": ["positive", "negative"]},
{"id": "d-002", "title": "Brute force then success", "status": "stable", "level": "high", "owner": "det-eng/minh",
"attack": ["T1110.001"], "logsource": "authentication", "review_by": date(2025, 11, 30), "tests": ["positive", "negative"]},
{"id": "d-003", "title": "Rare domain beaconing", "status": "test", "level": "medium", "owner": "",
"attack": ["T1071.004"], "logsource": "dns", "review_by": date(2026, 9, 1), "tests": ["positive"]},
{"id": "d-004", "title": "LSASS memory read", "status": "production", "level": "critical", "owner": "det-eng/lan",
"attack": ["T1003.1"], "logsource": "windows/process_access", "review_by": date(2026, 4, 1), "tests": []},
{"id": "d-005", "title": "New Domain Admin member", "status": "stable", "level": "high", "owner": "det-eng/anh",
"attack": ["T1098"], "logsource": "windows/security", "review_by": date(2026, 3, 1), "tests": ["positive", "negative"]},
]
ATTACK_ID = re.compile(r"^T\d{4}(\.\d{3})?quot;)
def lint(r):
problems = [f"missing {f}" for f in REQUIRED if not r.get(f)]
if r["status"] not in STATUSES:
problems.append(f"unknown status '{r['status']}'")
problems += [f"bad ATT&CK id {t}" for t in r["attack"] if not ATTACK_ID.match(t)]
if r["status"] in ("test", "stable") and not {"positive", "negative"} <= set(r["tests"]):
problems.append(f"needs positive and negative tests (has {r['tests'] or 'none'})")
if r["review_by"] < TODAY:
problems.append(f"review overdue since {r['review_by']}")
return problems
failed = 0
for r in rules:
p = lint(r)
failed += bool(p)
print(f"{r['id']} {r['title']:33} {'OK' if not p else 'FAIL: ' + '; '.join(p)}")
print(f"\n{failed} of {len(rules)} rules block the merge")d-001 Office application spawns a shell OK
d-002 Brute force then success FAIL: review overdue since 2025-11-30
d-003 Rare domain beaconing FAIL: missing owner; needs positive and negative tests (has ['positive'])
d-004 LSASS memory read FAIL: unknown status 'production'; bad ATT&CK id T1003.1
d-005 New Domain Admin member OK
3 of 5 rules block the merge
Three of five rules block the merge, each for a reason a reviewer could easily miss by eye. d-002 is a good rule whose review date passed in November; the pipeline forces someone to confirm it still works. d-003 has no owner and only a positive test, so nobody would answer its false positives and nothing proves it stays quiet on normal DNS traffic. d-004 uses a status the tooling does not know (production, so dashboards would not count it) and a malformed technique ID (T1003.1 instead of T1003.001), which would silently drop it from every ATT&CK coverage report. And because its status is not recognised, the "needs tests" check never ran: d-004 has no tests at all, which only shows up once the status is fixed. Linting is cheap; it turns team conventions into checks that run on every change.
How a detection programme fails, and the fix
| Failure | How you notice | Fix |
|---|---|---|
| Rules silently stop firing (field renamed, source broken) | A rule with zero alerts for months; validation test fails | Scheduled validation (re-run true-positive tests in production, or purple-team), source health checks |
| Rules nobody understands | Analysts close its alerts without investigating | ADS documentation, owner in metadata |
| Unreviewed changes break production | Spike of alerts after a deploy | Mandatory review and CI tests; deploy to staging first |
| The rule set only grows | Hundreds of rules, low precision | Lifecycle with review dates and retirement |
Pitfalls
- Code without tests. A repository of untested rules is a wiki with extra steps. The tests are the point.
- Editing in the console "just this once". The next deploy overwrites it, or worse, the repository and production diverge. Make the console read-only for rules managed as code.
- Treating
status: stableas permanent. Environments change; stable rules need review dates too.
Practice
1. Fix rule d-004 so it passes the linter. What changes?
status must be one of the known values (stable or test), the ATT&CK ID must be T1003.001 (OS Credential Dumping: LSASS Memory; sub-technique IDs have three digits), and it needs positive and negative tests. Until it has tests it can only be experimental.
2. Write the "blind spots" section for "Office application spawns a shell".
For example: does not catch macros that use COM or WMI to start processes (the parent is then WmiPrvSE.exe or svchost.exe, not Office); misses Office applications not in the list (Publisher, Visio) and renamed shells (use OriginalFileName); does not see code that runs inside the Office process without a child; depends on process-creation telemetry with parent fields (Sysmon 1 or EDR).
3. Why are positive and negative tests both required before `test` status?
Positives show the rule detects what it claims; negatives (legitimate look-alikes) show it doesn't alert on known benign activity. A rule with only positives can be "fixed" into matching everything.
Test yourself
What is detection as code?
- Writing malware detections in assembly
- Managing detections as version-controlled text with review, automated tests and deployment pipelines
- Using only built-in vendor rules
- Encrypting the SIEM
Why did rule d-002 fail the lint even though its content is fine?
- Bad ATT&CK ID
- Its review date (2025-11-30) is in the past
- No owner
- Unknown status
Which ADS section tells hunters what the rule cannot catch?
- Goal
- Blind spots and assumptions
- Priority
- Response
In which lifecycle stage does a rule run on production data without paging anyone?
- Idea
- Testing / staging (silent mode)
- Retirement
- Review