Get a Pentest and security assessment of your IT network.

Cyber Security

Breaking JWT Signatures: Brute Force HMAC SHA256

TL;DR

Yes, a brute-force attack on the HMAC SHA256 (HS256) signature used in JSON Web Tokens (JWTs) can effectively break the token’s security. This is because HS256 relies solely on a secret key. If an attacker guesses or discovers this key, they can forge valid tokens.

Understanding JWT and HMAC SHA256

JSON Web Tokens (JWTs) are commonly used for authentication. They consist of three parts: a header, payload, and signature. HMAC SHA256 is a specific signing algorithm often used with JWTs.

  • Header: Contains information about the token type and hashing algorithm (e.g., HS256).
  • Payload: Holds the claims – data you want to transmit (user ID, roles, etc.).
  • Signature: Created by combining the header, payload, and a secret key using HMAC SHA256. This signature verifies the token’s integrity and authenticity.

HS256 uses a symmetric key – meaning the same key is used for both signing *and* verifying the token.

How Brute Force Attacks Work

A brute-force attack attempts to guess the secret key used to sign the JWT. Here’s how it works:

  1. Obtain a Valid Token: The attacker needs access to a legitimate, signed JWT.
  2. Extract Header and Payload: They decode the header and payload from the token (these are base64 encoded, not encrypted).
  3. Attempt Key Guesses: The attacker systematically tries different possible secret keys. This could involve:

    • Dictionary Attacks: Trying common passwords or phrases.
    • Random String Generation: Generating random strings of varying lengths.
    • Known Vulnerabilities: If the application has known key weaknesses, exploiting those.
  4. Verify Signature: For each guessed key, the attacker recalculates the HMAC SHA256 signature using the header, payload, and the current key guess. They then compare this calculated signature to the original signature in the JWT.
  5. Successful Match: If the recalculated signature matches the original, the attacker has found the secret key! They can now forge valid tokens.

Steps to Test for Brute Force Vulnerability (Example using Python)

Disclaimer: This is for educational purposes only. Attempting to crack JWTs without authorization is illegal and unethical.

  1. Install Required Libraries: You’ll need libraries like pyjwt and potentially others for dictionary attacks (e.g., hashlib).
pip install pyjwt
  1. Decode the JWT: Extract the header and payload.
import jwt

token = "YOUR_JWT_TOKEN"

try:
    decoded_payload = jwt.decode(token, options={'verify': False})
    header = decoded_payload['header']
    payload = decoded_payload['payload']
except jwt.exceptions.DecodeError as e:
    print(f"Error decoding token: {e}")
    exit()
  1. Brute-Force the Key (Simple Example): This example tries a few hardcoded keys. A real attack would use a much larger key space.
import hashlib
import hmac

secret_keys = ["secret", "password123", "mykey"]

for key in secret_keys:
    try:
        message = header + '.' + payload
        hashed = hmac.new(key.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest()
        if hashed == token.split('.')[2]:
            print(f"Key found: {key}")
            exit()
    except Exception as e:
        pass # Handle potential errors during hashing
  1. Advanced Techniques: For more realistic attacks, consider:

    • Using wordlists and dictionary attacks.
    • Implementing rate limiting to slow down the attack (attacker side).
    • Trying common key patterns.

Mitigation Strategies

  1. Use Strong, Random Keys: The most important step! Generate keys with sufficient length and entropy. Avoid predictable or easily guessable keys.
  2. Key Rotation: Regularly change the secret key used for signing.
  3. Consider Asymmetric Algorithms (RS256): Use algorithms like RS256, which use a private/public key pair. The public key can be distributed freely for verification, while the private key remains secure. This eliminates the need to share a symmetric secret.
  4. Rate Limiting: Limit the number of failed signature attempts from a single IP address or user account.
  5. Monitor for Suspicious Activity: Look for unusual patterns in token requests that might indicate an attack.
Related posts
Cyber Security

Zip Codes & PII: Are They Personal Data?

Cyber Security

Zero-Day Vulnerabilities: User Defence Guide

Cyber Security

Zero Knowledge Voting with Trusted Server

Cyber Security

ZeroNet: 51% Attack Risks & Mitigation