Careers Post-AI
Security: all chapters

SecurityPart 5: Detection and response

Chapter 18Detection engineering

32 min read, 1 lab, Intermediate

In a public 2020 attack recording used in this chapter's lab, the attacker steals credentials with one command, rundll32.exe calling the MiniDump export of the signed Windows file comsvcs.dll, leaving no malware hash or attacker domain to block. This chapter teaches you to detect behaviors like that as tested code, map them to MITRE ATT&CK, and keep them quiet enough that analysts trust them.

After this chapter you can

  • Explain the Pyramid of Pain and choose between signature, behavior and anomaly detections
  • Write Sigma rules with selections, filters, modifiers and correlations
  • Convert Sigma to backend queries and diagnose field-mapping and case-sensitivity failures
  • Build a detection-as-code repository with positive and negative tests in CI
  • Measure ATT&CK coverage and alert quality honestly, and tune false positives without creating blind spots
  • Judge where ML and LLM triage help and where they mislead

Aim high on the Pyramid of Pain

David Bianco's Pyramid of Pain (2013) ranks the indicators you can detect by how much it hurts an attacker when you do. Blocking a file hash costs them a recompile. Detecting a technique, such as dumping LSASS memory from a signed binary, forces them to find a new way to do the job. Detect what is expensive to change.

TTPs means tactics, techniques and procedures: what the attacker is trying to achieve and how. Detections themselves come in three styles, each with a different failure mode.

Signature

  • Matches a known exact value: a hash, a string, a domain
  • Very precise, near-zero false positives
  • Breaks when one byte changes

Behavior

  • Matches a pattern of activity: rundll32 plus comsvcs plus MiniDump
  • Survives new tools and recompiles
  • Needs tuning for legitimate look-alikes

Anomaly

  • Flags deviation from a learned baseline: a first-time admin login at 3 a.m.
  • Can find the unknown
  • Noisy, and hard to explain to an analyst

Most mature programs are mostly behavioral, with signatures for fresh intel and anomalies as hunting leads rather than pager alerts.

The detection lifecycle as code

A detection is software. It has requirements, it has bugs, it needs tests and it eventually needs retiring. Detection-as-code means rules live in Git, change through pull requests, and are tested automatically before they reach production.

Research is the step people skip. Before writing anything, find out which log records the behavior, whether you collect it, and what normal looks like. A rule for a field you do not collect is worse than no rule, because it shows up as coverage on a dashboard.

A practical repository looks like this. Every rule has a matching test folder, and CI refuses rules without one.

detections/ repository layout
detections/
  rules/
    proc_creation_win_rundll32_comsvcs_minidump.yml
  tests/
    proc_creation_win_rundll32_comsvcs_minidump/
      positive.jsonl      # real events the rule must match
      negative.jsonl      # benign look-alikes it must not match
      logsource           # e.g. --product windows --category process_creation
  scripts/test_rules.sh
  .github/workflows/detections.yml

Anatomy of a Sigma rule

Sigma is an open, vendor-neutral YAML format for log detections. You write the logic once and convert it to Splunk, Elasticsearch, Microsoft Sentinel and dozens of other query languages. Here is the rule from this chapter's opening, written in full.

rules/proc_creation_win_rundll32_comsvcs_minidump.yml
title: LSASS Dump via Comsvcs MiniDump
id: 0f1c6a52-3f7e-4f0b-9d55-4b8f7c2a9e11
status: experimental
description: Detects rundll32 calling the MiniDump export of comsvcs.dll, a common way to dump LSASS memory with a signed Windows binary.
references:
    - https://attack.mitre.org/techniques/T1003/001/
author: You
date: 2026-12-01
tags:
    - attack.credential-access
    - attack.t1003.001
logsource:
    category: process_creation
    product: windows
detection:
    selection_img:
        - Image|endswith: '\rundll32.exe'
        - OriginalFileName: 'RUNDLL32.EXE'
    selection_cli:
        CommandLine|contains|all:
            - 'comsvcs'
            - 'minidump'
    condition: all of selection_*
