TExcelTAD
Home › Defensive Security: SOC, SIEM, Detection Engineering & Threat Hunting › Baselining: Stacking, Frequency Analysis and z-Scores

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.

python · try it yourself
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 xx against a baseline with mean μ\mu and standard deviation σ\sigma is

z=x−μσz = \frac{x - \mu}{\sigma}

If the baseline were normally distributed, ∣z∣>3\lvert z \rvert > 3 would happen by chance about 0.3 % of the time. Security data is rarely normal (it is skewed, bursty and has outliers), so treat zz as a ranking, not a probability.

Two problems follow from using the mean and standard deviation:

  1. Masking. If the baseline period already contains an outlier, it inflates σ\sigma and hides the next one.
  2. Skew. One-off spikes in normal behaviour (a backup, a big download) make σ\sigma large for everybody.

The robust z-score replaces them with the median x~\tilde{x} and the median absolute deviation MAD=median⁡(∣xi−x~∣)\text{MAD} = \operatorname{median}(\lvert x_i - \tilde{x} \rvert):

zr=0.6745 (x−x~)MADz_r = \frac{0.6745\,(x - \tilde{x})}{\text{MAD}}

The factor 0.67450.6745 makes zrz_r comparable with zz 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.

python · try it yourself
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 (z=138.9z = 138.9) 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 zz 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 zr=56.7z_r = 56.7. 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 zr=3.1z_r = 3.1 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 (log⁡(1+x)\log(1 + x)), 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, ∣z∣>3\lvert z \rvert > 3 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 zz as a probability. Heavy tails make large zz values far more common than the normal distribution suggests.
  • Dividing by zero. A user who uploads exactly the same amount every day has σ=0\sigma = 0 or MAD=0\text{MAD} = 0; 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?

z=(72−40)/8=4z = (72 - 40) / 8 = 4. 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?

  1. The most common values
  2. The rarest values, seen on one or a few systems
  3. Only Windows services
  4. Values sorted alphabetically

What is the z-score of x=70x = 70 for a baseline with μ=50\mu = 50 and σ=5\sigma = 5?

  1. 22
  2. 44
  3. 2020
  4. 0.250.25

Why use the median and MAD instead of the mean and standard deviation?

  1. They are faster to compute
  2. Outliers already in the baseline barely move them, so they don't mask new outliers
  3. They always give larger scores
  4. They need no data

At 10,000 users, why is 'alert on z>3z > 3' a problem even for normal data?

  1. zz cannot exceed 3
  2. About 0.13 % exceed it by chance on each side, which is still a dozen or more alerts a day
  3. Users have no baselines
  4. It is too slow