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 01 · 40 minutes

Find a failed login and a strange request in three kinds of log

After this lesson you can
  • Name the fields of an auth log line, a web access log line and a syslog line
  • Answer questions about a day of logs with grep, awk and sort
  • Answer the same questions with a short Python program
Lab files of this lesson (3)

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

It is your first week in the security team of Fernwood Press, an invented publisher. The shop runs on one server, web01. A colleague says that the admin pages "felt odd" around lunchtime on Friday. Your team lead does not want a tool yet: "Read the logs of web01 by hand first. Tell me what is in them, which files answer which question, and what you can already count." You get one day of three log files.

The idea

A log is a text file in which a program writes one line for each thing that it does. A security team reads logs because they are the only record of what happened on a machine. Each program writes its own format, so you must learn what the fields of each line mean before you search.

Where the logs of web01 come from
web01Log filesYour desksshd and sudoWeb serverKernel and cronauth.logaccess.logsysloggrep and awkPythonAnalyst12345678web01Log filesYour desksshd and sudoWeb serverKernel andcronauth.logaccess.logsysloggrep and awkPythonAnalyst12345678
  1. sshd and sudo → auth.log: logins, sudo, new accounts
  2. Web server → access.log: one line for each request
  3. Kernel and cron → syslog: firewall, cron, services
  4. auth.log → grep and awk: pick lines, cut fields
  5. access.log → grep and awk: requests, status, size
  6. syslog → grep and awk: firewall blocks, cron jobs
  7. grep and awk → Python: count, sort and join
  8. Python → Analyst: a number you can defend

Web01 writes three files:

FileWritten byHolds
auth.logsshd (the server for remote logins by ssh), sudo, useraddLogins, privilege use, new accounts
access.logthe web serverOne line for each web request
syslogthe systemCron jobs, services, kernel and firewall messages

A classic line of auth.log and syslog (newer Ubuntu adds year and zone) is a syslog line: Nov 20 13:59:21 web01 sshd[1664]: Accepted password for mwebb from 203.0.113.50 port 38086 ssh2.

A syslog line of auth.log
Nov 20 13:59:21host clock, no year, no zoneweb01host that wrote the linesshd[1664]:program and process numberAccepted password for...free text, differs by programNov 20 13:59:21host clock, no year, no zoneweb01host that wrote the linesshd[1664]:program and process numberAccepted password for...free text, differs by program

Words that you will meet in the messages:

WordMeaning
UFW BLOCKThe Linux firewall (UFW, Uncomplicated Firewall) refused a connection.
SRC, DSTSource and destination address of that connection.
SPT, DPTSource and destination port. Port 22 is ssh, 23 is telnet, 3389 is Windows remote desktop.
sudoA user runs one command as root. TTY is the terminal that the user typed in.
useraddThe command that creates an account.
CRONThe scheduler that runs jobs at fixed times. pam_unix is the part that checks passwords and opens sessions.

A line of access.log is in the combined log format: 203.0.113.50 - mwebb [20/Nov/2026:13:03:51 +0000] "GET /admin/export/customers.csv HTTP/1.1" 200 2481722 "-" "Mozilla/5.0".

A line of access.log
203.0.113.50address of the client- mwebbidentity, then logged-in user[20/Nov/2026:13:03:51 +0000]time and offset from UTC"GET /admin/..."method, path, protocol200status of the answer2481722size of the answer in bytes203.0.113.50address of the client- mwebbidentity, then logged-in user[20/Nov/2026:13:03:51 +0000]time and offset from UTC"GET /admin/..."method, path, protocol200status of the answer2481722size of the answer in bytes

The last two parts of the line are the page that linked here (- is none) and the client program (the user agent). The status says how it went: 2xx worked, 3xx redirect, 4xx the client was refused or wrong, 5xx the server failed. +0000 means UTC, the world time without daylight saving.

You know grep, awk, sort and uniq from "Linux" Part 1, lessons 4 to 6. Here they answer questions about security.

