TExcelTAD
Home › Windows & Active Directory Security › A Small Detection Pipeline in pandas

A Small Detection Pipeline in pandas

Single rules produce single alerts, and a SOC that receives "spray from 10.10.0.66", "Kerberoasting by bob", "DCSync by svc-backup" as three unrelated tickets on three desks will miss the story. A detection pipeline does three things in order: normalise events from many sources into one schema, apply rules that each encode one technique from this course, and correlate the alerts into incidents by the entity they share (a source host, an account) and the time they happen. This lesson builds all three in pandas on a synthetic day of DC and server events from corp.lab.test. The same structure, with a real SIEM's query language instead of pandas, is how production detection works; Defensive Security covers SIEMs and Sigma in depth.

The schema

Windows events have dozens of fields with different names in different IDs (TargetUserName in 4624, TargetUserName and ServiceName in 4769, SubjectUserName in 4662). The pipeline maps everything to one small schema:

Column Meaning
time event time (UTC)
id event ID
actor the account doing the thing (who logged on, who requested, who changed)
ip the network source, where the event has one
target the object acted on (service, attribute, group, account)
detail the one or two fields the rules need (encryption type, logon type and package, status)

The pipeline

The input is a day in the lab compressed to an hour: normal activity, plus one intruder working from 10.10.0.66 through the techniques of the weaknesses section. Each rule is a function that returns alerts with a technique label (MITRE ATT&CK IDs, which SOCs use to classify alerts); correlation then groups alerts by source address into incidents.

python · try it yourself
import pandas as pd

raw = [  # (time, id, actor, ip, target, detail) after normalisation
    ("09:00", 4768, "alice", "10.10.0.21", "krbtgt", "etype=0x12 preauth=2"),
    ("09:01", 4769, "alice", "10.10.0.21", "FS01
quot;, "etype=0x12"), ("09:02", 4624, "alice", "10.10.0.21", "FS01", "type=3 pkg=Kerberos"), ("09:05", 4625, "bob", "10.10.0.22", "WS02", "type=2 status=0xC000006A"), *[(f"09:1{i}", 4771, u, "10.10.0.66", "krbtgt", "code=0x18") for i, u in enumerate(["alice", "bob", "carol", "dave", "erin", "frank", "gina"])], ("09:18", 4768, "hank", "10.10.0.66", "krbtgt", "etype=0x17 preauth=2"), # spray hit *[(f"09:2{i}", 4769, "hank", "10.10.0.66", s, "etype=0x17") for i, s in enumerate(["svc-sql", "svc-backup", "svc-report", "svc-web", "svc-crm"])], ("09:30", 4768, "svc-legacy", "10.10.0.66", "krbtgt", "etype=0x17 preauth=0"), ("09:40", 4624, "svc-backup", "10.10.0.66", "FS01", "type=3 pkg=NTLM"), ("09:45", 4662, "svc-backup", "10.10.0.66", "DC=corp,DC=lab,DC=test", "props=1131f6ad-9c07-11d1-f79f-00c04fc2dcd2"), ("09:47", 4662, "DC02
quot;, "10.10.0.26", "DC=corp,DC=lab,DC=test", "props=1131f6ad-9c07-11d1-f79f-00c04fc2dcd2"), ("09:50", 5136, "svc-backup", "10.10.0.66", "CN=Domain Admins", "attr=member value=hank"), ("09:52", 5136, "carol", "10.10.0.22", "CN=Marketing", "attr=description"), ] ev = pd.DataFrame(raw, columns=["time", "id", "actor", "ip", "target", "detail"]) ev["time"] = pd.to_datetime("2026-01-15 " + ev["time"]) kv = ev["detail"].str.extractall(r"(\w+)=(\S+)").reset_index().pivot(index="level_0", columns=0, values=1) ev = ev.join(kv) # one column per detail field DCS = {"DC01
quot;: "10.10.0.20", "DC02
quot;: "10.10.0.26"} USER_SPNS = {"svc-sql", "svc-backup", "svc-report", "svc-web", "svc-crm"} PRIV_GROUPS = {"CN=Domain Admins", "CN=Enterprise Admins", "CN=Administrators"} PRIV_ACCOUNTS = {"svc-backup", "alice"} def spray(e): f = e[(e.id == 4771) & (e.code == "0x18")] g = f.groupby("ip").agg(n=("actor", "nunique"), t=("time", "min")) return [(r.t, ip, "T1110.003 password spraying", f"{r.n} accounts failed") for ip, r in g.iterrows() if r.n >= 5] def kerberoast(e): f = e[(e.id == 4769) & e.target.isin(USER_SPNS)] g = f.groupby(["ip", "actor"]).agg(n=("target", "nunique"), rc4=("etype", lambda s: (s == "0x17").sum()), t=("time", "min")) return [(r.t, ip, "T1558.003 Kerberoasting", f"{actor}: {r.n} user SPNs, {r.rc4} RC4") for (ip, actor), r in g.iterrows() if r.n >= 4] def asrep(e): f = e[(e.id == 4768) & (e.preauth == "0")] return [(r.time, r.ip, "T1558.004 AS-REP roasting", f"no pre-auth for {r.actor}") for r in f.itertuples()] def dcsync(e): f = e[(e.id == 4662) & e.props.str.contains("1131f6ad", na=False)] return [(r.time, r.ip, "T1003.006 DCSync", f"by {r.actor}") for r in f.itertuples() if DCS.get(r.actor) != r.ip] def priv_group(e): f = e[(e.id == 5136) & e.target.isin(PRIV_GROUPS) & (e.attr == "member")] return [(r.time, r.ip, "T1098 privileged group change", f"{r.actor} added {r.value} to {r.target}") for r in f.itertuples()] def ntlm_priv(e): f = e[(e.id == 4624) & (e.pkg == "NTLM") & e.actor.isin(PRIV_ACCOUNTS)] return [(r.time, r.ip, "T1550.002 pass-the-hash?", f"NTLM network logon of {r.actor} to {r.target}") for r in f.itertuples()] alerts = pd.DataFrame([a for rule in (spray, kerberoast, asrep, dcsync, priv_group, ntlm_priv) for a in rule(ev)], columns=["time", "ip", "technique", "what"]).sort_values("time") print(f"{len(ev)} events -> {len(alerts)} alerts -> {alerts.ip.nunique()} incident(s)\n") for ip, inc in alerts.groupby("ip"): span = inc.time.max() - inc.time.min() print(f"INCIDENT source {ip}: {len(inc)} alerts over {int(span.total_seconds() // 60)} min") for r in inc.itertuples(): print(f" {r.time:%H:%M} {r.technique:30} {r.what}")
23 events -> 6 alerts -> 1 incident(s)

