04 / REUSABLE INVESTIGATION TOOLS · LESSON 13

Build a configurable detection function

Combine a UTC window and threshold into a reusable rule with evidence IDs.

15 min · learn at your pace

Keep policy outside the detection loop

A reusable rule receives its settings as data. Here a policy supplies start, end, and threshold. Changing a rule's window should not require changing its implementation. Validate the settings before examining events, including when the event list is empty.

Reuse the earlier window and grouping ideas. Select the half-open UTC window, keep failures, normalize account names, then group source IDs. The output includes both a count and the IDs behind it so a reviewer can inspect the supporting observations.

Make the function easy to test

Accept lists and dictionaries and return structured results. File reading and report writing belong at the edge of the tool. A detector with no input prompts or hidden global state can be called with small examples and reused with another export.

This rule counts all failures in the selected window, including those separated by successful logons. It does not implement a rolling window, consecutive failures, or password-spray detection across accounts. Giving the rule a precise definition is more useful than a broad label that implies capabilities it does not have.

Sort accounts and event IDs for reproducible output. The caller supplies validated, uniquely identified events. Collection errors should be reported separately rather than silently converted into a detector result. Later lessons combine these boundaries into a complete investigation tool.

Try an example.py
import json
from pathlib import Path
policy = json.loads(Path("policy.json").read_text(encoding="utf-8"))
print(policy["start"], policy["threshold"])
YOUR TURN

Put it into practice.

Define detect_failures(events, policy). Policy requires aware ISO start/end with start < end and a positive integer threshold (not bool). Invalid settings raise ValueError even with no events. Count failure events in [start,end), grouped by user.strip().casefold(). Return user, failures and sorted event_ids for groups at or above threshold, sorted by user. Inputs are validated and have unique IDs. Keep the rule independent of files and input().

See an explained solution
One way to solve it.py
from datetime import datetime, timezone

def parse_utc(value):
    moment = datetime.fromisoformat(value)
    if moment.tzinfo is None or moment.utcoffset() is None:
        raise ValueError("Timestamp needs an offset")
    return moment.astimezone(timezone.utc)

def in_window(events, start, end):
    first, last = parse_utc(start), parse_utc(end)
    if first >= last:
        raise ValueError("Window must have a positive duration")
    return [event for event in events if first <= parse_utc(event["timestamp"]) < last]

def detect_failures(events, policy):
    threshold = policy.get("threshold")
    if type(threshold) is not int or threshold < 1:
        raise ValueError("Threshold must be a positive integer")
    if not all(isinstance(policy.get(key), str) for key in ("start", "end")):
        raise ValueError("Policy needs start and end")
    groups = {}
    for event in in_window(events, policy["start"], policy["end"]):
        if event["outcome"] == "failure":
            user = event["user"].strip().casefold()
            groups.setdefault(user, []).append(event["id"])
    return [{"user": user, "failures": len(ids), "event_ids": sorted(ids)} for user, ids in sorted(groups.items()) if len(ids) >= threshold]

Separating policy, filtering and grouping makes the detector reusable. Every result carries the evidence IDs supporting its inclusive threshold.