Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Baselines: knowing what normal looks like

After this lesson: I can compare today's activity with a baseline to find what is unusual.

65 min lesson12 commandsDetection engineering lab: Suricata rules, Sigma rules and Zeek-style logs on one private Ubuntu VM

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

Seventy-five megabytes at two in the morning

A PC in the office sent 75 MB to the internet on Tuesday. Is that a problem? For a video editor it might be a quiet hour. For a receptionist's PC at 2 a.m., it is worth a look.

You cannot call anything unusual until you know what usual is. You build that from a made-up week of the office's traffic, in your own lab copy.

By the end of this lesson

Note

I can compare today's activity with a baseline to find what is unusual.

Key words

WordWhat it means
Baselinewhat normal looks like for one thing over time
Meanthe average of the values
Standard deviationhow far values usually spread from the mean
Z-scorehow many standard deviations a value is from the mean
Prevalencehow many hosts share something

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

The one rule

Important

Build baselines only from your own lab copy's data. Profiling a real network's users needs written permission, and their privacy matters too. Unauthorised access to data is an offence under the Computer Misuse Act 1990. The week here is made up.

A baseline is normal for one thing

A baseline describes one measure, for one host or user, over a period. Here the measure is the kilobytes each PC sends a day. The first six working days are the baseline, and Tuesday 10 November is tested against them.

The Runs write a script that makes the week from a fixed seed, then the baseline itself.

Move into the lab's folder

Command
cd ~/detect

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Make sure the hunt folder exists

Command
mkdir -p hunt

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the week maker, part 1

Command
printf '%s\n' 'import random' 'from datetime import datetime, timezone' 'r = random.Random(20261110)' 'PCS = ["10.20.1.10", "10.20.1.11", "10.20.1.12", "10.20.1.13", "10.20.1.14"]' 'SITES = ["192.0.2.10", "192.0.2.25", "10.20.0.80", "203.0.113.40"]' 'DAYS = [2, 3, 4, 5, 6, 9, 10]' 'rows = []' 'for day in DAYS:' '    t0 = datetime(2026, 11, day, tzinfo=timezone.utc).timestamp()' '    for pc in PCS:' '        for i in range(r.randint(40, 60)):' '            rows.append((t0 + r.uniform(8.5, 17.5) * 3600, pc, r.choice(SITES), r.randint(400, 2400)))' '    if day == 10:' '        for pc in PCS:' '            rows.append((t0 + r.uniform(9, 10) * 3600, pc, "203.0.113.44", r.randint(400, 900)))' '        for i in range(30):' '            rows.append((t0 + 7800 + 60 * i, "10.20.1.13", "203.0.113.61", r.randint(2000000, 3000000)))' 'rows.sort()' 'out = open("hunt/week.log", "w")' 'out.write("#path" + chr(9) + "conn" + chr(10))' > hunt/week.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the week maker, part 2

Command
printf '%s\n' 'out.write("#fields" + chr(9) + chr(9).join(["ts", "id.orig_h", "id.resp_h", "id.resp_p", "proto", "orig_bytes"]) + chr(10))' 'for t, a, b, sent in rows:' '    out.write(chr(9).join(["%.6f" % t, a, b, "443", "tcp", str(sent)]) + chr(10))' 'out.close()' 'print(len(rows), "hunt/week.log")' >> hunt/week.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Make the week of connections

Command
python3 hunt/week.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Read the columns it wrote

Command
grep "^#fields" hunt/week.log

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the baseline script, part 1

Command
printf '%s\n' 'import statistics' 'from datetime import datetime, timezone' 'def log(name):' '    fields, rows = [], []' '    for line in open(name):' '        parts = line.rstrip(chr(10)).split(chr(9))' '        if parts[0] == "#fields":' '            fields = parts[1:]' '        elif not line.startswith("#"):' '            rows.append(dict(zip(fields, parts)))' '    return rows' 'days, sent = [], {}' 'for row in log("hunt/week.log"):' '    day = datetime.fromtimestamp(float(row["ts"]), timezone.utc).strftime("%m-%d")' '    if day not in days:' '        days.append(day)' '    key = (row["id.orig_h"], day)' '    sent[key] = sent.get(key, 0) + int(row["orig_bytes"]) / 1000' 'today = days[-1]' 'print("host mean_kb sd_kb", today + "_kb z")' > hunt/baseline.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the baseline script, part 2