INCIDENT source 10.10.0.66: 6 alerts over 40 min
  09:10  T1110.003 password spraying    7 accounts failed
  09:20  T1558.003 Kerberoasting        hank: 5 user SPNs, 5 RC4
  09:30  T1558.004 AS-REP roasting      no pre-auth for svc-legacy
  09:40  T1550.002 pass-the-hash?       NTLM network logon of svc-backup to FS01
  09:45  T1003.006 DCSync               by svc-backup
  09:50  T1098 privileged group change  svc-backup added hank to CN=Domain Admins

Twenty-three events become six alerts and one incident, and the incident reads as a timeline: a spray finds hank's password, hank Kerberoasts five service accounts, one of them (svc-backup) is used with NTLM within twenty minutes, then performs a DCSync and adds hank to Domain Admins. The AS-REP request for svc-legacy sits in the middle. The normal events (alice's file access, bob's typo, DC02 replicating, carol editing a description) produced nothing. That ratio is what makes a pipeline usable.

Tuning and testing

  • Every rule needs a test. Keep synthetic positive and negative events for each rule (as above) and run them in CI when rules change; a rule that silently stops matching is worse than no rule.
  • Thresholds come from baselines, not from this lesson: measure distinct accounts per source, SPNs per client and NTLM rates on your own data for a few weeks first.
  • Allow-lists are per entity and context: a vulnerability scanner's address for the spray rule, the sync server for DCSync, a PAW for admin NTLM, each with an owner and an expiry date.
  • Correlate by more than IP. Real intrusions change hosts; join alerts on accounts as well (the account found by the spray, hank, is also the one added to Domain Admins) and on time windows.
  • Severity follows the chain: a lone AS-REP request is medium; the same request inside an incident that ends with DCSync is critical.

From pandas to a SIEM

The same rules are written as SIEM queries or, portably, as Sigma rules (YAML that converters translate into Splunk, Elastic, Microsoft Sentinel and other query languages). A Sigma rule for the DCSync detection says: product windows, service security, EventID: 4662, Properties|contains: 1131f6ad-9c07-11d1-f79f-00c04fc2dcd2, filter SubjectUserName|endswith: '

#39; for DC accounts. The pandas version is a place to understand and test the logic; production belongs in the SIEM with forwarding from every DC.

Pitfalls

  • Normalising badly. Mixing DOMAIN\user, user@domain and user forms breaks joins; lower-case and strip domains consistently.
  • Clock and time-zone drift between sources reorders a chain.
  • Correlating everything with everything. A shared proxy or NAT address merges unrelated users into one "incident"; know which addresses are shared.
  • Alerting on rules nobody owns. Each rule needs an owner who handles its false positives.

Practice

1. Which rule would fire if the intruder used AES tickets for the Kerberoasting step, and what would change in the output?

The Kerberoasting rule still fires (five user SPNs from one client), with 0 RC4 in the text. The detection relies on the shape, not only the encryption type.

2. Write a seventh rule: a 4624 logon of a DC computer account to a non-DC system. What fields does it use?

id == 4624, actor in the DC list (ends with $ and is a DC), target not a DC, plus pkg (NTLM is especially suspicious, as in relay of a coerced DC). Label it with relay/coercion and add a negative test (DC01$ logging on to DC02 for replication).

3. Why does DC02's 4662 at 09:47 not alert, and what would make it alert?

Its actor and address match the DC list. It would alert if DC02$ appeared from another address, for example a stolen machine credential used from 10.10.0.66.

Test yourself

What are the three stages of the detection pipeline in this lesson?

  1. Collect, delete, archive
  2. Normalise events, apply technique rules, correlate alerts into incidents
  3. Encrypt, sign, send
  4. Scan, exploit, report

Which ATT&CK technique ID corresponds to DCSync?

  1. T1558.003
  2. T1003.006
  3. T1110.003
  4. T1550.002

Why should allow-lists be per entity and context?

  1. To save memory
  2. A legitimate account used from an unexpected host is exactly the case to catch
  3. SIEMs require it
  4. They shouldn't exist

What is Sigma?

  1. A Windows event ID
  2. A generic YAML format for detection rules, converted into SIEM query languages
  3. A Kerberos encryption type
  4. A Sysinternals tool