Lesson 08 · 55 minutes
Find a burst of failed logins in a time window and pin it with a test
- Parse a log time and compare times in UTC with datetime and timedelta
- Check a function with unittest, read a failure and pin a bug before you fix it
- Join the events of two servers that log in different time zones
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 rule says: "10 failed SSH logins from one address inside 5 minutes". Your colleague counts failures for the whole day, so an attacker who stays under the daily limit is never seen. Your lead asks for a function that counts inside a time window, and for tests that prove its edge cases.
Recall
Lesson 2: a dictionary holds a list for each address. How do you add an item to the list of a new address?
Make the list first, with if address not in times: times[address] = [], and then call .append. Step 3 of this lesson writes a function that groups the times by address in this way.
Lesson 1: a traceback has many lines. Which one do you read first?
The last one. It names the error and its reason. The lines above show where it happened.
The idea
| Tool | What it is | The rule |
|---|---|---|
datetime | one point in time | Give it a time zone. Store and compare in UTC. |
timedelta | a length of time | later - earlier gives one. Compare it with <=. |
unittest | a test runner | A test states the right answer for a fixed input. |
Time zones. A time with no zone is naive: 08:00:02 alone could be any of 24 moments. A time with a zone is aware, and Python refuses to compare the two kinds. A syslog time such as Nov 21 08:00:02 has no zone and no year, so you add both when you read it. The habit: turn every time into UTC (Coordinated Universal Time, which has no summer time) as you read it, store and compare only UTC, and convert to local time only to show a person.
A time window is a span of fixed length that slides along the sorted events of one address. If the 10th event, counted from any event, is at most 5 minutes after it, 10 events fit in one window:
Worked example
1. Make the log
This lesson starts the project folder that lessons 9 and 10 use. genlog.py writes 2,000 lines of an invented SSH log. An optional second word sets the seed; without it the seed is 1, so your file matches this lesson. You do not need to study the generator: it only makes the data.
mkdir -p ~/krlab/python/loganalyse
cd ~/krlab/python/loganalysegenlog.py
import random
import sys
from datetime import datetime, timedelta
rng = random.Random(int(sys.argv[2]) if len(sys.argv) > 2 else 1)
clock = datetime(2026, 11, 21, 8, 0, 0)
GUESSES = ["root", "admin", "oracle", "test", "git", "guest"]
STAFF = ["192.0.2.50", "192.0.2.51"]
with open(sys.argv[1], "w", encoding="latin-1") as out:
for _ in range(2000):
clock += timedelta(seconds=rng.randint(1, 6))
head = f"{clock:%b %d %H:%M:%S} krbox sshd[{rng.randint(800, 9999)}]:"
port, roll = rng.randint(30000, 60000), rng.random()
user, staff = rng.choice(["alice", "bob", "carol"]), rng.choice(STAFF)
if roll < 0.55:
ip = rng.choices(["203.0.113.7", "198.51.100.23", "192.0.2.77"], [10, 4, 1])[0]
guess = rng.choice(GUESSES)
who = guess if guess == "root" else "invalid user " + guess
line = f"{head} Failed password for {who} from {ip} port {port} ssh2"
elif roll < 0.60:
line = f"{head} Failed password for {user} from {staff} port {port} ssh2"
elif roll < 0.80:
line = f"{head} Accepted publickey for {user} from {staff} port {port} ssh2"
elif roll < 0.98:
line = f"{head} pam_unix(sshd:session): session opened for user {user}"
else:
line = f"{head} Failed password for caf\xe9 from 192.0.2.99 port {port} ssh2"
out.write(line + "\n")Read only the time lines. datetime(2026, 11, 21, 8, 0, 0) makes a point in time. timedelta(seconds=...) is a length of time, and clock += ... moves the clock by it. In an f-string, {clock:%b %d %H:%M:%S} writes the time in the log format.
python3 genlog.py auth.log
head -1 auth.logNov 21 08:00:02 krbox sshd[1833]: Failed password for invalid user admin from 203.0.113.7 port 38358 ssh22. Turn log text into a time
datetime.strptime(text, format) (string parse time) reads a text into a datetime; the format says where each part is. The log has no year, so put one in front. Without it Python uses 1900, and Python 3.13 and later warn.
Create clock.py. The other new words:
- The module and its main type are both called
datetime. .replace(tzinfo=timezone.utc)gives a naive time the zone UTC.timezone(timedelta(hours=1))is a fixed zone one hour ahead of UTC..astimezone(zone)shows the same moment in another zone..isoformat()writes the standard ISO 8601 form, with the offset..total_seconds()gives atimedeltain seconds.
clock.py
from datetime import datetime, timedelta, timezone
first = datetime.strptime("2026 Nov 21 08:00:02", "%Y %b %d %H:%M:%S")
first = first.replace(tzinfo=timezone.utc)
later = datetime(2026, 11, 21, 8, 4, 30, tzinfo=timezone.utc)
gap = later - first
print(first.isoformat())
print(gap, gap.total_seconds(), gap <= timedelta(minutes=5))
plus_one = timezone(timedelta(hours=1))
print(first.astimezone(plus_one).isoformat())
print(datetime(2026, 11, 21, 9, 0, 2, tzinfo=plus_one) == first)python3 clock.py2026-11-21T08:00:02+00:00
0:04:28 268.0 True
2026-11-21T09:00:02+01:00
TrueThe last line matters: 09:00:02 at UTC+01:00 and 08:00:02 in UTC are the same moment, and Python knows it because both times are aware.
3. Write the window function
Create burst.py. parse_time turns a log time into UTC; zone is the zone of the server that wrote the log. burst groups the times by address and applies the rule of the drawing. break leaves the inner loop at once. This version has a bug on purpose.
burst.py
"""Find the addresses with many events inside a short time window."""
from datetime import datetime, timezone
def parse_time(stamp, year=2026, zone=timezone.utc):
"""Turn a log time such as 'Nov 21 08:00:02' into a time in UTC."""
local = datetime.strptime(f"{year} {stamp}", "%Y %b %d %H:%M:%S")
return local.replace(tzinfo=zone).astimezone(timezone.utc)
def burst(events, window, limit):
"""Return {address: start} for each address with limit events or more inside window."""
times = {}
for when, address in events:
if address not in times:
times[address] = []
times[address].append(when)
found = {}
for address, stamps in times.items():
for i in range(len(stamps) - limit + 1):
if stamps[i + limit - 1] - stamps[i] <= window:
found[address] = stamps[i]
break
return foundevents is a list of pairs of a time and an address. stamps[i + limit - 1] is the event limit - 1 places after event i. With fewer events than limit, the range is empty.
4. Write tests
A test runs your function on a small input whose right answer you know. unittest is the test module of the standard library. Create test_burst.py. The new words:
class BurstTest(unittest.TestCase):makes a group of tests. A class is a named group of functions; that is all you need of classes here.- Each function of the group whose name starts with
testis one test.unittestfills in its first parameter,self. self.assertEqual(result, expected)fails the test when the two differ, and prints both.
The tests pin the cases that are often wrong: an event exactly at the edge of the window, one just outside, an empty list, events out of order, and a server one hour ahead of UTC.
test_burst.py
import unittest
from datetime import datetime, timedelta, timezone
from burst import burst, parse_time
START = datetime(2026, 11, 21, 8, 0, 0, tzinfo=timezone.utc)
FIVE = timedelta(minutes=5)
def at(minutes, address="203.0.113.7"):
"""One event: a time some minutes after START, and an address."""
return (START + timedelta(minutes=minutes), address)
class BurstTest(unittest.TestCase):
def test_edge_of_window_counts(self):
self.assertEqual(burst([at(0), at(2), at(5)], FIVE, 3), {"203.0.113.7": START})
def test_one_minute_too_late(self):
self.assertEqual(burst([at(0), at(2), at(6)], FIVE, 3), {})
def test_empty_list(self):
self.assertEqual(burst([], FIVE, 3), {})
def test_out_of_order(self):
self.assertEqual(burst([at(20), at(0), at(10)], FIVE, 3), {})
def test_parse_time_in_utc(self):
self.assertEqual(parse_time("Nov 21 09:00:00", zone=timezone(timedelta(hours=1))), START)
if __name__ == "__main__":
unittest.main()5. Run the tests and read the failure
python3 -m unittest -v test_burst runs the tests of the file, and -v (verbose) names each one.
python3 -m unittest -v test_burst
echo "exit code: $?"test_edge_of_window_counts (test_burst.BurstTest.test_edge_of_window_counts) ... ok
test_empty_list (test_burst.BurstTest.test_empty_list) ... ok
test_one_minute_too_late (test_burst.BurstTest.test_one_minute_too_late) ... ok
test_out_of_order (test_burst.BurstTest.test_out_of_order) ... FAIL
test_parse_time_in_utc (test_burst.BurstTest.test_parse_time_in_utc) ... ok
======================================================================
FAIL: test_out_of_order (test_burst.BurstTest.test_out_of_order)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/you/krlab/python/loganalyse/test_burst.py", line 26, in test_out_of_order
self.assertEqual(burst([at(20), at(0), at(10)], FIVE, 3), {})
~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: {'203.0.113.7': datetime.datetime(2026, 11[38 chars]utc)} != {}
- {'203.0.113.7': datetime.datetime(2026, 11, 21, 8, 20, tzinfo=datetime.timezone.utc)}
+ {}
----------------------------------------------------------------------
Ran 5 tests in 0.007s
FAILED (failures=1)
exit code: 1Read it as a traceback (lesson 1): the failed test, its line, then the result against the expected value. The - line is what burst returned, the + line what the test wanted. Three failures over 20 minutes are no burst, but the function said yes: in the order 08:20, 08:00, 08:10, the last minus the first is minus 10 minutes, which is "at most 5 minutes". Logs joined from two servers are often out of order, so the bug is real. The test pins it: it fails until the bug is gone, and again if the bug ever comes back.
6. Fix the bug and run the tests again
.sort() puts a list in order in place. Add one line in burst, under for address, stamps in times.items():, indented by eight spaces:
stamps.sort()python3 -m unittest test_burst
echo "exit code: $?".....
----------------------------------------------------------------------
Ran 5 tests in 0.006s
OK
exit code: 0Each dot is a test that passed. The exit code tells a build job whether to stop.
7. The finished file
The finished file: burst.py
burst.py
"""Find the addresses with many events inside a short time window."""
from datetime import datetime, timezone
def parse_time(stamp, year=2026, zone=timezone.utc):
"""Turn a log time such as 'Nov 21 08:00:02' into a time in UTC."""
local = datetime.strptime(f"{year} {stamp}", "%Y %b %d %H:%M:%S")
return local.replace(tzinfo=zone).astimezone(timezone.utc)
def burst(events, window, limit):
"""Return {address: start} for each address with limit events or more inside window."""
times = {}
for when, address in events:
if address not in times:
times[address] = []
times[address].append(when)
found = {}
for address, stamps in times.items():
stamps.sort()
for i in range(len(stamps) - limit + 1):
if stamps[i + limit - 1] - stamps[i] <= window:
found[address] = stamps[i]
break
return foundYour turn
An attacker can spread guesses over two servers and stay under the limit on each. Server A, krbox, logs in UTC. Server B, a clone (same host name in its lines), logs in Central European Time, UTC+01:00 in November. Make the two logs with other seeds:
python3 genlog.py server-a.log 4
python3 genlog.py server-b.log 2Write twoservers.py in the same folder. It must:
- Read the failed logins of each log into a list of events, every time in UTC. Use the zone of the server for each log.
- Print each address with 10 or more failed logins inside 2 minutes: for A alone, for B alone, and for both lists joined.
A line starts with its time: line[:15] is its first 15 characters, a slice as in lesson 4. The address is line.split(" from ")[1].split()[0]. An event is a pair of a time and an address, as in burst.
Add a test to test_burst.py that pins the join: two lists of events with a burst that exists only when you join them. Run all tests. Then answer from your own output.
Check yourself
You read "Nov 21 08:00:02" with the format "%b %d %H:%M:%S". What year does the result have, and why is that a problem?
1900, the default. Every time is then 126 years in the past, and 29 February cannot be read, because 1900 was not a leap year. Add the year yourself, as parse_time does.
You compare a time from the log, read without a zone, with datetime.now(timezone.utc). What happens?
Python raises TypeError: can't compare offset-naive and offset-aware datetimes. It refuses to guess the zone. Give the log time its zone and convert it to UTC when you read it.
Why write the test before you fix the bug, when the fix is only one line?
A test that fails first proves that it can see the bug. A test written after the fix that passes may test nothing. It also keeps the bug from coming back unseen.
Field notes
pytestis the test tool of most Python projects. It runsunittesttests as they are, and plain functions withassert. Install it in the venv and pin it (lesson 7).- A fixed offset is right for half a year where summer time applies.
zoneinfo.ZoneInfo("Europe/Berlin")follows the rules of the system's time zone database (or of thetzdatapackage where the system has none). Better: make servers log in UTC, with year and offset in every line (ISO 8601). - A log that runs over New Year: take the year from the file's date, and add one when the month goes back from December to January.
- Your own
/var/log/auth.logmay not look like the lesson. Some systems, among them recent Ubuntu releases, start each line with an ISO 8601 time such as2026-11-22T08:00:02+00:00. Then the first 15 characters of a line makestrptimeraiseValueError. Read that form withdatetime.fromisoformat(line.split()[0]): it is aware already. Look at the first line of your own log before you choose a format.