falsepositives:
    - None known; investigate every hit
level: high
PartWhat it does
id, title, statusStable identity and maturity: experimental, test, stable, deprecated
tagsATT&CK tactic and technique; this is what coverage reports read
logsourceWhich kind of event: category (process_creation), product (windows), service
detectionNamed selections (maps are AND, lists are OR) and a condition combining them
falsepositives, levelGuidance for the analyst and a severity from informational to critical

Field names follow Sigma's taxonomy, which for Windows process events matches Sysmon's names (Image, CommandLine, ParentImage). Matching is case-insensitive by default. Modifiers after a pipe change how a value matches:

ModifierMeaningExample
contains, startswith, endswithSubstring, prefix, suffixImage|endswith: '\net.exe'
allEvery listed value must match (default is any)CommandLine|contains|all
reRegular expressionCommandLine|re: '-e(nc)?\s'
windashAlso match / and en-dash variants of - flagsCommandLine|windash|contains: '-enc'
base64offsetMatch a string hidden inside base64 at any alignmentCommandLine|base64offset|contains: 'IEX'
cidrIP in a network rangeDestinationIp|cidr: '10.0.0.0/8'
casedForce case-sensitive matchingCommandLine|cased|contains: 'MiniDump'

Notice the OriginalFileName alternative. Attackers copy rundll32.exe to x.exe to dodge path-based rules, but the name compiled into the file's version resource travels with the copy.

From Sigma to a backend query

Conversion has two parts. A processing pipeline maps Sigma's generic field names onto your data's schema, and a backend writes the query language. The same rule produces very different queries depending on the pipeline:

sigma convert output for the rule above
# -t lucene --without-pipeline  (fields already use Sysmon names)
(Image:*\\rundll32.exe OR OriginalFileName:RUNDLL32.EXE) AND (CommandLine:*comsvcs* AND CommandLine:*minidump*)
 
# -t lucene -p ecs_windows  (data shipped by Winlogbeat in ECS)
(process.executable.caseless:*\\rundll32.exe OR process.pe.original_file_name:RUNDLL32.EXE) AND (process.command_line:*comsvcs* AND process.command_line:*minidump*)
 
# -t esql --without-pipeline
from * metadata _id, _index, _version | where (ends_with(Image, "\\rundll32.exe") or OriginalFileName=="RUNDLL32.EXE") and CommandLine like "*comsvcs*" and CommandLine like "*minidump*"

Read the last two queries carefully, because they hide the most common conversion bug. Sigma promised case-insensitive matching, but a Lucene wildcard on a plain keyword field and ES|QL's like are both case-sensitive. The real event contains MiniDump, so against a default mapping this rule converts cleanly, deploys green, and never fires.

Tool versions move fast here. As of late 2026, sigma-cli 4.x runs on pySigma 2, and its check and match commands work without any backend. The Elasticsearch backend plugin still requires pySigma 1.x, so the lab uses a second, pinned environment for conversion. Check sigma plugin list first, since the backend may have caught up by the time you read this.

Sigma also supports correlation rules that count matches of a base rule over time. This one turns a noisy "invalid SSH user" rule into an alert on four or more distinct usernames from one source in five minutes, which is what password spraying looks like.

rules/lnx_sshd_invalid_user_burst.yml
title: Burst of SSH Logins for Nonexistent Users From One Source
id: 9b7c2e10-4d3f-4a8b-8e61-0f2a5c7d9e43
status: experimental
correlation:
    type: value_count
    rules:
        - sshd_invalid_user        # the base rule's name: field
    group-by:
        - source.ip
    timespan: 5m
    condition:
        field: user.name
        gte: 4
level: medium
converted with -t esql (base rule included)
from * metadata _id, _index, _version | where message like "*Invalid user*"
| eval timebucket=date_trunc(5minutes, @timestamp) | stats value_count=count_distinct(user.name) by timebucket, source.ip
| where value_count >= 4

Mapping to ATT&CK and measuring coverage

