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

Free lesson

Stacking to find rare events

After this lesson: I can stack a field across hosts to find rare values worth investigating.

60 min lesson9 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

Four million lines and one odd one

Forty web requests can be read by eye. A college network makes millions a day, and nobody reads those. Yet one of them may come from a program that should not be there.

Hunters count instead of read. They turn a log into a short list of values and how often each appears, then look at the rare end. You do it on the lab's office capture.

By the end of this lesson

Note

I can stack a field across hosts to find rare values worth investigating.

Key words

WordWhat it meansExample
Stackingcounting how often each value of a field appears
Long tailthe many values seen only a few times
Least frequency of occurrencelooking at the rarest values first
Distinct hostshow many different machines share a value
User-Agentthe name a program sends with a web requestupdater/1.4

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

Stack only your own lab copy's logs. A real network's logs show what people did, so reading them needs written permission. Unauthorised access to data is an offence under the Computer Misuse Act 1990. The office and its traffic are made up.

Stacking turns a log into a short list

Stacking counts each value of one field. Sorted from the rarest, it puts the odd values at the top: least frequency of occurrence.

A count alone can mislead, so the script also counts distinct hosts. A value used a lot by one machine is very different from one used by every machine.

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.

Turn the office capture into logs

Command
zeek-lite -r pcaps/office.pcap

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

Write the stacking script

Command
printf '%s\n' 'import sys' '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' 'count, hosts = {}, {}' 'for row in log(sys.argv[1]):' '    value = row[sys.argv[2]]' '    count[value] = count.get(value, 0) + 1' '    hosts.setdefault(value, set()).add(row["id.orig_h"])' 'print("count hosts", sys.argv[2])' 'for value in sorted(count, key=lambda v: (len(hosts[v]), count[v], v)):' '    print(count[value], len(hosts[value]), value)' > hunt/stack.py

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

Stack the User-Agents

Command
python3 hunt/stack.py http.log user_agent

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

The long tail holds good and bad

Stack the names the office looked up. The top of the list is a long tail of names seen once. Some are four hex characters before cdn-update.example, which no person types.

Others are look-alikes, such as cdn-updates.example, which real software here uses. Grouping each name by its last two labels shows the five lookups under one parent.

Stack the names looked up

Command
python3 hunt/stack.py dns.log query

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

Group the names by their last two labels

Command
zeek-cut query < dns.log | awk -F. '{print $(NF-1) "." $NF}' | sort | uniq -c | sort -n

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

A common mistake

Warning

Many people think rare means malicious. Most rare values are a new laptop, an odd update or one person's habit. Stacking tells you where to look first; each rare value still needs checking against what you know.

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

Stack anything a host does

Any field can be stacked: destinations in conn.log, or the command lines in the Windows events. On the endpoint, the rare end holds the hidden encoded PowerShell, beside an administrator's own encoded command.

Stacking finds both. Telling them apart is the hunter's job: who ran it, on which PC, and what came next.

Stack the destinations

Command
python3 hunt/stack.py conn.log id.resp_h

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

Stack the command lines in the events

Command
sqlite3 logs/events.db "SELECT COUNT(*), COUNT(DISTINCT Computer), CommandLine FROM logs GROUP BY CommandLine ORDER BY 2, 1"

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

Try it: stack a list of User-Agents

Code: python
from collections import Counter

agents = ["Mozilla/5.0"] * 6 + ["curl/8.5"] + ["Mozilla/5.0"] * 3 + ["python-requests/2.32"]
stack = Counter(agents)
for value, count in sorted(stack.items(), key=lambda pair: pair[1]):
    print(count, value)
# Add "curl/8.5" twice more to the list, then press Run.

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

Assignment: stack a field across hosts

rows is a list of dictionaries, each one line of a log.

stack(rows, field) returns a list of (count, value) pairs, one for each value of field, sorted by count and then by value.

rare(rows, field, host_field, most) returns, sorted, the values of field seen on at most most distinct hosts, the host being row[host_field].

parent(name) returns the last two labels of a domain name joined by a dot, or the name itself if it has fewer than two.

Code: python
def stack(rows, field):
    return []

def rare(rows, field, host_field, most):
    return []

def parent(name):
    return name

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.