Learn / Stage 2: Linux / Lesson 2.4

$ lesson 2.4 --stage linux --blue-team

Linux Logging, Auditing and Hardening

Every intrusion leaves a trail, if the system was recording and someone knows where to look. Learn how Linux logs work, record exactly who changed what with auditd, investigate a hacked server step by step, and harden your own VM with checks you can prove.

  • Stage 2 Linux
  • Level Intermediate
  • 65 min
  • 6 sections, quiz, lab

Start the lesson Jump to the lab

By the end of this lesson you can

  • Explain how journald, rsyslog and auditd fit together and where each writes
  • Answer investigation questions with journalctl, auth.log, last and ausearch
  • Write auditd rules for identity files, sudoers, SSH and cron
  • Hunt cron, systemd, SSH key and account persistence with a repeatable checklist
  • Harden a server against the same attack and prove it with Lynis or CIS checks
2.4.01

Where Linux keeps its evidence

When something goes wrong on a Linux server, the logs are the crime scene. Modern Ubuntu has two logging systems working together, plus an optional third for security auditing:

Where Linux logs go: programs, the kernel and services write to journald; rsyslog writes text files in /var/log and can forward copies to a log server; auditd records kernel audit events in audit.logsshd, sudo, cronprogramskerneldrivers, firewallsystemd unitsservicesjournaldjournalctlrsyslogtext files/var/logauth.log, sysloglog serverSIEM, off boxauditdaudit.logkernel audit events
Programs, the kernel and services send messages to journald. rsyslog writes the classic text files in /var/log and can forward a copy to a log server. auditd records the kernel's security audit events separately.
  • systemd-journald collects messages from every service, the kernel and early boot into a structured, indexed journal. You read it with journalctl. If the folder /var/log/journal exists, the journal is kept on disk and survives reboots; otherwise it lives in memory under /run/log/journal.
  • rsyslog writes plain text files that every tool understands. On Ubuntu the important ones are /var/log/auth.log (logins, sudo, SSH), /var/log/syslog (general system messages) and /var/log/kern.log. It can also forward logs to another server.
  • auditd (install the auditd package) records detailed kernel events you ask for: who opened /etc/shadow, who ran a program, which syscalls failed.
  • Binary login records: last reads /var/log/wtmp (logins and reboots) and sudo lastb reads /var/log/btmp (failed logins).
Where to look first
QuestionWhere to look
Who logged in over SSH, and from where?/var/log/auth.log, journalctl -u ssh, last
Who used sudo, and to run what?grep sudo /var/log/auth.log
Did a service crash or restart?journalctl -u name, systemctl status name
What happened around boot?journalctl -b (this boot), journalctl -b -1 (previous boot)
Who changed a watched file?sudo ausearch -k key -i
2.4.02

Reading logs fast with journalctl and grep

$ journalctl -u ssh --since "1 hour ago"
$ journalctl -p err -b
$ journalctl -f
$ journalctl _UID=1001 --since today
$ journalctl -u cron -n 20 --no-pager
$ sudo grep -E 'Accepted|Failed' /var/log/auth.log | tail -20
$ sudo grep 'sudo:' /var/log/auth.log | grep COMMAND
$ last -a | head
$ sudo lastb | head
  • -u filters by unit, --since and --until by time ("2026-11-20 08:00" or "1 hour ago"), -p err by priority, -b by boot, and -f follows new lines live like tail -f.
  • -g pattern (or --grep) searches message text, and -o json gives machine readable output for scripts.
  • Normal users see only their own journal entries unless they are in the adm or systemd-journal group, which is why investigations use sudo.

Read a successful login line carefully, because each field answers a question:

Nov 20 08:31:07 cwm-lab sshd[944]: Accepted password for backup_svc from 203.0.113.45 port 41377 ssh2

When, on which host, which program and process ID, how they authenticated (password, not a key), which account, from which IP. A service account logging in with a password from an internet address that just spent ten minutes failing as root is the moment an investigation starts.

2.4.03

auditd: recording exactly who touched what

Normal logs tell you that someone logged in. The Linux audit system tells you that user 1001, through sudo, ran sed on /etc/passwd at 08:34:02. You decide what to watch with rules:

