Slide 1

Slide 1 text

Cracking JWT tokens a tale of magic, Node.js and parallel computing Node.js Dublin 30 NOV 2017 Luciano Mammino ( ) @loige loige.link/jwt-crack-dublin 1

Slide 2

Slide 2 text

loige.link/jwt-crack-dublin 2

Slide 3

Slide 3 text

Luciano... who!? Visit my castle: - - Twitter GitHub Linkedin https://loige.co Principal Application Engineer 3

Slide 4

Slide 4 text

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

Slide 5

Slide 5 text

Agenda What's JWT How it works Testing JWT tokens Brute-forcing a token! 5

Slide 6

Slide 6 text

— RFC 7519 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. JSON Web Token (JWT) 6

Slide 7

Slide 7 text

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZX NzYWdlIjoiaGVsbG8gZHVibGluIn0.3XcG- nyWravBScxDH1amc7- APwEq6H1eEAM_6PV9umc 7

Slide 8

Slide 8 text

OK Let's try to make it simpler... 8

Slide 9

Slide 9 text

JWT is... An URL safe, stateless protocol for transferring claims 9

Slide 10

Slide 10 text

URL safe? stateless? claims? 10

Slide 11

Slide 11 text

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

Slide 12

Slide 12 text

Stateless? Token validity can be verified without having to interrogate a third-party service (Sometimes also defined as "self-contained") 12

Slide 13

Slide 13 text

What is a claim? 13

Slide 14

Slide 14 text

some certified information identity (login session) authorisation to perform actions (api key) ownership (a ticket belongs to somebody) 14

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

also... protocol information Type of token Algorithm 16

Slide 17

Slide 17 text

In general All the bits of information transferred with the token 17

Slide 18

Slide 18 text

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZX NzYWdlIjoiaGVsbG8gZHVibGluIn0.3XcG- nyWravBScxDH1amc7- APwEq6H1eEAM_6PV9umc 18

Slide 19

Slide 19 text

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZX NzYWdlIjoiaGVsbG8gZHVibGluIn0.3XcG- nyWravBScxDH1amc7- APwEq6H1eEAM_6PV9umc 3 parts separated by "." 19

Slide 20

Slide 20 text

HEADER: eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp XVCJ9 PAYLOAD: eyJtZXNzYWdlIjoiaGVsbG8gZHVib GluIn0 SIGNATURE: 3XcG-nyWravBScxDH1amc7- APwEq6H1eEAM_6PV9umc 20

Slide 21

Slide 21 text

Header and Payload are encoded let's decode them! Base64Url 21

Slide 22

Slide 22 text

HEADER: The decoded info is JSON! PAYLOAD: {"alg":"HS256","typ":"JWT"} {"message":"hello dublin"} 22

Slide 23

Slide 23 text

HEADER: {"alg":"HS256","typ":"JWT"} alg: the kind of algorithm used "HS256" HMACSHA256 Signature (secret based hashing) "RS256" RSASHA256 Signature (public/private key hashing) "none" NO SIGNATURE! (This is " ") infamous 23

Slide 24

Slide 24 text

PAYLOAD: {"message":"hello dublin"} Payload can be anything that you can express in JSON 24

Slide 25

Slide 25 text

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") 25

Slide 26

Slide 26 text

PAYLOAD: "registered" (or standard) claims: { "iss": "auth0", "sub": "johndoe@gmail.com", "aud": "https://someapp.com", "exp": "1510047437793", "nbf": "1510046471284", "iat": "1510045471284" } 26

Slide 27

Slide 27 text

So far it's just metadata... What makes it safe? 27

Slide 28

Slide 28 text

SIGNATURE: 3XcG-nyWravBScxDH1amc7- APwEq6H1eEAM_6PV9umc A Base64URL encoded cryptographic signature of the header and the payload 28

Slide 29

Slide 29 text

With HS256 signature = HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), password ) header payload secret SIGNATURE + + = 29

Slide 30

Slide 30 text

If a system knows the secret It can verify the authenticity of the token With HS256 30

Slide 31

Slide 31 text

Playground for JWT JWT.io 31

Slide 32

Slide 32 text

An example Session token 32

Slide 33

Slide 33 text

Classic implementation cookie/session based 33

Slide 34

Slide 34 text

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)

hello luciano

Server 34 Sessions Database id:"Y4sHySEPWAjc" user:"luciano" SID:"Y4sHySEPWAjc"

Slide 35

Slide 35 text

JWT implementation 35

Slide 36

Slide 36 text

Browser 1. POST /login 3. JWT Token {"sub":"luciano"} user:"luciano" pass:"mariobros" 6. (page)

hello luciano

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

Slide 37

Slide 37 text

