SlideShare a Scribd company logo
Cracking JWT tokens: a tale of magic,
Node.js and parallel computing
CODEMOTION MILAN - SPECIAL EDITION 10 - 11 NOVEMBER 2017
Luciano Mammino ( )@loige
loige.link/cracking-jwt-codemotion 1
loige.link/cracking-jwt-codemotion
2
About Luciano
Let's connect:
- -Twitter GitHub Linkedin
https://loige.co
Principal Application Engineer
3
Based on prior work
Chapters 10 & 11 in (book)
2-parts article on RisingStack:
" "
Node.js design patterns
ZeroMQ & Node.js Tutorial - Cracking JWT Tokens
github.com/lmammino/jwt-cracker
github.com/lmammino/distributed-jwt-cracker
4
Agenda
What's JWT
How it works
Testing JWT tokens
Brute-forcing a token!
5
RFC 7519
JSON Web Token (JWT)
is a compact, URL-safe means of representing claims to be transferred between
two parties. The claims in a JWT are encoded as a JSON object that is used as the
payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON
Web Encryption (JWE) structure, enabling the claims to be digitally signed or
integrity protected with a Message Authentication Code (MAC) and/or
encrypted.
6
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVC
J9.eyJtZXNzYWdlIjoiaGVsbG8gY29kZ
W1vdGlvbiJ9.LfQ4AOIjQPeAotn237m
5yiMgJacC_00ePvlFC4fyRXE
7
OK
Let's try to make it
simpler...
8
JWT is...
An URL safe, stateless protocol
for transferring claims
9
URL safe?
stateless?
claims?
10
URL Safe...
It's a string that can be safely used as part of a URL
(it doesn't contain URL separators like "=", "/", "#" or "?")
11
Stateless?
Token validity can be verified without having to
interrogate a third-party service
12
What is a claim?
13
some certified information
identity (login session)
authorisation to perform actions (api key)
ownership (a ticket belongs to somebody)
14
also...
validity constraints
token time constraints (dont' use before/after)
audience (a ticket only for a specific concert)
issuer identity (a ticket issued by a specific reseller)
15
also...
protocol information
Type of token
Algorithm
16
In general
All the bits of information transferred through the token
17
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ
9.eyJtZXNzYWdlIjoiaGVsbG8gY29kZW1
vdGlvbiJ9.LfQ4AOIjQPeAotn237m5yiM
gJacC_00ePvlFC4fyRXE
18
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ
9.eyJtZXNzYWdlIjoiaGVsbG8gY29kZW1
vdGlvbiJ9.LfQ4AOIjQPeAotn237m5yiM
gJacC_00ePvlFC4fyRXE
19
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ
9.eyJtZXNzYWdlIjoiaGVsbG8gY29kZW1
vdGlvbiJ9.LfQ4AOIjQPeAotn237m5yiM
gJacC_00ePvlFC4fyRXE
3 parts
separated by "."
20
HEADER:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
PAYLOAD:
eyJtZXNzYWdlIjoiaGVsbG8gY29kZW1vd
GlvbiJ9
SIGNATURE:
LfQ4AOIjQPeAotn237m5yiMgJacC_00e
PvlFC4fyRXE 21
Header and Payload are
encoded
let's decode them!
Base64Url
22
HEADER:
{"alg":"HS256","typ":"JWT"}
The decoded info is JSON!
PAYLOAD:
{"message":"hello codemotion"}
23
HEADER:
{"alg":"HS256","typ":"JWT"}
alg: the kind of algorithm used
"HS256" HMACSHA256 Signature
(secret based hashing)
"RS256" RSASHA256 Signature
(public/private key hashing)
24
PAYLOAD:
{"message":"hello codemotion"}
Payload can be anything you can
express in JSON
25
PAYLOAD:
registered (or standard) claims
iss: issuer ID ("auth0")
sub: subject ID ("johndoe@gmail.com")
aud: audience ID ("https://someapp.com")
exp: expiration time ("1510047437793")
nbf: not before ("1510046471284")
iat: issue time ("1510045471284")
jti: Unique identifier ("36c56616-2125-4a6e-b333-bc8327bd39d6")
26
So far it's just metadata...
What makes it safe?
27
SIGNATURE:
LfQ4AOIjQPeAotn237m5yiMgJacC_00e
PvlFC4fyRXE
A Base64URL encoded cryptographic
signature of the header and the payload
28
With HS256
signature = HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
password
)
header payload secret SIGNATURE+ + =
29
If a system knows the secret
It can verify the authenticity
of the token
30
Playground for JWT
JWT.io
31
An example
Session token
32
Classic implementation
Without JWT
33
Browser
1. POST /login
2. generate session
id:"Y4sHySEPWAjc"
user:"luciano"
user:"luciano"
pass:"mariobros"
3. session cookie
SID:"Y4sHySEPWAjc"
4. GET /profile
5. query
id:"Y4sHySEPWAjc"
6. record
id:"Y4sHySEPWAjc"
user:"luciano"
7. (page)
<h1>hello luciano</h1>
Server
34
Sessions
Database
id:"Y4sHySEPWAjc"
user:"luciano"SID:"Y4sHySEPWAjc"
JWT implementation
(NO session database)
35
Browser
1. POST /login
3. JWT Token
{"sub":"luciano"}
user:"luciano"
pass:"mariobros"
6. (page)
<h1>hello luciano</h1>
Server
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ
zdWIiOiJsdWNpYW5vIn0.V92iQaqMrBUhkgEAyRa
CY7pezgH-Kls85DY8wHnFrk4
4. GET /profile
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ
zdWIiOiJsdWNpYW5vIn0.V92iQaqMrBUhkgEAyRa
CY7pezgH-Kls85DY8wHnFrk4
Token says this is "luciano"
Signature looks OK
5. verify
Create Token for "luciano"
Add signature
2. create
JWT
36
JWT LOOKS GREAT!
But there are pitfalls...
37
Data is public
If you have a token,
you can easily read the claims!
You only have to Base64Url-decode the token header and payload
and you have a readable JSON
38
No token database...
...maybe I can forge a token and
nobody will know it's not authentic!
39
DEMO
JWT based web app
github.com/lmammino/sample-jwt-webapp
40
Given an HS256 signed JWT
We can try to "guess" the password!
41
How difficult can it be?
42
Let's build a distributed JWT
token cracker!
npm.im/distributed-jwt-cracker
43
The idea...
Take a valid JWT token
try to "guess" the secret and validate the token against it
if the token is validated, then you found the secret!
YOU CAN NOW CREATE AND SIGN ANY JWT TOKEN FOR THIS APPLICATION!
44
Tools of the trade
Node.js
module
ZeroMQ
jsonwebtoken
45
ZeroMQ
an open source embeddable
networking library and a
concurrency framework
46
The brute force problem
"virtually infinite" solutions space
all the strings (of any length) that can be generated within a given alphabet
(empty string), a, b, c, 1, aa, ab, ac, a1, ba, bb, bc, b1, ca, cb, cc, c1, 1a, 1b, 1c, 11,
aaa, aab, aac, aa1, aba, ...
47
bijection (int) (string)
if we sort all the possible strings over an alphabet
Alphabet = [a,b]
0 ⟶ (empty string)
1 ⟶ a
2 ⟶ b
3 ⟶ aa
4 ⟶ ab
5 ⟶ ba
6 ⟶ bb
7 ⟶ aaa
8 ⟶ aab
9 ⟶ aba
10 ⟶ abb
11 ⟶ baa
12 ⟶ bab
13 ⟶ bba
14 ⟶ bbb
15 ⟶ aaaa
16 ⟶ aaab
17 ⟶ aaba
18 ⟶ aabb
...
48
Architecture
Server
Initialised with a valid JWT token
and an alphabet
coordinates the brute force
attempts among connected
clients
Client
knows how to verify a token
against a given secret
receives ranges of secrets to
check
49
Networking patterns
Router channels:
dispatch jobs
receive results
Pub/Sub channel:
termination
signal
50
Server state
the solution space can be sliced into
chunks of fixed length (batch size)
51
Initial server state
{
"cursor": 0,
"clients": {}
}
52
The first client connects
{
"cursor": 3,
"clients": {
"client1": [0,2]
}
}
53
Other clients connect
{
"cursor": 9,
"clients": {
"client1": [0,2],
"client2": [3,5],
"client3": [6,8]
}
} 54
Client 2 finishes its job
{
"cursor": 12,
"clients": {
"client1": [0,2],
"client2": [9,11],
"client3": [6,8]
}
} 55
let cursor = 0
const clients = new Map()
const assignNextBatch = client => {
const from = cursor
const to = cursor + batchSize - 1
const batch = [from, to]
cursor = cursor + batchSize
client.currentBatch = batch
client.currentBatchStartedAt = new Date()
return batch
}
const addClient = channel => {
const id = channel.toString('hex')
const client = {id, channel, joinedAt: new Date()}
assignNextBatch(client)
clients.set(id, client)
return client
} Server
56
Messages flow
JWT Cracker
Server
JWT Cracker
Client
1. JOIN
2. START
{token, alphabet, firstBatch}
3. NEXT
4. BATCH
{nextBatch}
5. SUCCESS
{secret}
57
const router = (channel, rawMessage) => {
const msg = JSON.parse(rawMessage.toString())
switch (msg.type) {
case 'join': {
const client = addClient(channel)
const response = {
type: 'start',
id: client.id,
batch: client.currentBatch,
alphabet,
token
}
batchSocket.send([channel, JSON.stringify(response)])
break
}
case 'next': {
const batch = assignNextBatch(clients.get(channel.toString('hex')))
batchSocket.send([channel, JSON.stringify({type: 'batch', batch})])
break
}
case 'success': {
const pwd = msg.password
// publish exit signal and closes the app
signalSocket.send(['exit', JSON.stringify({password: pwd, client: channel.toString('hex')})], 0, () => {
batchSocket.close()
signalSocket.close()
exit(0)
})
break
}
}
}
Server
58
let id, variations, token
const dealer = rawMessage => {
const msg = JSON.parse(rawMessage.toString())
const start = msg => {
id = msg.id
variations = generator(msg.alphabet)
token = msg.token
}
const batch = msg => {
processBatch(token, variations, msg.batch, (pwd, index) => {
if (typeof pwd === 'undefined') {
// request next batch
batchSocket.send(JSON.stringify({type: 'next'}))
} else {
// propagate success
batchSocket.send(JSON.stringify({type: 'success', password: pwd, index}))
exit(0)
}
})
}
switch (msg.type) {
case 'start':
start(msg)
batch(msg)
break
case 'batch':
batch(msg)
break
}
}
Client
59
How a chunk is processed
Given chunk [3,6] over alphabet "ab"
[3,6]
3 ⟶ aa
4 ⟶ ab
5 ⟶ ba
6 ⟶ bb
⇠ check if one of
the strings is the
secret that validates
the current token
60
const jwt = require('jsonwebtoken')
const generator = require('indexed-string-variation').generator;
const variations = generator('someAlphabet')
const processChunk = (token, from, to) => {
let pwd
for (let i = from; i < to; i++) {
pwd = variations(i)
jwt.verify(token, pwd, {
ignoreExpiration: true,
ignoreNotBefore: true
})
// finished, password found
return ({found: i})
}
// finished, password not found
return null
} Client
61
Demo
62
Closing off
63
Is JWT safe to use?
64
Definitely
YES!
65
but...
66
Use strong (≃long) passwords and
keep them SAFE!
Or, even better
Use RS256 (RSA public/private key
pair) signature
Use it wisely!
67
Should I be worried about
brute force?
68
Not really
... As long as you know the basic rules
(and the priorities) to defend yourself
69
A challenge for you:
Can you crack this one?
eyJhbGciOiJIUzI1NiIsInR5cCI6I
kpXVCJ9.eyJjcmFjayI6Im1lIiwia
WYiOiJ5b3UgY2FuIn0.tI8zO0gj6W
BgaVoKNeHwCKOxOlr3Jo7OqKHwMgr
qJJE
If you can, tweet the secret to
I have a prize for the first one!
@loige
70
{"THANK":"YOU"}
@loige
https://loige.co
loige.link/cracking-jwt-codemotion
71

More Related Content

PDF
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing - Node.j...
PPTX
Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018)
PPTX
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
PPTX
MongoDB Live Hacking
PDF
Certified Pseudonym Colligated with Master Secret Key
PPTX
分散式系統
PPT
WebSocket JSON Hackday
PDF
[BlackHat USA 2016] Nonce-Disrespecting Adversaries: Practical Forgery Attack...
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing - Node.j...
Blockchain Cryptography for Developers (Nakov @ BGWebSummit 2018)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
MongoDB Live Hacking
Certified Pseudonym Colligated with Master Secret Key
分散式系統
WebSocket JSON Hackday
[BlackHat USA 2016] Nonce-Disrespecting Adversaries: Practical Forgery Attack...

