TExcelTAD
Home › Programming for Security: Python, Bash, PowerShell & C Tools › Project: Log Analyser for Failed Logins and Top Talkers

Project: Log Analyser for Failed Logins and Top Talkers

Every earlier lesson parsed logs for one question. This project combines them into the tool a small team actually runs every morning, or every five minutes from cron: read the SSH and web logs, and report bursts of failed logins, password spraying, a success right after failures, and the top talkers by requests and bytes. It is a miniature of what a SIEM correlation rule does (the blue-team course covers the full version), written so you can read, test and tune every rule.

The logs are synthetic, from the lab host web1.lab.test. In the browser the data is embedded in the code; on a server the same functions read files.

The rules

Rule Logic Typical cause
burst one source, at least BURST_N failures within WINDOW seconds brute force or a broken script
spray one source, failures on at least SPRAY_N distinct accounts within WINDOW password spraying
success-after-fail a success from a source that failed at least BURST_N times before it within WINDOW a guessed password
top-talkers requests and bytes per client from the web log scraping, scanning, a stuck client, data exfiltration

Design

  • Parse once into events (time, source, user, ok); every rule works on events, never on raw lines. Lines that look relevant but don't parse are counted and reported (Designing a Small Security Tool).
  • Sliding windows per source with a deque, the same structure that the testing lesson tested, so a burst that straddles a fixed bucket boundary is not split (pandas for Log Analysis).
  • One finding per rule and source, with the first time, the count and the evidence (accounts tried), so the report stays short during an attack.
  • Allowlist for known noisy sources (a monitoring probe, a NAT gateway), applied after detection and shown in the report, so suppressions are visible.
python · try it yourself
import json, re
from collections import Counter, defaultdict, deque
from datetime import datetime

SSH = re.compile(r"^(?P<ts>\w{3} [ \d]\d \d\d:\d\d:\d\d) \S+ sshd\[\d+\]: "
                 r"(?P<res>Failed|Accepted) (?:password|publickey) for (?:invalid user )?(?P<user>\S+) "
                 r"from (?P<src>\S+) port \d+")
WEB = re.compile(r'^(?P<src>\S+) \S+ \S+ \[[^\]]+\] "[^"]*" (?P<status>\d{3}) (?P<size>\d+|-)')
WINDOW, BURST_N, SPRAY_N = 300, 8, 5
ALLOW = {"10.10.0.250": "monitoring probe (expected failures)"}

ssh_log = []
def add(ts, res, user, src):
    ssh_log.append(f"Jan 15 {ts} web1 sshd[{900 + len(ssh_log)}]: {res} password for {user} from {src} port {40000 + len(ssh_log)} ssh2")
add("08:00:05", "Accepted", "alice", "10.10.0.21")
for i in range(10):                                          # brute force, then a success
    add(f"09:00:{i * 5:02d}", "Failed", "root", "203.0.113.7")
add("09:01:00", "Accepted", "root", "203.0.113.7")
for i, u in enumerate(["alice", "bob", "carol", "dave", "erin", "frank"]):   # spray
    add(f"09:10:{i * 7:02d}", "Failed", "invalid user " + u if u in ("dave", "frank") else u, "198.51.100.9")
for i in range(9):                                           # monitoring probe with a stale password
    add(f"09:{20 + i // 3:02d}:{(i % 3) * 20:02d}", "Failed", "monitor", "10.10.0.250")
add("09:30:00", "Failed", "bob", "10.10.0.22")
ssh_log.append("Jan 15 09:31:00 web1 sshd[999]: Failed password for")   # truncated line

web_log = ["10.10.0.21 - - [15/Jan/2026:09:00:00 +0000] \"GET / HTTP/1.1\" 200 5120"] * 40 + \
          ["198.51.100.20 - - [15/Jan/2026:09:05:00 +0000] \"GET /export?page=1 HTTP/1.1\" 200 950000"] * 12 + \
          ["203.0.113.7 - - [15/Jan/2026:09:06:00 +0000] \"GET /.git/config HTTP/1.1\" 404 0"] * 25

