#!/bin/sh
# DF-0220 manufactured pre-reseed window experiment (run as ROOT on the guest).
#
# Proves, with live kernel state, the exact mechanism DF-0220 describes and
# characterizes what the window emits — while showing that its precondition
# (reseed_cnt==0 AND pool[0].bytes<96 at an UNLIMITED read) can only be
# manufactured with root /dev/kmem access, never observed naturally by an
# unprivileged user on this kernel (rand_initialize pre-feeds every state's
# pool[0] with ~15 KB before any read).
#
# Uses cpu2's state (idle); reads pinned with `usched :3` (= cpu2).
set -e
SYM=$(nm /boot/kernel/kernel | awk '/ csprng_pcpu$/ {print $1}')
SYM=0x$SYM
CPU=2; USCHED_CPU=3
cd "$(dirname "$0")"
echo "== symbol csprng_pcpu = $SYM =="

echo; echo "== [0] all states BEFORE experiment (expect: every state keyed, reseed_cnt>=1; cpu0 frozen at 1 per DF-5766) =="
./csprng_force_zero $SYM info

echo; echo "== [1] baseline: rand_mode=csprng, 4x32B /dev/urandom pinned to cpu$CPU (pre-force; expect non-zero, non-deterministic) =="
sysctl kern.rand_mode=csprng >/dev/null
usched :$USCHED_CPU dd if=/dev/urandom bs=32 count=4 2>/dev/null | hexdump -C

echo; echo "== [2] FORCE state[$CPU] into pre-reseed condition =="
./csprng_force_zero $SYM force $CPU

echo; echo "== [3] window read #1: 4x32B /dev/urandom pinned to cpu$CPU (expect: block1 = 00*32 fixed point, then deterministic rekey stream) =="
usched :$USCHED_CPU dd if=/dev/urandom bs=32 count=4 2>/dev/null | hexdump -C

echo; echo "== [4] FORCE again and repeat the exact same read (expect: byte-identical output => deterministic) =="
./csprng_force_zero $SYM force $CPU
usched :$USCHED_CPU dd if=/dev/urandom bs=32 count=4 2>/dev/null | hexdump -C

echo; echo "== [5] FORCE again; read in default mixed mode (expect: NON-zero — IBAA masks the zero csprng contribution) =="
sysctl kern.rand_mode=mixed >/dev/null
./csprng_force_zero $SYM force $CPU
usched :$USCHED_CPU dd if=/dev/urandom bs=32 count=4 2>/dev/null | hexdump -C
sysctl kern.rand_mode=csprng >/dev/null

echo; echo "== [6] self-heal watch: state[$CPU] should reseed within seconds as rand_thread refills pool[0] =="
i=0
while [ $i -lt 20 ]; do
    ./csprng_force_zero $SYM check $CPU
    sleep 1
    i=$((i+1))
done

echo; echo "== [7] all states AFTER experiment =="
./csprng_force_zero $SYM info
echo "== restoring default rand_mode =="
sysctl kern.rand_mode=mixed