Every rule's attack.t... tags map it to ATT&CK techniques, which lets you draw a coverage heat map in the ATT&CK Navigator. The map is useful for spotting gaps and dangerous when read as a score. One rule tagged T1003.001 covers one procedure for dumping LSASS memory, not the technique; there are dozens of others.

Grade coverage by evidence, not by tags:

LevelMeaningHow you know
0. No dataThe telemetry is not collectedData-source inventory
1. Data onlyLogged and searchable, no ruleHunt queries return results
2. Rule, untestedA rule existsTag in the repo
3. Rule, testedFires on recorded positives, quiet on negativesCI test results
4. Validated liveFired end to end in production on emulated activityAtomic Red Team or purple-team run, alert in the queue

A short script turns your tags into a Navigator layer you can upload and screenshot for your portfolio:

scripts/coverage_layer.py
#!/usr/bin/env python3
"""Build an ATT&CK Navigator layer from the attack.t* tags in Sigma rules."""
import json
import sys
from collections import defaultdict
from pathlib import Path
 
import yaml
 
rules_dir = Path(sys.argv[1] if len(sys.argv) > 1 else "rules")
covered = defaultdict(list)
for path in sorted(rules_dir.glob("**/*.yml")):
    rule = yaml.safe_load(path.read_text())
    for tag in rule.get("tags", []):
        if tag.startswith("attack.t"):
            covered[tag.split(".", 1)[1].upper()].append(rule["title"])
 
layer = {
    "name": "Detection coverage",
    "domain": "enterprise-attack",
    "versions": {"layer": "4.5"},
    "techniques": [
        {"techniqueID": tid, "score": len(titles), "comment": "; ".join(titles)}
        for tid, titles in sorted(covered.items())
    ],
}
json.dump(layer, sys.stdout, indent=2)

Tuning and alert quality

A false positive is an alert on benign activity; a false negative is an attack with no alert. Tuning trades one for the other, and the goal is an alert an analyst can act on, not zero alerts. Good tuning narrows on something the attacker cannot easily control.

Tuning moveExampleRisk
Filter a known-benign parentParentImage is the inventory agent and User is its service accountAttacker who compromises that agent is invisible
Deduplicatenet.exe spawns net1.exe; drop the child so one command makes one alertLow
Threshold or correlateAlert on four usernames in five minutes, not oneSlow, careful attackers stay under it
Enrich and scoreAdd asset criticality, raise risk instead of alerting directlyNeeds a risk-based alerting pipeline
Allowlist by pathExclude C:\Tools\High: attackers can write there too

Measure alert quality per rule so you know which ones to fix:

MetricDefinitionWhy it matters
PrecisionTrue positives divided by all alertsLow precision trains analysts to ignore the rule
VolumeAlerts per dayCapacity planning; a sudden spike often means a broken filter
Time to triageAlert created to verdictLong times mean missing context in the alert
Detection latencyEvent time to alert timeA rule that fires an hour late misses containment windows
SilenceDays since last hit, and last successful testA rule that never fires may be broken, not lucky

Where ML and LLMs help and where they mislead

Machine learning and large language models are now part of most detection stacks. They are good at scale and summarization and bad at being accountable. Use them where a wrong answer is cheap to catch.

UseWhere it helpsWhere it misleads
Anomaly models (UEBA, user and entity behavior analytics)Rare logons, impossible travel, unusual data volumesBaselines drift; attackers who move slowly become the baseline
LLM alert triageGathers context, summarizes a process tree, drafts the case noteConfident wrong verdicts; invents details not in the data
LLM rule draftingBoilerplate Sigma, conversions, test-event ideasInvented modifiers or field names, wrong technique IDs
LLM query translationSPL to ES|QL and backSubtle semantic drift, such as case sensitivity or null handling

The safest pattern is to let the model draft and let tests decide. An LLM-written rule goes through sigma check, the positive and negative tests, and a backend run against known events, exactly like a human-written one.

Key terms

