A Correlation Engine in pandas
A SIEM is, at its core, three things: a table of normalised events, a set of rules that turn events into alerts, and a step that groups alerts about the same entity into something an analyst can work as one case. This lesson builds all three in pandas on a synthetic day of lab.test telemetry from five sources (identity-provider sign-ins, VPN, web proxy, DNS and EDR process events) with one intrusion hidden in normal activity. The following lessons each add one detection to this structure; A Small Detection Pipeline built a smaller version on Windows events alone.
The design
events (one schema) -> rules: f(events) -> alerts -> correlate by entity + time -> incidents (cases)
time, source, user, host, src_ip, action, object rule, time, user, host, score entity, rules, span, score- One schema for every source:
time(UTC),source,user,host,src_ip,actionandobject(what was acted on: a domain, a process, a URL). Normalisation is assumed done (Normalisation and Schemas). - Rules are plain functions that take the event table and return alerts with a risk score. Adding a detection means adding a function, and every function can be tested on its own (Testing Detections).
- Correlation maps alerts to an entity (here the user, with hosts mapped to their user) and opens one incident per entity when alerts from at least two different rules fall within a time window, or when one alert alone is severe enough.
The data and the engine
import numpy as np, pandas as pd
rng = np.random.default_rng(7)
USERS = ["alice", "bob", "carol", "dave", "erin", "frank", "grace", "heidi", "ivan", "judy"]
HOST = {u: f"ws{11 + i}" for i, u in enumerate(USERS)} # erin -> ws15
day = pd.Timestamp("2026-01-15")
def t(h): # hours after midnight -> timestamp
return day + pd.to_timedelta(h, unit="h")
ev = [] # (time, source, user, host, src_ip, action, object)
for u in USERS: # normal office day for everyone
start = 8 + rng.random()
ev.append((t(start), "idp", u, HOST[u], f"10.10.0.{20 + USERS.index(u)}", "signin_ok", "mail"))
for k in range(int(rng.integers(20, 40))):
h = start + rng.random() * 9
ev.append((t(h), "proxy", u, HOST[u], "", "GET", rng.choice(["intranet.lab.test", "docs.example", "news.example"])))
ev.append((t(h), "dns", u, HOST[u], "", "query", rng.choice(["intranet.lab.test", "docs.example", "news.example"])))
for p in rng.choice(["outlook.exe", "winword.exe", "excel.exe", "teams.exe", "chrome.exe"], 6):
ev.append((t(start + rng.random() * 9), "edr", u, HOST[u], "", "process", f"explorer.exe>{p}"))
if rng.random() < 0.4: # some people work from home
ev.append((t(19 + rng.random()), "vpn", u, HOST[u], "192.0.2.10", "vpn_ok", "vpn01"))
# Benign oddities: heidi signs in late at night, grace's spreadsheet macro runs a reporting script.
ev += [(t(23.2), "idp", "heidi", "ws18", "192.0.2.10", "signin_ok", "mail"),
(t(14.0), "edr", "grace", "ws17", "", "process", "excel.exe>cmd.exe")]
# The intrusion: erin's password was phished; the attacker signs in from abroad, then uses her laptop's VPN.
ev += [(t(2.10), "idp", "erin", "", "203.0.113.9", "signin_fail", "mail"),
(t(2.12), "idp", "erin", "", "203.0.113.9", "signin_ok", "mail"),
(t(2.30), "vpn", "erin", "ws15", "203.0.113.9", "vpn_ok", "vpn01"),
(t(2.40), "edr", "erin", "ws15", "", "process", "winword.exe>powershell.exe")]
ev += [(t(2.5 + k / 12), "dns", "erin", "ws15", "", "query", "upd.cdn-lab.example") for k in range(18)]
ev.append((t(3.95), "proxy", "erin", "ws15", "", "POST", "upd.cdn-lab.example"))
ev = pd.DataFrame(ev, columns=["time", "source", "user", "host", "src_ip", "action", "object"]).sort_values("time", ignore_index=True)
ev["time"] = ev.time.dt.floor("s")
print(len(ev), "events:", ev.source.value_counts().to_dict())
# --- rules: each returns rows (rule, time, user, score, detail) ---
def off_hours_signin(e):
f = e[(e.action == "signin_ok") & ((e.time.dt.hour < 6) | (e.time.dt.hour >= 22))]
return [("off-hours sign-in", r.time, r.user, 20, f"from {r.src_ip}") for r in f.itertuples()]
def office_child_shell(e):
f = e[(e.source == "edr") & e.object.str.match(r"(winword|excel|outlook)\.exe>(powershell|cmd|wscript)\.exe")]
return [("office app spawned shell", r.time, r.user, 60, r.object) for r in f.itertuples()]
def chatty_new_domain(e, min_queries=12):
dns = e[e.action == "query"]
users_per_domain = dns.groupby("object").user.nunique() # stand-in for a 30-day baseline
rare = users_per_domain[users_per_domain == 1].index # only one user ever resolves it
q = dns[dns.object.isin(rare)].groupby(["user", "object"]).time.agg(["size", "min"]).reset_index()
return [("rare domain, many queries", r.min, r.user, 40, f"{r.object} x{r.size}")
for r in q[q["size"] >= min_queries].itertuples()]
RULES = [off_hours_signin, office_child_shell, chatty_new_domain]
alerts = pd.DataFrame([a for rule in RULES for a in rule(ev)], columns=["rule", "time", "user", "score", "detail"])
print(f"\n{len(alerts)} alerts")
print(alerts.sort_values("time").assign(time=lambda a: a.time.dt.strftime("%H:%M:%S")).to_string(index=False))
# --- correlation: per user, alerts of >= 2 different rules within 4 hours, or one alert with score >= 80 ---
inc = []
for user, g in alerts.sort_values("time").groupby("user"):
span = g.time.max() - g.time.min()
if (g.rule.nunique() >= 2 and span <= pd.Timedelta("4h")) or g.score.max() >= 80:
inc.append((user, g.rule.nunique(), g.score.sum(), g.time.min(), span))
print("\nINCIDENTS")
for user, n, score, first, span in inc:
print(f" {user}: {n} rules, risk {score}, first alert {first:%H:%M}, span {int(span.total_seconds() // 60)} min")729 events: {'dns': 333, 'proxy': 316, 'edr': 62, 'idp': 13, 'vpn': 5}
5 alerts
rule time user score detail
off-hours sign-in 02:07:12 erin 20 from 203.0.113.9
office app spawned shell 02:24:00 erin 60 winword.exe>powershell.exe
rare domain, many queries 02:30:00 erin 40 upd.cdn-lab.example x18
office app spawned shell 14:00:00 grace 60 excel.exe>cmd.exe
off-hours sign-in 23:12:00 heidi 20 from 192.0.2.10
INCIDENTS
erin: 3 rules, risk 120, first alert 02:07, span 22 min
Reading the result
729 events become 5 alerts and 1 incident. Two of the alerts are benign and stay single: heidi signing in at 23:12 through the company VPN gateway, and grace's spreadsheet starting cmd.exe for a reporting script. Each would be worth a glance on a dashboard, neither pages anyone. erin's three alerts come from three different rules and three different sources (identity provider, EDR, DNS) within 22 minutes, and together they read as a story: a sign-in at 02:07 from an address abroad, a Word document starting PowerShell on her laptop at 02:24, then the laptop resolving an unknown domain every five minutes from 02:30.
Notice what the engine did not need: none of the three rules is precise on its own (off-hours sign-ins and Office macros starting shells happen in every company), but their combination on one entity is rare. Notice also what it missed: the failed sign-in just before, the VPN session from the same foreign address and the POST upload at 03:57 raised nothing, because no rule looks for them. Each following lesson adds one such rule: impossible travel, brute force followed by success, new admins and rare processes, beaconing and enrichment.
How the engine itself fails
A correlation engine has its own failure modes, separate from any one rule:
- Entity resolution. Correlation by user only works if every source names users the same way and hosts are mapped to users. The VPN and the EDR here carry a user; real EDR data often carries only a host, which must be joined with an asset or login table (Enrichment).
- Window choice. Four hours catches this intrusion; a patient attacker spreading steps over days defeats it. Production engines keep per-entity risk over a longer period (often 24 hours to 7 days) and decay it.
- Shared entities. Service accounts, shared workstations and NAT addresses connect unrelated activity. Exclude or treat them specially.
- Rule interdependence. Two rules that fire on the same event count twice. Count distinct rules, or distinct data sources, not alerts.
How it is fixed in production
The same three-stage design appears in every serious SIEM, under different names: correlation searches and risk-based alerting in Splunk, building-block rules and alert grouping in Elastic Security, analytics rules and incidents with entity mapping in Microsoft Sentinel. What you build here in pandas maps one to one: normalise, detect with small testable rules, correlate on entities, and only page a human for the correlated result.
Pitfalls
- Testing on the data you built the rules from. The thresholds above were chosen knowing the intrusion; the exercises and the mini-project give you other data.
- Hard-coding baselines.
users_per_domainis computed on the same day here; a real rule uses the domains seen in the last 30 days, and that baseline has to be maintained. - Letting low scores accumulate forever. Without decay or a window, every user eventually crosses any threshold.
Practice
1. Add a rule "VPN from an address the user has never used" and give it score 30. Which alerts does it add?
Group VPN events by user and source IP; an address is new if it does not appear in the user's history (here, everything before the day, which you can simulate with a set of known pairs such as every user's 192.0.2.10). It adds an alert for erin at 02:18 from 203.0.113.9; nobody else used a new address.
2. Change the correlation to require two different data sources (`source`) instead of two different rules. What do you need to add to the alerts?
Each alert must carry the source(s) of the events it was built from (idp, edr, dns). Then count nunique() of sources per user. This is stricter and resists two rules that fire on the same event.
3. Why is "only one user ever resolves it" part of the domain rule?
Popular domains are resolved by many users and are almost never command-and-control; a domain that only one host resolves, many times, is unusual. The condition is a crude rarity test; Baselining does it properly with frequency analysis over a long period.
Test yourself
What are the three stages of the correlation engine?
- Collect, compress, delete
- Events in one schema, rules that produce alerts, correlation of alerts by entity and time into incidents
- Scan, exploit, report
- Index, shard, replicate
Why are rules written as small separate functions?
- Python requires it
- Each can be tested, owned and tuned on its own, and adding a detection doesn't touch the others
- It makes them faster
- SIEMs cannot run large rules
What problem does counting distinct rules (not alerts) per entity avoid?
- Too few alerts
- One noisy rule firing many times pushing an entity over the incident threshold by itself
- Clock skew
- Missing logs
Why is entity resolution critical for correlation?
- It encrypts the data
- Alerts can only be grouped if all sources name the same user or host the same way, and hosts are mapped to users
- It reduces storage
- It is optional