What's hot (20)

ODP
Applying Security Algorithms Using openSSL crypto library
ODP
MQTT and Java - Client and Broker Examples
PDF
Braga Blockchain - Ethereum Smart Contracts programming
PDF
Understanding c# for java
PPS
Singleton
PPT
Singleton
PDF
CIS14: Developing with OAuth and OIDC Connect
PDF
Tendermint in a nutshell
PPTX
Java with a Clojure mindset
PDF
Ethereum VM and DSLs for Smart Contracts (updated on May 12th 2015)
PDF
Java Concurrency Idioms
PPTX
Uniface Lectures Webinar - Application & Infrastructure Security - JSON Web T...
KEY
Introduction to Functional Programming with Scheme
PPTX
Weaponizing the Windows API with Metasploit's Railgun
PDF
Qt Rest Server
PDF
Actor Concurrency
PPTX
Final requirement in programming niperos
PDF
Circuit breaker
PDF
Silicon Valley JUG: JVM Mechanics
PPTX
Final requirement in programming vinson
Applying Security Algorithms Using openSSL crypto library
MQTT and Java - Client and Broker Examples
Braga Blockchain - Ethereum Smart Contracts programming
Understanding c# for java
Singleton
Singleton
CIS14: Developing with OAuth and OIDC Connect
Tendermint in a nutshell
Java with a Clojure mindset
Ethereum VM and DSLs for Smart Contracts (updated on May 12th 2015)
Java Concurrency Idioms
Uniface Lectures Webinar - Application & Infrastructure Security - JSON Web T...
Introduction to Functional Programming with Scheme
Weaponizing the Windows API with Metasploit's Railgun
Qt Rest Server
Actor Concurrency
Final requirement in programming niperos
Circuit breaker
Silicon Valley JUG: JVM Mechanics
Final requirement in programming vinson
Ad

