Part 3 · Networking and hardening · Lesson 10 · 45 minutes
Build a hardening check that proves your settings
- Write a script that compares the settings of a server with the rules of this part
- Print ok or FAIL for each rule and end with an exit code that a pipeline can use
- Run the check on a sample, break it on purpose and repair it
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 says: "After every change I want proof that the server is still hardened. Not a story: a command that prints ok or FAIL for each rule, and fails as a whole when one rule fails." You have the rules from this part: SSH, the firewall, the database, the web folder and the kernel. You turn them into one script. To keep the lesson safe and repeatable, the script reads a sample tree of settings first, and only later your real system.
Recall
Two files of /etc/ssh/sshd_config.d set PermitRootLogin to different values. Which one counts?
The first value that sshd reads wins, and files are read in name order. A file 00-legacy.conf beats 01-krlab.conf, as the test of lesson 4 shows.
Which settings keep a kernel parameter after a reboot?
A line NAME = VALUE in a file *.conf in /etc/sysctl.d/. sysctl -w changes only the running kernel (lesson 9).
The idea
A check has three parts: read a setting, compare it with the wanted value, and report. A set of checks becomes a tool when its result is machine-readable. The exit code is that result: 0 when every check passes, 1 when one fails. A pipeline or a timer can then stop on a failure, with no person to read the text.
- Read the setting → Compare: the value that the system uses
- Compare → Report: ok, or FAIL with both values
- Report → Count: every FAIL adds one
- Count → Exit code: 0 only when none failed
- Check script → ssh files: first value wins
- Check script → nftables.conf: reads the policy word
- Check script → mariadb .cnf: last value wins
- Check script → sysctl.d files: last value wins
- Check script → Report: ok or FAIL for each rule
Two rules about "the value that the system uses" come from earlier lessons. For sshd the first value wins. For sysctl and MariaDB files the last value wins. A check that reads only one file, or the wrong end of the list, gives a false ok. The script of this lesson reads the files, so it can run on any folder that has the same layout. The web folder is the one exception: the script reads it with find, not from a file. Here are the ten rules:
| Check | Wanted | Lesson |
|---|---|---|
PermitRootLogin | no | 4 |
PasswordAuthentication | no | 4 |
KbdInteractiveAuthentication | no | 4 |
| Policy of the input chain | drop | 3 |
bind-address of MariaDB | 127.0.0.1 | 8 |
| Entries of the web folder that others can write | 0 | 8 |
kernel.randomize_va_space | 2 | 9 |
net.ipv4.tcp_syncookies | 1 | 9 |
net.ipv4.conf.all.accept_redirects | 0 | 9 |
net.ipv4.conf.all.send_redirects | 0 | 9 |
Worked example
1. Build the sample tree
Make the lab folder, and save the script sample.sh in it. It builds a small tree of settings in a folder, in the same places as a real server (etc/ssh, etc/nftables.conf, etc/mysql, etc/sysctl.d, var/www/html). bash sample.sh FOLDER good builds a hardened tree, and weak plants five faults, among them a legacy SSH file that is read first.
mkdir -p ~/krlab/linux-advanced/check && cd ~/krlab/linux-advanced/checksample.sh
#!/bin/bash
# sample.sh - builds a small sample of a server's settings in a folder.
# Usage: bash sample.sh FOLDER good|weak
root=$1
state=${2:-good}
rm -rf "$root"
mkdir -p "$root/etc/ssh/sshd_config.d" "$root/etc/mysql/mariadb.conf.d" "$root/etc/sysctl.d" "$root/var/www/html/uploads"
printf 'Port 22\nPermitRootLogin prohibit-password\n' > "$root/etc/ssh/sshd_config"
printf 'PermitRootLogin no\nPasswordAuthentication no\nKbdInteractiveAuthentication no\n' > "$root/etc/ssh/sshd_config.d/01-krlab.conf"
printf 'table inet krlab {\n chain input {\n type filter hook input priority 0; policy drop;\n }\n}\n' > "$root/etc/nftables.conf"
printf '[mysqld]\nbind-address = 127.0.0.1\n' > "$root/etc/mysql/mariadb.conf.d/99-krlab.cnf"
printf 'kernel.randomize_va_space = 2\nnet.ipv4.tcp_syncookies = 1\nnet.ipv4.conf.all.accept_redirects = 0\nnet.ipv4.conf.all.send_redirects = 0\n' > "$root/etc/sysctl.d/90-krlab.conf"
echo "<h1>shop</h1>" > "$root/var/www/html/index.html"
chmod 750 "$root/var/www/html" "$root/var/www/html/uploads"
chmod 640 "$root/var/www/html/index.html"
if [ "$state" = weak ]; then
printf 'PermitRootLogin yes\nPasswordAuthentication yes\nKbdInteractiveAuthentication yes\n' > "$root/etc/ssh/sshd_config.d/00-legacy.conf"
sed -i 's/policy drop/policy accept/' "$root/etc/nftables.conf"
sed -i 's/127.0.0.1/0.0.0.0/' "$root/etc/mysql/mariadb.conf.d/99-krlab.cnf"
sed -i 's/accept_redirects = 0/accept_redirects = 1/' "$root/etc/sysctl.d/90-krlab.conf"
chmod 777 "$root/var/www/html/uploads"
fibash sample.sh lab good
find lab -type f | sortlab/etc/mysql/mariadb.conf.d/99-krlab.cnf
lab/etc/nftables.conf
lab/etc/ssh/sshd_config
lab/etc/ssh/sshd_config.d/01-krlab.conf
lab/etc/sysctl.d/90-krlab.conf
lab/var/www/html/index.html2. Read one setting the way the system does
The function setting prints the first or the last value of a key. cat joins the files in the order that you give. sed -nE 's/PATTERN//p' prints only the lines that the pattern matched, and the pattern removes the key and the =, so that only the value is left. head -n 1 keeps the first line and tail -n 1 the last. shift 2 drops the first two arguments (mode and key), so that "$@" holds the file names. Type it into your shell and try it on the sshd files (the glob *.conf sorts by name).
setting() {
local mode=$1 key=$2
shift 2
cat "$@" 2> /dev/null | sed -nE "s/^[[:space:]]*$key[[:space:]]*=?[[:space:]]*//p" | if [ "$mode" = first ]; then head -n 1; else tail -n 1; fi
}
setting first PermitRootLogin lab/etc/ssh/sshd_config.d/*.conf lab/etc/ssh/sshd_config
setting last net.ipv4.tcp_syncookies lab/etc/sysctl.d/*.confno
1The main file says prohibit-password, but the drop-in comes first and says no. That is the value that sshd uses.
3. Compare and report
The function check NAME WANTED FOUND prints ok when the two values are equal. Otherwise it prints FAIL with both values, and counts the failure. A missing setting is reported as nothing, and it fails: an absent rule is not a passed rule. The firewall check reads the word after policy in etc/nftables.conf, and the web check counts the entries that find -perm -o+w lists (the same test as lesson 8).
check() {
total=$((total + 1))
if [ "$3" = "$2" ]; then
echo "ok $1"
else
echo "FAIL $1 (wanted '$2', found '${3:-nothing}')"
fails=$((fails + 1))
fi
}4. Save the finished file
The script ends with the line [ "$fails" -eq 0 ]. A command that is false has the exit code 1, and as the last command of the script it gives the script that code. Save the finished file as krharden-check.sh.
The file uses some shell syntax that the steps above did not need. Read this table before you save it.
| Syntax | What it does |
|---|---|
root=${1:-} | $1 is the first argument of the script. After :- comes the value to use when there is none, here nothing. With no folder given, root is empty and the paths point to the real system. |
ssh=(A B) | Makes a list of words (an array) named ssh. |
"${ssh[@]}" | Every word of the list, each as one argument. The glob *.conf inside the list is expanded when the list is made. |
[ -z "$v" ] | True when the text in v is empty. |
A && B | Runs B only when A succeeded. |
local v | Keeps the variable v inside its function. |
sysval NAME | Like setting last, for the sysctl files. When no file names the rule and root is empty (the real system), it asks the running kernel with sysctl -n NAME, which prints only the value. |
The finished file: krharden-check.sh
krharden-check.sh
#!/usr/bin/env bash
# krharden-check.sh - checks the settings of a server against the rules of Part 3.
# Usage: bash krharden-check.sh [ROOT] ROOT is the folder that holds etc/ and var/ (default: the real system).
# It only reads. Exit code: 0 when every check passes, 1 when one fails.
root=${1:-}
total=0
fails=0
# setting first|last KEY FILE...: the first or the last value of a line "KEY value" or "KEY = value"
setting() {
local mode=$1 key=$2
shift 2
cat "$@" 2> /dev/null | sed -nE "s/^[[:space:]]*$key[[:space:]]*=?[[:space:]]*//p" | if [ "$mode" = first ]; then head -n 1; else tail -n 1; fi
}
# check NAME WANTED FOUND: prints ok or FAIL for one rule
check() {
total=$((total + 1))
if [ "$3" = "$2" ]; then
echo "ok $1"
else
echo "FAIL $1 (wanted '$2', found '${3:-nothing}')"
fails=$((fails + 1))
fi
}
ssh=("$root"/etc/ssh/sshd_config.d/*.conf "$root"/etc/ssh/sshd_config)
check "ssh PermitRootLogin" no "$(setting first PermitRootLogin "${ssh[@]}")"
check "ssh PasswordAuthentication" no "$(setting first PasswordAuthentication "${ssh[@]}")"
check "ssh KbdInteractiveAuthentication" no "$(setting first KbdInteractiveAuthentication "${ssh[@]}")"
policy=$(grep -o 'policy [a-z]*' "$root/etc/nftables.conf" 2> /dev/null | head -n 1 | cut -d' ' -f2)
check "firewall input policy" drop "$policy"
check "database bind-address" 127.0.0.1 "$(setting last bind-address "$root"/etc/mysql/mariadb.conf.d/*.cnf)"
writable=$(find "$root/var/www/html" -perm -o+w 2> /dev/null | wc -l)
check "web entries that others can write" 0 "$writable"
# sysval NAME: the last value in the sysctl files; on the real system, when no file names it, the live value
sysctl=("$root"/etc/sysctl.d/*.conf)
sysval() {
local v
v=$(setting last "$1" "${sysctl[@]}")
if [ -z "$v" ] && [ -z "$root" ]; then v=$(sysctl -n "$1" 2> /dev/null); fi
echo "$v"
}
check "kernel.randomize_va_space" 2 "$(sysval kernel.randomize_va_space)"
check "net.ipv4.tcp_syncookies" 1 "$(sysval net.ipv4.tcp_syncookies)"
check "net.ipv4.conf.all.accept_redirects" 0 "$(sysval net.ipv4.conf.all.accept_redirects)"
check "net.ipv4.conf.all.send_redirects" 0 "$(sysval net.ipv4.conf.all.send_redirects)"
echo "failed: $fails of $total"
[ "$fails" -eq 0 ]5. Run it on the good tree
bash krharden-check.sh lab
echo "exit code: $?"ok ssh PermitRootLogin
ok ssh PasswordAuthentication
ok ssh KbdInteractiveAuthentication
ok firewall input policy
ok database bind-address
ok web entries that others can write
ok kernel.randomize_va_space
ok net.ipv4.tcp_syncookies
ok net.ipv4.conf.all.accept_redirects
ok net.ipv4.conf.all.send_redirects
failed: 0 of 10
exit code: 06. Run it on the weak tree, and repair one fault
The weak tree has the legacy file 00-legacy.conf, which says yes and is read first, although the good file 01-krlab.conf is also there. Remove the legacy file and run the check again.
bash sample.sh lab weak
bash krharden-check.sh lab
echo "exit code: $?"
rm lab/etc/ssh/sshd_config.d/00-legacy.conf
bash krharden-check.sh lab | grep -E "ssh|failed"FAIL ssh PermitRootLogin (wanted 'no', found 'yes')
FAIL ssh PasswordAuthentication (wanted 'no', found 'yes')
FAIL ssh KbdInteractiveAuthentication (wanted 'no', found 'yes')
FAIL firewall input policy (wanted 'drop', found 'accept')
FAIL database bind-address (wanted '127.0.0.1', found '0.0.0.0')
FAIL web entries that others can write (wanted '0', found '1')
ok kernel.randomize_va_space
ok net.ipv4.tcp_syncookies
FAIL net.ipv4.conf.all.accept_redirects (wanted '0', found '1')
ok net.ipv4.conf.all.send_redirects
failed: 7 of 10
exit code: 1
ok ssh PermitRootLogin
ok ssh PasswordAuthentication
ok ssh KbdInteractiveAuthentication
failed: 4 of 10One file made three checks fail, and one removal fixed both. Each FAIL line has four parts:
7. Point it at the real system
With no argument the script reads the real files, /etc and /var/www/html. It only reads. Lesson 8 closed the web folder to your own account, so use sudo: without it, find cannot look in and counts 0, which is a false ok.
sudo bash krharden-check.sh | tail -n 1The last line is failed: N of 10, with your N. The result depends on which lessons you kept on your practice system: a check for a rule that you removed in a clean-up prints FAIL, and that is correct.
The script also has a limit. A good value is often a default of the kernel or of the program, and no file names it. For the four kernel rules, sysval (step 4) therefore asks the running kernel when no file in /etc/sysctl.d names the rule, so a stock randomize_va_space of 2 passes. The other rules read files only. If no file names PermitRootLogin or the firewall policy, the check prints FAIL with found 'nothing', even when the live setting is good. A real audit also reads the live state: sudo sshd -T and sudo nft list ruleset.
Your turn
Make a new tree with bash sample.sh task good. Break it in three ways, with no help from the script. Then run the check, read it, and repair each fault until the check passes.
- Add a file
task/etc/ssh/sshd_config.d/00-test.confwith the linePasswordAuthentication yes. - Change
net.ipv4.tcp_syncookies = 1to0in the sysctl file of the tree. - Make the file
task/var/www/html/index.htmlwritable for everybody (chmod 666).
Check yourself
Why does the script read files and not run sshd -T?
Files can be copied into a sample folder, so the lesson gives the same result on every machine and nothing real is at risk. On a real server the live value matters too: sshd -T and sysctl -n show what the program uses now, and a changed file that was never reloaded can still say ok. A real audit checks both. Step 7 shows the one place where the script already asks the live kernel.
Why is a missing setting a FAIL and not an ok?
A rule that is not in the files means that the program uses its default, which may be the weak value. An audit passes only what it can prove.
Why does the script end with an exit code and not only with text?
A person reads text. A timer, a pipeline or another script reads the exit code, so the check can stop a release or send an alarm with no person involved.
The check reads sshd files first to last. Why is that wrong for sysctl?
sshd takes the first value of a key. sysctl loads the files in order, and a later value replaces an earlier one, so the last value wins. A check must copy the rule of the program that it audits.
Field notes
- Keep the check in the same repository as the rules, and run it after every change and on a timer. A control that nobody runs proves nothing.
- Established tools do this at scale. The CIS Benchmarks list the rules, and scanners such as Lynis and OpenSCAP check them. Writing a small check first teaches you what those tools read.
- Print the wanted value with every FAIL, as here. A person who sees only
FAILmust search for the rule. - Add rules slowly. A check with 200 rules that always fails is ignored; a check with 10 that always passes is trusted.
- Store the output with a date, and compare it with the last run. A rule that turns from ok to FAIL tells you when the change happened.