Exploit database

GH-e7dc15685a35f12d6d762114af72a264

keraattin/mongobleed-detector-cve-2025-14847

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2025-14847

23 sources

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

Repository files3
keraattin/mongobleed-detector-cve-2025-14847Revision 4f298d96dee0

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

mongobleed_detector.py

Suggested starting filePython · 30,791 bytes
#!/usr/bin/env python3
"""
=============================================================================
MongoBleed Scanner v1.3.0 - Multi-Target Vulnerability Scanner
=============================================================================
CVE-2025-14847 - MongoDB Memory Leak Vulnerability

A professional scanning tool for detecting MongoBleed vulnerability across
multiple MongoDB instances.

Features:
- Multi-target scanning (comma-separated or file input)
- Version detection and vulnerability assessment
- zlib compression status detection
- Clean, readable output with detailed findings
- Export results to file (TXT, JSON, CSV)

Usage:
    python scanner.py -t 192.168.1.100
    python scanner.py -t 192.168.1.100,192.168.1.101:27018
    python scanner.py -f targets.txt
    python scanner.py -t 192.168.1.100 -o results.json

=============================================================================
LEGAL DISCLAIMER:
This tool is intended for authorized security testing and educational
purposes only. Users must obtain proper authorization before scanning
any systems they do not own or have explicit permission to test.
Unauthorized access to computer systems is illegal.
=============================================================================
"""

import socket
import struct
import sys
import argparse
import json
import csv
from datetime import datetime
from typing import List, Optional, Tuple
from dataclasses import dataclass, asdict
from pathlib import Path


# =============================================================================
# SECTION 1: CONSTANTS
# =============================================================================

VERSION = "1.3.0"
DEFAULT_PORT = 27017
SOCKET_TIMEOUT = 5

# MongoDB opcodes
OPCODE_COMPRESSED = 2012
OPCODE_MSG = 2013
COMPRESSOR_ZLIB = 2

# Vulnerability database
# Source: MongoDB Security Advisory - December 2025
# https://www.mongodb.com/docs/manual/release-notes/
VULNERABLE_VERSIONS = {
    "8.2": {"max": (8, 2, 2), "fixed": "8.2.3"},
    "8.0": {"max": (8, 0, 16), "fixed": "8.0.17"},
    "7.0": {"max": (7, 0, 27), "fixed": "7.0.28"},
    "6.0": {"max": (6, 0, 26), "fixed": "6.0.27"},
    "5.0": {"max": (5, 0, 31), "fixed": "5.0.32"},
    "4.4": {"max": (4, 4, 29), "fixed": "4.4.30"},
    "4.2": {"max": (4, 2, 99), "fixed": "EOL"},
    "4.0": {"max": (4, 0, 99), "fixed": "EOL"},
    "3.6": {"max": (3, 6, 99), "fixed": "EOL"},
}

# Wire protocol version to MongoDB version mapping
# Used when buildInfo requires authentication (MongoDB 8.2+)
# Source: https://www.mongodb.com/docs/manual/reference/mongodb-wire-protocol/
WIRE_VERSION_MAP = {
    6: "3.0",
    7: "3.2",
    8: "3.4",
    9: "3.6",
    10: "4.0",
    11: "4.2",
    12: "4.4",
    13: "5.0",
    17: "6.0",
    21: "7.0",
    25: "8.0",
    27: "8.2",
}


# =============================================================================
# SECTION 2: DATA STRUCTURES
# =============================================================================

@dataclass
class ScanResult:
    """
    Holds the result of scanning a single target.
    Using dataclass for clean, structured data.
    """
    host: str
    port: int
    is_reachable: bool
    version: str
    version_is_exact: bool  # True if exact version, False if estimated from wire version
    is_version_vulnerable: Optional[bool]
    is_zlib_enabled: bool
    is_vulnerable: bool
    fixed_version: str
    scan_time: float
    error: str

    def to_dict(self) -> dict:
        """Convert to dictionary for JSON export."""
        return asdict(self)


# =============================================================================
# SECTION 3: OUTPUT HELPERS
# =============================================================================