Similar to Cracking JWT tokens: a tale of magic, Node.JS and parallel computing (20)

PDF
Cracking JWT tokens: a tale of magic, Node.js and parallel computing - Code E...
PDF
Cracking JWT tokens: a tale of magic, Node.js and parallel computing - WebReb...
PDF
Cracking JWT tokens: a tale of magic, Node.js and parallel computing - FullSt...
PDF
Landscape
PDF
Landscape
PDF
5 easy steps to understanding json web tokens (jwt)
PDF
Modern API Security with JSON Web Tokens
PPTX
Json Web Token - JWT
PDF
JWT(JSON WEB TOKEN) hand book for beginner
PDF
Building Web APIs that Scale
PDF
Jwt Security
PDF
Are You Properly Using JWTs?
PPTX
Micro Web Service - Slim and JWT
PDF
JSON Web Tokens Will Improve Your Life
PDF
Matthew Eernisse, NodeJs, .toster {webdev}
PDF
Oauth Nightmares Abstract OAuth Nightmares
PDF
[WTMC 2019] Detecting malicious campaigns in obfuscated JavaScript with scala...
PDF
Introduction to JWT and How to integrate with Spring Security
PDF
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
PDF
JSON Web Tokens Will Improve Your Life
Cracking JWT tokens: a tale of magic, Node.js and parallel computing - Code E...
Cracking JWT tokens: a tale of magic, Node.js and parallel computing - WebReb...
Cracking JWT tokens: a tale of magic, Node.js and parallel computing - FullSt...
Landscape
Landscape
5 easy steps to understanding json web tokens (jwt)
Modern API Security with JSON Web Tokens
Json Web Token - JWT
JWT(JSON WEB TOKEN) hand book for beginner
Building Web APIs that Scale
Jwt Security
Are You Properly Using JWTs?
Micro Web Service - Slim and JWT
JSON Web Tokens Will Improve Your Life
Matthew Eernisse, NodeJs, .toster {webdev}
Oauth Nightmares Abstract OAuth Nightmares
[WTMC 2019] Detecting malicious campaigns in obfuscated JavaScript with scala...
Introduction to JWT and How to integrate with Spring Security
Java EE 7 (Lyon JUG & Alpes JUG - March 2014)
JSON Web Tokens Will Improve Your Life
Ad

