Exploit databaseDownload repository ZIP
GH-f94d8bfcd17b8c61fd03586eae936aa0
abatsakidis/wp-cve-2026-87902-checker
Sources for CVE-2026-87902
16 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files3
abatsakidis/wp-cve-2026-87902-checkerRevision e3009d7452b4
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
wp-cve-2026-87902-remote.py
Python · 20,181 bytes#!/usr/bin/env python3
"""
wp-cve-2026-87902-remote.py
Remote, non-destructive WordPress CVE-2026-87902 checker.
This tool performs HTTP/HTTPS reconnaissance only:
- detects WordPress
- fingerprints the WordPress Core version where possible
- compares it with the fixed releases
- discovers public WordPress REST information when available
- attempts to identify the active theme
- probes for common public page-* theme directories
- reports whether the known preconditions can/cannot be established
It deliberately does NOT:
- send traversal/LFI payloads
- include arbitrary local files
- create or modify files
- execute commands
- attempt PEAR/RCE
Usage:
python wp-cve-2026-87902-remote.py https://example.com
python wp-cve-2026-87902-remote.py https://example.com --verbose
python wp-cve-2026-87902-remote.py https://example.com --insecure
Exit codes:
0 = no current exposure established / patched / not WordPress
1 = potentially affected version + page-* precondition established
2 = target/error/insufficient information
"""
from __future__ import annotations
import argparse
import json
import re
import ssl
import sys
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple
VERSION = "1.0.0"
PATCHED = {
"7.1": "7.1.2",
"7.0": "7.0.6",
"6.9": "6.9.9",
"6.8": "6.8.10",
"6.7": "6.7.9",
"6.6": "6.6.9",
"6.5": "6.5.12",
"6.4": "6.4.12",
"6.3": "6.3.12",
"6.2": "6.2.13",
"6.1": "6.1.14",
"6.0": "6.0.16",
"5.9": "5.9.18",
"5.8": "5.8.17",
"5.7": "5.7.19",
"5.6": "5.6.21",
"5.5": "5.5.22",
"5.4": "5.4.23",
"5.3": "5.3.25",
"5.2": "5.2.28",
"5.1": "5.1.26",
"5.0": "5.0.29",
"4.9": "4.9.33",
"4.8": "4.8.32",
"4.7": "4.7.37",
}
COMMON_PAGE_DIRS = [
"page-templates",
"page-template",
"page_templates",
"page-templates-custom",
"page-template-custom",
]
DEFAULT_TIMEOUT = 12
@dataclass
class Response:
status: int
url: str
headers: Dict[str, str]
body: bytes
class Colors:
# Windows 10/11: enable native ANSI/VT processing in the console.
# This avoids printing literal escape sequences in CMD/PowerShell.
RESET = "\033[0m"
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
CYAN = "\033[96m"
BOLD = "\033[1m"
_enabled = False
@classmethod
def setup(cls) -> None:
if not sys.stdout or not hasattr(sys.stdout, "isatty") or not sys.stdout.isatty():
cls._enabled = False
return
if sys.platform != "win32":
cls._enabled = True
return
# ENABLE_PROCESSED_OUTPUT = 0x0001
# ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
try:
import ctypes
import msvcrt
kernel32 = ctypes.windll.kernel32
handle = msvcrt.get_osfhandle(sys.stdout.fileno())
mode = ctypes.c_uint32()
if kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
new_mode = mode.value | 0x0001 | 0x0004
if kernel32.SetConsoleMode(handle, new_mode):
cls._enabled = True
return
except (ImportError, OSError, AttributeError, ValueError):
pass
# If native VT cannot be enabled, fall back to plain text rather than
# displaying ugly literal ANSI sequences.
cls._enabled = False
@classmethod
def c(cls, value: str, color: str) -> str:
if not cls._enabled:
return value
return color + value + cls.RESET
def ok(msg: str) -> None:
print(Colors.c("[+]", Colors.GREEN), msg)
def info(msg: str) -> None:
print(Colors.c("[*]", Colors.CYAN), msg)
def warn(msg: str) -> None:
print(Colors.c("[!]", Colors.YELLOW), msg)
def bad(msg: str) -> None:
print(Colors.c("[!]", Colors.RED), msg)
def parse_version(v: str) -> Optional[Tuple[int, int, int]]:
m = re.match(r"^\s*(\d+)\.(\d+)(?:\.(\d+))?", v)
if not m:
return None
return int(m.group(1)), int(m.group(2)), int(m.group(3) or 0)
def version_branch(v: str) -> Optional[str]:
p = parse_version(v)
return f"{p[0]}.{p[1]}" if p else None
def compare_version(a: str, b: str) -> int:
pa = parse_version(a)
pb = parse_version(b)
if not pa or not pb:
return 0
return (pa > pb) - (pa < pb)
def version_status(version: str) -> Tuple[str, Optional[str], str]:
branch = version_branch(version)
parsed = parse_version(version)
if not branch or not parsed:
return "UNKNOWN", None, "Unrecognised version format."
if branch in PATCHED:
fixed = PATCHED[branch]
if compare_version(version, fixed) >= 0:
return "PATCHED", fixed, f"{version} is at or above {fixed} for branch {branch}."
return "AFFECTED", fixed, f"{version} is below {fixed} for branch {branch}."
if parsed > (7, 1, 2):
return "POSTFIX", None, "Version is newer than the affected range."
if parsed < (4, 7, 0):
return "UNKNOWN", None, "Version predates the advisory's affected range."
return "UNKNOWN", None, "Branch not represented in the embedded backport table."
def normalize_target(target: str) -> str:
if not re.match(r"^https?://", target, re.I):
target = "https://" + target
target = target.strip()
parsed = urllib.parse.urlsplit(target)
if not parsed.netloc:
raise ValueError("Invalid URL.")
return target.rstrip("/")
class Scanner:
def __init__(self, target: str, timeout: int, insecure: bool, verbose: bool):
self.target = normalize_target(target)
self.timeout = timeout
self.verbose = verbose
self.ctx = ssl._create_unverified_context() if insecure else ssl.create_default_context()
self.session_headers = {
"User-Agent": (
"Mozilla/5.0 (compatible; WP-CVE-2026-87902-RemoteChecker/"
+ VERSION
+ "; defensive scanner)"
),
"Accept": "text/html,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8",
}
self.requests = 0
def get(self, url: str) -> Optional[Response]:
self.requests += 1
req = urllib.request.Request(url, headers=self.session_headers, method="GET")
try:
with urllib.request.urlopen(req, timeout=self.timeout, context=self.ctx) as r:
body = r.read(2 * 1024 * 1024)
headers = {k.lower(): v for k, v in r.headers.items()}
return Response(r.status, r.geturl(), headers, body)
except urllib.error.HTTPError as e:
try:
body = e.read(512 * 1024)
except Exception:
body = b""
headers = {k.lower(): v for k, v in e.headers.items()} if e.headers else {}
return Response(e.code, e.geturl(), headers, body)
except Exception as e:
if self.verbose:
warn(f"GET failed: {url} -> {e}")
return None
def headless_url(self, path: str) -> str:
return self.target + "/" + path.lstrip("/")
def fetch_home(self) -> Optional[Response]:
return self.get(self.target + "/")
def detect_wordpress(self, response: Optional[Response]) -> Dict[str, object]:
result: Dict[str, object] = {
"is_wordpress": False,
"confidence": "low",
"signals": [],
}
if not response:
return result
body = response.body.decode("utf-8", errors="replace")
headers = response.headers
signals = []
if "/wp-content/" in body or "/wp-includes/" in body:
signals.append("wp-content/wp-includes reference")
if re.search(r'<meta[^>]+name=["\']generator["\'][^>]+WordPress', body, re.I):
signals.append("WordPress generator meta")
if "wp-json" in body:
signals.append("wp-json reference")
if "wordpress" in headers.get("x-powered-by", "").lower():
signals.append("X-Powered-By WordPress")
if "/wp-includes/" in body and "/wp-content/" in body:
result["confidence"] = "high"
elif signals:
result["confidence"] = "medium"
result["signals"] = signals
result["is_wordpress"] = bool(signals)
return result
@staticmethod
def extract_versions(text: str) -> List[str]:
versions = set()
patterns = [
r'content=["\']WordPress\s+([0-9]+\.[0-9]+(?:\.[0-9]+)?)',
r'WordPress\s+([0-9]+\.[0-9]+(?:\.[0-9]+)?)',
r'wordpress(?:/|[- ])([0-9]+\.[0-9]+(?:\.[0-9]+)?)',
]
for pattern in patterns:
for m in re.finditer(pattern, text, re.I):
versions.add(m.group(1))
return sorted(versions, key=lambda x: parse_version(x) or (0, 0, 0))
def discover_version(self, home: Optional[Response]) -> Tuple[Optional[str], List[str]]:
candidates: List[str] = []
if home:
body = home.body.decode("utf-8", errors="replace")
candidates.extend(self.extract_versions(body))
# Passive public endpoints. No authentication and no mutation.
endpoints = [
"readme.html",
"feed/",
"wp-json/",
]
for path in endpoints:
r = self.get(self.headless_url(path))
if not r:
continue
text = r.body.decode("utf-8", errors="replace")
candidates.extend(self.extract_versions(text))
if path == "wp-json/" and r.status == 200:
try:
data = json.loads(text)
if isinstance(data, dict):
for key in ("version",):
val = data.get(key)
if isinstance(val, str) and parse_version(val):
candidates.append(val)
except Exception:
pass
candidates = sorted(
set(candidates),
key=lambda x: parse_version(x) or (0, 0, 0),
reverse=True,
)
return (candidates[0] if candidates else None), candidates
def discover_theme(self, home: Optional[Response]) -> Dict[str, object]:
result: Dict[str, object] = {
"theme": None,
"stylesheet_url": None,
"signals": [],
}
if not home:
return result
body = home.body.decode("utf-8", errors="replace")
urls = re.findall(
r'https?://[^"\']+/wp-content/themes/([^/"\']+)',
body,
re.I,
)
rels = re.findall(
r'(?:/|["\'])wp-content/themes/([^/"\']+)',
body,
re.I,
)
names = []
for name in urls + rels:
if name not in names:
names.append(name)
if names:
result["theme"] = names[0]
result["signals"].append("theme asset URL in public HTML")
result["stylesheet_url"] = self.target + "/wp-content/themes/" + names[0]
# WordPress REST API: /wp-json/wp/v2/themes requires authentication on
# many installations, so it is deliberately not relied upon.
# The public HTML remains the primary passive signal.
return result
def probe_page_dirs(self, theme: Optional[str]) -> Dict[str, object]:
result: Dict[str, object] = {
"theme": theme,
"found": [],
"not_found": [],
"unknown": [],
}
if not theme:
return result
base = self.target + "/wp-content/themes/" + urllib.parse.quote(theme, safe="-_.~") + "/"
for dirname in COMMON_PAGE_DIRS:
url = base + dirname + "/"
r = self.get(url)
if not r:
result["unknown"].append(dirname)
continue
# A directory itself may return 403, which is still evidence that
# the directory exists. A 301/302 to index.php can also indicate
# a real directory, but we avoid treating arbitrary 200 pages as
# proof unless the response is clearly directory-like.
if r.status in (401, 403):
result["found"].append((dirname, r.status))
elif r.status in (301, 302, 307, 308):
result["found"].append((dirname, r.status))
elif r.status == 200:
final_path = urllib.parse.urlsplit(r.url).path.rstrip("/")
requested_path = urllib.parse.urlsplit(url).path.rstrip("/")
if final_path == requested_path or final_path.endswith("/" + dirname):
result["found"].append((dirname, r.status))
else:
result["unknown"].append(dirname)
elif r.status == 404:
result["not_found"].append(dirname)
else:
result["unknown"].append(dirname)
return result
def passive_exposure_signals(self) -> Dict[str, object]:
result = {
"wp_login": None,
"wp_admin": None,
"wp_cron": None,
"wp_xmlrpc": None,
}
for path, key in [
("wp-login.php", "wp_login"),
("wp-admin/", "wp_admin"),
("wp-cron.php", "wp_cron"),
("xmlrpc.php", "wp_xmlrpc"),
]:
r = self.get(self.headless_url(path))
if r:
result[key] = r.status
return result
def run(self) -> int:
print("=" * 68)
print(f" WP-CVE-2026-87902 REMOTE CHECKER v{VERSION}")
print("=" * 68)
print(f"Target: {self.target}")
print("Mode: HTTP/HTTPS, non-destructive")
print()
info("Requesting public home page...")
home = self.fetch_home()
if not home:
bad("Target could not be reached.")
return 2
info(f"HTTP status: {home.status}")
info(f"Final URL: {home.url}")
wp = self.detect_wordpress(home)
if wp["is_wordpress"]:
ok(f"WordPress detected ({wp['confidence']} confidence)")
for signal in wp["signals"]:
print(f" - {signal}")
else:
bad("WordPress was not established from public signals.")
print(" The target may still be WordPress with fingerprinting disabled.")
return 2
print()
info("Attempting passive WordPress version fingerprinting...")
version, candidates = self.discover_version(home)
if version:
ok(f"Detected WordPress version: {version}")
if len(candidates) > 1:
print(f" Candidates: {', '.join(candidates[:8])}")
else:
warn("WordPress version could not be determined remotely.")
print(" Version may be hidden or public fingerprinting may be disabled.")
status = "UNKNOWN"
fixed = None
if version:
status, fixed, reason = version_status(version)
if status == "PATCHED":
ok(f"Core status: PATCHED ({reason})")
elif status == "POSTFIX":
ok(f"Core status: newer than affected range ({reason})")
elif status == "AFFECTED":
bad(f"Core status: AFFECTED ({reason})")
print(f" Minimum fixed version for this branch: {fixed}")
else:
warn(f"Core status: UNKNOWN ({reason})")
print()
info("Attempting passive active-theme fingerprinting...")
theme_info = self.discover_theme(home)
theme = theme_info["theme"]
if theme:
ok(f"Theme candidate from public HTML: {theme}")
else:
warn("Active theme could not be identified from public HTML.")
print()
info("Checking common public page-* directory names...")
page_dirs = self.probe_page_dirs(theme)
if page_dirs["found"]:
bad("Potential page-* precondition detected:")
for name, status_code in page_dirs["found"]:
print(f" - {name}/ -> HTTP {status_code}")
else:
ok("No common page-* directory was positively identified.")
if page_dirs["unknown"]:
print(" Unknown/not provable:")
print(" " + ", ".join(page_dirs["unknown"]))
print()
info("Collecting passive WordPress endpoint signals...")
endpoints = self.passive_exposure_signals()
print(
" "
+ " | ".join(
f"{k}={v if v is not None else 'unknown'}"
for k, v in endpoints.items()
)
)
print()
print("-" * 68)
print(" RESULT")
print("-" * 68)
if status == "PATCHED" or status == "POSTFIX":
ok("NOT CURRENTLY AFFECTED BY CORE VERSION")
if page_dirs["found"]:
print(" A page-* directory appears to exist, but the patched Core")
print(" version prevents the known vulnerable template-resolution path.")
print(" This scan cannot establish whether the site was compromised before patching.")
return 0
if status == "AFFECTED" and page_dirs["found"]:
bad("POTENTIALLY VULNERABLE")
print(" Two important conditions are visible remotely:")
print(" 1. WordPress Core is in an affected version range.")
print(" 2. A page-* theme-directory precondition was detected.")
print()
print(" This checker intentionally does NOT send an LFI/traversal")
print(" payload, so it does not claim exploitability from this result alone.")
print()
print(" Recommended action: upgrade to the fixed release for the branch.")
return 1
if status == "AFFECTED":
warn("AFFECTED CORE VERSION, BUT PAGE-* PRECONDITION WAS NOT ESTABLISHED")
print(" The site should still be upgraded to the fixed branch release.")
print(" Public HTTP checks cannot prove the absence of other theme layouts.")
return 1
warn("INCONCLUSIVE")
print(" The scanner could not establish enough public information to classify the target.")
print(" Check the WordPress version from the server/hosting panel or WP-CLI.")
return 2
def main() -> int:
Colors.setup()
parser = argparse.ArgumentParser(
description="Remote, non-destructive CVE-2026-87902 WordPress checker."
)
parser.add_argument("url", help="Target WordPress URL, e.g. https://example.com")
parser.add_argument(
"--timeout",
type=int,
default=DEFAULT_TIMEOUT,
help=f"HTTP timeout in seconds (default: {DEFAULT_TIMEOUT})",
)
parser.add_argument(
"--insecure",
action="store_true",
help="Disable TLS certificate verification (use only for your own test systems).",
)
parser.add_argument(
"--verbose",
action="store_true",
help="Show failed HTTP requests.",
)
args = parser.parse_args()
if args.timeout < 1 or args.timeout > 120:
parser.error("--timeout must be between 1 and 120 seconds")
try:
scanner = Scanner(
args.url,
timeout=args.timeout,
insecure=args.insecure,
verbose=args.verbose,
)
rc = scanner.run()
print()
print(f"HTTP requests made: {scanner.requests}")
return rc
except ValueError as e:
print(f"ERROR: {e}")
return 2
except KeyboardInterrupt:
print("\nInterrupted.")
return 130
if __name__ == "__main__":
raise SystemExit(main())