Pyramid of Pain
A ranking of indicator types by how costly it is for an attacker to change them, from hashes up to TTPs.
Sigma
A vendor-neutral YAML format for log detection rules that converts to many query languages.
Processing pipeline
A Sigma component that maps generic field names and log sources onto a specific data schema.
Backend
A Sigma component that turns a rule into one query language, such as Lucene, ES|QL or SPL.
Detection-as-code
Managing detections in version control with review, automated tests and controlled deployment.
Correlation rule
A Sigma rule that alerts on counts or sequences of other rules' matches over a time window.
False positive
An alert raised on benign activity.
Precision
The share of a rule's alerts that are true positives.
ATT&CK coverage
The set of ATT&CK techniques for which you have detections, ideally graded by test evidence.
Lab

Write, test, convert and tune three Sigma rules

Intermediate, 120 min

Goal: build a small detection-as-code repo with three Sigma rules, prove each one with positive and negative events, tune a noisy rule until its tests pass, then convert all three and run them in the Elasticsearch stack from the logging chapter.

You need: the ~/seclab stack from the "Logging and telemetry" lab, running and loaded. Python 3.11 or newer, jq, and Git. All test activity targets the lab container you built; the Windows attacks are recorded datasets, so nothing malicious runs on your machine.

  1. Create the repo and two Python environments: one with the current sigma-cli for checks and tests, one pinned for the Elasticsearch backend.
mkdir -p ~/detections/rules ~/detections/tests ~/detections/scripts && cd ~/detections
git init -q
python3 -m venv .venv && . .venv/bin/activate
pip install -q sigma-cli
sigma version
sigma plugin install elasticsearch || echo "backend not yet compatible, using pinned env"
python3 -m venv .venv-convert
.venv-convert/bin/pip install -q "sigma-cli<4" pysigma-backend-elasticsearch
.venv-convert/bin/sigma list targets

Expect sigma version to print 4.x, and the pinned environment to list lucene, eql, esql and elastalert targets.

  1. Save the comsvcs rule from this chapter as rules/proc_creation_win_rundll32_comsvcs_minidump.yml, then add the two rules below.
rules/proc_creation_win_net_user_discovery.yml
title: Local Account Discovery via Net
id: 7d2b0c1e-58a4-4c39-b1f2-2a6e9d4c8b70
status: experimental
description: Detects net.exe or net1.exe listing local user accounts.
references:
    - https://attack.mitre.org/techniques/T1087/001/
author: You
date: 2026-12-01
tags:
    - attack.discovery
    - attack.t1087.001
logsource:
    category: process_creation
    product: windows
detection:
    selection_img:
        Image|endswith:
            - '\net.exe'
            - '\net1.exe'
    selection_cli:
        CommandLine|contains: ' user'
    condition: all of selection_*
falsepositives:
    - Administrators and inventory scripts
level: low
rules/lnx_sshd_invalid_user.yml
title: SSH Login Attempt for Nonexistent User
id: 3a9e4f61-1b7c-4d2e-9a0f-6c5d8e2b1f34
name: sshd_invalid_user
status: experimental
description: Detects sshd rejecting a login for a username that does not exist on the host.
references:
    - https://attack.mitre.org/techniques/T1110/001/
author: You
date: 2026-12-01
tags:
    - attack.credential-access
    - attack.t1110.001
logsource:
    product: linux
    service: sshd
detection:
    selection:
        message|contains: 'Invalid user'
    condition: selection
falsepositives:
    - Users mistyping their username
level: low

Most SigmaHQ Linux rules use bare keywords lists. The ES|QL backend cannot convert those, so this rule names the message field your pipeline produces.

  1. Validate syntax and metadata.
sigma check rules/

Expect No validation issues found. The tag validator downloads ATT&CK data. If you see CERTIFICATE_VERIFY_FAILED on a python.org build of Python for macOS, run its "Install Certificates" command or export SSL_CERT_FILE=$(python -m certifi) after pip install certifi.

  1. Build test fixtures from real events. Positives are events the rule must catch; negatives are look-alikes it must ignore.