def print_banner():
    """Display program banner with legal disclaimer."""
    banner = f"""
+================================================================+
|     MongoBleed Scanner v{VERSION}                                  |
|     CVE-2025-14847 - MongoDB Memory Leak Vulnerability         |
+================================================================+
|  LEGAL: Authorized security testing only. Obtain permission    |
|         before scanning systems you do not own.                |
+================================================================+
"""
    print(banner)


def print_info(message: str):
    """Print info message."""
    print(f"[*] {message}")


def print_success(message: str):
    """Print success message."""
    print(f"[+] {message}")


def print_warning(message: str):
    """Print warning message."""
    print(f"[!] {message}")


def print_error(message: str):
    """Print error message."""
    print(f"[-] {message}")


# =============================================================================
# SECTION 4: TARGET PARSING
# =============================================================================

def parse_target(target_str: str) -> Tuple[str, int]:
    """
    Parse target string into host and port.
    
    Formats supported:
        - "192.168.1.100"       -> ("192.168.1.100", 27017)
        - "192.168.1.100:27018" -> ("192.168.1.100", 27018)
    
    Args:
        target_str: Target string in format "host" or "host:port"
    
    Returns:
        Tuple of (host, port)
    """
    target_str = target_str.strip()
    
    if ":" in target_str:
        parts = target_str.rsplit(":", 1)
        host = parts[0]
        try:
            port = int(parts[1])
        except ValueError:
            port = DEFAULT_PORT
    else:
        host = target_str
        port = DEFAULT_PORT
    
    return (host, port)


def load_targets_from_string(targets_str: str) -> List[Tuple[str, int]]:
    """
    Parse comma-separated targets string.
    
    Args:
        targets_str: Comma-separated targets like "host1,host2:27018,host3"
    
    Returns:
        List of (host, port) tuples
    """
    targets = []
    for target in targets_str.split(","):
        target = target.strip()
        if target:
            targets.append(parse_target(target))
    return targets


def load_targets_from_file(file_path: str) -> List[Tuple[str, int]]:
    """
    Load targets from a file (one target per line).
    
    Args:
        file_path: Path to targets file
    
    Returns:
        List of (host, port) tuples
    """
    targets = []
    path = Path(file_path)
    
    if not path.exists():
        print_error(f"File not found: {file_path}")
        return targets
    
    with open(path, 'r') as f:
        for line in f:
            line = line.strip()
            # Skip empty lines and comments
            if line and not line.startswith("#"):
                targets.append(parse_target(line))
    
    return targets


# =============================================================================
# SECTION 5: MONGODB PROTOCOL
# =============================================================================

def create_mongodb_header(length: int, request_id: int, opcode: int) -> bytes:
    """Create 16-byte MongoDB wire protocol header."""
    return struct.pack('<iiii', length, request_id, 0, opcode)


def create_bson_doc(fields: dict) -> bytes:
    """Create simple BSON document from dictionary."""
    elements = b''
    
    for key, value in fields.items():
        key_bytes = key.encode('utf-8') + b'\x00'
        
        if isinstance(value, int):
            elements += b'\x10' + key_bytes + struct.pack('<i', value)
        elif isinstance(value, str):
            val_bytes = value.encode('utf-8') + b'\x00'
            elements += b'\x02' + key_bytes + struct.pack('<i', len(val_bytes)) + val_bytes
    
    elements += b'\x00'
    return struct.pack('<i', 4 + len(elements)) + elements


def create_op_msg(doc: bytes) -> bytes:
    """Wrap BSON in OP_MSG format."""
    return struct.pack('<I', 0) + b'\x00' + doc


def send_mongo_command(sock: socket.socket, command: dict) -> bytes:
    """Send command to MongoDB and return response."""
    doc = create_bson_doc(command)
    msg = create_op_msg(doc)
    header = create_mongodb_header(16 + len(msg), 1, OPCODE_MSG)
    
    sock.sendall(header + msg)
    
    # Read response
    response = b''
    try:
        length_bytes = sock.recv(4)
        if len(length_bytes) >= 4:
            msg_len = struct.unpack('<i', length_bytes)[0]
            response = length_bytes
            remaining = msg_len - 4
            while remaining > 0:
                chunk = sock.recv(min(remaining, 4096))
                if not chunk:
                    break
                response += chunk
                remaining -= len(chunk)
    except socket.timeout:
        pass
    
    return response


