Testing Detections with Synthetic True and False Positives
A detection that has never fired is in one of two states: there was nothing to find, or it is broken. From the console you cannot tell which. Rules break for boring reasons: a parser update renames a field, a log source stops sending, an EDR update changes a path, someone "fixes" a false positive with a filter that also removes the true positives. Detection tests make the difference visible: each rule ships with events it must match and events it must not, and a pipeline checks both on every change, and regularly in production. This lesson writes such tests in Python, shows a field-rename regression being caught, and tests a rule against variants an attacker might use.
Three kinds of test
| Test | Question | When it runs |
|---|---|---|
| Unit (fixture) tests | Does the rule logic match the positives and ignore the negatives? | On every change, in CI, on synthetic events |
| Variant (robustness) tests | Does it still match when the attacker changes case, switch order, path, encoding? | In CI, from a list of known variants per technique |
| End-to-end validation | Does the deployed rule fire on a real event that went through collection, parsing and the SIEM? | Scheduled in production or staging: a harmless test action in the lab, or a purple-team test (Purple-Team Exercises) |
Unit tests catch logic errors; only end-to-end tests catch broken collection and parsing.
Fixture tests, and a regression they catch
The program defines three small rules as Python functions over normalised events, gives each positive and negative fixtures, and runs them twice: once with the current parser output, and once after a "parser upgrade" that renamed command_line to cmdline.
def office_shell(e):
return (e.get("parent", "").lower().endswith(("\\winword.exe", "\\excel.exe", "\\outlook.exe"))
and e.get("image", "").lower().endswith(("\\cmd.exe", "\\powershell.exe", "\\mshta.exe"))
and "lab-finance-report.cmd" not in e.get("command_line", "").lower())
def encoded_ps(e):
c = e.get("command_line", "").lower()
return e.get("image", "").lower().endswith("\\powershell.exe") and "-enc" in c and "-nop" in c
def new_domain_admin(e):
return e.get("event_id") == 4728 and e.get("group") == "Domain Admins" and e.get("member") not in {"adm-alice", "adm-bob"}
W, X, P = "C:\\Program Files\\Office\\WINWORD.EXE", "C:\\Program Files\\Office\\EXCEL.EXE", "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
TESTS = {
office_shell: {
"positive": [{"parent": W, "image": P, "command_line": "powershell -nop -enc SQBFAFgA"}],
"negative": [{"parent": X, "image": "C:\\Windows\\System32\\cmd.exe", "command_line": "cmd /c lab-finance-report.cmd"},
{"parent": "C:\\Windows\\explorer.exe", "image": P, "command_line": "powershell"}]},
encoded_ps: {
"positive": [{"image": P, "command_line": "powershell -nop -enc SQBFAFgA"},
{"image": P, "command_line": "powershell -enc SQBFAFgA -nop"}],
"negative": [{"image": P, "command_line": "powershell -nop -file inventory.ps1"}]},
new_domain_admin: {
"positive": [{"event_id": 4728, "group": "Domain Admins", "member": "hank"}],
"negative": [{"event_id": 4728, "group": "Domain Admins", "member": "adm-bob"},
{"event_id": 4728, "group": "Helpdesk", "member": "carol"}]},
}
def run(tests, transform=lambda e: e):
failures = []
for rule, cases in tests.items():
for kind, events in cases.items():
for i, e in enumerate(events):
got = rule(transform(dict(e)))
if got != (kind == "positive"):
failures.append(f"{rule.__name__}: {kind} #{i + 1} {'missed' if kind == 'positive' else 'alerted'}")
total = sum(len(v) for c in tests.values() for v in c.values())
print(f"{total - len(failures)}/{total} passed", *failures, sep="\n ")
print("current parser:")
run(TESTS)
def parser_upgrade(e): # the new parser version renamed one field
if "command_line" in e:
e["cmdline"] = e.pop("command_line")
return e
print("\nafter the parser upgrade:")
run(TESTS, parser_upgrade)current parser:
9/9 passed
after the parser upgrade:
6/9 passed
office_shell: negative #1 alerted
encoded_ps: positive #1 missed
encoded_ps: positive #2 missed
With the current parser all nine fixtures pass. After the upgrade, three fail, and in two different ways. encoded_ps misses both positives: it reads command_line, which no longer exists, so the attack goes undetected. office_shell alerts on its negative: the rule's filter for the finance macro reads the command line too, and a filter that cannot see its field never matches, so the benign macro now raises an alert. new_domain_admin does not use the field and passes. Without the tests, the first failure would be invisible (a rule that quietly stops firing) and the second would show up as a mysterious new false positive in the queue the next morning.
Variant tests: does the rule survive small changes?
Attackers rarely type the command a rule author expects. For each technique, keep a list of variants and check which ones the rule still catches. PowerShell's -EncodedCommand parameter, for example, is accepted under its documented short forms -e and -ec (even though -ExecutionPolicy also starts with e) and as prefixes of the full name (-en, -enc, -encod… -EncodedCommand), with / instead of - as well; the binary can be copied under another name.
def encoded_ps(image, cmd): # the rule under test, as above
c = cmd.lower()
return image.lower().endswith("\\powershell.exe") and "-enc" in c and "-nop" in c
def encoded_ps_v2(image, cmd, original_name="powershell.exe"):
import re
c = cmd.lower()
is_ps = image.lower().endswith(("\\powershell.exe", "\\pwsh.exe")) or original_name.lower() in ("powershell.exe", "pwsh.dll")
enc = re.search(r"\s[-/–](e|ec|en|enc|enco|encod|encode|encoded|encodedc\w*)\s", c + " ")
return bool(is_ps and enc)
P = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
variants = [
("baseline", P, "powershell -nop -enc SQBFAFgA", "powershell.exe"),
("full parameter name", P, "powershell -NoProfile -EncodedCommand SQBFAFgA", "powershell.exe"),
("shortest prefix", P, "powershell -nop -e SQBFAFgA", "powershell.exe"),
("slash instead of dash", P, "powershell /nop /enc SQBFAFgA", "powershell.exe"),
("no -nop at all", P, "powershell -ec SQBFAFgA", "powershell.exe"),
("renamed binary", "C:\\Users\\Public\\notepad.exe", "notepad -nop -enc SQBFAFgA", "PowerShell.EXE"),
]
print(f"{'variant':24} {'v1':>4} {'v2':>4}")
for name, img, cmd, orig in variants:
print(f"{name:24} {'hit' if encoded_ps(img, cmd) else '-':>4} {'hit' if encoded_ps_v2(img, cmd, orig) else '-':>4}")variant v1 v2
baseline hit hit
full parameter name hit hit
shortest prefix - hit
slash instead of dash - hit
no -nop at all - hit
renamed binary - hit
The first version catches only the spelling its author typed and the full parameter name (which happens to contain both -enc and -nop as prefixes). It misses the shortest prefix, the / syntax, a command without -nop, and a renamed copy of PowerShell. The second version matches the parameter as a word with any accepted prefix and either dash or slash, drops the -nop requirement, and identifies PowerShell by the original file name from the executable's version information (which Sysmon records as OriginalFileName) as well as by path. Every variant in the list becomes a permanent test case.
How tests are kept honest
- Positives come from reality. Generate them in the lab (run the technique against a lab VM with logging on, under the lab rules of Security Foundations) and export the resulting events, or take them (sanitised) from real incidents. Invented events test your imagination, not the rule.
- Negatives come from production. Sample real benign events that look similar (admins' PowerShell, the finance macro) and keep them as fixtures.
- Tests travel with the rule. Same repository, same review (Detection as Code).
- Validate end to end on a schedule. A daily harmless test event (for example a command line containing a unique test marker, executed by a scheduled job on a lab host) must produce an alert in the SIEM; if it doesn't, the pipeline is broken somewhere.
Pitfalls
- Testing the rule against its own author's assumptions only. Variant lists from ATT&CK procedure examples, red-team reports and purple-team exercises widen them.
- Fixtures that bypass normalisation. If tests feed already-normalised events, a parser change is only caught by end-to-end validation; keep some raw-event fixtures that go through the parser too.
- Chasing every variant in one rule. Some variants are better caught by another rule (a renamed binary by an "original file name differs from image name" rule). Document which rule covers which variant.
Practice
1. Add a negative fixture for encoded_ps that the first version wrongly alerts on.
{"image": P, "command_line": "powershell -nop -file C:\\scripts\\x-encrypt.ps1"}: the file name contains -encrypt, so the substring -enc is present and v1 alerts on a harmless script. v2 requires the parameter to be a separate word (whitespace before the dash or slash) and does not match.
2. How would you make the office_shell rule survive the field rename without editing every rule?
Fix the parser mapping so cmdline is mapped back to the schema's command_line (normalisation is the place for this), and add raw-event fixtures that go through the parser in CI, so the next rename fails a test before deployment.
3. Which variant does v2 still miss, and which other telemetry would catch it?
PowerShell code run without powershell.exe at all (through a .NET host process loading the automation library) has no PowerShell command line. PowerShell's own script-block logging (event 4104) and EDR telemetry about the loaded modules see it (PowerShell Security).
Test yourself
What does a negative fixture check?
- That the rule matches an attack
- That the rule does not alert on a known benign look-alike
- That the SIEM is online
- That the rule is fast
After the parser renamed command_line to cmdline, why did office_shell fail a negative test rather than a positive one?
- Its positive used a different field
- Its filter reads the command line; with the field gone, the filter never matches and the finance macro alerts
- Negatives are always run first
- It didn't fail
Which test type is the only one that catches a broken log collector?
- Unit tests on fixtures
- Variant tests
- End-to-end validation with a real test event through collection, parsing and the SIEM
- Linting
Why did the v1 encoded_ps rule miss powershell -nop -e SQBFAFgA?
- The image was wrong
- It looked for the literal string
-enc, but PowerShell accepts the shorter prefix-e - Base64 was invalid
- It has no -nop