D=~/seclab/data
T=tests/proc_creation_win_rundll32_comsvcs_minidump; mkdir -p $T
jq -c 'select(.EventID==1 and (.CommandLine // "" | test("comsvcs";"i")))' $D/psh_lsass*.json > $T/positive.jsonl
jq -c 'select(.EventID==1 and (.CommandLine // "" | test("comsvcs";"i") | not))' $D/*.json > $T/negative.jsonl
echo "--product windows --category process_creation" > $T/logsource
 
T=tests/proc_creation_win_net_user_discovery; mkdir -p $T
jq -c 'select(.EventID==1 and .Image=="C:\\Windows\\System32\\net.exe")' $D/empire*.json > $T/positive.jsonl
jq -c 'select(.EventID==1 and .Image=="C:\\Windows\\System32\\net1.exe")' $D/empire*.json > $T/negative.jsonl
printf '%s\n' '{"EventID":1,"UtcTime":"2026-12-01 09:00:00.000","Image":"C:\\Windows\\System32\\net.exe","CommandLine":"net user","ParentImage":"C:\\Program Files\\Contoso\\Inventory\\invagent.exe","User":"CORP\\svc_inventory"}' >> $T/negative.jsonl
echo "--product windows --category process_creation" > $T/logsource
 
T=tests/lnx_sshd_invalid_user; mkdir -p $T
curl -s -G localhost:9200/linux-sshd/_search --data-urlencode 'q=event.action:"Invalid user"' -d size=50 | jq -c '.hits.hits[]._source' > $T/positive.jsonl
curl -s -G localhost:9200/linux-sshd/_search --data-urlencode 'q=event.outcome:success' -d size=50 | jq -c '.hits.hits[]._source' > $T/negative.jsonl
echo "--product linux --service sshd" > $T/logsource
wc -l tests/*/*.jsonl

The net rule's negatives encode two decisions: the net1.exe child is a duplicate of the net.exe parent, and the inventory agent is approved activity.

  1. Add the test runner and run it.