# =============================================================================
# SECTION 6: VERSION DETECTION AND ANALYSIS
# =============================================================================

def parse_version(version_str: str) -> Tuple[int, int, int]:
    """Parse version string to tuple (major, minor, patch)."""
    try:
        parts = version_str.split("-")[0].split(".")
        return (
            int(parts[0]) if len(parts) > 0 else 0,
            int(parts[1]) if len(parts) > 1 else 0,
            int(parts[2]) if len(parts) > 2 else 0
        )
    except (ValueError, IndexError):
        return (0, 0, 0)


def extract_version_from_response(response: bytes) -> str:
    """
    Extract version string from MongoDB command response.
    
    Handles responses from:
    - buildInfo command (has 'version' field)
    - hello command (has 'maxWireVersion', need to map or find version elsewhere)
    - isMaster command (similar to hello)
    
    Args:
        response: Raw BSON response bytes
    
    Returns:
        Version string like "8.0.16" or empty string if not found
    """
    if not response or len(response) < 20:
        return ""
    
    try:
        # Method 1: Look for "version" field directly (buildInfo response)
        search = b'version\x00'
        pos = response.find(search)
        
        if pos > 0 and response[pos - 1] == 0x02:  # String type
            val_pos = pos + len(search)
            if val_pos + 4 < len(response):
                str_len = struct.unpack('<i', response[val_pos:val_pos + 4])[0]
                if str_len > 0 and str_len < 50:  # Reasonable version string length
                    version = response[val_pos + 4:val_pos + 4 + str_len - 1]
                    version_str = version.decode('utf-8', errors='ignore')
                    # Validate it looks like a version (X.Y.Z format)
                    if version_str and version_str[0].isdigit() and '.' in version_str:
                        return version_str
    except Exception:
        pass
    
    # Method 2: Regex pattern matching for version anywhere in response
    # This catches version strings in various response formats
    try:
        import re
        # Match patterns like "8.0.16", "8.2.2", "7.0.27"
        matches = re.findall(rb'["\x02]?(\d+\.\d+\.\d+)', response)
        if matches:
            # Return first valid-looking version
            for match in matches:
                version_str = match.decode('utf-8')
                # Filter out obviously wrong matches (like dates, IPs, etc)
                parts = version_str.split('.')
                if len(parts) == 3:
                    major, minor, patch = int(parts[0]), int(parts[1]), int(parts[2])
                    # MongoDB versions: major 3-9, minor 0-99, patch 0-99
                    if 3 <= major <= 9 and 0 <= minor <= 99 and 0 <= patch <= 99:
                        return version_str
    except Exception:
        pass
    
    return ""


def check_version_vulnerable(version_str: str) -> Tuple[Optional[bool], str]:
    """
    Check if version is vulnerable.
    
    Handles both exact versions (8.0.16) and estimated versions (8.2.x).
    For estimated versions (ending in .x), we can only determine the branch,
    not whether the specific patch is vulnerable.
    
    Args:
        version_str: Version string like "8.0.16" or "8.2.x"
    
    Returns:
        Tuple of (is_vulnerable, fixed_version)
        - is_vulnerable: True/False/None (None if cannot determine)
    """
    # Handle estimated versions (e.g., "8.2.x")
    if version_str.endswith('.x'):
        branch = version_str[:-2]  # Remove ".x" to get "8.2"
        if branch in VULNERABLE_VERSIONS:
            info = VULNERABLE_VERSIONS[branch]
            # For estimated versions, we can't be certain
            # Return None to indicate "possible but unconfirmed"
            return (None, info["fixed"])
        return (None, "")
    
    # Handle exact versions
    version = parse_version(version_str)
    if version == (0, 0, 0):
        return (None, "")
    
    branch = f"{version[0]}.{version[1]}"
    
    if branch in VULNERABLE_VERSIONS:
        info = VULNERABLE_VERSIONS[branch]
        max_vuln = info["max"]
        
        if version <= max_vuln:
            return (True, info["fixed"])
        else:
            return (False, info["fixed"])
    
    return (None, "")