Worked example

1. Make the logs

The generator gen_logs.py writes the three files into a folder data. It uses a fixed seed, so you get the same files as this lesson. You do not need to read it.

The finished file: gen_logs.py

gen_logs.py

"""gen_logs.py: write one day of invented logs for Fernwood Press. The same day always gives the same files.

    python3 gen_logs.py [day] [folder]      day 1 (default) or 2; folder default: data
"""
import hashlib
import random
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path

# day: (seed, date, address of the intruder, account that the intruder guesses, first guess at hh:mm UTC)
DAYS = {
    1: (7, (2026, 11, 20), "203.0.113.50", "mwebb", (12, 55)),
    2: (8, (2026, 11, 23), "198.51.100.140", "pdiaz", (9, 40)),
}
day = int(sys.argv[1]) if len(sys.argv) > 1 else 1
out = Path(sys.argv[2] if len(sys.argv) > 2 else "data")
seed, ymd, INTRUDER, VICTIM, (ah, am) = DAYS[day]

r = random.Random(seed)  # only random() is used: it gives the same numbers on every Python version


def rnd(n):
    return int(r.random() * n)


def pick(items):
    return items[rnd(len(items))]


MON = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()
STAFF = {"alice": ("192.0.2.101", 1001), "bob": ("192.0.2.102", 1002), "carol": ("192.0.2.103", 1003),
         "mwebb": ("192.0.2.104", 1005), "pdiaz": ("192.0.2.105", 1006)}
BROWSERS = ["Mozilla/5.0 (X11; Linux x86_64) Firefox/126.0", "Mozilla/5.0 (Windows NT 10.0) Chrome/124.0",
            "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4) Safari/605.1"]
CUSTOMERS = [f"198.51.100.{n}" for n in range(100, 140)] + [f"203.0.113.{n}" for n in range(100, 120)]
PAGES = [("/", 200, 5120), ("/shop/", 200, 18240), ("/shop/book/N", 200, 7410), ("/about", 200, 3310),
         ("/cart", 200, 2210), ("/static/site.css", 200, 14420), ("/favicon.ico", 404, 196),
         ("/downloads/catalogue-2026.pdf", 200, 3276800)]
PROBES = ["/wp-login.php", "/.env", "/phpmyadmin/", "/admin.php", "/.git/config", "/server-status", "/xmlrpc.php",
          "/backup.zip"]

DAY = datetime(*ymd, tzinfo=timezone.utc)
lines = {"auth.log": [], "access.log": [], "syslog": []}  # file -> [(utc time, text)]
pids = [1000]


def at(h, m=0, s=0):
    return DAY + timedelta(hours=h, minutes=m, seconds=s)


def pid():
    pids[0] += 1 + rnd(9)
    return pids[0]


def local(t):  # the clock of web01 runs in UTC+01:00, and syslog lines carry no year and no zone
    t += timedelta(hours=1)
    return f"{MON[t.month - 1]} {t.day:2d} {t:%H:%M:%S}"


def sys_line(file, t, proc, text, with_pid=True, p=None):
    who = f"{proc}[{p or pid()}]" if with_pid else proc
    lines[file].append((t, f"{local(t)} web01 {who}: {text}"))


def ssh(t, ok, user, ip, how="password", invalid=False, stay=0):
    port, p = 32768 + rnd(28000), pid()
    if ok:
        sys_line("auth.log", t, "sshd", f"Accepted {how} for {user} from {ip} port {port} ssh2", p=p)
        uid = STAFF.get(user, ("", 1500))[1]
        sys_line("auth.log", t, "sshd", f"pam_unix(sshd:session): session opened for user {user}(uid={uid}) by (uid=0)", p=p)
        sys_line("auth.log", t + timedelta(seconds=stay or 60 + rnd(900)), "sshd",
                 f"pam_unix(sshd:session): session closed for user {user}", p=p)
    else:
        who = f"invalid user {user}" if invalid else user
        sys_line("auth.log", t, "sshd", f"Failed password for {who} from {ip} port {port} ssh2", p=p)


