#!/bin/sh
# DF-0761 run: orchestrate the securelevel-bypass test.
#
# Pre-conditions (enforced here):
#   - guest freshly reset to `with-src` baseline (securelevel=-1, no ipfw3)
#   - this script runs as root inside the guest (we test a root@securelevel>=3
#     threat model — see VERDICT.md)
#
# Sequence:
#   1. kldload ipfw3          (only possible at securelevel<1)
#   2. add a default rule via the ipfw3 IP_FW_X path (gives FLUSH something to do)
#   3. raise kern.securelevel -> 3
#   4. run ./df0761  which issues setsockopt(IP_FW_X, FLUSH) at securelevel=3
#      - unpatched: returns 0 (BYPASS)
#      - patched  : returns EPERM (GATED)
#
# NOTE: securelevel cannot be lowered in a running kernel, so this script MUST
# be the only consumer of the guest since the last `vm.sh reset with-src`.
set -u
cd "$(dirname "$0")"

echo "=== [0] environment ==="
uname -a
id
sysctl kern.securelevel

echo "=== [1] load ipfw3 module ==="
# ipfw3 defaults to DENY when loaded (sys/net/ipfw3/ip_fw3.c:1468).  That
# would immediately black-hole our ssh session.  Flip the pfil tunable to
# ACCEPT first so loading ipfw3 does not cut our control channel.  This
# does not affect the securelevel-bypass test at all (the test exercises the
# IP_FW_X dispatch path, which is gated by securelevel independent of the
# default policy).
sysctl net.filters_default_to_accept=1
if ! kldstat -m ipfw3 >/dev/null 2>&1; then
	kldload ipfw3 && echo "kldload ipfw3 OK"
else
	echo "ipfw3 already loaded"
fi
kldstat | grep ipfw || true

echo "=== [2] seed a rule so FLUSH is meaningful (via the IP_FW_X path) ==="
# We use the in-tree `ipfw3` CLI to add a benign allow-all rule.  This itself
# goes through IP_FW_X — it will succeed because securelevel is still <3 here.
ipfw3 add 65000 allow ip from any to any 2>&1 || echo "ipfw3 add rc=$?"
ipfw3 show 2>&1 | head -5 || true

echo "=== [3] raise kern.securelevel to 3 (network-immutable gate) ==="
sysctl kern.securelevel=3
sysctl kern.securelevel

echo "=== [4] attempt IP_FW_X FLUSH at securelevel=3 (the bypass probe) ==="
./df0761
RC=$?
echo "df0761 exit code: $RC"
echo "=== run.sh done ==="