def parse_ssh(lines, year=2026):
    events, bad = [], 0
    for line in lines:
        m = SSH.match(line)
        if m:
            t = datetime.strptime(f"{year} {m['ts']}", "%Y %b %d %H:%M:%S")
            events.append((t, m["src"], m["user"], m["res"] == "Accepted"))
        elif "sshd[" in line and ("Failed" in line or "Accepted" in line):
            bad += 1
    return sorted(events), bad

def detect(events):
    fails, users, findings, seen = defaultdict(deque), defaultdict(deque), [], set()
    def emit(rule, src, t, **ev):
        if (rule, src) not in seen:
            seen.add((rule, src))
            findings.append({"rule": rule, "src": src, "first": t.strftime("%H:%M:%S"), **ev})
    for t, src, user, ok in events:
        for q in (fails[src], users[src]):
            while q and (t - q[0][0]).total_seconds() >= WINDOW:
                q.popleft()
        if ok:
            if len(fails[src]) >= BURST_N:
                emit("success-after-fail", src, t, user=user, fails_before=len(fails[src]))
            continue
        fails[src].append((t, user))
        users[src].append((t, user))
        if len(fails[src]) >= BURST_N:
            emit("burst", src, t, count=len(fails[src]))
        accounts = {u for _, u in users[src]}
        if len(accounts) >= SPRAY_N:
            emit("spray", src, t, accounts=sorted(accounts))
    return findings

def top_talkers(lines, n=3):
    req, size = Counter(), Counter()
    for line in lines:
        m = WEB.match(line)
        if m:
            req[m["src"]] += 1
            size[m["src"]] += 0 if m["size"] == "-" else int(m["size"])
    return [(src, req[src], size[src]) for src, _ in size.most_common(n)]

events, unparsed = parse_ssh(ssh_log)
findings = detect(events)
print(f"ssh events: {len(events)}, unparsed relevant lines: {unparsed}")
for f in findings:
    note = ALLOW.get(f["src"])
    print(("SUPPRESSED " if note else "") + json.dumps(f) + (f"  # {note}" if note else ""))
print("top talkers by bytes:")
for src, n, b in top_talkers(web_log):
    print(f"  {src:<14} {n:>3} requests {b / 1e6:7.2f} MB")
ssh events: 28, unparsed relevant lines: 1
{"rule": "burst", "src": "203.0.113.7", "first": "09:00:35", "count": 8}
{"rule": "success-after-fail", "src": "203.0.113.7", "first": "09:01:00", "user": "root", "fails_before": 10}
{"rule": "spray", "src": "198.51.100.9", "first": "09:10:28", "accounts": ["alice", "bob", "carol", "dave", "erin"]}
SUPPRESSED {"rule": "burst", "src": "10.10.0.250", "first": "09:22:20", "count": 8}  # monitoring probe (expected failures)
top talkers by bytes:
  198.51.100.20   12 requests   11.40 MB
  10.10.0.21      40 requests    0.20 MB
  203.0.113.7     25 requests    0.00 MB

The report tells a story in a few lines:

  • 203.0.113.7 failed ten times in 45 seconds on root (burst) and then logged in (success-after-fail). That last finding is the one to act on first: the password was guessed. Contain the host, reset the credential, and look at what the session did. The same address also probed /.git/config 25 times on the web server.
  • 198.51.100.9 failed once each on six accounts, two of which (dave, frank) don't exist; the spray finding fired at the fifth distinct account, while no single account came near any threshold.
  • The monitoring probe 10.10.0.250 triggers burst, but it is on the allowlist, so the finding is shown as suppressed rather than hidden.
  • The truncated last line is counted as unparsed, so the analyst knows the input was not clean.
  • The top talker by bytes is not the one with the most requests: twelve /export downloads from 198.51.100.20 moved 11.4 MB, which deserves a look for data exfiltration or scraping.

Tuning: false positives and false negatives

Thresholds are a trade-off. The probe is a false positive at BURST_N = 8; raising the threshold to 10 would silence it but would also miss an attacker who stays at nine attempts per window. The better fix is the one used here: fix or allowlist the known source, keep the threshold. For spraying, attackers spread attempts over hours and many addresses; a second, slower rule (distinct accounts failed per day, across all sources) catches what a 5-minute window can't. Record every threshold change with a reason.

