Exploit database

GH-af2e11313aeafac58e6a125c70fd479c

sonofabot/-cve-2026-18963-poc

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-18963

12 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files4
sonofabot/-cve-2026-18963-pocRevision ba29700a805f

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

cve-2026-18963-hunt.py

Python · 14,692 bytes
#!/usr/bin/env python3
"""Hunt CVE-2026-18963-style password resets via the Keycloak Admin Events API.
CVE-2026-18963 is a reset-credentials flow bypass in Keycloak 26.0.0 through
26.7.1 (fixed in 26.7.2, 26.4.15, and 26.6.6). An attacker who knows a username
can reach UPDATE_PASSWORD without clicking the email action-token link.
See https://access.redhat.com/security/cve/cve-2026-18963 , issue #51833,
and fix PR #51844.
Fingerprint: SEND_RESET_PASSWORD or SEND_RESET_PASSWORD_ERROR, then
UPDATE_PASSWORD or UPDATE_CREDENTIAL (password) on the same code_id, with
delta <= --threshold-ms (default 5000). EXECUTE_ACTION_TOKEN is not a reliable
success signal for this path. This is a heuristic, not proof of exploit: a
legitimate reset completed very quickly can also match.
Requires Direct Access Grants on the OIDC client (admin-cli by default) and
realm-management/view-events. If listing realms is forbidden, only
--auth-realm is scanned.
Examples:
  python3 cve-2026-18963-hunt.py --base https://keycloak.example --admin alice --since 7d --skip-master
  python3 cve-2026-18963-hunt.py --base https://keycloak.example --auth-realm myrealm --admin alice --realm myrealm --since 24h
Environment: KC_BASE, KC_AUTH_REALM, KC_CLIENT, KC_CLIENT_SECRET, KC_ADMIN,
KC_ADMIN_PASS, KC_TOTP, KC_SINCE, THRESHOLD_MS.
Exit codes: 0 no pair under threshold, 1 at least one SUSPECT, 2 login failure.
"""
from __future__ import annotations

import argparse
import datetime as dt
import getpass
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from typing import Any, Dict, Iterable, List, Optional, Tuple

SEND_TYPES = ("SEND_RESET_PASSWORD", "SEND_RESET_PASSWORD_ERROR")
UPDATE_TYPES = ("UPDATE_PASSWORD", "UPDATE_CREDENTIAL")
PAGE = 100


COLOR_LOG = sys.stderr.isatty()


def log(msg: str) -> None:
    ts = dt.datetime.now().strftime("%H:%M:%S")
    prefix = f"[{ts}]"
    if COLOR_LOG:
        prefix = f"\033[2m{prefix}\033[0m"
    sys.stderr.write(f"{prefix} {msg}\n")
    sys.stderr.flush()


def parse_since(value: str) -> int:
    """Return epoch milliseconds. Accepts 90m / 24h / 7d / ISO-8601 / epoch-ms."""
    raw = value.strip()
    now = time.time()
    if raw.isdigit():
        n = int(raw)
        return n if n > 10_000_000_000 else int(n * 1000)
    unit = raw[-1].lower()
    if unit in "smhd" and raw[:-1].replace(".", "", 1).isdigit():
        qty = float(raw[:-1])
        mult = {"s": 1, "m": 60, "h": 3600, "d": 86400}[unit]
        return int((now - qty * mult) * 1000)
    iso = raw.replace("Z", "+00:00")
    parsed = dt.datetime.fromisoformat(iso)
    if parsed.tzinfo is None:
        parsed = parsed.replace(tzinfo=dt.timezone.utc)
    return int(parsed.timestamp() * 1000)