More from Luciano Mammino (20)

PDF
Serverless Rust: Your Low-Risk Entry Point to Rust in Production (and the ben...
PDF
Did you know JavaScript has iterators? DublinJS
PDF
What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...
PDF
Building an invite-only microsite with Next.js & Airtable - ReactJS Milano
PDF
From Node.js to Design Patterns - BuildPiper
PDF
Let's build a 0-cost invite-only website with Next.js and Airtable!
PDF
Everything I know about S3 pre-signed URLs
PDF
Serverless for High Performance Computing
PDF
Serverless for High Performance Computing
PDF
JavaScript Iteration Protocols - Workshop NodeConf EU 2022
PDF
Building an invite-only microsite with Next.js & Airtable
PDF
Let's take the monolith to the cloud 🚀
PDF
A look inside the European Covid Green Certificate - Rust Dublin
PDF
Monoliths to the cloud!
PDF
The senior dev
PDF
Node.js: scalability tips - Azure Dev Community Vijayawada
PDF
A look inside the European Covid Green Certificate (Codemotion 2021)
PDF
AWS Observability Made Simple
PDF
Semplificare l'observability per progetti Serverless
PDF
Finding a lost song with Node.js and async iterators - NodeConf Remote 2021
Serverless Rust: Your Low-Risk Entry Point to Rust in Production (and the ben...
Did you know JavaScript has iterators? DublinJS
What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...
Building an invite-only microsite with Next.js & Airtable - ReactJS Milano
From Node.js to Design Patterns - BuildPiper
Let's build a 0-cost invite-only website with Next.js and Airtable!
Everything I know about S3 pre-signed URLs
Serverless for High Performance Computing
Serverless for High Performance Computing
JavaScript Iteration Protocols - Workshop NodeConf EU 2022
Building an invite-only microsite with Next.js & Airtable
Let's take the monolith to the cloud 🚀
A look inside the European Covid Green Certificate - Rust Dublin
Monoliths to the cloud!
The senior dev
Node.js: scalability tips - Azure Dev Community Vijayawada
A look inside the European Covid Green Certificate (Codemotion 2021)
AWS Observability Made Simple
Semplificare l'observability per progetti Serverless
Finding a lost song with Node.js and async iterators - NodeConf Remote 2021

Recently uploaded (20)

PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Machine learning based COVID-19 study performance prediction
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Big Data Technologies - Introduction.pptx
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Spectroscopy.pptx food analysis technology
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Electronic commerce courselecture one. Pdf
A comparative analysis of optical character recognition models for extracting...
Unlocking AI with Model Context Protocol (MCP)
Machine learning based COVID-19 study performance prediction
Agricultural_Statistics_at_a_Glance_2022_0.pdf
The AUB Centre for AI in Media Proposal.docx
gpt5_lecture_notes_comprehensive_20250812015547.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Dropbox Q2 2025 Financial Results & Investor Presentation
Big Data Technologies - Introduction.pptx
NewMind AI Weekly Chronicles - August'25-Week II
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Spectral efficient network and resource selection model in 5G networks
Reach Out and Touch Someone: Haptics and Empathic Computing
Spectroscopy.pptx food analysis technology
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
Electronic commerce courselecture one. Pdf

Cracking JWT tokens: a tale of magic, Node.JS and parallel computing