# =============================================================================
# SECTION 7: SCANNING FUNCTIONS
# =============================================================================

def extract_int32_field(response: bytes, field_name: str) -> int:
    """
    Extract int32 field from BSON response.
    
    Args:
        response: Raw BSON response bytes
        field_name: Name of the field to extract
    
    Returns:
        Field value as int, or -1 if not found
    """
    search = field_name.encode('utf-8') + b'\x00'
    pos = response.find(search)
    
    if pos > 0 and response[pos - 1] == 0x10:  # int32 type
        val_pos = pos + len(search)
        if val_pos + 4 <= len(response):
            return struct.unpack('<i', response[val_pos:val_pos + 4])[0]
    return -1


def check_connection_and_version(host: str, port: int) -> Tuple[bool, str, bool]:
    """
    Test TCP connection and get MongoDB version.
    
    Uses multiple methods to detect version:
    1. 'hello' command - get maxWireVersion (always works without auth)
    2. 'buildInfo' command - get exact version (may require auth on 8.2+)
    3. Fallback to wire version mapping if buildInfo fails
    
    Args:
        host: MongoDB server address
        port: MongoDB port
    
    Returns:
        Tuple of (success, version_string, is_version_exact)
        - is_version_exact: True if we got exact version, False if estimated from wire version
    """
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(SOCKET_TIMEOUT)
        sock.connect((host, port))
        
        # Step 1: Send 'hello' command to get maxWireVersion
        # This always works without authentication
        hello_response = send_mongo_command(sock, {"hello": 1, "$db": "admin"})
        
        max_wire_version = -1
        if hello_response:
            max_wire_version = extract_int32_field(hello_response, "maxWireVersion")
        
        # Step 2: Try 'buildInfo' command for exact version
        # This may require authentication on MongoDB 8.2+
        build_response = send_mongo_command(sock, {"buildInfo": 1, "$db": "admin"})
        sock.close()
        
        # Check if buildInfo succeeded (no auth error)
        if build_response and b"requires authentication" not in build_response:
            version = extract_version_from_response(build_response)
            if version:
                return (True, version, True)  # Exact version
        
        # Step 3: Fallback to wire version mapping
        if max_wire_version > 0 and max_wire_version in WIRE_VERSION_MAP:
            estimated_branch = WIRE_VERSION_MAP[max_wire_version]
            # Return branch with .x suffix to indicate it's estimated
            return (True, f"{estimated_branch}.x", False)  # Estimated version
        
        # Connection works but couldn't determine version
        return (True, "unknown", False)
        
    except socket.timeout:
        return (False, "Connection timeout", False)
    except ConnectionRefusedError:
        return (False, "Connection refused", False)
    except OSError as e:
        return (False, f"Network error: {e}", False)
    except Exception as e:
        return (False, str(e), False)


def check_zlib_enabled(host: str, port: int) -> bool:
    """Check if zlib compression is enabled."""
    try:
        import zlib
        
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(SOCKET_TIMEOUT)
        sock.connect((host, port))
        
        # Create compressed ping
        doc = create_bson_doc({"ping": 1, "$db": "admin"})
        msg = create_op_msg(doc)
        compressed = zlib.compress(msg)
        
        # OP_COMPRESSED body
        body = struct.pack('<i', OPCODE_MSG)  # Original opcode
        body += struct.pack('<i', len(msg))   # Uncompressed size
        body += struct.pack('<B', COMPRESSOR_ZLIB)  # Compressor ID
        body += compressed
        
        header = create_mongodb_header(16 + len(body), 2, OPCODE_COMPRESSED)
        sock.sendall(header + body)
        
        response = sock.recv(4096)
        sock.close()
        
        return len(response) >= 16
        
    except Exception:
        return False