$ sudo apt install -y auditd
$ sudo nano /etc/audit/rules.d/cwm.rules
-w /etc/passwd -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/sudoers -p wa -k sudoers
-w /etc/ssh/sshd_config -p wa -k sshd
-w /etc/crontab -p wa -k cron
$ sudo augenrules --load
$ sudo auditctl -l
$ sudo ausearch -k identity -i
$ sudo aureport --summary
  • -w path watches a file or folder, -p wa records writes and attribute changes (add r for reads, x for executes), and -k attaches a key name you can search for.
  • Rule files in /etc/audit/rules.d/ are merged and loaded by augenrules --load and at boot; auditctl -l lists what is active.
  • ausearch -i turns numeric IDs into names. The auid field (audit user ID) is the account that originally logged in, and it stays the same after sudo, so you can see who really became root.
  • Adding -e 2 as the last rule makes the configuration immutable until reboot, so an attacker with root cannot quietly switch auditing off without a reboot that itself gets noticed.
2.4.04

Hunting persistence: a repeatable checklist

Once attackers get in, they make sure they can come back after a reboot or a password change. On Linux the same handful of places cover most cases, and each one has a MITRE ATT&CK technique ID that defenders and reports use:

Common Linux persistence spots with their MITRE ATT&CK technique IDs: cron, systemd services, SSH authorized_keys, shell profile files and new accountsattacker gets instolen password, bugcron or timerT1053.003systemd serviceT1543.002authorized_keysT1098.004.bashrc, profileT1546.004new UID 0 userT1136.001
Where attackers hide a way back in, labelled with their MITRE ATT&CK technique IDs. A hunt checks every one of these spots, for every user.
# 1. scheduled jobs, every user
$ for u in $(cut -d: -f1 /etc/passwd); do sudo crontab -l -u "$u" 2>/dev/null | sed "s/^/$u: /"; done
$ ls -la /etc/cron.d /etc/cron.daily /var/spool/cron/crontabs 2>/dev/null
$ systemctl list-timers --all
# 2. services
$ systemctl list-unit-files --type=service --state=enabled
$ ls -lt /etc/systemd/system/ | head
# 3. SSH keys for every account
$ sudo find / -name authorized_keys -path '*/.ssh/*' 2>/dev/null -exec ls -l {} \;
# 4. accounts with UID 0 or a new login shell
$ awk -F: '$3==0 || $7 ~ /bash|sh$/' /etc/passwd
# 5. shell startup files changed recently
$ sudo find /home /root -maxdepth 2 -name '.*rc' -mtime -7 -ls

What makes something suspicious is rarely its name. Attackers pick names like sysupdate, dbus-helper or .cache. Look instead for things that do not fit: a service running a file from /tmp or a hidden folder, a cron job for an account that should never log in, a key in authorized_keys that nobody recognises, files changed on the day of the suspicious login.

2.4.05

Practice: investigate a compromised server

This practice server was brute forced on 20 November. Use the logs to find out how the attacker got in and what they left behind, then contain it. Use sudo where a file needs root; this is your own lab box.

student@cwm-lab: Persistence hunt

