Part 4 · Operations and troubleshooting · Lesson 10 · 50 minutes
Build a troubleshooting kit that collects evidence
- Write a read-only script that collects the same evidence from any machine into a dated folder
- Print a short summary and seal the bundle with checksums so that a change can be seen
- Use the kit on a machine with a planted fault and hand over the result
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
When a server misbehaves at night, the person on call types the same twenty commands from memory, and forgets three of them. The next person has no record of what was run. Your lead wants one command that collects the standard evidence, the same way every time, into a folder with the date in its name, and prints a summary that fits on one screen. The command must only read: nobody should fear to run it on a sick machine. You build it from what this part taught.
Recall
Which command lists the failed units, and which lesson showed it?
systemctl --failed (lesson 8 of Part 2). The status code and the journal of each unit then give the cause (lesson 9 of this part).
In which order do you check a full volume (lesson 8)?
Space with df -h, inodes with df -i, the place with du, deleted files that are still open with lsof +aL1, the owner and mode with ls -ld, and the mount options with findmnt.
The idea
Good evidence has six properties. It is read-only, so collecting it cannot change the case. It is complete: the same sections every time, with a heading for each command. It is dated, with the time in UTC. It is safe to read: it holds no process arguments. It does hold the name servers, the release name, addresses, names, paths and the text of up to 50 error lines of the journal, so read it before you send it. It is tolerant: a command that is missing or not allowed prints a note, and the collection goes on. And it is sealed: a list of checksums shows later whether a file was changed.
- Collect → Summarise: read-only commands, six files
- Summarise → Seal: seven fixed lines
- Seal → Hand over: sha256 of every file
- On-call person → kr-evidence.sh: runs it as an ordinary user
- kr-evidence.sh → Live system: read-only commands only
- kr-evidence.sh → Bundle folder: six files, summary, manifest
- Bundle folder → Archive: tar -czf, then the checksum
Each section of the bundle comes from a lesson of this part:
| File | Content | Lesson |
|---|---|---|
01-system.txt | Host, time, kernel, uptime, state of systemd | 1 |
02-network.txt | Addresses, routes, listening ports, name servers | 6 |
03-cpu-memory.txt | Load, memory, pressure, busy processes, zombies | 7 |
04-disk.txt | Space, inodes, read-only mounts, deleted open files | 8 |
05-services.txt | Failed units and running services | 9 |
06-errors.txt | Error messages of the journal since boot | 9 |
Worked example
1. Write the function that runs one command
The function show prints a heading and runs one command with bash -c, so that a pipe works inside the command. A failed command must not stop the script: the script uses set -u (an unset variable is an error) and not set -e (stop at the first failure). Many tools exit with code 1 when they find nothing, so show treats 0 and 1 as normal. It prints (none) for an empty result, and (not available here: exit code N) for any other code. Type it in your shell and try it.
show() {
local text code
echo "== $1 =="
text=$(bash -c "$2" 2>&1)
code=$?
[ -n "$text" ] && printf '%s\n' "$text"
if [ "$code" -gt 1 ]; then
echo "(not available here: exit code $code)"
elif [ -z "$text" ]; then
echo "(none)"
fi
echo
}
show "read-only mounts of real disks" 'findmnt -rn -O ro -t ext4,xfs,btrfs,vfat'
show "a missing tool" 'no-such-tool'== read-only mounts of real disks ==
(none)
== a missing tool ==
bash: line 1: no-such-tool: command not found
(not available here: exit code 127)The filter -t ext4,xfs,btrfs,vfat keeps real disks only. Without it, findmnt lists the read-only squashfs mounts of snap packages, and a healthy machine looks sick.
2. Collect six files
Each file of the table is one block of show lines, written into the file with > FILE. The block for the disk shows the pattern. The other five are in the finished file.
{
show "space" 'df -hT -x tmpfs -x devtmpfs'
show "inodes" 'df -i -x tmpfs -x devtmpfs'
show "mounted read-only (real file systems)" 'findmnt -rn -O ro -t ext4,xfs,btrfs,vfat -o TARGET,FSTYPE,OPTIONS'
show "deleted files that are still open" 'lsof -nP +L1 2> /dev/null'
} > "$out/04-disk.txt"The ps list prints only command names, not arguments, because the arguments of a process can hold a password. -x tmpfs leaves out the file systems in memory.
3. Summarise and seal
The summary has seven fixed lines, and each number comes from one command. In the finished file, ss -tln | tail -n +2 drops the header line, grep -c . counts the non-empty lines, df -P prints one line for each file system, and the awk test keeps the file systems whose Use% is 90 or more (NR > 1 skips the header). If the journal cannot be read by your account, the line says unreadable and not a wrong number. The seal is a list of checksums, written last.
if journalctl -b -n 1 --no-pager -q 2>&1 | grep -q "No journal files"; then
errors="unreadable (run it with sudo)"
else
errors="$(journalctl -p err -b --no-pager -q 2> /dev/null | wc -l) error lines since boot"
fi
(cd "$out" && sha256sum 0*.txt summary.txt > manifest.sha256)4. Save the finished file
getopts reads the option -o, and any other option ends the script with the exit code 2. The folder is named evidence- and a time stamp, and KR_STAMP replaces the stamp, which makes a test repeatable. If the folder exists, the script refuses with the exit code 1, so a second run never overwrites evidence.
The finished file: kr-evidence.sh
kr-evidence.sh
#!/usr/bin/env bash
# kr-evidence.sh - collects a standard evidence bundle about this machine.
# It only READS the system. It writes into one new folder and nowhere else.
# Usage: bash kr-evidence.sh [-o PARENT-FOLDER] (default: the current folder)
# The folder is named evidence-DATE-TIME. For a fixed name set KR_STAMP, for example KR_STAMP=demo.
# Exit codes: 0 done, 1 the folder exists already or cannot be made, 2 a wrong option.
set -u
export LC_ALL=C PATH="$PATH:/usr/sbin:/sbin"
parent=.
while getopts ":o:" opt; do
case $opt in
o) parent=$OPTARG ;;
*) echo "usage: kr-evidence.sh [-o PARENT-FOLDER]"; exit 2 ;;
esac
done
stamp=${KR_STAMP:-$(date +%Y%m%d-%H%M%S)}
out="$parent/evidence-$stamp"
if [ -e "$out" ]; then echo "kr-evidence: $out exists, nothing written"; exit 1; fi
mkdir -p "$out" || exit 1
# show HEADING COMMAND: prints the heading and what the command printed.
# Exit code 0 or 1 is normal (1 often means "nothing found"). Any other code is a note.
show() {
local text code
echo "== $1 =="
text=$(bash -c "$2" 2>&1)
code=$?
[ -n "$text" ] && printf '%s\n' "$text"
if [ "$code" -gt 1 ]; then
echo "(not available here: exit code $code)"
elif [ -z "$text" ]; then
echo "(none)"
fi
echo
}
{
show "host and time" 'hostname; date -u +%Y-%m-%dT%H:%M:%SZ'
show "system" 'uname -srm; grep PRETTY_NAME /etc/os-release'
show "uptime" 'uptime'
show "state of systemd" 'systemctl is-system-running'
} > "$out/01-system.txt"
{
show "addresses" 'ip -br addr'
show "routes" 'ip route'
show "listening TCP ports" 'ss -tln'
show "name servers" 'grep -v "^#" /etc/resolv.conf'
} > "$out/02-network.txt"
{
show "CPUs and load" 'nproc; cat /proc/loadavg'
show "memory" 'free -m'
show "memory pressure" 'cat /proc/pressure/memory'
show "top 10 processes by CPU (names only, no arguments)" 'ps -eo pid,ppid,stat,pcpu,pmem,comm --sort=-pcpu | head -n 11'
show "zombies" "ps -eo pid,ppid,stat,comm | awk '\$3 ~ /^Z/'"
} > "$out/03-cpu-memory.txt"
{
show "space" 'df -hT -x tmpfs -x devtmpfs'
show "inodes" 'df -i -x tmpfs -x devtmpfs'
show "mounted read-only (real file systems)" 'findmnt -rn -O ro -t ext4,xfs,btrfs,vfat -o TARGET,FSTYPE,OPTIONS'
show "deleted files that are still open" 'lsof -nP +L1 2> /dev/null'
} > "$out/04-disk.txt"
{
show "failed units" 'systemctl --failed --no-pager --no-legend'
show "running services" 'systemctl list-units --type=service --state=running --no-pager --no-legend'
} > "$out/05-services.txt"
{
show "errors since boot (last 50)" 'journalctl -p err -b --no-pager -q -n 50'
} > "$out/06-errors.txt"
# the summary: seven fixed lines
addresses=$(ip -br addr | wc -l)
ports=$(ss -tln | tail -n +2 | wc -l)
zombies=$(ps -eo stat | grep -c '^Z')
full=$(df -P -x tmpfs -x devtmpfs | awk 'NR > 1 && $5 + 0 >= 90' | wc -l)
failed=$(systemctl --failed --no-pager --no-legend 2> /dev/null | grep -c .)
if journalctl -b -n 1 --no-pager -q 2>&1 | grep -q "No journal files"; then
errors="unreadable (run it with sudo)"
else
errors="$(journalctl -p err -b --no-pager -q 2> /dev/null | wc -l) error lines since boot"
fi
{
echo "kr-evidence $stamp"
echo "system: $(hostname), $(uname -sr)"
echo "network: $addresses interfaces, $ports listening TCP ports"
echo "cpu-memory: load $(cut -d' ' -f1 /proc/loadavg) on $(nproc) CPUs, $zombies zombies"
echo "disk: $full file systems at 90% or more"
echo "services: $failed failed unit(s)"
echo "errors: $errors"
} > "$out/summary.txt"
# a checksum list, so that anyone can see that the bundle was not changed later
(cd "$out" && sha256sum 0*.txt summary.txt > manifest.sha256)
cat "$out/summary.txt"
echo "bundle: $out"5. Run it as an ordinary user
The script needs no administrator rights, and that is part of the proof that it only reads. -o bundles puts the folder inside bundles.
cd ~/krlab/linux-operations
KR_STAMP=demo bash kr-evidence.sh -o bundleskr-evidence demo
system: krbox, Linux 6.8.0-149-generic
network: 2 interfaces, 2 listening TCP ports
cpu-memory: load 0.00 on 4 CPUs, 0 zombies
disk: 0 file systems at 90% or more
services: 0 failed unit(s)
errors: 0 error lines since boot
bundle: bundles/evidence-demoThe file summary.txt has seven lines. The script prints it and adds a last line that names the folder. A line has three parts:
Your numbers differ. Run it again with sudo for a fuller picture: some commands, such as lsof and the journal, show more to an administrator: an account outside the groups adm and systemd-journal reads only its own messages, so the errors line said 0 here. If your account cannot read the journal, the last line of the summary says unreadable, and not a number.
6. Look inside the bundle
ls bundles/evidence-demo
head -n 6 bundles/evidence-demo/02-network.txt01-system.txt
02-network.txt
03-cpu-memory.txt
04-disk.txt
05-services.txt
06-errors.txt
manifest.sha256
summary.txt
== addresses ==
lo UNKNOWN 127.0.0.1/8 ::1/128
enp5s0 UP 10.168.79.32/24 metric 100 fe80::1266:6aff:fe98:bc1b/64
== routes ==
default via 10.168.79.1 dev enp5s0 proto dhcp src 10.168.79.32 metric 100 7. Check the seal
sha256sum -c FILE reads a list of checksums and checks each file (lesson 9 of Part 2). Check the bundle, change one file as a tamperer would, and check again.
cd bundles/evidence-demo
sha256sum -c manifest.sha256 | tail -n 2
echo "edited" >> 03-cpu-memory.txt
sha256sum -c manifest.sha256 | grep -v OK
cd ../..06-errors.txt: OK
summary.txt: OK
sha256sum: WARNING: 1 computed checksum did NOT match
03-cpu-memory.txt: FAILEDThe seal shows the change, but it does not prevent it: someone who can edit the file can also edit the list. Copy the manifest to another machine, or write it down in the ticket, to make the seal count.
8. Use it on a machine with a fault
Plant the faulty service of lesson 9, collect a second bundle, and compare the services line. The lab script needs sudo.
sudo bash accesslab.sh up
sudo systemctl start kr-user
KR_STAMP=fault bash kr-evidence.sh -o bundles > /dev/null
grep -h "^services" bundles/evidence-demo/summary.txt bundles/evidence-fault/summary.txt
grep -A1 "failed units" bundles/evidence-fault/05-services.txt
sudo bash accesslab.sh downservices: 0 failed unit(s)
services: 1 failed unit(s)
== failed units ==
* kr-user.service loaded failed failed Runs as an account that does not existThe bundle names the failed unit (the script sets LC_ALL=C, so the mark in front of the name is a plain *). The person who takes over the case opens 05-services.txt and knows where to start, with no questions to the person on call.
9. Hand it over
tar -czf ARCHIVE -C FOLDER NAME packs a folder (lesson 9 of Part 1). Pack the bundle and write the checksum of the archive. The checksum goes in the ticket.
tar -czf evidence-fault.tar.gz -C bundles evidence-fault
sha256sum evidence-fault.tar.gz | cut -c1-1623416dedd31fdd84The first characters of your checksum differ, because the archive holds your machine's data.
Your turn
Use the kit as a person who has to hand over two bundles. There are no steps here.
- Make two bundles in a folder
handoverwith the stampsoneandtwo. - Run the script a third time with the stamp
one, and note the exit code. - Run the script with the option
-z, and note the exit code. - Add a line to
03-cpu-memory.txtof the bundletwo, and check its seal.
Remove the folders bundles and handover and the archive when you have finished.
Check yourself
Why does the script use set -u and not set -e?
On a sick machine some commands fail: a tool is missing, or the right is lacking. With set -e the script would stop at the first failure and the rest of the evidence would be lost. set -u still catches a spelling mistake in a variable name. Each failure is recorded as a note instead.
Why does the script refuse to write into a folder that exists?
Evidence must not be overwritten. A second run with the same name would replace the first record with a later state, and the first state would be lost. The refusal forces a new name.
Why is the ps list limited to command names?
The arguments of a process often hold a password, a token or a path with a user name. A bundle is shared with other people, so it must not contain them. If you need the arguments, collect them by hand and redact them.
A checksum list sits in the same folder as the files. What does it prove, and what does it not?
It proves that a file differs from what was listed: a mistake or a careless change shows. It does not stop a person who can edit both the file and the list. Keep a copy of the list somewhere else to make it proof.
Field notes
- Run the kit first, before you change anything. The first bundle is the state of the incident, and every repair changes it.
- Compare two bundles with
diff -ror a tool of your own. A baseline bundle taken on a healthy day makes the sick day clear. - Run it as an ordinary user and as an administrator. The user bundle is the one to ask of a customer, after the customer has read it. The administrator bundle shows more.
- Evidence that contains personal data or secrets is regulated. Keep bundles in a place with access control, and delete them when the case is closed. The names of the commands may be harmless, while the output is not.
- Write the time in UTC, and note whether the clock was right. A log without a trusted time is hard to match with other logs.