def scan_target(host: str, port: int) -> ScanResult:
    """
    Perform full vulnerability scan on a single target.
    
    Args:
        host: Target hostname or IP
        port: Target port
    
    Returns:
        ScanResult with all findings
    """
    start_time = datetime.now()
    
    # Initialize result
    result = ScanResult(
        host=host,
        port=port,
        is_reachable=False,
        version="",
        version_is_exact=False,
        is_version_vulnerable=None,
        is_zlib_enabled=False,
        is_vulnerable=False,
        fixed_version="",
        scan_time=0.0,
        error=""
    )
    
    # Step 1: Check connection and get version
    is_reachable, version_or_error, is_exact = check_connection_and_version(host, port)
    
    if not is_reachable:
        result.error = version_or_error
        result.scan_time = (datetime.now() - start_time).total_seconds()
        return result
    
    result.is_reachable = True
    result.version = version_or_error
    result.version_is_exact = is_exact
    
    # Step 2: Check if version is vulnerable
    if result.version and result.version != "unknown":
        is_vuln, fixed = check_version_vulnerable(result.version)
        result.is_version_vulnerable = is_vuln
        result.fixed_version = fixed
    
    # Step 3: Check zlib compression
    result.is_zlib_enabled = check_zlib_enabled(host, port)
    
    # Step 4: Final verdict
    # Vulnerable = vulnerable version AND zlib enabled
    if result.is_version_vulnerable and result.is_zlib_enabled:
        result.is_vulnerable = True
    
    result.scan_time = (datetime.now() - start_time).total_seconds()
    return result


# =============================================================================
# SECTION 8: OUTPUT AND REPORTING
# =============================================================================

def get_status_symbol(result: ScanResult) -> str:
    """Get status symbol for result display."""
    if not result.is_reachable:
        return "[-]"  # Unreachable
    elif result.is_vulnerable:
        return "[!]"  # Vulnerable
    elif result.is_version_vulnerable is None and result.is_zlib_enabled and result.version.endswith('.x'):
        return "[?!]"  # Possibly vulnerable (estimated version)
    elif result.is_version_vulnerable and not result.is_zlib_enabled:
        return "[~]"  # Mitigated
    elif result.is_version_vulnerable is False:
        return "[+]"  # Safe
    else:
        return "[?]"  # Unknown


def print_scan_result(result: ScanResult, verbose: bool = False):
    """Print single scan result."""
    symbol = get_status_symbol(result)
    target = f"{result.host}:{result.port}"
    
    if not result.is_reachable:
        print(f"  {symbol} {target:<25} UNREACHABLE ({result.error})")
        return
    
    # Build version string (add ~ prefix if estimated)
    version_str = result.version if result.version else "unknown"
    if not result.version_is_exact and version_str != "unknown":
        version_str = f"~{version_str}"  # ~ indicates estimated
    
    zlib_str = "zlib:ON" if result.is_zlib_enabled else "zlib:OFF"
    
    if result.is_vulnerable:
        status = f"VULNERABLE  v{version_str}  {zlib_str}  -> Update to {result.fixed_version}"
    elif result.is_version_vulnerable is None and result.is_zlib_enabled and result.version.endswith('.x'):
        # Estimated version with zlib enabled - potentially vulnerable
        status = f"POSSIBLY VULNERABLE  v{version_str}  {zlib_str}  -> Check version, update to {result.fixed_version}"
    elif result.is_version_vulnerable and not result.is_zlib_enabled:
        status = f"MITIGATED   v{version_str}  {zlib_str}  (zlib disabled)"
    elif result.is_version_vulnerable is False:
        status = f"SAFE        v{version_str}  {zlib_str}"
    else:
        status = f"UNKNOWN     v{version_str}  {zlib_str}"
    
    print(f"  {symbol} {target:<25} {status}")