def iso_utc(ms: int) -> str:
    return dt.datetime.fromtimestamp(ms / 1000, dt.timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")


def http_json(
    method: str,
    url: str,
    *,
    token: Optional[str] = None,
    form: Optional[Dict[str, str]] = None,
    timeout: int = 60,
) -> Tuple[int, Any]:
    data = None
    headers = {"Accept": "application/json"}
    if form is not None:
        data = urllib.parse.urlencode(form).encode()
        headers["Content-Type"] = "application/x-www-form-urlencoded"
    if token:
        headers["Authorization"] = f"Bearer {token}"
    req = urllib.request.Request(url, data=data, headers=headers, method=method)
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            body = resp.read().decode("utf-8", errors="replace")
            return resp.status, json.loads(body) if body else None
    except urllib.error.HTTPError as e:
        body = e.read().decode("utf-8", errors="replace")
        try:
            parsed = json.loads(body) if body else {}
        except json.JSONDecodeError:
            parsed = {"error": body}
        return e.code, parsed


def login(
    base: str,
    auth_realm: str,
    user: str,
    password: str,
    totp: Optional[str],
    client_id: str,
    client_secret: Optional[str],
) -> str:
    form = {
        "client_id": client_id,
        "username": user,
        "password": password,
        "grant_type": "password",
    }
    if totp:
        form["totp"] = totp
    if client_secret:
        form["client_secret"] = client_secret
    url = f"{base}/realms/{urllib.parse.quote(auth_realm)}/protocol/openid-connect/token"
    status, body = http_json("POST", url, form=form)
    if status == 200 and isinstance(body, dict) and body.get("access_token"):
        return str(body["access_token"])
    desc = ""
    if isinstance(body, dict):
        desc = str(body.get("error_description") or body.get("error") or body)
    raise RuntimeError(f"Admin login failed on realm {auth_realm} (HTTP {status}): {desc}")


def needs_otp(exc: RuntimeError) -> bool:
    msg = str(exc).lower()
    return any(k in msg for k in ("otp", "totp", "mfa", "invalid user credentials", "invalid_grant"))


def fetch_events(base: str, token: str, realm: str, event_type: str, date_from_ms: Optional[int], cap: int) -> List[dict]:
    out: List[dict] = []
    first = 0
    while first < cap:
        q = {
            "type": event_type,
            "first": str(first),
            "max": str(min(PAGE, cap - first)),
        }
        if date_from_ms is not None:
            q["dateFrom"] = str(date_from_ms)
        url = f"{base}/admin/realms/{urllib.parse.quote(realm)}/events?{urllib.parse.urlencode(q)}"
        status, body = http_json("GET", url, token=token)
        if status == 403:
            log(f"  skip {realm}/{event_type}: HTTP 403 (no view-events?)")
            return []
        if status != 200 or not isinstance(body, list):
            log(f"  skip {realm}/{event_type}: HTTP {status} {body}")
            return []
        out.extend(body)
        if len(body) < PAGE:
            break
        first += PAGE
    return out


def is_password_update(event: dict) -> bool:
    if event.get("type") == "UPDATE_PASSWORD":
        return True
    details = event.get("details") or {}
    return details.get("credential_type") == "password" or details.get("custom_required_action") == "UPDATE_PASSWORD"


def code_id(event: dict) -> str:
    return str((event.get("details") or {}).get("code_id") or "")


def username(event: dict) -> str:
    return str((event.get("details") or {}).get("username") or event.get("userId") or "?")


def ts(event: dict) -> int:
    return int(event.get("time") or 0)


def pairs_for_realm(sends: Iterable[dict], updates: Iterable[dict], threshold_ms: int) -> List[dict]:
    by_code: Dict[str, List[dict]] = {}
    for e in sends:
        cid = code_id(e)
        if cid:
            by_code.setdefault(cid, []).append(e)

    rows = []
    seen = set()
    for u in sorted(updates, key=ts):
        cid = code_id(u)
        if not cid or cid in seen:
            continue
        cands = [s for s in by_code.get(cid, []) if ts(s) <= ts(u)]
        if not cands:
            continue
        send = max(cands, key=ts)
        delta = ts(u) - ts(send)
        seen.add(cid)
        rows.append(
            {
                "delta_ms": delta,
                "suspect": delta <= threshold_ms,
                "username": username(u),
                "send": send.get("type"),
                "update_utc": iso_utc(ts(u)),
                "code_id": cid,
                "user_id": u.get("userId") or "",
            }
        )
    return rows


def term_width() -> int:
    try:
        return max(80, os.get_terminal_size().columns)
    except OSError:
        return 120


def paint(text: str, color: str, enabled: bool) -> str:
    if not enabled:
        return text
    codes = {"red": "31", "green": "32", "yellow": "33", "bold": "1", "dim": "2"}
    return f"\033[{codes[color]}m{text}\033[0m"


def print_table(rows: List[dict], color: bool) -> None:
    if not rows:
        print("  (no send->update pair on the same code_id)")
        return
    headers = ["delta_ms", "verdict", "username", "send", "update (UTC)", "code_id"]
    cells = []
    for r in rows:
        verdict = "SUSPECT" if r["suspect"] else "ok"
        cells.append(
            [
                str(r["delta_ms"]),
                verdict,
                r["username"],
                str(r["send"]),
                r["update_utc"],
                r["code_id"],
            ]
        )
    widths = [len(h) for h in headers]
    for row in cells:
        for i, cell in enumerate(row):
            widths[i] = max(widths[i], len(cell))
    budget = term_width() - 4 - 3 * (len(headers) - 1)
    extra = sum(widths) - budget
    if extra > 0:
        widths[-1] = max(12, widths[-1] - extra)

    def fmt_row(cols: List[str], *, header: bool = False, suspect: bool = False) -> str:
        padded = []
        for i, col in enumerate(cols):
            val = col if len(col) <= widths[i] else col[: max(0, widths[i] - 3)] + "..."
            padded.append(val.ljust(widths[i]) if i else val.rjust(widths[i]))
        line = "  " + "   ".join(padded)
        if header:
            return paint(line, "bold", color)
        if suspect:
            return paint(line, "red", color)
        return line

    print(fmt_row(headers, header=True))
    print("  " + paint("-" * min(term_width() - 2, sum(widths) + 3 * (len(headers) - 1)), "dim", color))
    for r, cols in zip(rows, cells):
        print(fmt_row(cols, suspect=r["suspect"]))


def main() -> int:
    p = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description=__doc__,
    )
    p.add_argument(
        "--base",
        default=os.environ.get("KC_BASE"),
        required=not os.environ.get("KC_BASE"),
        help="Keycloak base URL (or $KC_BASE)",
    )
    p.add_argument("--realm", action="append", dest="realms", help="Realm to scan (repeatable). Default: all, or auth-realm if listing fails")
    p.add_argument("--auth-realm", default=os.environ.get("KC_AUTH_REALM", "master"), help="Realm used for the password grant (default: master)")
    p.add_argument("--client", default=os.environ.get("KC_CLIENT", "admin-cli"), help="Client id for password grant (default: admin-cli)")
    p.add_argument("--client-secret", default=os.environ.get("KC_CLIENT_SECRET"), help="Client secret if the client is confidential")
    p.add_argument("--skip-master", action="store_true", help="Skip master when scanning all realms")
    p.add_argument(
        "--admin",
        default=os.environ.get("KC_ADMIN"),
        help="Admin username for the password grant (or $KC_ADMIN). Prompted if missing",
    )
    p.add_argument("--admin-pass", default=os.environ.get("KC_ADMIN_PASS"))
    p.add_argument("--totp", default=os.environ.get("KC_TOTP"), help="OTP code (or $KC_TOTP). Prompted if login requires it")
    p.add_argument("--since", default=os.environ.get("KC_SINCE", "7d"), help="Window: 90m, 24h, 7d, or ISO-8601 (default: 7d)")
    p.add_argument("--since-hours", type=float, help="Deprecated alias of --since Nh")
    p.add_argument("--threshold-ms", type=int, default=int(os.environ.get("THRESHOLD_MS", "5000")))
    p.add_argument("--max", type=int, default=5000, dest="cap", help="Max events per type per realm")
    p.add_argument("--no-color", action="store_true")
    args = p.parse_args()

    color = sys.stdout.isatty() and not args.no_color
    global COLOR_LOG
    COLOR_LOG = sys.stderr.isatty() and not args.no_color
    base = args.base.rstrip("/")
    since = f"{args.since_hours}h" if args.since_hours is not None else args.since
    date_from = parse_since(since)
    admin = args.admin or input("Admin username: ").strip()
    if not admin:
        log("admin username required")
        return 2
    password = args.admin_pass or getpass.getpass(f"Password for {admin}: ")
    totp = args.totp

    log(f"login {args.client} as {admin} on realm {args.auth_realm} ({base})")
    try:
        token = login(base, args.auth_realm, admin, password, totp, args.client, args.client_secret)
    except RuntimeError as e:
        if totp or not needs_otp(e):
            log(str(e))
            return 2
        totp = getpass.getpass("OTP: ")
        log("retry login with OTP")
        try:
            token = login(base, args.auth_realm, admin, password, totp, args.client, args.client_secret)
        except RuntimeError as e2:
            log(str(e2))
            return 2
    log("token OK")

    if args.realms:
        realms = args.realms
    else:
        status, body = http_json("GET", f"{base}/admin/realms", token=token)
        if status == 200 and isinstance(body, list):
            realms = [str(r.get("realm")) for r in body if r.get("realm")]
            if args.skip_master:
                realms = [r for r in realms if r != "master"]
            log(f"{len(realms)} realm(s): {', '.join(realms)}")
        else:
            log(f"cannot list all realms (HTTP {status}); scan auth-realm only: {args.auth_realm}")
            realms = [args.auth_realm]

    print()
    print(paint("CVE-2026-18963 reset timing hunt", "bold", color))
    print(f"  instance   {base}")
    print(f"  auth-realm {args.auth_realm}  client={args.client}")
    print(f"  since      {iso_utc(date_from)}  ({since})")
    print(f"  threshold  {args.threshold_ms} ms")
    print()

    all_rows: List[Tuple[str, dict]] = []
    for realm in realms:
        log(f"scan realm {realm}")
        sends: List[dict] = []
        for t in SEND_TYPES:
            sends.extend(fetch_events(base, token, realm, t, date_from, args.cap))
        updates: List[dict] = []
        for t in UPDATE_TYPES:
            updates.extend(e for e in fetch_events(base, token, realm, t, date_from, args.cap) if is_password_update(e))
        rows = pairs_for_realm(sends, updates, args.threshold_ms)
        suspects = sum(1 for r in rows if r["suspect"])
        log(f"  {realm}: sends={len(sends)} updates={len(updates)} pairs={len(rows)} suspect={suspects}")
        print(paint(f"> {realm}", "bold", color) + paint(f"   {len(sends)} send | {len(updates)} update | {len(rows)} pair", "dim", color))
        print_table(rows, color)
        print()
        for r in rows:
            all_rows.append((realm, r))

    suspects = [(realm, r) for realm, r in all_rows if r["suspect"]]
    print(paint("summary", "bold", color))
    print(f"  realms={len(realms)}  pairs={len(all_rows)}  suspect={len(suspects)}")
    if suspects:
        print(paint("  -> review SUSPECT rows (send then password change on same code_id).", "yellow", color))
        return 1
    print(paint("  -> no pair under threshold.", "green", color))
    return 0


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