Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 10 · 60 minutes

Build a log analyser that flags a brute-force attack

After this lesson you can
  • Build a command-line tool that reads an auth log and counts failed logins
  • Flag a noisy source address and write a JSON report
  • Extend the tool to find a login that succeeded after many failures
Lab files of this lesson (30)

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

An SSH server that faces the internet is tried by strangers within minutes. The log shows who and how often, but nobody can read two million lines. Your manager asks for the tool that a defender writes first: it counts failures for each source address and user name, flags the noisy address, and writes a JSON report that other tools can read. Then comes the hard question of every incident: did a guess work? You build the tool in the worked example. In "Your turn" you teach it that second question, on a new log.

Recall

Lesson 4: why do you open a log with errors="replace"?

A real log can hold bytes that are not valid UTF-8, and an attacker can put them in a user name on purpose. Without errors="replace" the program stops at the first one. With it, the bad byte becomes the mark � and the work goes on.

Lesson 7: this tool imports no package that you install with pip. Why is that a good thing?

Every package is code from other people that runs with your access, and each one is a way into your tool through the supply chain. A tool that needs only the standard library has nothing to pin, hash or copy.

The idea

loganalyse.py has four functions: parse_line picks the fields out of one line, analyse counts, table prints, and main handles the command line, errors and logs. Exit codes: 0 clean, 1 an address above the threshold, 2 bad usage, 3 a file that could not be read or written.

From a log file to a report
Log fileparse_lineanalysemainOutputsone line at a time(user, address) or Nonea dictionary of countsreport.json, tables, exit codeLog fileparse_lineanalysemainOutputs1234
  1. Log file → parse_line: one line at a time
  2. parse_line → analyse: (user, address) or None
  3. analyse → main: a dictionary of counts
  4. main → Outputs: report.json, tables, exit code

A regular expression (regex) describes the shape of a text. Python's re module reads it. These are all the parts that the course uses:

