Unit 12: Auditing and hardening · Lesson 4 of 7 · 22 min

Scripting the audit

Turn your checks into a small bash script that prints PASS or FAIL with evidence.

mission

You are
You are making the audit repeatable.
Situation
Fixes will be applied next week. You want to rerun every check in seconds and show which ones now pass.
Goal
Write audit.sh with one line per check and run it.
Hand in
audit.sh and its output saved to report.txt.

From checklist to script

  1. CheckOne command per control
  2. PASS or FAILOne line per check
  3. ReportRedirect to a dated file
  4. ScheduleRun it again tomorrow
01

Write the script

Each check runs a command, then prints PASS or FAIL with the evidence. The heredoc writes everything up to EOF into the file.

learner@root-lab
cat > audit.sh <<'EOF'
#!/bin/bash
uid0=$(awk -F: '$3 == 0' /etc/passwd | wc -l)
[ "$uid0" -eq 1 ] && echo "PASS uid0" || echo "FAIL uid0: $uid0 accounts have UID 0"
suid=$(find /usr/local -type f -perm -4000 2>/dev/null)
[ -z "$suid" ] && echo "PASS suid" || echo "FAIL suid: $suid"
ww=$(find /etc /opt /usr/local -type f -perm -0002 2>/dev/null)
[ -z "$ww" ] && echo "PASS writable" || echo "FAIL writable: $ww"
grep -q '^PermitRootLogin no' /etc/ssh/sshd_config && echo "PASS root-login" || echo "FAIL root-login"
grep -q '^PasswordAuthentication no' /etc/ssh/sshd_config && echo "PASS passwords" || echo "FAIL passwords"
ss -tlnH | grep -q ':4444 ' && echo "FAIL port-4444" || echo "PASS port-4444"
EOF
02

Make it private and run it

learner@root-lab
chmod 700 audit.sh
./audit.sh
FAIL uid0: 2 accounts have UID 0
FAIL suid: /usr/local/bin/backup-helper
FAIL writable: /opt/scripts/rotate.sh
FAIL root-login
FAIL passwords
FAIL port-4444

you should see Six checks, six failures. Each line names its evidence.

defender tip 700 keeps the script and its findings to you, the same idea as umask 077.

03

Save the result

learner@root-lab
./audit.sh > report.txt
grep -c FAIL report.txt
6

you should see Run it again after the fixes and the count should drop to zero.

Manual and scripted

By hand
awk ... /etc/passwd
find ... -perm -4000
find ... -perm -0002
grep ... sshd_config

Slow, easy to skip one

Scripted
./audit.sh > report.txt

Same checks every time

What a defender takes away

  1. 1Every manual check can become one script line.
  2. 2Print evidence, not just PASS or FAIL.
  3. 3Rerun after fixes to prove they worked.

Questions

0 of 2 solved

Answer each one from what you find on your lab machine.

  1. Show hint

    ./audit.sh | grep -c FAIL

  2. Show hint

    Read the uid0 line.