8a. JWT

8a. JWT

1. JWT (JSON Web Token) Overview

A JWT is a URL-safe JSON claims container that may be signed as a JWS and/or encrypted as a JWE. JWT is a format used by some authentication and authorization designs; it is not itself a session-management strategy.

1.1 JWT Structure

A compact JWS has three Base64url-encoded segments. A compact JWE has five segments, so “every JWT has three parts” is incorrect.

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 Requires shared or partitioned state; mature designs scale horizontally. Can reduce centralized session lookups, but key, replay, and revocation systems still need state.
Performance May require a cache or database lookup. Local verification may be fast; authorization data can become stale.
Storage Session state remains server-side; the browser holds an opaque identifier. Storage depends on the client and threat model; do not put bearer tokens in browser local storage by default.
Session Expiry Server can invalidate session state. Expiry is encoded, while revocation can use short lifetimes, rotation, deny lists, or introspection.
Security Security depends on cookie, session, and server controls. Security depends on issuer/audience validation, algorithms, keys, storage, replay controls, and lifecycle.
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. It separates signing from verification but still requires sound algorithms, key management, and verifier policy.

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: Trick a server that uses RS256 (asymmetric) into verifying a token with HS256 (symmetric), using its own public key as the HMAC secret — a key the attacker can obtain legitimately.

Exploitation Steps:

  1. Obtain the server's RSA public key (often exposed at /jwks.json or similar).
  2. Change the JWT alg header from RS256 to HS256.
  3. Re-sign the modified JWT using the server's public key as the HMAC secret.
  4. The vulnerable server, seeing alg: HS256, verifies the signature using its public key as the HMAC secret — and accepts the forged token.

✅ 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 JOSE header parameter.
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. Configure an explicit allowed algorithm set and keep symmetric and asymmetric verification paths separate.
  2. Validate issuer (iss), audience (aud), subject and token type as required by the application.
  3. Validate exp and nbf with bounded clock skew; define replay and revocation behavior.
  4. Reject unsigned tokens, unexpected critical headers, untrusted key references, and keys not bound to the issuer.
  5. Rotate signing keys safely and test overlap, revocation, and failure behavior.

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):

In an isolated fixture, store a non-secret marker where the application would store a token and confirm that an injected script can read the marker. Do not collect or transmit a real token.

✅ 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: