Lesson 06 · 50 minutes
Detect a password attack in a log and write the incident note
- Say what a useful log line holds and why logs are the base of detection
- Write a detection rule that finds many failures followed by a success
- Write a five-line incident note and name the steps of a response
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 are the on-call analyst of a small hosting firm. A customer writes: "I think someone got into our server last night, but nothing looks strange." You get the login log of the server for one hour and no other tool. You must say whether an account was guessed, who it was, from which address, and what the firm must do next. First you build a detector on a log that you make yourself. Then you use it on the log of the customer.
Recall
Lesson 3: an attacker guesses a password, and the site has a second factor. What does the attacker still lack?
The second factor, for example the one-time code from the phone of the user. A guessed password alone is not enough. This is why the detection of guessing is still useful: it shows the attack even when it fails.
Lesson 4: who should be able to write or delete a log, and who should only read it?
Only the logging system should write, and nobody should delete. Auditors and analysts get read access. Least privilege applies to logs too, because an attacker who can edit the log can hide.
The idea
A log is a record of events, written by a system as they happen. A good line answers six questions:
| Question | In the line |
|---|---|
| When | A timestamp with a time zone (UTC is best) |
| Where | The host and the program |
| Who | The user name or the account |
| What | The action and its result (success or failure) |
| From where | The source address |
| Which one | An identifier, such as a process or request number |
A log with these answers gives accountability: a user cannot deny an act that the log records. This is why only the logging system may write a log (lesson 4).
Detection is a rule that runs over events and raises an alert when they match a pattern. One failed login means nothing. Eight failures and then a success from the same address mean that someone guessed a password.
- Event → Log line: the system writes it down
- Log line → Rule: the rule reads every line
- Rule → Alert: a pattern matches
- Alert → Analyst: decides if it is real
- Analyst → Response: contain, eradicate, recover
- Response → Rule: tune the rule
When an alert is real, you start the response. The steps are:
- Prepare: have logs, contacts and a plan before you need them.
- Detect: see the event and decide that it is an incident.
- Contain: stop the damage from spreading (block the address, end the session).
- Eradicate: remove the cause (reset the password, close the hole).
- Recover: return to normal and watch for a repeat.
- Learn: write down what happened and what will change.
Worked example
1. Make a sample log
You make your own log. Write make_log.py in ~/krlab/security-basics/logs. It mixes normal use, a noisy scanner and one attack. The addresses come from ranges that are reserved for examples. Each line looks like a line of sshd, the program that lets people log in to a Linux machine over the network (SSH). Four things in it are new:
random.seed(7)fixes the random numbers, so that the program makes the same log every time.datetimeandtimedeltawork with dates and time spans, andstrftimewrites a date as text in a format that you choose.- A tuple such as
(t, "Failed", user, ip)is a small fixed group of values, and a list of tuples can be sorted. sorted(events)puts the events in time order.
mkdir -p ~/krlab/security-basics/logs
cd ~/krlab/security-basics/logsmake_log.py
import random
from datetime import datetime, timedelta, timezone
random.seed(7)
start = datetime(2026, 11, 21, 8, 0, 0, tzinfo=timezone.utc)
events = [] # (seconds after start, result, user, address)
# Normal use: people log in from their usual addresses, some mistype once.
for user, ip in [("alice", "192.0.2.10"), ("bob", "192.0.2.20"), ("carol", "192.0.2.30")]:
for _ in range(4):
t = random.randint(0, 3000)
if random.random() < 0.4:
events.append((t, "Failed", user, ip))
t += random.randint(3, 8)
events.append((t, "Accepted", user, ip))
# Noise: a scanner tries six times and never gets in.
for i in range(6):
events.append((900 + i * 5, "Failed", "root", "198.51.100.9"))
# The attack: guesses against alice, then one success.
for i in range(8):
events.append((1800 + i * 4, "Failed", "alice", "203.0.113.50"))
events.append((1840, "Accepted", "alice", "203.0.113.50"))
with open("auth.log", "w") as f:
for i, (t, result, user, ip) in enumerate(sorted(events)):
stamp = (start + timedelta(seconds=t)).strftime("%Y-%m-%dT%H:%M:%SZ")
f.write(f"{stamp} krbox sshd[{4000 + i}]: {result} password for {user} from {ip}\n")
print("wrote", len(events), "lines")2. Run it and read the log
head -3 prints the first three lines of a file.
python3 make_log.py
head -3 auth.logwrote 31 lines
2026-11-21T08:04:02Z krbox sshd[4000]: Accepted password for bob from 192.0.2.20
2026-11-21T08:04:13Z krbox sshd[4001]: Accepted password for carol from 192.0.2.30
2026-11-21T08:04:56Z krbox sshd[4002]: Accepted password for alice from 192.0.2.10Each line holds the six answers.
3. Look with plain tools first
Count the failures for each address. You can already see the problem here. Four small tools make a pipeline:
grep Failed auth.logkeeps the lines that hold the wordFailed.awk '{print $NF}'prints the last field of each line (NFis the number of fields), which is the address.sortputs equal lines side by side, anduniq -ccounts each group.sort -rnsorts by number, the highest first.
grep Failed auth.log | awk '{print $NF}' | sort | uniq -c | sort -rn 8 203.0.113.50
6 198.51.100.9
2 192.0.2.20
1 192.0.2.30
1 192.0.2.10Two addresses stand out. The second never got in, so it is noise. A rule must tell the two apart.
4. Write the detection rule
Write detect.py. It keeps the failure times of each address. At each success it counts the failures of that address in the last five minutes, and alerts when there are five or more. The clear() after an alert empties the list, so that the same failures cannot raise a second alert. Two parts are new: re is the regular-expression module (a pattern that matches the shape of a line and pulls out its parts), and defaultdict(list) is a dictionary that makes an empty list for a key that it has not seen.
detect.py
import re
import sys
from collections import defaultdict
from datetime import datetime, timedelta
LINE = re.compile(r"^(\S+) (\S+) sshd\[\d+\]: (Failed|Accepted) password for (\S+) from (\S+)$")
WINDOW = timedelta(minutes=5)
LIMIT = 5
path = sys.argv[1] if len(sys.argv) > 1 else "auth.log"
failures = defaultdict(list) # address -> times of failures
alerts = 0
for line in open(path):
m = LINE.match(line.strip())
if not m:
continue
when = datetime.fromisoformat(m[1].replace("Z", "+00:00"))
result, user, ip = m[3], m[4], m[5]
if result == "Failed":
failures[ip].append(when)
else:
recent = [t for t in failures[ip] if when - t <= WINDOW]
if len(recent) >= LIMIT:
alerts += 1
failures[ip].clear()
print(f"ALERT {m[1]} {len(recent)} failure(s) then success for {user} from {ip}")
print(f"{alerts} alert(s)")How the key line works: \S+ is one or more characters that are not spaces, and \d+ is one or more digits. (Failed|Accepted) is one of the two words. Each pair of brackets saves what it matched, so m[1] is the time, m[3] the result, m[4] the user and m[5] the address. replace("Z", "+00:00") is there because older Pythons do not read the letter Z at the end of a time.
python3 detect.pyALERT 2026-11-21T08:30:40Z 8 failure(s) then success for alice from 203.0.113.50
1 alert(s)One alert, for the attack. The scanner never succeeded, and one typing mistake is below the limit.
The lines here are simplified. A real /var/log/auth.log line has a different date format and ends with port N ssh2, so this pattern would match none of them and print "0 alert(s)". Lesson 10 of the Python course builds a fuller analyser. This one is the smallest tool that shows the idea.
5. Tune the rule
Set LIMIT = 1 in a copy and run it. sed 's/old/new/' file prints a file with the first old of each line replaced, and rm deletes the copy after the test.
sed 's/^LIMIT = 5/LIMIT = 1/' detect.py > noisy.py
python3 noisy.py | tail -3
rm noisy.pyALERT 2026-11-21T08:30:40Z 8 failure(s) then success for alice from 203.0.113.50
ALERT 2026-11-21T08:34:41Z 1 failure(s) then success for bob from 192.0.2.20
5 alert(s)Five alerts, and four are people who mistyped. An analyst who sees this every day stops reading alerts. Every rule balances missed attacks against noise.
6. Write the incident note
Write the facts, with no guess, in five lines. wc -l counts the lines of a file.
cat > incident.txt <<'EOF'
What: Password guessing against the account alice, then a successful login.
When: 2026-11-21 08:30:00 to 08:30:40 UTC, on krbox.
Source: 203.0.113.50 (8 failures in 28 seconds, then one success).
Impact: The account alice was used by an unknown party; the data it can reach is at risk.
Actions: Block the address, end the session, reset the password and add a second factor.
EOF
wc -l incident.txt5 incident.txtIn the Actions line, block and end the session is contain, and reset the password is eradicate. For the learn step, add a limit on attempts.
Your turn
Now work on the log of the customer. Save the generator below as make_log2.py in the same folder and run it with Python. It writes auth2.log, a log of one hour from another server, always the same. Use detect.py and the plain tools of the worked example. There are no steps here: read the log, find what the rule finds, and find what it misses.
make_log2.py
import random
from datetime import datetime, timedelta, timezone
random.seed(11)
start = datetime(2026, 11, 21, 22, 0, 0, tzinfo=timezone.utc)
events = [] # (seconds after start, result, user, address)
for user, ip in [("dave", "192.0.2.41"), ("erin", "192.0.2.42"), ("frank", "192.0.2.43"), ("grace", "192.0.2.44")]:
for _ in range(3):
t = random.randint(0, 3000)
if random.random() < 0.3:
events.append((t, "Failed", user, ip))
t += random.randint(3, 8)
events.append((t, "Accepted", user, ip))
for i, user in enumerate(["admin", "test", "guest", "oracle", "ubuntu", "backup"]):
events.append((600 + i * 10, "Failed", user, "198.51.100.23"))
for i in range(4):
events.append((1000 + i * 180, "Failed", "dave", "203.0.113.200"))
events.append((1725, "Accepted", "dave", "203.0.113.200"))
for i in range(7):
events.append((2000 + i * 3, "Failed", "erin", "203.0.113.77"))
events.append((2025, "Accepted", "erin", "203.0.113.77"))
with open("auth2.log", "w") as f:
for i, (t, result, user, ip) in enumerate(sorted(events)):
stamp = (start + timedelta(seconds=t)).strftime("%Y-%m-%dT%H:%M:%SZ")
f.write(f"{stamp} krbox sshd[{5000 + i}]: {result} password for {user} from {ip}\n")
print("wrote", len(events), "lines")Last, write the incident note for the confirmed attack in five lines, and add one sentence on how you would change the rule to catch the address that stayed silent. Try your change on the log before you write the sentence.
Compare with this
A model note, in the five lines of step 6:
What: Password guessing against the account erin, then a successful login.
When: 2026-11-21 22:33:20 to 22:33:45 UTC, on krbox.
Source: 203.0.113.77 (7 failures in 18 seconds, then one success).
Impact: The account erin was used by an unknown party; the data it can reach is at risk.
Actions: Block the address, end the session, reset the password and add a second factor.Two things hid the login of dave from 203.0.113.200: there were only four failures (below LIMIT = 5), and they were 180 seconds apart, so only one of them lay inside the five-minute window. A lower LIMIT = 4 alone still prints 1 alert. LIMIT = 4 with WINDOW = timedelta(minutes=15) prints 2 alerts (dave and erin) and no false alert on this log. The normal address of dave is 192.0.2.41, so a success from a new address is a signal in its own right.
Check yourself
Why must a log line hold a time zone, and why is UTC the best choice?
Logs from many systems join into one timeline. Local times, with daylight-saving shifts, put events in the wrong order. UTC has no shifts.
The attacker has full control of the server. Why is it a risk to keep the only copy of the logs on that server?
The attacker can delete or edit the lines that show them. Send logs at once to another system that the server cannot change.
The rule alerts only when a success follows the failures. What does it miss?
Slow attacks, where the failures are too far apart for the window (the login of dave in auth2.log), attacks from many addresses, and attempts that never succeed. Add other rules for those.
Field notes
- NIST SP 800-61 is the standard guide for incident response. Revision 2 has four phases (preparation, detection and analysis, containment eradication and recovery, post-incident activity); the six steps above split the same work further. Revision 3 (2025) replaces it and arranges the work under the functions of the NIST Cybersecurity Framework 2.0. Many teams and job interviews still use the four phases, so know both.
- NIST SP 800-92 covers log management. Protect logs from change, keep them for a set time, and keep all clocks in step (NTP).
- Never write secrets into logs: not passwords, tokens or card numbers. Guard against log injection: a user name that holds a newline can forge a line.
- MITRE ATT&CK names the technique in this lesson Brute Force (T1110), a good tag for an alert.