def web(t, ip, method, path, status, size, user="-", ua=None):
    ua = ua or pick(BROWSERS)
    stamp = f"{t.day:02d}/{MON[t.month - 1]}/{t.year}:{t:%H:%M:%S} +0000"
    lines["access.log"].append((t, f'{ip} - {user} [{stamp}] "{method} {path} HTTP/1.1" {status} {size} "-" "{ua}"'))


def block(t, ip, port):
    sys_line("syslog", t, "kernel", f"[{int(t.timestamp()) % 90000}.{rnd(10)}] UFW BLOCK IN=eth0 SRC={ip} "
             f"DST=192.0.2.10 PROTO=TCP SPT={32768 + rnd(28000)} DPT={port}", with_pid=False)


# 1. Normal life
for _ in range(330):  # customers on the shop
    ip, ua = pick(CUSTOMERS), pick(BROWSERS)
    t = at(0) + timedelta(seconds=int((r.random() + r.random()) / 2 * 86400))
    for _ in range(1 + rnd(4)):
        t += timedelta(seconds=1 + rnd(20))
        path, status, size = pick(PAGES)
        path = path.replace("/N", f"/{100 + rnd(40)}")
        web(t, ip, "GET", path, status, size + rnd(400) * (status == 200), ua=ua)
for i in range(144):  # the monitor asks for /healthz every 10 minutes
    web(at(0, 10 * i), "192.0.2.5", "GET", "/healthz", 200, 2, ua="kr-monitor/1.0")
for i in range(10):  # the editor uses the admin pages from the usual address
    web(at(8, 5 * i, rnd(60)), STAFF[VICTIM][0], "GET", "/admin/orders", 200, 9100 + rnd(900), user=VICTIM)
for name, (ip, _uid) in STAFF.items():  # staff log in
    for _ in range(2):
        ssh(at(7 + rnd(9), rnd(60), rnd(60)), True, name, ip, pick(["password", "publickey"]))
t = at(8, 40, 10)
for _ in range(4):  # a typing mistake that is below any sensible limit
    ssh(t, False, "alice", STAFF["alice"][0])
    t += timedelta(seconds=6 + rnd(6))
ssh(t, True, "alice", STAFF["alice"][0])
for h in range(24):  # the deploy job of the CI server
    ssh(at(h, 5, rnd(30)), True, "deploy", "192.0.2.8", "publickey", stay=20)
for _ in range(10):  # the internet knocks now and then
    ssh(at(rnd(24), rnd(60), rnd(60)), False, pick(["admin", "test", "oracle", "git"]), pick(CUSTOMERS), invalid=True)
for h in range(24):  # system work
    sys_line("syslog", at(h, 16, 1), "CRON", "(root) CMD (cd / && run-parts --report /etc/cron.hourly)")
sys_line("syslog", at(2), "CRON", "(root) CMD (/usr/local/bin/backup.sh)")
sys_line("syslog", at(2, 6, 41), "backup.sh", "backup finished, 1.2 GB written")
sys_line("syslog", at(5, 12, 9), "kernel", f"[{5 * 3600 + 700}.3] Out of memory: Killed process 3301 (convert) "
         "total-vm:812340kB", with_pid=False)
sys_line("syslog", at(5, 0, 2), "systemd", "Starting Daily apt upgrade and clean activities...")
sys_line("syslog", at(5, 0, 31), "systemd", "Finished Daily apt upgrade and clean activities.")
sys_line("syslog", at(9, 3, 12), "systemd", "Reloading A high performance web server and a reverse proxy server.")

