---
title: "Linux Logging, auditd and Hardening | CyberWithMadhav"
description: "Free lesson: read Linux logs with journalctl and auth.log, record file changes with auditd, hunt cron, systemd and SSH key persistence, then harden with CIS."
url: https://www.cyberwithmadhav.com/learn-linux-logging-auditing-hardening.html
source_format: markdown rendering of the HTML page
---

[Learn](https://www.cyberwithmadhav.com/learn.html) / [Stage 2: Linux](https://www.cyberwithmadhav.com/learn.html#stage-2) / 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

## In this lesson

1. Where Linux keeps its evidence
2. Reading logs fast with journalctl and grep
3. auditd: recording exactly who touched what
4. Hunting persistence: a repeatable checklist
5. Practice: investigate a compromised server
6. Hardening: CIS style, then prove it
7. Flashcards
8. Quick quiz
9. Hands-on lab
10. Key takeaways

## 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:

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).

| Question | Where 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` |

Think of it like this

journald is the building's CCTV recorder, rsyslog prints the daily visitor register in plain text, and auditd is the extra camera you point at the safe. A smart burglar tries to wipe the register, which is why a copy must leave the building.

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.
How attackers abuse this

After getting in, attackers commonly try to erase their tracks: deleting or truncating `auth.log`, clearing shell history, or stopping logging services (MITRE ATT&CK T1070.002, clearing Linux logs). They can only erase what is on the machine they control.
Defender move

Forward logs off the box in real time so deleted local copies do not matter. With rsyslog a single line such as `*.* @@logserver.lab:514` in a file under `/etc/rsyslog.d/` sends everything over TCP (one `@` means UDP); production setups add TLS. Tools like Wazuh or the Elastic stack collect, store and alert on these logs, and you will build one in stage 5.

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.

Defender move

Start small. Watching the identity files, sudoers, SSH config, cron and systemd unit folders gives high value with little noise. Watching every syscall on a busy server produces gigabytes nobody reads.

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:

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.
How attackers abuse this

A typical chain on an internet facing server: brute force a weak password on a service account, add an SSH key for quiet access, then install a cron job or systemd service that restarts a crypto miner or backdoor from a hidden folder. Exactly the scenario in the practice shell below.
Defender move

Keep a baseline from a clean machine (enabled services, cron tables, SUID files, authorized_keys hashes) and compare against it. The difference is your list of leads. Before removing anything, **collect evidence**: copy the files and record hashes, because deleting first destroys what you need for the report.

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.

| Area | Do this | Check it with |
| --- | --- | --- |
| Accounts | Service accounts get `/usr/sbin/nologin`; lock unused accounts | `awk -F: '$7 !~ /nologin/false/' /etc/passwd` |
| SSH | Keys only, no root login, only listed users (`AllowUsers`) | `sudo sshd -T / grep -Ei 'passwordauth/permitroot/allowusers'` |
| Brute force | fail2ban bans IPs after repeated failures | `sudo fail2ban-client status sshd` |
| Updates | `unattended-upgrades` installs security updates daily | `systemctl status unattended-upgrades` |
| Firewall | Default deny incoming, allow only what is needed | `sudo ufw status verbose` |
| Services | Disable what you do not use | `systemctl list-unit-files --state=enabled` |
| Temp folders | Mount `/tmp` with `noexec,nosuid,nodev` where your software allows | `findmnt /tmp` |
| Logging | Persistent journal, auditd rules, logs forwarded off box | `ls /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.
Defender move

In the practice scenario three controls would each have stopped the attack: a service account with `nologin` (no interactive login at all), SSH with keys only (no passwords to guess), and fail2ban (the IP banned after a few failures). Defence in depth means you want all three, because one will eventually be misconfigured.

## 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.

### Q1 Which command shows only the SSH service's journal for the last hour?

### Q2 A log shows `Accepted password for backup_svc from 203.0.113.45`. What is most alarming?

### Q3 What does `-p wa` mean in an auditd watch rule?

### Q4 A service file runs `/tmp/.cache/.u` with `Restart=always`. Why suspicious?

### Q5 You found a backdoor key in authorized_keys. Best first action?

### Q6 Which control alone would have blocked the password brute force?

**0 / 6**

## Hands-on lab

lab  60 minutes  your 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.

**Only on machines you own.** Do this lab on your own VM or computer. Scanning, testing or accessing anyone else's system without written permission can be an offence under the Information Technology Act, 2000 (for example Sections 43 and 66).

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.  Done
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`.  Done
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.  Done
4. Hunt it with the checklistRun 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.  Done
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.  Done

**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)](https://www.cyberwithmadhav.com/assets/learn/learn-linux-logging-auditing-hardening-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.

[Previous 2.3 Bash Scripting for Security](https://www.cyberwithmadhav.com/learn-bash-scripting-for-security.html)[Next 3.1 Network Building Blocks: OSI, TCP/IP, Devices, Cabling, Interfaces](https://www.cyberwithmadhav.com/learn-ccna-network-building-blocks.html)
