Baselining: Stacking, Frequency Analysis and z-Scores
"Is this unusual?" is the question behind most hunts, and it has no answer without a baseline: a description of what normal looks like for this host, this user, this time of day. Two statistical tools do most of the work in practice. Stacking (frequency analysis) counts how often each value occurs across many systems and puts the rare ones at the top of the list. z-scores measure how far a number lies from an entity's usual values, in units of its usual spread. Both are simple, both fail in predictable ways, and this lesson shows the failures along with the methods.
Stacking
Collect one field from many systems, count each distinct value, sort ascending. Common values are almost always benign (an attacker rarely runs on every machine at once); the long tail of values seen on one or two systems is where to look. New Admins and Rare Processes stacked parent and child processes; the same works for services, scheduled tasks, autorun entries, DLL paths, user agents and listening ports.
import pandas as pd
services = pd.DataFrame( # (host, installed service name) from 50 workstations, synthetic
[(f"ws{i:02d}", s) for i in range(1, 51) for s in ["Spooler", "WinDefend", "LabEDR", "wuauserv", "Dnscache"]]
+ [(f"ws{i:02d}", "LabVPNClient") for i in range(1, 36)]
+ [(f"ws{i:02d}", "LabPrinterHelper") for i in (3, 7, 9, 12, 21, 30)]
+ [("ws15", "WinUpdateSvcHelper"), ("ws41", "DevDockerService"), ("ws42", "DevDockerService")],
columns=["host", "service"])
stack = services.groupby("service").host.agg(hosts="nunique", where=lambda s: ",".join(sorted(s)[:3]))
stack["share"] = (stack.hosts / services.host.nunique()).map("{:.0%}".format)
print(stack.sort_values("hosts").to_string()) hosts where share
service
WinUpdateSvcHelper 1 ws15 2%
DevDockerService 2 ws41,ws42 4%
LabPrinterHelper 6 ws03,ws07,ws09 12%
LabVPNClient 35 ws01,ws02,ws03 70%
Dnscache 50 ws01,ws02,ws03 100%
LabEDR 50 ws01,ws02,ws03 100%
Spooler 50 ws01,ws02,ws03 100%
WinDefend 50 ws01,ws02,ws03 100%
wuauserv 50 ws01,ws02,ws03 100%
The tail holds three candidates. LabPrinterHelper on six hosts belongs to the printer driver package (check that those six are the hosts near the department printers). DevDockerService on two developer machines is explained by their role. WinUpdateSvcHelper on one host has a name chosen to look like Windows Update, which no real Windows service is called; that is where an analyst starts. Stacking does not decide anything; it orders the work.
z-scores
For a numeric quantity (bytes uploaded per day, logons per hour, processes per host), the z-score of a new observation against a baseline with mean and standard deviation is
If the baseline were normally distributed, would happen by chance about 0.3 % of the time. Security data is rarely normal (it is skewed, bursty and has outliers), so treat as a ranking, not a probability.
Two problems follow from using the mean and standard deviation:
- Masking. If the baseline period already contains an outlier, it inflates and hides the next one.
- Skew. One-off spikes in normal behaviour (a backup, a big download) make large for everybody.
The robust z-score replaces them with the median and the median absolute deviation :
The factor makes comparable with for normal data; outliers in the baseline barely move the median or the MAD.
Uploads per user, three ways
The program builds 30 days of daily upload volume for four users. On day 30, erin uploads 900 MB; grace had a one-off 2,000 MB upload on day 10 (a legitimate video export, already in the baseline); ivan is a developer whose uploads vary a lot.
import numpy as np, pandas as pd
rng = np.random.default_rng(3)
days = 29
base = {"alice": rng.normal(40, 8, days), "erin": rng.normal(35, 6, days),
"grace": rng.normal(50, 10, days), "ivan": rng.normal(150, 60, days)}
base["grace"][9] = 2000 # one legitimate big export in the baseline
today = {"alice": 52, "erin": 900, "grace": 640, "ivan": 330} # MB uploaded on day 30
rows = []
for user, hist in base.items():
hist = np.clip(hist, 0, None)
mu, sd = hist.mean(), hist.std(ddof=1)
med = np.median(hist)
mad = np.median(np.abs(hist - med))
x = today[user]
rows.append((user, x, round(mu, 1), round(sd, 1), round((x - mu) / sd, 1), round(med, 1), round(mad, 1),
round(0.6745 * (x - med) / mad, 1)))
df = pd.DataFrame(rows, columns=["user", "today", "mean", "sd", "z", "median", "MAD", "robust_z"])
print(df.to_string(index=False))
print("\nz > 3: ", list(df[df.z > 3].user))
print("robust_z > 3:", list(df[df.robust_z > 3].user)) user today mean sd z median MAD robust_z
alice 52 40.2 9.3 1.3 38.1 3.5 2.7
erin 900 34.4 6.2 138.9 35.5 3.7 159.6
grace 640 116.0 362.5 1.4 50.6 7.0 56.7
ivan 330 153.8 62.0 2.8 158.1 37.4 3.1
z > 3: ['erin']
robust_z > 3: ['erin', 'grace', 'ivan']
Read the last two lines first. The ordinary z-score finds only erin: 900 MB against a usual 34 MB is so extreme () that any method finds it. It misses grace: her 640 MB is twelve times her median, but the 2,000 MB export in her baseline pushed her standard deviation to 362.5 MB, so is only 1.4. That is masking. The robust score ignores the single spike (her MAD is 7.0 MB) and ranks her second with . If grace's upload is a second legitimate export, a quick check closes it; if not, it is exactly the kind of exfiltration a masked baseline would have hidden.
ivan shows the other side: with he is barely over the threshold, on a day that is unremarkable for a developer whose uploads range widely. A fixed threshold of 3 is a convention, not a law; in practice scores are ranked, and borderline ones are combined with other context (destination, time of day, data type) before anyone is paged (Enrichment).
Making baselines fit the data
- Per entity, not global. A developer and an accountant have different normal; the program compared each user only with their own history. With few data points per entity, compare with a peer group (same role or department) instead.
- Seasonality. Logons on Monday mornings, backups at night, month-end in finance. Baseline per hour of day or day of week when the quantity follows a calendar.
- Clean the baseline. Exclude known incidents and documented one-off events from the look-back, or use robust statistics that tolerate them.
- Transform skewed quantities. Byte counts are better compared on a log scale (), where a tenfold increase counts the same for small and large users.
- Enough history. A baseline of five days is noise; 30 days per entity is a common minimum for daily quantities.
How these methods fail, and the fix
| Failure | Example | Fix |
|---|---|---|
| Masking by earlier outliers | grace's export hides her next spike | Robust statistics; remove documented one-offs |
| Slow drift | an attacker raises volume a little every day, and the baseline follows | Compare with a fixed older reference period too; cap daily baseline updates |
| Too many entities | at 10,000 users, flags dozens by chance every day | Combine with other signals (risk scoring), raise thresholds, rank instead of alert |
| Rarity is not malice | a new software rollout puts a new service on 5 hosts | Join with change records; stack again after the rollout |
Pitfalls
- Reading as a probability. Heavy tails make large values far more common than the normal distribution suggests.
- Dividing by zero. A user who uploads exactly the same amount every day has or ; guard against it (add a small floor).
- Baselining the attacker. If the intrusion is older than the look-back, its activity is part of normal; this is why hunts also compare across peers, not only over time.
Practice
1. A user's baseline has mean 40 MB and standard deviation 8 MB. Today they upload 72 MB. What is $z$, and is it worth a look?
. Worth a look as a ranking signal, especially combined with other context (destination, time of day); alone, at large scale, it would not justify an alert.
2. Why did grace's ordinary z-score stay below 3 although she uploaded 640 MB?
Her baseline contains the 2,000 MB export, which raises the mean and inflates the standard deviation to several hundred MB, so 640 MB looks only moderately unusual. The median and MAD ignore the single spike, so the robust score is very large.
3. In the stacking example, the VPN client is on 70 % of hosts. Is the 30 % without it interesting?
Possibly: stacking also works in reverse. Hosts missing a common security service (here the VPN client, more importantly LabEDR or WinDefend) are gaps worth checking. In the example every host has the EDR, so the missing VPN client is probably desk-bound staff.
Test yourself
What does stacking put at the top of the list?
- The most common values
- The rarest values, seen on one or a few systems
- Only Windows services
- Values sorted alphabetically
What is the z-score of for a baseline with and ?
Why use the median and MAD instead of the mean and standard deviation?
- They are faster to compute
- Outliers already in the baseline barely move them, so they don't mask new outliers
- They always give larger scores
- They need no data
At 10,000 users, why is 'alert on ' a problem even for normal data?
- cannot exceed 3
- About 0.13 % exceed it by chance on each side, which is still a dozen or more alerts a day
- Users have no baselines
- It is too slow