Logging, Monitoring & Detection
Prevention eventually fails somewhere. What matters then is how quickly you notice. Industry reports regularly find that intrusions go undetected for weeks. Good logging and monitoring shrink that window, and they are what make investigation and recovery possible at all.
What to log
Log security-relevant events with enough context to answer who did what, when, from where, and with what result:
| Event | Why |
|---|---|
| Logins (success and failure), logouts, MFA challenges | Detect guessing, stuffing and account takeover |
| Password and MFA changes, account recovery | Common takeover steps |
| Permission and role changes, new admin accounts | Privilege escalation |
| Access denied (authorization failures) | Probing for IDOR and missing checks |
| Input validation failures at scale | Automated attack tools |
| Administrative actions, configuration changes | Insider misuse, persistence |
| Data exports and bulk reads | Data theft |
Each entry should include a timestamp in UTC, the user, the source IP, the action, the outcome and a request/correlation ID. Use a structured format such as JSON lines, so machines can parse it reliably.
What not to log: passwords (even wrong ones; they are often a real password with a typo), session tokens, full card numbers, secrets, and more personal data than necessary.
Tip: Send logs off the machine to a central store quickly. An attacker with admin rights on a server can delete its local logs.
Parsing an authentication log
Here is a small log in a classic sshd-like text format. The first job is turning lines into structured events:
import re
LOG = """\
2026-03-02T08:01:12Z sshd: Accepted password for alice from 198.51.100.7
2026-03-02T08:03:40Z sshd: Failed password for root from 203.0.113.50
2026-03-02T08:03:41Z sshd: Failed password for root from 203.0.113.50
2026-03-02T08:03:43Z sshd: Failed password for admin from 203.0.113.50
2026-03-02T08:03:44Z sshd: Failed password for invalid user test from 203.0.113.50
2026-03-02T08:03:46Z sshd: Failed password for root from 203.0.113.50
2026-03-02T08:03:47Z sshd: Failed password for root from 203.0.113.50
2026-03-02T08:10:05Z sshd: Failed password for bob from 192.0.2.44
2026-03-02T08:10:30Z sshd: Accepted password for bob from 192.0.2.44
2026-03-02T08:15:00Z sshd: Accepted password for carol from 203.0.113.50
"""
PATTERN = re.compile(
r"(?P<time>\S+) sshd: (?P<result>Accepted|Failed) password for "
r"(?:invalid user )?(?P<user>\S+) from (?P<ip>\S+)")
events = [m.groupdict() for m in map(PATTERN.match, LOG.splitlines()) if m]
print(len(events), "events parsed")
for e in events[:3]:
print(e)10 events parsed
{'time': '2026-03-02T08:01:12Z', 'result': 'Accepted', 'user': 'alice', 'ip': '198.51.100.7'}
{'time': '2026-03-02T08:03:40Z', 'result': 'Failed', 'user': 'root', 'ip': '203.0.113.50'}
{'time': '2026-03-02T08:03:41Z', 'result': 'Failed', 'user': 'root', 'ip': '203.0.113.50'}
Detecting brute force
A simple and effective rule: alert when one source has many failures in a short time. Then check whether that source succeeded afterwards, which turns "noise" into "possible compromise":
import re
from datetime import datetime
LOG = """\
2026-03-02T08:01:12Z sshd: Accepted password for alice from 198.51.100.7
2026-03-02T08:03:40Z sshd: Failed password for root from 203.0.113.50
2026-03-02T08:03:41Z sshd: Failed password for root from 203.0.113.50
2026-03-02T08:03:43Z sshd: Failed password for admin from 203.0.113.50
2026-03-02T08:03:44Z sshd: Failed password for invalid user test from 203.0.113.50
2026-03-02T08:03:46Z sshd: Failed password for root from 203.0.113.50
2026-03-02T08:03:47Z sshd: Failed password for root from 203.0.113.50
2026-03-02T08:10:05Z sshd: Failed password for bob from 192.0.2.44
2026-03-02T08:10:30Z sshd: Accepted password for bob from 192.0.2.44
2026-03-02T08:15:00Z sshd: Accepted password for carol from 203.0.113.50
"""
PATTERN = re.compile(r"(?P<time>\S+) sshd: (?P<result>Accepted|Failed) password for "
r"(?:invalid user )?(?P<user>\S+) from (?P<ip>\S+)")
events = []
for m in map(PATTERN.match, LOG.splitlines()):
if m:
e = m.groupdict()
e["time"] = datetime.fromisoformat(e["time"].replace("Z", "+00:00"))
events.append(e)
THRESHOLD, WINDOW = 5, 60 # 5 failures within 60 seconds
failures = {}
for e in events:
if e["result"] == "Failed":
failures.setdefault(e["ip"], []).append(e["time"])
for ip, times in failures.items():
burst = any((times[i + THRESHOLD - 1] - times[i]).total_seconds() <= WINDOW
for i in range(len(times) - THRESHOLD + 1))
users = sorted({e["user"] for e in events if e["ip"] == ip and e["result"] == "Failed"})
print(f"{ip:<14} failures={len(times)} burst={burst} users={users}")
if burst:
later = [e for e in events if e["ip"] == ip and e["result"] == "Accepted"
and e["time"] > times[-1]]
for e in later:
print(f" HIGH: {e['user']} logged in from the same IP at {e['time']:%H:%M:%S}")203.0.113.50 failures=6 burst=True users=['admin', 'root', 'test']
HIGH: carol logged in from the same IP at 08:15:00
192.0.2.44 failures=1 burst=False users=['bob']
One failed attempt followed by success (bob) is a normal typo. Six failures in seven seconds across several usernames, followed by a successful login for carol from the same address, deserves an immediate look: was carol's password guessed?
Credential stuffing and impossible travel
Two more patterns worth knowing:
- Credential stuffing: attackers replay username/password pairs leaked from other sites. The signature is many different usernames from one source (or a botnet of sources), each tried once or twice, with a low success rate.
- Impossible travel: the same account logs in from two places too far apart for the time between them.
import math
from datetime import datetime
CITY = {"Hanoi": (21.03, 105.85), "Berlin": (52.52, 13.40), "Hamburg": (53.55, 9.99)}
def km(a, b):
(lat1, lon1), (lat2, lon2) = CITY[a], CITY[b]
p1, p2 = math.radians(lat1), math.radians(lat2)
dlat, dlon = p2 - p1, math.radians(lon2 - lon1)
h = math.sin(dlat / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dlon / 2) ** 2
return 2 * 6371 * math.asin(math.sqrt(h))
logins = [
("dana", "2026-03-02T07:00:00", "Berlin"),
("dana", "2026-03-02T09:30:00", "Hamburg"),
("dana", "2026-03-02T10:15:00", "Hanoi"),
]
MAX_KMH = 900 # roughly airliner speed
for (u1, t1, c1), (u2, t2, c2) in zip(logins, logins[1:]):
hours = (datetime.fromisoformat(t2) - datetime.fromisoformat(t1)).total_seconds() / 3600
distance = km(c1, c2)
speed = distance / hours
flag = "IMPOSSIBLE TRAVEL" if speed > MAX_KMH else "ok"
print(f"{c1} -> {c2}: {distance:,.0f} km in {hours:.2f} h = {speed:,.0f} km/h {flag}")Berlin -> Hamburg: 255 km in 2.50 h = 102 km/h ok
Hamburg -> Hanoi: 8,516 km in 0.75 h = 11,354 km/h IMPOSSIBLE TRAVEL
VPNs and mobile networks cause false positives (a VPN exit node in another country), which is why such alerts are usually combined with other signals before anyone is woken up at night.
Detection quality
Every detection rule trades off two kinds of error:
- False positive: an alert for something harmless. Too many cause alert fatigue, and real alerts get ignored.
- False negative: a real attack that raises no alert.
Tune thresholds with real data, document each rule's purpose, and test rules regularly (for example by replaying a recorded attack in a lab) to make sure they still fire.
Go further: Brute Force Followed by Success tunes threshold rules and adds a sequence rule, and Impossible Travel builds that detection properly.
Test yourself
Which of these should never be written to a log?
- The username of a failed login
- The source IP address
- The password that was entered
- The timestamp in UTC
Many failed logins from one IP, followed by a successful login from the same IP. Why is that more serious than failures alone?
- It isn't
- It suggests the guessing may have succeeded
- It means the firewall is off
- It proves it was a typo
What is the typical signature of credential stuffing?
- One username, thousands of passwords
- Many different usernames, each tried with one leaked password
- Logins only at night
- Requests with SQL keywords