scripts/test_rules.sh
#!/usr/bin/env bash
# Each rules/<stem>.yml must match tests/<stem>/positive.jsonl at least once
# and must not match tests/<stem>/negative.jsonl at all.
set -uo pipefail
status=0
for rule in rules/*.yml; do
  stem=$(basename "$rule" .yml)
  dir="tests/$stem"
  if [ ! -d "$dir" ]; then echo "FAIL $stem: no tests"; status=1; continue; fi
  read -r -a src < "$dir/logsource"
  hits=$(sigma match -q -F jsonl "${src[@]}" -e "$dir/positive.jsonl" "$rule" | wc -l | tr -d ' ')
  if [ "$hits" -lt 1 ]; then echo "FAIL $stem: missed every positive"; status=1; continue; fi
  if ! sigma match -q --fail-on-match "${src[@]}" -e "$dir/negative.jsonl" "$rule" > /dev/null; then
    echo "FAIL $stem: fired on a negative"; status=1; continue
  fi
  echo "ok   $stem ($hits positive hits)"
done
exit $status
chmod +x scripts/test_rules.sh && ./scripts/test_rules.sh 2>/dev/null

Expect two ok lines and FAIL proc_creation_win_net_user_discovery: fired on a negative. That failure is the point: your tests describe the behavior you want before the rule does.

  1. Tune the net rule. Replace its condition line with two filters and a new condition, then rerun the tests until all three pass.
rules/proc_creation_win_net_user_discovery.yml (detection block)
detection:
    selection_img:
        Image|endswith:
            - '\net.exe'
            - '\net1.exe'
    selection_cli:
        CommandLine|contains: ' user'
    filter_main_net1_child:
        ParentImage|endswith: '\net.exe'
    filter_optional_inventory:
        ParentImage: 'C:\Program Files\Contoso\Inventory\invagent.exe'
        User: 'CORP\svc_inventory'
    condition: all of selection_* and not 1 of filter_*

The filter_main_ and filter_optional_ prefixes follow SigmaHQ convention: main filters are always safe, optional ones are environment-specific allowlists.

  1. Convert all three rules to Lucene and ES|QL. The data uses Sysmon-style field names, which already match Sigma's taxonomy, so no pipeline is needed.
.venv-convert/bin/sigma convert -t lucene --without-pipeline rules/
.venv-convert/bin/sigma convert -t esql --without-pipeline rules/lnx_sshd_invalid_user.yml > ~/seclab/hunts/sshd-invalid-user.esql
echo '| KEEP @timestamp, source.ip, user.name, message' >> ~/seclab/hunts/sshd-invalid-user.esql

The converted ES|QL starts with from *, so it searches every index; the KEEP line trims the output to readable columns.

  1. Run each Lucene query against the stack and compare with your test expectations.
count() { curl -s -G "localhost:9200/$1/_count" --data-urlencode "q=$2" | jq .count; }
count winlogs-lab '(Image:*\\rundll32.exe OR OriginalFileName:RUNDLL32.EXE) AND (CommandLine:*comsvcs* AND CommandLine:*minidump*)'
count winlogs-lab '((Image:(*\\net.exe OR *\\net1.exe)) AND CommandLine:*\ user*) AND (NOT (ParentImage:*\\net.exe OR (ParentImage:"C\:\\Program Files\\Contoso\\Inventory\\invagent.exe" AND User:CORP\\svc_inventory)))'
count linux-sshd 'message:*Invalid\ user*'

Expect 1, 1 and the number of invalid-user lines you generated. Paste your own converted output if it differs slightly from these strings.

  1. Trigger the Linux rule with fresh, safe activity against your own container and watch the count rise.
for u in deploy git jenkins; do
  ssh -p 2222 -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null "$u@127.0.0.1" true 2>/dev/null
done
sleep 5; count linux-sshd 'message:*Invalid\ user*'
cd ~/seclab && ./esql.sh hunts/sshd-invalid-user.esql && cd ~/detections
  1. Wire up CI and a coverage layer, then commit.
.github/workflows/detections.yml
name: detections
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.12"
      - run: pip install sigma-cli
      - run: sigma check rules/
      - run: ./scripts/test_rules.sh
.venv/bin/python scripts/coverage_layer.py rules > coverage-layer.json
printf '.venv*/\n' > .gitignore && git add . && git commit -qm "Three tested Sigma rules" && git log --oneline

Upload coverage-layer.json in the ATT&CK Navigator ("Open Existing Layer", then "Upload from local") to see three techniques shaded.

Check your work: ./scripts/test_rules.sh prints three ok lines and exits 0, the three backend counts match your expectations, and the Linux count went up by three after step 9.

Stretch: add the correlation rule from this chapter, extend the test runner to pass both the base rule and the correlation to sigma match, and prove it fires on your spray loop but not on a single mistyped username. Then convert it with -t esql and run it with esql.sh.

Check yourself

An attacker copies rundll32.exe to C:\Users\Public\svc.exe and runs the comsvcs MiniDump command from the copy. Which part of the lab's rule still catches it?

A converted Lucene rule containing CommandLine:*minidump* passes all Sigma tests but returns zero hits in Elasticsearch on a known-positive event whose command line contains MiniDump. What is the most likely cause?

Your coverage dashboard shows 70 percent of ATT&CK techniques covered, counted from rule tags. Which addition makes that number most trustworthy?

An analyst asks you to stop a noisy rule firing on their admin scripts by excluding every process under C:\Tools\. What is the main risk?

An LLM triage assistant marks an alert benign, citing a note in the process command line that says the activity was approved by IT. What should happen?

Recap

  • Detect behaviors high on the Pyramid of Pain, because they are expensive for attackers to change.
  • A Sigma rule is selections, filters and a condition over a log source, with ATT&CK tags and false-positive notes.
  • Conversion depends on pipelines and backends; prove every converted query against real backend data, especially for case sensitivity.
  • Treat detections as code: positive and negative tests, CI, staged deployment and owned exclusions.
  • Grade ATT&CK coverage by test evidence and measure precision, latency and silence per rule.
  • Let ML and LLMs draft and summarize, and let tests and humans decide.

Go deeper