Lesson 04 · 40 minutes
Find unusual logins with a z-score and an isolation forest
- Build a simple statistical detector and an isolation forest on login sessions
- Compare the two with the same alert budget on a fixed week
- Explain why an anomaly is not always an attack
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
The SOC keeps a week of login sessions of its 24 staff: the hour, the failed attempts before the login, the megabytes downloaded and the number of hosts touched. Nobody has labelled them, so there is no training set for a classifier. Your lead asks for a detector that points at strange sessions: "Show me a simple one and a clever one. Which one would you trust at night, when nobody reads more than eight alerts?" The data has seven planted anomalies that the detectors do not see, and you use them only to score the result.
Recall
Lesson 2: why did you measure the triage model on a week that it had never seen?
A model scores its own training data too well. A fresh week stands for the future and gives an honest count of misses.
Lesson 1: what is the baseline, and why do you need one?
The result of the team with no model, or with one simple rule. A new detector is worth its cost only if it beats the baseline on the same data.
The idea
Anomaly detection looks for what is unusual, with no labels. It learns what the data usually looks like and reports what does not fit. This is unsupervised learning, in contrast to the supervised classifier of lesson 2, which learned from true labels. Its strength is that it can point at an attack that nobody has described. Its weakness is that unusual does not mean malicious: a backup job and an attacker are both unusual.
You use two detectors:
| Detector | How it works | Weak spot |
|---|---|---|
| z-score | How many standard deviations a value is from the mean. Alert when any field is far out. | Misses a session that is a little odd in several fields at once. |
| Isolation forest | Random trees that split the data. A strange point is separated after few splits. | Needs a choice of how many alerts to raise, and it is harder to explain. |
- Session → Features: hour, failures, MB, hosts
- Features → Detector: z-score or isolation forest
- Detector → Score: the detector ranks sessions by strangeness
- Score → Alert: above the limit, raise it
The mean is the average of a field. The standard deviation is the usual size of the spread around the mean: about two thirds of the values lie within one standard deviation of it. A z-score is the distance of a value from the mean, counted in standard deviations. A z-score of 3.5 is very rare in a normal field.
Worked example
1. Look at the data
logins() returns 709 sessions. Each has hour, failed, mb_down and hosts. The field label is 0 for normal, 1 for a planted anomaly and 2 for a harmless backup run that is odd on purpose. The detectors never read label.
python3 -c "
from gen import logins
rows = logins()
for i in (0, 429, 323):
r = rows[i]
print(r['id'], r['user'].ljust(6), 'hour', r['hour'], ' failed', r['failed'], ' MB', r['mb_down'], ' hosts', r['hosts'], ' label', r['label'])
"L0001 alma hour 13 failed 0 MB 38 hosts 2 label 0
L0430 omar hour 8 failed 0 MB 516 hosts 2 label 1
L0324 kofi hour 5 failed 2 MB 60 hosts 4 label 1L0430 downloaded 516 MB, about seventeen times the usual 30. L0324 is quieter: it ran at 5 o'clock, with 2 failures, 60 MB and 4 hosts. Each value is only a little unusual. Together they are rare.
2. Save the detectors
Save anomaly.py. NumPy (np) works on whole tables of numbers at once. X.mean(axis=0) is the mean of each column, and .max(axis=1) is the largest value in each row. argsort() returns the positions that would sort an array, from the smallest. [::-1] reverses a list, so z.argsort()[::-1] puts the strangest session first. IsolationForest(n_estimators=200, contamination=0.02, random_state=0) builds 200 random trees. The setting contamination is the share of the data that you want to call an alert, here 2 percent. score_samples gives each session a score where a lower value means stranger, and predict gives -1 for each alert and 1 for each normal session.
anomaly.py
"""anomaly.py: two detectors on one week of login sessions, compared with the planted anomalies."""
import numpy as np
from sklearn.ensemble import IsolationForest
from gen import logins
FIELDS = ["hour", "failed", "mb_down", "hosts"]
Z_LIMIT = 3.5
def matrix(rows):
return np.array([[r[f] for f in FIELDS] for r in rows], dtype=float)
def zscores(X):
"""For each session, the largest distance from the mean in standard deviations, over all fields."""
return np.abs((X - X.mean(axis=0)) / X.std(axis=0)).max(axis=1)
def isolation(X, contamination=0.02):
"""An isolation forest. Returns the score of each session (lower means stranger) and a True for each alert."""
forest = IsolationForest(n_estimators=200, contamination=contamination, random_state=0).fit(X)
return forest.score_samples(X), forest.predict(X) == -1
def report(name, alert, rows):
ids = [r["id"] for r, hit in zip(rows, alert) if hit]
planted = [r["id"] for r in rows if r["label"] == 1]
found = [i for i in ids if i in planted]
print(f"{name:18} alerts {len(ids):2} planted found {len(found)} of {len(planted)} false alerts {len(ids) - len(found)}")
return ids
def in_top(order, rows, n):
"""How many planted anomalies are among the first n sessions of `order`?"""
return sum(rows[i]["label"] == 1 for i in order[:n])
if __name__ == "__main__":
rows = logins()
X = matrix(rows)
print("sessions:", len(rows), " planted anomalies:", sum(r["label"] == 1 for r in rows))
z = zscores(X)
report("z-score > 3.5", z > Z_LIMIT, rows)
score, flag = isolation(X)
report("isolation forest", flag, rows)
print("strangest session by z-score:", rows[int(z.argmax())]["id"], "with z =", round(float(z.max()), 1))
print("planted anomalies among the strangest n sessions of each detector:")
for n in (3, 5, 8):
print(f" n = {n} z-score {in_top(z.argsort()[::-1], rows, n)} isolation forest {in_top(score.argsort(), rows, n)}")python3 anomaly.pysessions: 709 planted anomalies: 7
z-score > 3.5 alerts 3 planted found 2 of 7 false alerts 1
isolation forest alerts 15 planted found 7 of 7 false alerts 8
strangest session by z-score: L0430 with z = 15.3
planted anomalies among the strangest n sessions of each detector:
n = 3 z-score 2 isolation forest 3
n = 5 z-score 4 isolation forest 5
n = 8 z-score 6 isolation forest 73. Read the result
The z-score detector with the limit 3.5 raises 3 alerts and finds 2 of the 7 planted anomalies. The one false alert is the backup run. The isolation forest raises 15 alerts and finds all 7, with 8 false alerts, one of which is the backup run again.
Neither is "better" in general. The z-score detector is quiet and misses the sessions that are odd in many fields a little. The forest finds them, and it costs 8 false alerts at this setting. Both flag the backup run: an anomaly is a lead, and an analyst decides if it is an attack.
4. Compare with the same budget
The two detectors raised different numbers of alerts, so the comparison is unfair. The last lines of the output give both the same budget: the first 3, 5 or 8 sessions in the order of each detector. With 8 reads, which is all that the night analyst can do, the z-score finds 6 of 7 and the forest finds 7. A comparison with an equal budget is the honest one.
Note that the order of the forest is stable, but two sessions near the top can swap places on another version of the library. Count what lies in the top n, and do not trust the exact rank of the first two.
5. Change the limit
The z limit of 3.5 is a choice. Run the detector with 3: it raises 10 alerts and finds all 7. The price is 3 false alerts: two normal sessions and the backup run. Lowering a threshold finds more, and it costs more reading. This is the trade of lesson 2 again, and the same method decides it: write the rule about risk and then take the setting that meets it.
Your turn
Use anomaly.py and the same sessions. Write a short script that does three things.
- Count the alerts of the z-score detector with the limit 3.
- Count the alerts of the isolation forest with
contamination=0.01. - For the night analyst who reads 8 alerts, count how many of the 7 planted anomalies each detector has in its first 8.
Last, in one sentence, say which detector you would run at night and with which setting.
Check yourself
The forest raised 15 alerts and found all 7. Why is that not "better" by itself than 3 alerts and 2 found?
It cost 8 false alerts, which is about 48 minutes of analyst time at 6 minutes each. The z-score detector with the limit 3 also found 7, with 3 false alerts. The setting decides as much as the method.
Why can the detector not use the label to learn?
In real life you have no label for most sessions. The label here is the key to the test, and it is used only to score. An anomaly detector learns the normal pattern from the data alone.
The backup run is flagged by both detectors. Is that a failure?
No. Both did their job: the session is unusual. The failure would be to treat every alert as an attack. Add context (lesson 9): a known backup account and a known host could lower its priority.
Why is the top of the forest order not safe to quote as a fact?
Two sessions can have almost the same score. A new library version can change the last decimals and swap their order. The count in the top n is much more stable than the rank of one session.
Field notes
- The normal pattern changes: a new office, a new project, a holiday. A detector that learned last month's pattern raises alerts on the new normal. Retrain on a schedule, and watch the number of alerts per week as a sign of drift (the course "Detection and incident response for AI" covers this).
- Per-user baselines work better than one for all. A night shift worker at 3 o'clock is normal. Add a feature for the usual hour of that user, or train one model for each group.
- An attacker who knows a threshold can stay a little under it. A detector is a net with holes. Keep rules for known bad patterns next to it, as in lesson 6 of "Security fundamentals".
- Explainability matters at night. For every alert, show the fields that made it strange. A z-score gives that for free. For a forest you must add it, for example by showing the fields that are far from the median.
- MITRE ATT&CK has a technique called Valid Accounts, where the attacker uses a stolen login. A login anomaly is a way to see it. Take the current technique text from MITRE.