Cookie/session Needs a database to store the session data The database is queried for every request to fetch the session A session is identified only by a randomly generated string (session ID) No data attached Sessions can be invalidated at any moment JWT Doesn't need a session database The session data is embedded in the token For every request the token signature is verified Attached metadata is readable Sessions can't be invalidated, but tokens might have an expiry flag VS 37

Slide 38

Slide 38 text

JWT LOOKS GREAT! But there are pitfalls... 38

Slide 39

Slide 39 text

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 39

Slide 40

Slide 40 text

There's no token database... ...if I can forge a token nobody will know it's not authentic! 40

Slide 41

Slide 41 text

DEMO JWT based web app github.com/lmammino/sample-jwt-webapp 41

Slide 42

Slide 42 text

Given an HS256 signed JWT We can try to "guess" the password! 42

Slide 43

Slide 43 text

How difficult can it be? 43

Slide 44

Slide 44 text

Let's build a distributed JWT token cracker! npm.im/distributed-jwt-cracker 44

Slide 45

Slide 45 text

The idea... YOU CAN NOW CREATE AND SIGN ANY JWT TOKEN FOR THIS APPLICATION! if the token is validated, then you found the secret! try to "guess" the secret and validate the token against it Take a valid JWT token 45

Slide 46

Slide 46 text

Magic weapons Node.js module jsonwebtoken ZeroMQ 46

Slide 47

Slide 47 text

ZeroMQ an open source embeddable networking library and a concurrency framework 47

Slide 48

Slide 48 text

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, ... 48

Slide 49

Slide 49 text

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 ... 49

Slide 50

Slide 50 text

Architecture Server Client Initialised with a valid JWT token and an alphabet coordinates the brute force attempts among connected clients knows how to verify a token against a given secret receives ranges of secrets to check 50

Slide 51

Slide 51 text

Networking patterns Router channels: dispatch jobs receive results Pub/Sub channel: termination signal 51

Slide 52

Slide 52 text

Server state the solution space can be sliced into chunks of fixed length (batch size) 52

Slide 53

Slide 53 text

Initial server state { "cursor": 0, "clients": {} } 53

Slide 54

Slide 54 text

The first client connects { "cursor": 3, "clients": { "client1": [0,2] } } [0,2] 54

Slide 55

Slide 55 text

{ "cursor": 9, "clients": { "client1": [0,2], "client2": [3,5], "client3": [6,8] } } Other clients connect [0,2] [3,5] [6,8] 55

Slide 56

Slide 56 text

Client 2 finishes its job { "cursor": 12, "clients": { "client1": [0,2], "client2": [9,11], "client3": [6,8] } } [0,2] [9,11] [6,8] 56

Slide 57

Slide 57 text

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 57

Slide 58

Slide 58 text

Messages flow JWT Cracker Server JWT Cracker Client 1. JOIN 2. START {token, alphabet, firstBatch} 3. NEXT 4. BATCH {nextBatch} 5. SUCCESS {secret} 58

Slide 59

Slide 59 text

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 59

Slide 60

Slide 60 text

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 60

Slide 61

Slide 61 text

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 61

Slide 62

Slide 62 text

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++) { try { pwd = variations(i) jwt.verify(token, pwd, { ignoreExpiration: true, ignoreNotBefore: true }) // finished, password found return ({found: pwd}) } catch (err) {} // password not found, keep looping } // finished, password not found return null } Client 62

Slide 63

Slide 63 text

Demo 63

Slide 64

Slide 64 text

Closing off 64

Slide 65

Slide 65 text

Is JWT safe to use? 65

Slide 66

Slide 66 text

Definitely YES! Heavily used by: 66

Slide 67

Slide 67 text

but... 67

Slide 68

Slide 68 text

Use strong (≃long) passwords and keep them SAFE! Or, even better Use RS256 (RSA public/private key pair) signature Use it wisely! 68

Slide 69

Slide 69 text

But, what if I create only short lived tokens... 69

Slide 70

Slide 70 text

JWT is STATELESS! the expiry time is contained in the token... if you can edit tokens, you can extend the expiry time as needed! 70

Slide 71

Slide 71 text

Should I be worried about brute force? 71

Slide 72

Slide 72 text

Not really ... As long as you know the basic rules (and the priorities) to defend yourself 72

Slide 73

Slide 73 text

TLDR; JWT is a cool & stateless™ way to transfer claims! Choose the right Algorithm With HS256, choose a good password and keep it safe Don't disclose sensible information in the payload Don't be too worried about brute force, but understand how it works! 73

Slide 74

Slide 74 text

{"THANK":"YOU"} @loige https://loige.co loige.link/jwt-crack-dublin 74

Slide 75

Slide 75 text

Credits vector images designed by freepik an heartfelt thank you to: @AlleviTommaso @andreaman87 @cirpo @katavic_d @Podgeypoos79 @quasi_modal 75