def print_summary(results: List[ScanResult]):
    """Print scan summary statistics."""
    total = len(results)
    reachable = sum(1 for r in results if r.is_reachable)
    vulnerable = sum(1 for r in results if r.is_vulnerable)
    possibly_vuln = sum(1 for r in results if r.is_reachable and r.is_version_vulnerable is None 
                        and r.is_zlib_enabled and r.version.endswith('.x'))
    safe = sum(1 for r in results if r.is_reachable and r.is_version_vulnerable is False)
    mitigated = sum(1 for r in results if r.is_reachable and r.is_version_vulnerable and not r.is_zlib_enabled)
    unknown = reachable - vulnerable - possibly_vuln - safe - mitigated
    unreachable = total - reachable
    
    print("\n" + "=" * 70)
    print("  SCAN SUMMARY")
    print("=" * 70)
    print(f"  Total targets scanned:  {total}")
    print(f"  Reachable:              {reachable}")
    print(f"  Unreachable:            {unreachable}")
    print("-" * 70)
    print(f"  [!]  VULNERABLE:        {vulnerable}")
    print(f"  [?!] POSSIBLY VULN:     {possibly_vuln}  (version estimated, needs verification)")
    print(f"  [+]  SAFE (patched):    {safe}")
    print(f"  [~]  MITIGATED:         {mitigated}  (vulnerable version but zlib disabled)")
    print(f"  [?]  UNKNOWN:           {unknown}")
    print("=" * 70)
    
    # List vulnerable targets
    vulnerable_targets = [r for r in results if r.is_vulnerable]
    if vulnerable_targets:
        print("\n  VULNERABLE TARGETS REQUIRING IMMEDIATE ACTION:")
        print("-" * 70)
        for r in vulnerable_targets:
            zlib_info = "zlib:ON" if r.is_zlib_enabled else "zlib:OFF"
            print(f"    {r.host}:{r.port}  v{r.version}  {zlib_info}  -> Upgrade to {r.fixed_version}")
    
    # List possibly vulnerable targets
    possibly_vuln_targets = [r for r in results if r.is_reachable and r.is_version_vulnerable is None 
                             and r.is_zlib_enabled and r.version.endswith('.x')]
    if possibly_vuln_targets:
        print("\n  POSSIBLY VULNERABLE (requires manual verification):")
        print("-" * 70)
        for r in possibly_vuln_targets:
            print(f"    {r.host}:{r.port}  v~{r.version}  zlib:ON  -> Verify version, update to {r.fixed_version}")
        print("    Note: '~' indicates version estimated from wire protocol")
    
    # List mitigated targets
    mitigated_targets = [r for r in results if r.is_reachable and r.is_version_vulnerable and not r.is_zlib_enabled]
    if mitigated_targets:
        print("\n  MITIGATED TARGETS (upgrade recommended):")
        print("-" * 70)
        for r in mitigated_targets:
            print(f"    {r.host}:{r.port}  v{r.version}  zlib:OFF  -> Consider upgrading to {r.fixed_version}")
    
    print()


def export_results_txt(results: List[ScanResult], filepath: str):
    """Export results to text file."""
    with open(filepath, 'w') as f:
        f.write("=" * 70 + "\n")
        f.write("MongoBleed Scanner Results - CVE-2025-14847\n")
        f.write(f"Scan Time: {datetime.now().isoformat()}\n")
        f.write("=" * 70 + "\n\n")
        
        for r in results:
            status = "VULNERABLE" if r.is_vulnerable else "SAFE" if r.is_reachable else "UNREACHABLE"
            f.write(f"{r.host}:{r.port} - {status}\n")
            if r.is_reachable:
                f.write(f"  Version: {r.version}\n")
                f.write(f"  zlib compression: {'enabled' if r.is_zlib_enabled else 'disabled'}\n")
                f.write(f"  Version vulnerable: {r.is_version_vulnerable}\n")
                if r.fixed_version:
                    f.write(f"  Fixed in: {r.fixed_version}\n")
            else:
                f.write(f"  Error: {r.error}\n")
            f.write("\n")
    
    print_success(f"Results exported to: {filepath}")


def export_results_json(results: List[ScanResult], filepath: str):
    """Export results to JSON file."""
    data = {
        "scan_info": {
            "tool": "MongoBleed Scanner",
            "version": VERSION,
            "cve": "CVE-2025-14847",
            "scan_time": datetime.now().isoformat()
        },
        "summary": {
            "total_targets": len(results),
            "reachable": sum(1 for r in results if r.is_reachable),
            "vulnerable": sum(1 for r in results if r.is_vulnerable),
            "safe": sum(1 for r in results if r.is_reachable and r.is_version_vulnerable is False),
            "mitigated": sum(1 for r in results if r.is_reachable and r.is_version_vulnerable and not r.is_zlib_enabled)
        },
        "results": [r.to_dict() for r in results]
    }
    
    with open(filepath, 'w') as f:
        json.dump(data, f, indent=2)
    
    print_success(f"Results exported to: {filepath}")


