Part 2 · System administration · Lesson 13 · 55 minutes
Build audit.sh to check your own machine
- Write a read-only script that reports users, risky files, open ports, failed services and failed logins
- Explain what each finding means and what to do about it
- Test the script with problems that you plant yourself
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
Your team lead wants every new server checked the same way before it goes live, and the result kept as a dated report. "Do not give me a list of commands. Give me one script that I can run next month and compare." You build the script from the tools of this course, test it on faults that you plant yourself, and then use it on a folder and a log that she prepared. At the end, you can run it on a schedule (lesson 12).
Recall
In a script with "set -e", what does "grep error log.txt || true" do?
It stops grep from ending the script. grep exits with 1 when it finds nothing, and || true turns that into success, so the script carries on.
Which command lists the services that failed, in one line each, without a header?
systemctl --failed --no-legend --no-pager. Each line starts with a mark and the name of the unit.
The idea
The script answers eight questions. Each one is a place where machines drift from safe.
| Section | Tool (lesson) | Why it matters |
|---|---|---|
| File systems above 80 per cent | df -P (3) | A full disk stops services and logs. |
| Accounts with UID 0 | awk on /etc/passwd (6) | Only root should have the rights of root. |
| Users with a login shell | grep and cut on /etc/passwd (6) | Every account that can log in is a way in. |
Members of sudo or wheel | getent group (6) | Each member can become root. |
| SUID files | find -perm -4000 | A program that runs as its owner is a path to root if it has a flaw. |
| World-writable directories without the sticky bit | find -perm -0002 | Any user can delete or swap files there. |
| Listening ports | ss -tlnp | Each one is a door. |
| Failed services, failed logins | systemctl --failed (8), grep | A failed service is a fault. Failed logins show who is knocking. |
The script reads the machine and writes text. It changes nothing except its own report file:
- audit.sh → /etc/passwd: reads the accounts
- audit.sh → Files on disk: finds SUID files
- audit.sh → Open ports: lists them with ss
- audit.sh → Login log: counts failed logins
- audit.sh → Screen: tee shows the report
- audit.sh → audit-DATE.txt: tee saves it
A finding is not a verdict. You decide which lines are normal.
Worked example
1. Write the script
Save the script below as audit.sh in ~/krlab/linux-admin. Read first what its parts do:
- Setup.
roots=(...)is an array, a list of the folders to scan. Arguments replace it (if (( $# ))is true when there is at least one argument), and the script adds/rootwhen you run it as root:EUIDis your user ID, and(( EUID )) || roots+=(/root)runs its second part only whenEUIDis 0, which is root. Lesson 11 explainsif,for,(( ))and the tests of[[ ]].${AUDIT_OUT:-...}means "the variable, or this default", soAUDIT_OUTandAUDIT_LOGchange the report and the log without editing the script. The loop picks the log file that you may read:auth.log(Debian, Ubuntu) orsecure(Red Hat family). With no such file, the functionfailed_linesreads the journal of the SSH service, which is the only log on a system such as Fedora. - Users.
grep -vEdrops the lines of/etc/passwdthat match any of the three words (|means "or"): accounts withnologin,/bin/falseor/bin/syncas shell cannot log in.cut -d: -f1,3,7keeps the name, the UID and the shell. - Files.
-perm -4000finds a file whose SUID bit is set, and-perm -0002one that anybody may write to (a leading-means "all of these bits are set").-perm -1000is the sticky bit, and!means "not".-xdevkeepsfindon one file system.2>/dev/nullhides "permission denied", and|| truestopsset -efrom ending the script whenfindmeets an unreadable folder. - Ports.
ss -tlnplists sockets:-tfor TCP,-lfor those that listen,-nfor numbers and not names, and-pfor the process that owns each one (root only, so a normal user sees an empty column). - Disks.
df -Pprints one line for each file system in a fixed format.$5 + 0turns81%into the number 81. - Text in variables.
<<< "$lines"(a here-string) gives the text of a variable to a command as its input."${roots[@]}"is every folder as its own word, and${roots[*]}is all of them as one text.printf '\n== %s ==\n'prints a blank line and a heading:%sis the place of the text. - Last lines.
teecopies its input to the screen and to a file, so the report is shown and saved.
audit.sh
#!/usr/bin/env bash
# audit.sh - read-only report on this machine. It writes only the report file.
# usage: ./audit.sh [DIRECTORY...] (default: the system folders below)
set -euo pipefail
roots=(/usr /opt /srv /etc /var /tmp /home)
(( EUID )) || roots+=(/root)
if (( $# )); then
roots=("$@")
fi
out=${AUDIT_OUT:-$HOME/krlab/linux-admin/audit-$(date +%F).txt}
log=${AUDIT_LOG:-}
if [[ -z $log ]]; then
for f in /var/log/auth.log /var/log/secure; do
if [[ -r $f ]]; then log=$f; break; fi
done
fi
# the lines of failed logins: from the log file, or else from the journal
failed_lines() {
if [[ -n $log ]]; then
grep "Failed password" "$log"
else
journalctl -u ssh -u sshd --no-pager 2>/dev/null | grep "Failed password"
fi
}
section() { printf '\n== %s ==\n' "$1"; }
report() {
echo "Audit of $(hostname) on $(date '+%F %T') by $(id -un)"
echo "System: $(. /etc/os-release; echo "$PRETTY_NAME"), kernel $(uname -r)"
echo "Scanned: ${roots[*]}"
section "File systems above 80 per cent"
df -P | awk 'NR > 1 && $5 + 0 > 80 { print $6, $5 }'
section "Accounts with UID 0"
awk -F: '$3 == 0 { print $1 }' /etc/passwd
section "Users with a login shell"
grep -vE 'nologin|/bin/false|/bin/sync' /etc/passwd | cut -d: -f1,3,7
section "Members of the sudo or wheel group"
getent group sudo wheel | awk -F: '{ print $1 ": " $4 }' || true
section "SUID files"
find "${roots[@]}" -xdev -type f -perm -4000 2>/dev/null | sort || true
section "World-writable directories without the sticky bit"
find "${roots[@]}" -xdev -type d -perm -0002 ! -perm -1000 2>/dev/null | sort || true
section "Listening TCP ports (address:port, process)"
ss -tlnp | awk 'NR > 1 { print $4, $6 }' | sort -u
section "Failed services"
systemctl --failed --no-legend --no-pager | awk '{ print $2 }' || true
section "Failed logins"
echo "log: ${log:-the journal of ssh}"
lines=$(failed_lines || true)
echo "failures: $(grep -c . <<< "$lines" || true)"
if [[ -z $lines && -z $log ]]; then
echo "none found (run with sudo, or join the group adm, to read the logs)"
elif [[ -z $lines ]]; then
echo "none found"
else
grep -oE "from [0-9a-fA-F.:]+" <<< "$lines" | cut -d' ' -f2 | sort | uniq -c | sort -rn | head -n 5
fi
}
report | tee "$out"
echo
echo "Report saved to $out"2. Run it
Make it executable and run it. It takes a second or two. The output below comes from a test virtual machine, shortened.
chmod +x ~/krlab/linux-admin/audit.sh
~/krlab/linux-admin/audit.shAudit of krbox on 2026-11-21 19:52:22 by you
System: Ubuntu 24.04.5 LTS, kernel 6.8.0-149-generic
Scanned: /usr /opt /srv /etc /var /tmp /home
== File systems above 80 per cent ==
== Accounts with UID 0 ==
root
== Users with a login shell ==
root:0:/bin/bash
ubuntu:1000:/bin/bash
you:1001:/bin/bash
== Members of the sudo or wheel group ==
sudo: ubuntu,you
== SUID files ==
/usr/bin/at
/usr/bin/chfn
/usr/bin/chsh
/usr/bin/fusermount3
/usr/bin/gpasswd
== World-writable directories without the sticky bit ==
== Listening TCP ports (address:port, process) ==
0.0.0.0:22
127.0.0.53%lo:53
127.0.0.54:53
[::]:22
== Failed services ==
== Failed logins ==
log: the journal of ssh
failures: 0
none found (run with sudo, or join the group adm, to read the logs)
Report saved to /home/you/krlab/linux-admin/audit-2026-11-21.txtYours is different. The SUID list has 15 lines on this machine, and only the first five are shown. The port 22 is the SSH server: 0.0.0.0 and [::] mean that it listens on every address. A second run on the same day replaces the report, because the file name holds the date.
3. Read the findings
- Disks: an empty section is the goal. A line is a file system to clean (lesson 3).
- UID 0: only
root. Any other name is an alarm (lesson 6). - Users and sudo members: expect people you know. An unknown name needs an answer.
- SUID: the names above are normal. A file in
/tmpor a home folder is not. - World-writable: an empty section is the goal. Fix an entry with
chmod +torchmod o-w. - Ports:
0.0.0.0and[::]are open to the network,127.0.0.1and the127.0.0.53of the resolver are local. Close what you do not use. - Failed services: a name here is a service to repair with lesson 8.
- Failed logins: a fast-growing count from one address is a guessing attack.
4. Plant problems and find them
A test must be able to fail. Make a folder with a SUID file and an open directory, and scan only that folder, by giving it as an argument.
cd ~/krlab/linux-admin
mkdir -p audit-test/drop audit-test/inbox
cp /bin/true audit-test/mytool && chmod u+s audit-test/mytool
chmod 777 audit-test/drop
chmod 1777 audit-test/inbox
./audit.sh ~/krlab/linux-admin/audit-test | sed -n '/== SUID/,/== Listening/p'== SUID files ==
/home/you/krlab/linux-admin/audit-test/mytool
== World-writable directories without the sticky bit ==
/home/you/krlab/linux-admin/audit-test/drop
== Listening TCP ports (address:port, process) ==The script found the SUID file and the open directory drop, but not inbox, which has the sticky bit. sed -n '/A/,/B/p' prints the lines from the first match of A to the first match of B. Fix the faults with chmod u-s and chmod 755, and run it again: both sections are empty.
5. Test the failed-login part
Point the script at the fixed log from lesson 11 (~/krlab/linux-admin/sh/auth.log) with the variable AUDIT_LOG. grep -A4 prints the matching line and the four lines after it.
AUDIT_LOG=~/krlab/linux-admin/sh/auth.log ./audit.sh ~/krlab/linux-admin/audit-test | grep -A4 'Failed logins'== Failed logins ==
log: /home/you/krlab/linux-admin/sh/auth.log
failures: 6
5 203.0.113.50
1 198.51.100.7If you cannot read the real log, the script reads the journal, and says so when it finds nothing. With sudo it reads the real log, and the process names of the ports appear as well. sudo changes HOME to /root on Ubuntu, so the report goes to the home folder of root. Give the place yourself: sudo AUDIT_OUT=$HOME/krlab/linux-admin/audit-root.txt ./audit.sh.
Your turn
Your lead prepared a folder and a login log from a server that you do not have. Save the log as login.log in ~/krlab/linux-admin/audit-task, after you run the block below, which builds the folder with fixed modes. The block is not the task.
mkdir -p ~/krlab/linux-admin/audit-task && cd ~/krlab/linux-admin/audit-task
mkdir -p bin srv/uploads srv/shared srv/scratch
printf '#!/bin/sh\necho ok\n' > bin/helper
cp bin/helper bin/old-helper
cp bin/helper bin/report
chmod 4755 bin/helper
chmod 4750 bin/old-helper
chmod 755 bin/report
chmod 777 srv/uploads srv/scratch
chmod 1777 srv/sharedaudit-task/login.log
Nov 21 10:01:02 krbox sshd[2101]: Failed password for root from 198.51.100.23 port 41001 ssh2
Nov 21 10:01:05 krbox sshd[2103]: Failed password for root from 198.51.100.23 port 41003 ssh2
Nov 21 10:01:09 krbox sshd[2105]: Failed password for invalid user git from 198.51.100.23 port 41005 ssh2
Nov 21 10:02:30 krbox sshd[2110]: Accepted publickey for dana from 192.0.2.44 port 52100 ssh2
Nov 21 10:03:11 krbox sshd[2118]: Failed password for dana from 192.0.2.44 port 52111 ssh2
Nov 21 10:04:20 krbox sshd[2125]: Failed password for invalid user ubuntu from 203.0.113.9 port 33001 ssh2
Nov 21 10:04:24 krbox sshd[2127]: Failed password for invalid user pi from 203.0.113.9 port 33003 ssh2
Nov 21 10:05:41 krbox sshd[2133]: Failed password for root from 198.51.100.23 port 41009 ssh2
Nov 21 10:05:44 krbox sshd[2135]: Failed password for root from 198.51.100.23 port 41011 ssh2
Nov 21 10:09:00 krbox sshd[2150]: Accepted password for dana from 192.0.2.44 port 52200 ssh2Save this sample of an SSH server file in the same folder:
audit-task/sshd_config.task
# sample sshd_config of krbox
#PermitRootLogin no
Port 22
PermitRootLogin yes
PasswordAuthentication noThere are no steps here. Audit the folder audit-task with your audit.sh, and read the log login.log with it. Then add a check of your own to your copy of audit.sh: a section "Root login over SSH" that prints each line of the file named in SSHD_CONF (default /etc/ssh/sshd_config) that sets PermitRootLogin to yes. A line that starts with # is a comment and does not count. Run it with SSHD_CONF=sshd_config.task. Then answer from the report.
Last, fix the faults without breaking the site: the helper programs need no SUID bit, and uploads and scratch need the sticky bit but must stay writable. Run the audit again. The SUID section and the world-writable section must both be empty. Change yes to no in sshd_config.task, and your new section must be empty too. Then write the cron line that runs the audit every Monday at 07:00 with AUDIT_OUT set to a file of your own.
Check yourself
Why does the script scan with "find ... 2>/dev/null"? What could you miss?
Without it, the report fills with "Permission denied" lines. The cost is that folders you may not enter are skipped without a word. Run the script with sudo before you trust a clean report.
The script is "read-only", but it writes a file. Why is that acceptable?
It writes only the report, in your own folder. A tool that audits a machine must not change what it examines.
Your report lists "0.0.0.0:631". What do you do?
Find the owner with ss -tlnp as root. Port 631 is usually the printing service. If you do not print from this machine, stop and disable the service (lesson 8), or bind it to 127.0.0.1.
The section "Accounts with UID 0" lists a name that is not root. Is it a fault in the script?
No, it is the finding. Two accounts with UID 0 are two ways to be root, and an attacker often adds one. Check /var/log/auth.log for the time of its creation, as in the scenario test.
Field notes
- Keep the reports. A
diffof last month's and today's shows a new SUID file, account or port, which is the finding that matters. - Add checks as you learn them: keys in
authorized_keysand files in/etcthat anyone can write. The CIS Benchmark for your distribution is a good list to follow. - The script finds known kinds of faults, not malware. For that, use a file-integrity tool and the process checks of lesson 5.