PartMeaning
\S, \done character that is not a space, one digit
+one or more of the part before it: \d+ is a number
?the part before it is optional
{3}exactly three of the part before it
[A-Z], [\d.]one character from a set: a capital letter, a digit or a dot
[^\]]one character that is not in the set: anything but ]
( )keep this part: match.groups() returns it
(?: )group a part without keeping it, so that ? can apply to it
^, $the start and the end of the line
\[a real bracket: a backslash makes a special character plain

Worked example

1. Make the project

Work in the folder of lesson 8. It already holds genlog.py and its log auth.log: 2,000 lines of an invented SSH log in which three addresses attack, staff mistype now and then, and about 3% of the lines hold a byte that is not UTF-8. Give the project its own venv, as a habit of lesson 1. The tool needs no package (lesson 7).

cd ~/krlab/python/loganalyse
python3 -m venv .venv
source .venv/bin/activate

2. Look at the log

If auth.log is missing, run python3 genlog.py auth.log again: the seed is fixed, so you get the same file.

head -1 auth.log
Nov 21 08:00:02 krbox sshd[1833]: Failed password for invalid user admin from 203.0.113.7 port 38358 ssh2

3. Write the parser

Create loganalyse.py. The new words:

  • re.compile(pattern) prepares a regex, and .search(line) looks for it anywhere in the line. It returns a match, or None. match.groups() returns the parts in brackets.
  • ipaddress.ip_address(text) checks that the text is a real address. It raises ValueError if it is not.
  • log.warning(...) writes a warning to the log (lesson 5).

The pattern, taken apart:

The regex of the try-out and its groups
forthe text "for ", matched but not kept(?:invalid user )?optional, and not kept(\S+)group 1: the user namefromthe text " from "(\S+)group 2: the source addressport \d+"port " and a number: not keptforthe text "for ", matched but not kept(?:invalid user )?optional, and not kept(\S+)group 1: the user namefromthe text " from "(\S+)group 2: the source addressport \d+"port " and a number: not kept

Test the pattern on one line first. The r before the quote marks a raw text: a backslash stays a backslash. The second line has no invalid user.

python3 -c "
import re
p = r'for (?:invalid user )?(\S+) from (\S+)'
print(re.search(p, 'Failed password for invalid user admin from 203.0.113.7 port 1').groups())
print(re.search(p, 'Failed password for root from 192.0.2.9 port 2').groups())"
('admin', '203.0.113.7')
('root', '192.0.2.9')

parse_line returns the user and the address of a failed login, or None. A bad address is logged and skipped.

"""Count failed SSH logins in an auth log and flag noisy addresses."""
import argparse
import ipaddress
import json
import logging
import re
import sys
from collections import Counter

log = logging.getLogger("loganalyse")
FAILED = re.compile(r"Failed password for (?:invalid user )?(\S+) from (\S+) port \d+")


def parse_line(line):
    """Return (user, address) for a failed login, or None."""
    match = FAILED.search(line)
    if match:
        user, address = match.groups()
        try:
            ipaddress.ip_address(address)
            return user, address
        except ValueError:
            log.warning("bad address %r", address)
    return None

4. Count and print

Add two functions. An iterable is anything that you can loop over: a list or an open file. analyse takes any iterable of lines and reads one at a time, so memory does not grow with the file. Counter is a dictionary made for counting: counter[key] += 1 works for a new key. most_common() lists the pairs, biggest first. sum(...) adds numbers, and dict(...) turns the pairs into a dictionary. table prints the first top pairs in two columns: copy it.

def analyse(lines, threshold):
    by_address, by_user = Counter(), Counter()
    count = 0
    for count, line in enumerate(lines, start=1):
        found = parse_line(line)
        if found:
            by_user[found[0]] += 1
            by_address[found[1]] += 1
    return {
        "lines_read": count,
        "failed_total": sum(by_address.values()),
        "threshold": threshold,
        "flagged": [a for a, n in by_address.most_common() if n > threshold],
        "by_address": dict(by_address.most_common()),
        "by_user": dict(by_user.most_common()),
    }


def table(title, counts, top=5):
    print(f"\n{title}")
    for key, number in list(counts.items())[:top]:
        print(f"  {key:<16} {number:>5}")
python3 -c "
import loganalyse
r = loganalyse.analyse(open('auth.log', encoding='utf-8', errors='replace'), 100)
print(r['lines_read'], r['failed_total'], r['flagged'])
"
2000 1288 ['203.0.113.7', '198.51.100.23']

5. Add the command line

Add main at the end. description=__doc__ uses the text in triple quotes at the top of the file as the help text. json.dump(result, out, indent=2) writes the dictionary into a file. error.filename is the name of the file that failed. ", ".join(list) glues the items into one text.

def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("logfile")
    parser.add_argument("--threshold", type=int, default=100)
    parser.add_argument("--report", default="report.json")
    args = parser.parse_args(argv)
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")

    try:
        with open(args.logfile, encoding="utf-8", errors="replace") as handle:
            result = analyse(handle, args.threshold)
        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

    log.info("read %d lines, %d failed logins", result["lines_read"], result["failed_total"])
    table("By source address", result["by_address"])
    table("By user", result["by_user"])
    if result["flagged"]:
        log.warning("above %d failures: %s", args.threshold, ", ".join(result["flagged"]))
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())

6. Run it

python3 loganalyse.py auth.log
echo "exit code: $?"
2026-11-21 08:42:37,377 INFO read 2000 lines, 1288 failed logins
2026-11-21 08:42:37,378 WARNING above 100 failures: 203.0.113.7, 198.51.100.23

By source address
  203.0.113.7        753
  198.51.100.23      288
  192.0.2.77          94
  192.0.2.99          58
  192.0.2.51          51

By user
  git                214
  root               196
  oracle             195
  admin              184
  test               173
exit code: 1

About 64% of all lines are failures, and one address makes 753. The names git, root and admin are guesses: this is password guessing from outside (MITRE ATT&CK: Brute Force). The staff address 192.0.2.51 fails 51 times: too many for a mistyped password, so look for a stuck script or an old saved password. The 58 failures of 192.0.2.99 are the lines with the broken byte in the user name caf�. 192.0.2.77 makes 94 and stays under the limit: a threshold is a decision, not a fact.

7. Change the threshold and break the input

The tool also wrote report.json with the same counts. A higher threshold flags less, and a missing file is an error, not a crash. >/dev/null 2>&1 hides the output.