# 2. The authorised scan from scan01, 192.0.2.7
t = at(0, 30)
for _ in range(60):
    t += timedelta(seconds=1)
    path = pick(PROBES + ["/", "/shop/", "/about"])
    web(t, "192.0.2.7", "GET", path, 200 if path in ("/", "/shop/", "/about") else pick([404, 404, 403]), 196,
        ua="FernwoodScan/2.1")

# 3. A scanner and a password guesser from 198.51.100.77, which never get in
for i in range(6):
    block(at(2, 30, 5 * i + rnd(4)), "198.51.100.77", pick([23, 445, 3389]))
t = at(2, 40)
for _ in range(45):
    t += timedelta(seconds=rnd(2) + 1)
    web(t, "198.51.100.77", "GET", pick(PROBES), 404, 196, ua="python-requests/2.31.0")
t = at(2, 50)
for _ in range(40):
    t += timedelta(seconds=5 + rnd(4))
    name = pick(["root", "admin", "ubuntu", "test", "oracle", "postgres", "git", "user"])
    ssh(t, False, name, "198.51.100.77", invalid=name != "root")

# 4. A request that tries to bend a search page, from 198.51.100.23: the server refuses it
for i, (q, status) in enumerate([("1%27%20OR%20%271%27%3D%271", 500), ("%27%20UNION%20SELECT%20password%20FROM%20users--", 400),
                                  ("1%27%3B%20DROP%20TABLE%20books--", 400)]):
    web(at(10, 31, 7 + 9 * i), "198.51.100.23", "GET", f"/shop/search?q={q}", status, 312, ua="sqlmap-lab/1.0")

# 5. The intruder: a stolen account, guessed
for _ in range(2):
    block(at(ah, am - 18, 20 + rnd(20)), INTRUDER, pick([23, 3389]))
t = at(ah, am, 4)
for _ in range(16):
    ssh(t, False, VICTIM, INTRUDER)
    t += timedelta(seconds=11 + rnd(9))
t += timedelta(seconds=20)
ssh(t, True, VICTIM, INTRUDER, stay=28 * 60)
web(t - timedelta(minutes=6), INTRUDER, "GET", "/admin/", 401, 197, ua="Mozilla/5.0 (X11; Linux x86_64) Firefox/126.0")
for m, s, method, path, status, size, user in [(2, 5, "POST", "/admin/login", 302, 0, "-"),
                                               (2, 9, "GET", "/admin/", 200, 8120, VICTIM),
                                               (4, 30, "GET", "/admin/export/customers.csv", 200, 2481722, VICTIM)]:
    web(t + timedelta(minutes=m, seconds=s), INTRUDER, method, path, status, size, user,
        ua="Mozilla/5.0 (X11; Linux x86_64) Firefox/126.0")
lines["auth.log"].append((t + timedelta(minutes=3), f"{local(t + timedelta(minutes=3))} web01 sudo:   {VICTIM} : TTY=pts/0 ; "
                          f"PWD=/home/{VICTIM} ; USER=root ; COMMAND=/usr/bin/less /var/log/auth.log"))
lines["auth.log"].append((t + timedelta(minutes=5), f"{local(t + timedelta(minutes=5))} web01 sudo:   {VICTIM} : TTY=pts/0 ; "
                          f"PWD=/home/{VICTIM} ; USER=root ; COMMAND=/usr/sbin/useradd -m svc-update"))
sys_line("auth.log", t + timedelta(minutes=5, seconds=1), "useradd",
         "new user: name=svc-update, UID=1010, GID=1010, home=/home/svc-update, shell=/bin/bash")
sys_line("syslog", t + timedelta(minutes=8), "crontab", "(svc-update) REPLACE (svc-update)")
for m in (10, 15):
    sys_line("syslog", t + timedelta(minutes=m), "CRON", "(svc-update) CMD (/home/svc-update/.cache/sync)")