Command
printf '%s\n' 'for host in sorted({h for h, d in sent}):' '    past = [sent.get((host, d), 0) for d in days[:-1]]' '    mean, sd = statistics.mean(past), statistics.pstdev(past)' '    now = sent.get((host, today), 0)' '    z = (now - mean) / sd' '    print(host, round(mean), round(sd), round(now), round(z, 1), "UNUSUAL" if abs(z) > 3 else "")' >> hunt/baseline.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Compare Tuesday with the baseline

Command
python3 hunt/baseline.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

A z-score measures how far from normal

The mean says what a PC sends on an average day. The standard deviation says how much that usually varies. A z-score divides today's distance from the mean by the standard deviation.

Beyond 3 either way is a common line for a closer look. 10.20.1.13 is thousands of deviations high. 10.20.1.12 is flagged low: perhaps a day off, but worth a question.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A common mistake

Warning

Many people think a baseline is simply the recent past. If an attacker was already active in those days, their traffic becomes normal and hides. Choose a baseline period you have hunted, and rebuild it when the network changes.

New is not the same as bad

A baseline also tells you what is new: a destination nobody contacted before. New things happen every day, such as a software update. So ask about prevalence too: how many hosts did it?

A new server every PC reached at 9 a.m. looks like a rollout. A new server one PC reached at night is a lead.

Write the new things script, part 1

Command
printf '%s\n' 'from datetime import datetime, timezone' 'def log(name):' '    fields, rows = [], []' '    for line in open(name):' '        parts = line.rstrip(chr(10)).split(chr(9))' '        if parts[0] == "#fields":' '            fields = parts[1:]' '        elif not line.startswith("#"):' '            rows.append(dict(zip(fields, parts)))' '    return rows' 'before, today, night = {}, {}, {}' 'for row in log("hunt/week.log"):' '    when = datetime.fromtimestamp(float(row["ts"]), timezone.utc)' '    host, dest = row["id.orig_h"], row["id.resp_h"]' '    if when.day == 10:' '        today.setdefault(dest, set()).add(host)' '        if when.hour < 7 or when.hour > 18:' '            night[host] = night.get(host, 0) + 1' '    else:' '        before.setdefault(dest, set()).add(host)' > hunt/newthings.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the new things script, part 2

Command
printf '%s\n' 'for dest in sorted(today):' '    if dest not in before:' '        print("new destination", dest, "hosts", len(today[dest]), " ".join(sorted(today[dest])))' 'for host in sorted(night):' '    print("outside 07:00-19:00", host, night[host], "connections")' >> hunt/newthings.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

List what is new on Tuesday

Command
python3 hunt/newthings.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Try it: work out a z-score

Code: python
past = [70, 64, 81, 75, 68, 62]
today = 79

mean = sum(past) / len(past)
sd = (sum((x - mean) ** 2 for x in past) / len(past)) ** 0.5
z = (today - mean) / sd
print("mean", round(mean), "sd", round(sd, 1), "z", round(z, 1))
print("unusual" if abs(z) > 3 else "normal")
# Change today to 140, then press Run.

Make a free account to save your work and track your progress.

Assignment: find hosts outside their baseline

history is a dictionary from a host to a list of its past daily values, and today a dictionary from a host to today's value. A host missing from today sent 0.

profile(values) returns (mean, sd), where sd is the population standard deviation (divide by the number of values).

outliers(history, today, limit) returns, sorted, the hosts whose z-score today is above limit or below minus limit. A host whose sd is 0 is an outlier whenever today differs from its mean.

new_rare(before, now, most) takes two dictionaries from a destination to the set of hosts that reached it. It returns, sorted, the destinations in now that are not in before and were reached by at most most hosts.

Code: python
def profile(values):
    return (0, 0)

def outliers(history, today, limit):
    return []

def new_rare(before, now, most):
    return []

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.