Scenario test · 90 minutes
Scenario test - find what matters in a web server log
- Build a tool that reads a web server log and a CSV list of bad addresses
- Find probing, known bad sources and a login that worked after many failures
- Report your findings in a short document that an employer can read
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
You work for a small online shop. On Monday morning the owner says that the site was slow on Saturday afternoon, and that a customer saw "strange pages" in the address bar. Your team gives you two files. The first is access.log, the log of the web server for two hours of Saturday: 3,721 lines. The second is badips.csv, the list of addresses that your team already knows to be bad.
"Write a tool that finds what matters," says your lead. "Run it, and give the owner one page that says what happened and what to do."
Each line of the log has this shape, taken apart in the drawing below.
198.51.100.21 - - [21/Nov/2026:14:00:04 +0000] "GET / HTTP/1.1" 200 1563A line is malformed when it does not have this shape, or when its address is not a valid IP address. The list badips.csv has the columns address, reason and added.
Work in a new folder with its own venv, so that the lab is clean. Save gen10.py there. It builds both files with a fixed seed, so every reader gets the same data.
mkdir -p ~/krlab/python/final
cd ~/krlab/python/final
python3 -m venv .venv
source .venv/bin/activategen10.py
import random
from datetime import datetime, timedelta
rng = random.Random(9)
clock = datetime(2026, 11, 21, 14, 0, 0)
PAGES = ["/", "/products", "/products/7", "/cart", "/about", "/static/app.js", "/static/site.css"]
PROBES = ["/.env", "/wp-login.php", "/phpmyadmin/", "/admin/", "/.git/config", "/backup.sql"]
SCANNER, BRUTE, BOT, BIG = "203.0.113.50", "203.0.113.77", "198.51.100.200", "192.0.2.99"
STAFF = [f"192.0.2.{n}" for n in range(1, 7)]
VISITORS = [f"198.51.100.{n}" for n in range(1, 31)] + [f"192.0.2.{n}" for n in range(20, 61)]
plan = ["normal"] * 3500 + ["scan"] * 90 + ["brute"] * 41 + ["bot"] * 30 + ["big"] * 6
plan += ["login"] * 30 + ["junk"] * 14 + ["badaddr"] * 4 + ["latin"] * 6
rng.shuffle(plan)
lines, brute_seen = [], 0
for kind in plan:
clock += timedelta(seconds=rng.randint(1, 3))
stamp = f"[{clock:%d/%b/%Y:%H:%M:%S} +0000]"
if kind == "normal":
ip, method, path = rng.choice(VISITORS), "GET", rng.choice(PAGES)
status, size = rng.choice([200, 200, 200, 304]), rng.randint(300, 9000)
elif kind == "scan":
ip, method, path, status, size = SCANNER, "GET", rng.choice(PROBES), 404, 153
elif kind == "brute":
brute_seen += 1
ip, method, path, size = BRUTE, "POST", "/login", 120
status = 200 if brute_seen == 41 else 401
elif kind == "bot":
ip, method, path, status, size = BOT, "GET", rng.choice(PAGES), 200, rng.randint(300, 9000)
elif kind == "big":
ip, method, path, status, size = BIG, "GET", "/backup.zip", 200, rng.randint(40_000_000, 60_000_000)
elif kind == "login":
ip, method, path, size = rng.choice(STAFF), "POST", "/login", 120
status = rng.choice([401, 200, 200, 200])
elif kind == "latin":
ip, method, path, status, size = rng.choice(VISITORS), "GET", "/caf\xe9", 404, 153
elif kind == "badaddr":
lines.append(f'203.0.113.{rng.randint(256, 999)} - - {stamp} "GET / HTTP/1.1" 200 512')
continue
else:
lines.append(rng.choice(['198.51.100.9 - - ' + stamp + ' "\\x16\\x03\\x01\\x00" 400 150',
"203.0.113.5 - - [21/Nov/2026:14:",
"-"]))
continue
lines.append(f'{ip} - - {stamp} "{method} {path} HTTP/1.1" {status} {size}')
with open("access.log", "w", encoding="latin-1") as out:
out.write("\n".join(lines) + "\n")
with open("badips.csv", "w", encoding="utf-8") as out:
out.write("address,reason,added\n")
out.write("203.0.113.50,scanner,2026-10-02\n198.51.100.200,botnet,2026-10-15\n")
out.write("203.0.113.150,spam,2026-09-30\n198.51.100.17,credential stuffing,2026-11-01\n")
out.write("192.0.2.33,scanner,2026-11-12\n203.0.113.9,malware host,2026-08-20\n")Run python3 gen10.py. Look at both files with head before you start. Do not run anything that you find in them.
Your tasks
There is no code and no command list here. Use the whole course. Write the tool as webwatch.py, and build it step by step. You may parse a line with a regex (lesson 10) or with split('"'): the request is the second piece, and the status and the size are the first two words of the third piece.
- The tool and its contract.
webwatch.pytakes the log, the CSV, and the options--report(defaultreport.json),--min-404(default 15) and--min-fails(default 10). It reads the log one line at a time, so that a large log works, and it must survive bytes that are not valid UTF-8. It writes its findings toreport.json. It logs what it does to standard error. It returns0when it finds nothing,1when it finds something,2for bad usage and3when a file cannot be read, with one error line and no traceback. It uses only the standard library. - Count the lines. Count all lines, and count the malformed lines. A malformed line is counted and skipped: it must not stop the tool. Count the lines for each status code.
- Join with the bad list. Read
badips.csvinto a set. Count the requests that came from a listed address, and list which of the listed addresses appear in the log.
- Find probing. An address is a prober when it got at least
--min-404answers with the status 404. Find the probers. Count the requests for the path/.env.
- Find a guess that worked. While you read the lines in order, count the failed logins (
POST /loginwith the status 401) for each address. When aPOST /loginwith the status 200 comes from an address that already has--min-failsfailures or more, that is a finding. Find the address. Then check whetherbadips.csvlists it.
- Time the attack. Each line carries its time and its zone (
+0000), so you can read it as an aware time at once: the format code%zreads the offset. For the address of task 5, find the time of its first failed login and the time of the login that worked (lesson 8).
- Find the biggest download. Add up the bytes that each address received. Find the address with the most.
- Test the failures. Run the tool with a missing log file, and with no arguments. Check the exit codes (3 and 2) and that no traceback shows. Write one
unittesttest that pins how your tool treats a malformed line (lesson 8). - Stretch (no check). In a copy, read the bad list from a small local API with a key, as in lesson 6, and not from a file.
Hand in
Hand in three files: the tool webwatch.py, your test test_webwatch.py and a report for the owner, report.md, of one page. The report is the proof that you can show an employer. Use these headings:
- Summary. Three sentences for a reader who is not technical: what happened, how bad it is, what to do first.
- Data and method. The files you used, how many lines, how many were malformed, how the tool works in four sentences, and the packages it needs (and how you know).
- Findings. One short paragraph for each finding: the probing address, the known bad sources, the login that worked after failures, the large download. Give the address, the numbers and the time window.
- Evidence. The SHA-256 of the two input files (lesson 9), the exact command that you ran, the exit code, and three lines from the log that support your most serious finding.
- Limits and next steps. What the tool does not see, which thresholds you chose and why, and two actions for the owner (for example a block, a password reset, a rule in the firewall).
Review your work
Compare your tool with this model. It is one good answer, not the only one.
Model solution: webwatch.py
"""Find what matters in a web server access log."""
import argparse
import csv
import ipaddress
import json
import logging
import re
import sys
from collections import Counter
from datetime import datetime
log = logging.getLogger("webwatch")
LINE = re.compile(r'^(\S+) \S+ \S+ \[([^\]]+)\] "([A-Z]+) (\S+) HTTP/[\d.]+" (\d{3}) (\d+)$')
def valid_address(text):
try:
ipaddress.ip_address(text)
except ValueError:
return False
return True
def load_bad(path):
with open(path, newline="", encoding="utf-8", errors="replace") as handle:
return {row.get("address") for row in csv.DictReader(handle)}
def analyse(lines, bad, min_404, min_fails):
status, not_found, fails, sent = Counter(), Counter(), Counter(), Counter()
listed_hits, listed_seen, guess_worked, first_fail, timing = 0, set(), [], {}, {}
total = malformed = env_probes = 0
for total, line in enumerate(lines, start=1):
match = LINE.search(line.rstrip("\n"))
if not match or not valid_address(match.group(1)):
malformed += 1
log.debug("malformed line %d", total)
continue
address = match.group(1)
try:
when = datetime.strptime(match.group(2), "%d/%b/%Y:%H:%M:%S %z")
except ValueError:
malformed += 1
continue
method, path, code, size = match.group(3), match.group(4), match.group(5), int(match.group(6))
status[code] += 1
sent[address] += size
if code == "404":
not_found[address] += 1
if path == "/.env":
env_probes += 1
if address in bad:
listed_hits += 1
listed_seen.add(address)
if method == "POST" and path == "/login":
if code == "401":
fails[address] += 1
if address not in first_fail:
first_fail[address] = when
elif code == "200" and fails[address] >= min_fails and address not in guess_worked:
guess_worked.append(address)
timing[address] = {"login": f"{when:%H:%M:%S}", "after_first_fail": str(when - first_fail[address])}
top = sent.most_common(1)
top_sender = None
if top:
top_sender = top[0][0]
return {
"lines": total,
"malformed": malformed,
"status": dict(sorted(status.items())),
"listed_hits": listed_hits,
"listed_seen": sorted(listed_seen),
"probers": sorted(a for a, n in not_found.items() if n >= min_404),
"env_probes": env_probes,
"guess_worked": guess_worked,
"guess_timing": timing,
"top_sender": top_sender,
}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("logfile")
parser.add_argument("badfile")
parser.add_argument("--report", default="report.json")
parser.add_argument("--min-404", type=int, default=15)
parser.add_argument("--min-fails", type=int, default=10)
args = parser.parse_args(argv)
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
try:
bad = load_bad(args.badfile)
with open(args.logfile, encoding="utf-8", errors="replace") as handle:
result = analyse(handle, bad, args.min_404, args.min_fails)
with open(args.report, "w", encoding="utf-8") as out:
json.dump(result, out, indent=2)
except OSError as error:
log.error("%s: %s", error.filename, error.strerror)
return 3
except csv.Error as error:
log.error("badips file is not valid CSV: %s", error)
return 3
log.info("read %d lines, %d malformed", result["lines"], result["malformed"])
findings = result["listed_hits"] or result["probers"] or result["guess_worked"]
if result["guess_worked"]:
log.warning("login worked after failures: %s", ", ".join(result["guess_worked"]))
return 1 if findings else 0
if __name__ == "__main__":
sys.exit(main())Run it and read the report.
python3 webwatch.py access.log badips.csv
echo "exit code: $?"INFO read 3721 lines, 18 malformed
WARNING login worked after failures: 203.0.113.77
exit code: 1The file report.json then holds, among other keys, "listed_hits": 200, "probers": ["203.0.113.50"], "env_probes": 8, "guess_worked": ["203.0.113.77"], the login time 16:01:36 and the gap 1:59:46 under "guess_timing", and "top_sender": "192.0.2.99".
A model test, test_webwatch.py. It pins that a line that is not a log line is counted as malformed and skipped. Run it with python3 -m unittest test_webwatch.
import unittest
from webwatch import analyse
class WebwatchTest(unittest.TestCase):
def test_malformed_line_is_counted_and_skipped(self):
result = analyse(["not a log line"], set(), 15, 10)
self.assertEqual(result["malformed"], 1)
self.assertEqual(result["status"], {})
if __name__ == "__main__":
unittest.main().
----------------------------------------------------------------------
Ran 1 test in 0.000s
OKPoints to check in your own tool:
- The 14 broken lines and the 4 lines with an invalid address are counted as malformed, and nothing crashes. The six lines with a byte that is not UTF-8 are good lines: the path of each holds the mark
�. - A hostile
badips.csvmust not crash the tool. The model reads the CSV witherrors="replace"androw.get("address"). It handles an empty log, andmainreturns 3 for a CSV that thecsvmodule refuses (for example, one field of 200,000 characters). Try all three. - The counting of failures runs in the order of the file. A success that comes before the failures is no finding.
- The 40 failures of
203.0.113.77took almost two hours: about one guess every three minutes. A rule of 10 failures in 5 minutes, as in lesson 8, misses this attacker; the count over the whole log finds it. Use both. - The staff addresses
192.0.2.1to192.0.2.6mistype a password once or twice and then get in. Their counts stay below--min-fails, so they are not flagged. A lower threshold would flag them: a threshold is a decision. 203.0.113.50is in the bad list and is a prober.203.0.113.77is not in the list, and it is the most serious finding. The list is a gap, and the tool finds what the list does not.- The tool reads one line at a time, with memory that grows with the number of addresses, and not with the size of the file.
Mark your report
You mark this yourself, or you ask a colleague or a mentor to mark it. The page checks the numbers above; it cannot read your report.
| Criterion | Not yet | Meets the standard | Strong |
|---|---|---|---|
| Findings | Misses 203.0.113.77 or the prober. | Prober, four listed sources, login after 40 failures, large download, with numbers. | Notes that the bad list missed 203.0.113.77; the attack took two hours. |
| Evidence | Numbers with no command or log line. | Command, exit code and three log lines for the login. | Adds the SHA-256 of both inputs and UTC times; anyone can re-run it. |
| Judgement | All findings weigh the same. | Ranks the login first, says why, separates fact from opinion. | Names what the log cannot show: what happened after the login. |
| Actions | Vague or unordered. | Reset the password and check for changes, block the prober, list 203.0.113.77, limit failed logins. | Each action has an owner and a way to confirm it worked. |
| Limits | No thresholds or limits. | Thresholds, two hours of data, malformed lines. | Why each threshold, and what another value changes. |
| Writing | Long technical opening, or blames a person. | One dated page; the owner can act on the summary alone. | A reader who is not technical can repeat the summary. |
Meets the standard in every row: you can show this report as a work sample. Remove names and data that are not yours to share.
The report shows your work on this scenario, on your own machine, without a proctor. It does not show work under time pressure or on a real network.