# 6. Write the files, in time order
out.mkdir(parents=True, exist_ok=True)
for name, rows in lines.items():
    rows.sort(key=lambda row: row[0])
    if name == "access.log":  # a log that is cut when it rotates leaves two broken lines
        for i in (300, 900):
            rows[i] = (rows[i][0], rows[i][1][:45])
    if name == "syslog":  # and a marker that is not an event at all
        rows.insert(20, (rows[20][0], f"{local(rows[20][0])} --- MARK ---"))
    text = "".join(line + "\n" for _, line in rows)
    (out / name).write_text(text)
    print(f"{name:11s} {len(rows):5d} lines  sha256 {hashlib.sha256(text.encode()).hexdigest()[:12]}")
python3 gen_logs.py
auth.log      181 lines  sha256 20c90abd2b56
access.log   1070 lines  sha256 4552a5c6d74b
syslog         42 lines  sha256 a6d4a1dbfbea

The last column is the start of the SHA-256 hash of each file. If your hashes are the same, your files are the same as mine.

2. Count the lines and look at the first ones

wc -l counts lines. head -n 2 prints the first two lines of a file.

wc -l data/*
head -n 2 data/syslog
  1070 data/access.log
   181 data/auth.log
    42 data/syslog
  1293 total
Nov 20 01:16:01 web01 CRON[1268]: (root) CMD (cd / && run-parts --report /etc/cron.hourly)
Nov 20 02:16:01 web01 CRON[1273]: (root) CMD (cd / && run-parts --report /etc/cron.hourly)

3. Count the failed logins

grep -c counts the lines that match. The words Failed password are in every failed ssh login.

grep -c "Failed password" data/auth.log
70

To see which addresses failed, cut out the address. In a failed-login line the address is the fourth field from the end: from ADDRESS port PORT ssh2. In awk, NF is the number of fields in the line, and $(NF-3) is the field that is three before the last one. uniq -c counts equal neighbouring lines, so sort comes first, and sort -rn puts the biggest number on top.

grep "Failed password" data/auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head -n 4
     40 198.51.100.77
     16 203.0.113.50
      4 192.0.2.101
      2 198.51.100.108

Two addresses are far above the rest. Lesson 3 turns this count into a rule, and lesson 4 tells the two apart.

4. Cut the fields of the access log

awk splits a line at spaces. In the combined format the time is split into two fields, so the status code is field 9 and the size is field 10. Count the status codes.

awk '{print $9}' data/access.log | sort | uniq -c | sort -rn
    863 200
    185 404
     15 403
      2 400
      2 
      1 500
      1 401
      1 302

Two lines have an empty status. They are broken: a log that is cut when it rotates leaves half a line. A search with awk hides such lines in a count, and lesson 2 counts them on purpose.

5. Find the large answers

An answer of more than a million bytes is rare on this site. Print the path of each, count the equal ones.

awk '$10 > 1000000 {print $7}' data/access.log | sort | uniq -c
      1 /admin/export/customers.csv
    105 /downloads/catalogue-2026.pdf

The catalogue is a big public file, so many downloads are normal. One export of customer data is not. Find who asked for it.

grep "customers.csv" data/access.log
203.0.113.50 - mwebb [20/Nov/2026:13:03:51 +0000] "GET /admin/export/customers.csv HTTP/1.1" 200 2481722 "-" "Mozilla/5.0 (X11; Linux x86_64) Firefox/126.0"

6. Read syslog without the noise

grep -v keeps the lines that do NOT match. The hourly cron lines are noise here.

grep -v "CRON" data/syslog | head -n 8
Nov 20 03:06:41 web01 backup.sh[1379]: backup finished, 1.2 GB written
Nov 20 03:30:01 web01 kernel: [1801.2] UFW BLOCK IN=eth0 SRC=198.51.100.77 DST=192.0.2.10 PROTO=TCP SPT=45424 DPT=3389
Nov 20 03:30:06 web01 kernel: [1806.3] UFW BLOCK IN=eth0 SRC=198.51.100.77 DST=192.0.2.10 PROTO=TCP SPT=53899 DPT=23
Nov 20 03:30:12 web01 kernel: [1812.2] UFW BLOCK IN=eth0 SRC=198.51.100.77 DST=192.0.2.10 PROTO=TCP SPT=54730 DPT=23
Nov 20 03:30:17 web01 kernel: [1817.6] UFW BLOCK IN=eth0 SRC=198.51.100.77 DST=192.0.2.10 PROTO=TCP SPT=52185 DPT=3389
Nov 20 03:30:21 web01 kernel: [1821.3] UFW BLOCK IN=eth0 SRC=198.51.100.77 DST=192.0.2.10 PROTO=TCP SPT=33674 DPT=23
Nov 20 03:30:28 web01 kernel: [1828.6] UFW BLOCK IN=eth0 SRC=198.51.100.77 DST=192.0.2.10 PROTO=TCP SPT=59830 DPT=445
Nov 20 06:00:02 web01 systemd[1383]: Starting Daily apt upgrade and clean activities...

7. Ask the same question in Python

The program count_failures.py gives the answer of step 3 and the number of different addresses. re.compile makes a pattern (Python lesson 10), and Counter counts items and sorts them with most_common (Python lesson 2).

count_failures.py

import re
from collections import Counter

FAILED = re.compile(r"Failed password for (?:invalid user )?(\S+) from (\S+) port")
counts = Counter()
for line in open("data/auth.log"):
    m = FAILED.search(line)
    if m:
        counts[m[2]] += 1
for address, n in counts.most_common(3):
    print(n, address)
print(len(counts), "addresses,", sum(counts.values()), "failures")
python3 count_failures.py
40 198.51.100.77
16 203.0.113.50
4 192.0.2.101
12 addresses, 70 failures

The shell answers one question quickly. Python keeps the answer as data that you can use in the next step, and that is what the rest of the course does.

Your turn

The team lead wants to know who used the admin pages from outside the office. The office network is 192.0.2.0/24. Use the files of this lesson, grep, awk or Python. Count lines of the access log by path and address, and count lines of the auth log by message. Do not count the broken lines.

Check yourself

A line of auth.log says "Nov 20 13:59:21". What two things are missing from that time?

The year and the time zone. A syslog line carries neither. You must know the clock of the host to place the event in time, and lesson 2 shows how to do that.

Why is field 9 of an access log line the status and not field 6?

awk cuts at spaces. The time [20/Nov/2026:13:03:51 +0000] holds a space and makes two fields (4 and 5), and the request "GET /path HTTP/1.1" makes three (6, 7 and 8). So the status is field 9. A path with a space in it would shift the fields, which is one reason to parse with a pattern.

The count of 200 answers does not add up to the number of lines of access.log. Why?

There are other statuses (404, 403 and more), and two lines are cut short and have no status at all. A count by awk skips what it cannot see, so always compare the sum of your groups with the number of lines.

What does a 401 answer to an address outside the office tell you, and what does a later 200 for the same address tell you?

A 401 says that the page needs a login and the client had none. A later 200 for the same address and a user name means that a login worked. Together they are a first sign that someone got in. You still need the auth log to see how.

Field notes

  • A log line is evidence only if you can trust the log. A user who gets root can edit a local file. Send logs to a second machine as they are written, and treat the local copy as a convenience.
  • User names and paths in a log come from the client. A name that holds a newline can forge a second line, so a tool must not trust the shape of a line more than it checks.
  • Know the retention of each log. Many systems rotate auth.log weekly and keep four copies (auth.log.1, auth.log.2.gz). An incident that you notice on day 40 may have no log left.
  • On a system that uses systemd, the same messages are in the journal. journalctl -u ssh shows the ssh lines, and journalctl --since and --until select a period. On Windows, failed and successful logons are events 4625 and 4624 in the Security log, and lesson 5 reads them with the same parser idea.
  • Check every host clock with the same time source. Two logs with different clocks make a wrong story, and lesson 2 shows the damage.