python3 loganalyse.py auth.log --threshold 5000 >/dev/null 2>&1
echo "exit code: $?"
python3 loganalyse.py nothing.log
echo "exit code: $?"
exit code: 0
2026-11-21 08:42:37,564 ERROR nothing.log: No such file or directory
exit code: 3

8. The finished file

This is the whole file as it stands after the steps above. The lab files of the course hold it.

The finished file: loganalyse.py

loganalyse.py

"""Count failed SSH logins in an auth log and flag noisy addresses."""
import argparse
import ipaddress
import json
import logging
import re
import sys
from collections import Counter

log = logging.getLogger("loganalyse")
FAILED = re.compile(r"Failed password for (?:invalid user )?(\S+) from (\S+) port \d+")


def parse_line(line):
    """Return (user, address) for a failed login, or None."""
    match = FAILED.search(line)
    if match:
        user, address = match.groups()
        try:
            ipaddress.ip_address(address)
            return user, address
        except ValueError:
            log.warning("bad address %r", address)
    return None


def analyse(lines, threshold):
    by_address, by_user = Counter(), Counter()
    count = 0
    for count, line in enumerate(lines, start=1):
        found = parse_line(line)
        if found:
            by_user[found[0]] += 1
            by_address[found[1]] += 1
    return {
        "lines_read": count,
        "failed_total": sum(by_address.values()),
        "threshold": threshold,
        "flagged": [a for a, n in by_address.most_common() if n > threshold],
        "by_address": dict(by_address.most_common()),
        "by_user": dict(by_user.most_common()),
    }


def table(title, counts, top=5):
    print(f"\n{title}")
    for key, number in list(counts.items())[:top]:
        print(f"  {key:<16} {number:>5}")


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("logfile")
    parser.add_argument("--threshold", type=int, default=100)
    parser.add_argument("--report", default="report.json")
    args = parser.parse_args(argv)
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")

    try:
        with open(args.logfile, encoding="utf-8", errors="replace") as handle:
            result = analyse(handle, args.threshold)
        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

    log.info("read %d lines, %d failed logins", result["lines_read"], result["failed_total"])
    table("By source address", result["by_address"])
    table("By user", result["by_user"])
    if result["flagged"]:
        log.warning("above %d failures: %s", args.threshold, ", ".join(result["flagged"]))
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())

Your turn

A counter by address tells you who is noisy. It does not tell you whether a guess worked. Teach the tool that.

Save genlog2.py in ~/krlab/python/loganalyse. It writes a new invented log of 1,502 lines, with a fixed seed. One address hammers the server and then logs in. A second guesses all the time, has the most failures and never gets in. A third mistypes a password a few times and then gets it right. A login that worked is a line with Accepted password. You do not need to study this generator: it only makes the data.

genlog2.py

import random
import sys
from datetime import datetime, timedelta

rng = random.Random(8)
clock = datetime(2026, 11, 21, 22, 0, 0)
GUESSES = ["root", "admin", "test", "ubuntu", "postgres"]
STAFF = ["192.0.2.50", "192.0.2.51", "192.0.2.52"]
BRUTE, SPREAD, TYPO = "198.51.100.66", "203.0.113.200", "203.0.113.45"
brute_fails = typo_fails = 0