Missions 0/10

    Simulated in your browser. Nothing runs on a real machine.
    2.4.06

    Hardening: CIS style, then prove it

    Hardening means removing the openings you just hunted through, and then proving it, not just believing it. The CIS Benchmarks from the Center for Internet Security are free, detailed hardening guides for each distribution, including Ubuntu 24.04 LTS, and most audit tools map their checks to them. Canonical's Ubuntu Security Guide (usg, part of Ubuntu Pro, free for personal use on a small number of machines) can audit and apply CIS profiles automatically, and the open source Lynis gives a quick audit with suggestions.

    Hardening checklist
    AreaDo thisCheck it with
    AccountsService accounts get /usr/sbin/nologin; lock unused accountsawk -F: '$7 !~ /nologin|false/' /etc/passwd
    SSHKeys only, no root login, only listed users (AllowUsers)sudo sshd -T | grep -Ei 'passwordauth|permitroot|allowusers'
    Brute forcefail2ban bans IPs after repeated failuressudo fail2ban-client status sshd
    Updatesunattended-upgrades installs security updates dailysystemctl status unattended-upgrades
    FirewallDefault deny incoming, allow only what is neededsudo ufw status verbose
    ServicesDisable what you do not usesystemctl list-unit-files --state=enabled
    Temp foldersMount /tmp with noexec,nosuid,nodev where your software allowsfindmnt /tmp
    LoggingPersistent journal, auditd rules, logs forwarded off boxls /var/log/journal; sudo auditctl -l
    $ sudo apt install -y lynis fail2ban
    $ sudo lynis audit system
    $ grep -E 'warning|suggestion' /var/log/lynis-report.dat | head -20
    $ sudo usermod -s /usr/sbin/nologin backup_svc
    $ sudo passwd -l backup_svc

    Lynis prints a hardening index and a list of warnings and suggestions. Fix one area at a time, rerun the audit, and keep the reports: a rising score with a dated report is evidence you can show an auditor or an interviewer.

    Flashcards: do you remember?

    Tap a card to flip it. Try to answer in your head first; recalling is what makes it stick.

    Quick quiz

    Instant feedback on every answer. Score 70% or more to pass this lesson's quiz.

    Q1Which command shows only the SSH service's journal for the last hour?

    Q2A log shows Accepted password for backup_svc from 203.0.113.45. What is most alarming?

    Q3What does -p wa mean in an auditd watch rule?

    Q4A service file runs /tmp/.cache/.u with Restart=always. Why suspicious?

    Q5You found a backdoor key in authorized_keys. Best first action?

    Q6Which control alone would have blocked the password brute force?

    0 / 6

    Hands-on lab

    lab60 minutesyour own machines only

    Lab: log, attack, detect and harden your own VM

    You need: Your Ubuntu lab VM (snapshot first) and your own PC on the host-only network.

    1. Make the journal persistent and check rsyslog

      $ ls -ld /var/log/journal || sudo mkdir -p /var/log/journal && sudo systemctl restart systemd-journald
      $ journalctl --disk-usage
      $ systemctl status rsyslog --no-pager
      $ sudo tail -5 /var/log/auth.log

      Reboot, then confirm journalctl -b -1 shows the previous boot.

    2. Install auditd and add rules

      $ sudo apt install -y auditd
      $ sudo nano /etc/audit/rules.d/cwm.rules
      $ sudo augenrules --load && sudo auditctl -l

      Use the five rules from the auditd section, plus -w /etc/systemd/system -p wa -k systemd.

    3. Simulate the attacker safely

      $ sudo useradd -m -s /bin/bash labsvc && sudo passwd labsvc
      $ echo '*/10 * * * * /bin/true' | sudo crontab -u labsvc -
      $ printf '[Service]\nExecStart=/bin/sleep infinity\n[Install]\nWantedBy=multi-user.target\n' | sudo tee /etc/systemd/system/labtest.service
      $ sudo systemctl enable --now labtest

      These are harmless stand-ins (/bin/true and sleep) for a backdoor. From your PC, log in once as labsvc over SSH.

    4. Hunt it with the checklist

      Run every command from the persistence hunt section. Find the cron job, the service, the login in auth.log and last, and the audit events with sudo ausearch -k systemd -i. Write a five line incident note with times and evidence.

    5. Clean up and harden

      $ sudo systemctl disable --now labtest && sudo rm /etc/systemd/system/labtest.service
      $ sudo crontab -r -u labsvc && sudo userdel -r labsvc
      $ sudo apt install -y lynis fail2ban unattended-upgrades
      $ sudo lynis audit system | tee ~/lynis-before.txt

      Fix three warnings or suggestions from Lynis, run it again into ~/lynis-after.txt, and compare the hardening index.

    You are done when: Your hunt found every planted item from its logs, the audit trail shows who created them, and your second Lynis report scores higher than the first.

    Download the lab checklist (.txt)

    Key takeaways

    • journald, rsyslog and auditd each answer different questions; know where each writes.
    • Forward logs off the box, because attackers delete local logs.
    • auditd with a few focused rules shows who changed identity, sudo, SSH and cron files.
    • Hunt persistence by behaviour and location, not by names.
    • Harden, then prove it with an audit you can repeat.

    Finished the sections, quiz and lab? Mark the lesson complete. Progress is saved only in this browser.