The detection lab lets you watch that trade-off on one synthetic hour of sign-ins. Its two rules are close to burst and spray (failures per account, and distinct accounts per source, in a sliding window, one alert per key and window). With 10 failures per account it finds the brute force on admin at 20.9 min with 4 alerts, 1 of them false (VPN typos), so precision is 75 % and recall 69 % of the 42 attacker failures. Lower the per-account threshold to 5 and heidi, who forgot her password, becomes a second false alarm (60 % precision, 81 % recall); raise it to 30 and the brute force is only noticed at 22.9 min, after all 30 guesses, with recall down to 21 %.

failed ✕ and successful ● sign-ins over one hourbrute forcesprayadminalicebobcaroldaveerinfrankgraceheidiivanjudyken0 min10 min20 min30 min40 min50 min60 minalertsSAASalert on an attack (TP)false alarm (FP)A = per account, S = per sourceattacker failureuser typo / forgotten password

How the analyser fails (detection)

  • Year-less syslog timestamps: Jan 15 09:00:00 has no year and no time zone. The parser assumes one (year=2026, local time); logs that cross New Year or come from hosts in other zones need RFC 5424 timestamps or the journal's __REALTIME_TIMESTAMP.
  • Log format drift: OpenSSH changes wording between versions (Invalid user, Connection closed by authenticating user, maximum authentication attempts exceeded). Watch the unparsed count.
  • Rotation: a burst that spans auth.log.1 and auth.log is split unless the tool reads both in order.
  • Clock and order: events must be sorted by time before the sliding window works; merged logs from several hosts need synchronised clocks.

How to deploy it well (prevention)

  1. Run it on a copy of the logs or from the log collector, not as root on the server.
  2. Send findings, not logs: JSON lines to the ticket system or chat, with the evidence.
  3. Test every rule with synthetic events at and around its threshold, as the testing lesson did.
  4. Pair detection with prevention: rate limiting and lockout policies (MaxAuthTries, fail2ban, PasswordAuthentication no with keys or certificates) make the attacks this tool finds much less likely to succeed (config checker).

Pitfalls

  • Counting per account only misses spraying; per source only misses distributed attacks. Use both, plus a global rate.
  • NAT and proxies put many users behind one address; a busy office gateway looks like a brute forcer at a low threshold.
  • Alerting on every event during an attack floods the channel; one finding per rule and source per window, as here.

Practice

1. Change BURST_N to 10. Which findings disappear, and which remain?

The probe's burst disappears (it has 9 failures). 203.0.113.7 still reaches exactly 10 failures, so burst and success-after-fail remain. A 9-attempt attacker would now be missed.

2. Add a rule new-source-success: a successful login for an account from a source never seen before for it.

Keep a dict of account to set of sources seen in earlier runs (a baseline file); on a success, emit the finding if src not in baseline[user], then add it. root from 203.0.113.7 fires it too, and it is the most valuable rule against stolen credentials that were never guessed.

3. Why is the top-talker list sorted by bytes and not by requests here?

The question was data volume (exfiltration, scraping). By requests, 10.10.0.21 (40 small page loads) leads; by bytes, the 12 large exports lead. A good report shows both columns, as the tool does, so the reader sees which measure ranks the list.

Test yourself

Which finding in the report should an analyst act on first?

  1. The spray from 198.51.100.9
  2. The suppressed monitoring probe
  3. success-after-fail for root from 203.0.113.7
  4. The top talker by requests

Why is the monitoring probe shown as SUPPRESSED instead of left out?

  1. To fill the report
  2. So suppressions stay visible and can be reviewed; a hidden allowlist can hide a real attack
  3. Because it is the attacker
  4. Because JSON requires it

What does the spray rule count?

  1. Failures per account
  2. Distinct accounts failed by one source within the window
  3. Bytes per source
  4. Successful logins

Why can't syslog's Jan 15 09:00:00 timestamp be compared across hosts without care?

  1. It is in hexadecimal
  2. It has no year and no time zone
  3. It counts milliseconds
  4. It is always UTC

In the detection lab, lowering the per-account threshold from 10 to 5 failures does what?

  1. Nothing
  2. Raises recall (69 % to 81 %) but adds a false alarm for a user who forgot her password, so precision falls to 60 %
  3. Removes the spray alert
  4. Makes every alert a true positive