with open(sys.argv[1], "w", encoding="latin-1") as out:
    for _ in range(1500):
        clock += timedelta(seconds=rng.randint(1, 8))
        head = f"{clock:%b %d %H:%M:%S} krbox sshd[{rng.randint(800, 9999)}]:"
        tail = f"port {rng.randint(30000, 60000)} ssh2"
        roll, user = rng.random(), rng.choice(["alice", "bob", "carol"])
        if roll < 0.28 and brute_fails < 60:
            brute_fails += 1
            out.write(f"{head} Failed password for invalid user {rng.choice(GUESSES)} from {BRUTE} {tail}\n")
            if brute_fails == 60:
                clock += timedelta(seconds=3)
                out.write(f"{clock:%b %d %H:%M:%S} krbox sshd[4021]: Accepted password for admin from {BRUTE} {tail}\n")
        elif roll < 0.40:
            out.write(f"{head} Failed password for {rng.choice(GUESSES)} from {SPREAD} {tail}\n")
        elif roll < 0.43 and typo_fails < 12:
            typo_fails += 1
            out.write(f"{head} Failed password for bob from {TYPO} {tail}\n")
            if typo_fails == 12:
                out.write(f"{head} Accepted password for bob from {TYPO} {tail}\n")
        elif roll < 0.70:
            out.write(f"{head} Accepted publickey for {user} from {rng.choice(STAFF)} {tail}\n")
        else:
            out.write(f"{head} pam_unix(sshd:session): session opened for user {user}\n")
  1. Run python3 genlog2.py auth2.log. Run your analyser on it with --threshold 50 --report r2.json, and read the tables and the report.
  2. Copy loganalyse.py to loganalyse2.py. In the copy, add the new rule of the drawing below: while it reads the lines, one at a time, it keeps the failed logins so far for each address. At a line with Accepted password, if that address already has 20 failures or more, the tool writes a WARNING with the address, the user name and the number of earlier failures, and it counts as a finding.
  3. The tool must return the exit code 1 when an address is above the threshold or when the list findings is not empty. It must still read the file one line at a time.
  4. Run loganalyse2.py on auth2.log with --threshold 50.
The rule that finds a guess that worked
Read a lineAccepted password?20 failures or more?Add to findingsone line at a timeyes: take the addressyes: warn with address, user, countnext lineRead a lineAccepted password?20 failures or more?Add to findings1234
  1. Read a line → Accepted password?: one line at a time
  2. Accepted password? → 20 failures or more?: yes: take the address
  3. 20 failures or more? → Add to findings: yes: warn with address, user, count
  4. Add to findings → Read a line: next line

At each question, a line that answers no is passed over, and the loop takes the next line.

Hint: analyse already has a loop. Inside it, before found = parse_line(line), test if "Accepted password" in line:. Read the address as in lesson 2 (split on from), and the user name the same way after for. by_address already holds the failures so far: read it at an Accepted password line, before you count that line. Return the findings as a new key findings. Then answer from your own results.

One possible solution: the lines to add to loganalyse2.py

In analyse, make a list before the loop, and test each line before it is counted:

    findings = []
    for count, line in enumerate(lines, start=1):
        if "Accepted password" in line:
            address = line.split(" from ")[1].split()[0]
            user = line.split(" for ")[1].split()[0]
            if by_address[address] >= 20:
                findings.append({"address": address, "user": user, "failures": by_address[address]})
                log.warning("login worked after %d failures: %s from %s", by_address[address], user, address)
        found = parse_line(line)

Add "findings": findings, to the returned dictionary. In main, keep the log.warning for flagged, and change the test so that it flags both kinds of finding. Replace the lines from if result["flagged"]: to return 0 with:

    if result["flagged"]:
        log.warning("above %d failures: %s", args.threshold, ", ".join(result["flagged"]))
    if result["flagged"] or result["findings"]:
        return 1
    return 0

The run prints WARNING login worked after 60 failures: admin from 198.51.100.66 and exits with 1.

Check yourself

Why does analyse take an iterable of lines and not a file name?

It only counts, so you can test it with a list of three lines, and main passes an open file.

The threshold is 100. An attacker tries 40 guesses from each of 50 addresses. Does the tool flag them?

No, every address stays below 100. The tool finds one noisy source, not a spread-out attack. Count for each user name or in a time window too.

In auth2.log the noisiest address never logged in, and the address that did log in is only second. What does that teach?

A count of failures ranks noise, not danger. The question of an incident is "did a guess work?", so a rule that looks for a success after many failures matters more.

Field notes

  • Everything in a log is attacker-controlled: a user name can hold quotes, % or a fake log line. Treat each field as data, never as a command or a path.
  • Never pass log text to a shell (shell=True): a name such as x; rm -rf ~ would run. Pass a list of arguments, as in lesson 9.
  • This design suits a very large log: one line at a time, and only the counters stay in memory. The regex is the slow part, so test "Failed password" in line first.
  • A count for the whole file hides timing. 192.0.2.77 stays under 100 here, but burst() of lesson 8 finds 10 of its failures inside 5 minutes. Import it from burst.py, which is in the same folder, and add a --window option.