def export_results_csv(results: List[ScanResult], filepath: str):
    """Export results to CSV file."""
    with open(filepath, 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerow([
            "Host", "Port", "Reachable", "Version", 
            "Version Vulnerable", "zlib Enabled", "Vulnerable", 
            "Fixed Version", "Scan Time (s)", "Error"
        ])
        
        for r in results:
            writer.writerow([
                r.host, r.port, r.is_reachable, r.version,
                r.is_version_vulnerable, r.is_zlib_enabled, r.is_vulnerable,
                r.fixed_version, round(r.scan_time, 3), r.error
            ])
    
    print_success(f"Results exported to: {filepath}")


def export_results(results: List[ScanResult], filepath: str):
    """Export results based on file extension."""
    ext = Path(filepath).suffix.lower()
    
    if ext == ".json":
        export_results_json(results, filepath)
    elif ext == ".csv":
        export_results_csv(results, filepath)
    else:
        export_results_txt(results, filepath)


# =============================================================================
# SECTION 9: MAIN PROGRAM
# =============================================================================

def create_argument_parser() -> argparse.ArgumentParser:
    """Create and configure argument parser."""
    parser = argparse.ArgumentParser(
        description="MongoBleed Scanner - CVE-2025-14847 Vulnerability Scanner",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  %(prog)s -t 192.168.1.100
  %(prog)s -t 192.168.1.100:27017,192.168.1.101:27018
  %(prog)s -f targets.txt
  %(prog)s -t 192.168.1.100 -o results.json

Target formats:
  192.168.1.100        (uses default port 27017)
  192.168.1.100:27018  (custom port)
  mongodb.local        (hostname)

Output formats:
  results.txt          Plain text report
  results.json         JSON format with full details
  results.csv          CSV spreadsheet format

LEGAL DISCLAIMER:
  This tool is intended for authorized security testing only.
  Obtain proper permission before scanning any systems.
        """
    )
    
    # Target input (mutually exclusive)
    target_group = parser.add_mutually_exclusive_group(required=True)
    target_group.add_argument(
        "-t", "--targets",
        help="Comma-separated list of targets (host or host:port)"
    )
    target_group.add_argument(
        "-f", "--file",
        help="File containing targets (one per line)"
    )
    
    # Output options
    parser.add_argument(
        "-o", "--output",
        help="Output file path (.txt, .json, or .csv)"
    )
    
    # Other options
    parser.add_argument(
        "-q", "--quiet",
        action="store_true",
        help="Quiet mode - only show summary"
    )
    parser.add_argument(
        "-v", "--version",
        action="version",
        version=f"%(prog)s {VERSION}"
    )
    
    return parser


def main():
    """Main program entry point."""
    # Print banner
    print_banner()
    
    # Parse arguments
    parser = create_argument_parser()
    args = parser.parse_args()
    
    # Load targets
    if args.targets:
        targets = load_targets_from_string(args.targets)
    else:
        targets = load_targets_from_file(args.file)
    
    if not targets:
        print_error("No valid targets specified")
        sys.exit(1)
    
    # Remove duplicates while preserving order
    seen = set()
    unique_targets = []
    for t in targets:
        if t not in seen:
            seen.add(t)
            unique_targets.append(t)
    targets = unique_targets
    
    print_info(f"Loaded {len(targets)} target(s)\n")
    
    # Scan targets
    print("SCAN RESULTS:")
    print("-" * 70)
    
    results = []
    for host, port in targets:
        result = scan_target(host, port)
        results.append(result)
        
        if not args.quiet:
            print_scan_result(result)
    
    # Print summary
    print_summary(results)
    
    # Export if requested
    if args.output:
        export_results(results, args.output)
    
    # Exit code: 2 if any vulnerable, 1 if errors, 0 otherwise
    vulnerable_count = sum(1 for r in results if r.is_vulnerable)
    error_count = sum(1 for r in results if not r.is_reachable)
    
    if vulnerable_count > 0:
        sys.exit(2)
    elif error_count > 0:
        sys.exit(1)
    else:
        sys.exit(0)


# =============================================================================
# Entry point
# =============================================================================

if __name__ == "__main__":
    main()