From b6f97fecc58d105e052d3e86404b5f1694323825 Mon Sep 17 00:00:00 2001 From: neeraj netrakar Date: Mon, 16 Nov 2026 01:25:55 +0530 Subject: [PATCH] Require PEM armor for string keys in the python-ecdsa backend ecdsa.VerifyingKey.from_pem() ignores the armor lines and decodes bare base64 DER, so ECDSAECKey accepted EC public keys that HMACKey does not recognise as asymmetric. The same public key string could then be used as an HS256 secret to forge tokens. Only load PEM-armored keys, as the cryptography backend already does. --- jose/backends/ecdsa_backend.py | 9 ++++++++- tests/algorithms/test_EC.py | 16 ++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/jose/backends/ecdsa_backend.py b/jose/backends/ecdsa_backend.py index 756c7ea8..42864600 100644 --- a/jose/backends/ecdsa_backend.py +++ b/jose/backends/ecdsa_backend.py @@ -5,7 +5,7 @@ from jose.backends.base import Key from jose.constants import ALGORITHMS from jose.exceptions import JWKError -from jose.utils import base64_to_long, long_to_base64 +from jose.utils import base64_to_long, is_pem_format, long_to_base64 class ECDSAECKey(Key): @@ -58,6 +58,13 @@ def __init__(self, key, algorithm): key = key.encode("utf-8") if isinstance(key, bytes): + # python-ecdsa's from_pem() skips the "-----" armor lines and also + # decodes bare base64 DER. HMACKey only refuses PEM-armored keys, + # so a key accepted here without armor could also be used as an + # HMAC secret. Require real PEM, as the cryptography backend does. + if not is_pem_format(key): + raise JWKError("Unable to parse an ECKey from key: key is not in PEM format") + # Attempt to load key. We don't know if it's # a Signing Key or a Verifying Key, so we try # the Verifying Key first. diff --git a/tests/algorithms/test_EC.py b/tests/algorithms/test_EC.py index d8602a2b..76bca1af 100644 --- a/tests/algorithms/test_EC.py +++ b/tests/algorithms/test_EC.py @@ -95,6 +95,22 @@ def test_key_from_ecdsa(): assert not ECKey(key, ALGORITHMS.ES256).is_public() +@pytest.mark.ecdsa +@pytest.mark.skipif(None in (ECDSAECKey, ecdsa), reason="python-ecdsa backend not available") +def test_ecdsa_key_without_pem_armor_rejected(): + pem = ecdsa.SigningKey.from_pem(private_key).get_verifying_key().to_pem().decode() + bare = "".join(line for line in pem.splitlines() if not line.startswith("-----")) + + # Without the armor the key would also pass HMACKey's asymmetric key + # check, so the same public key string could verify an HS256 token. + with pytest.raises(JWKError): + ECDSAECKey(bare, ALGORITHMS.ES256) + with pytest.raises(JWKError): + ECDSAECKey(pem.replace("PUBLIC KEY", "EC PUBLIC KEY"), ALGORITHMS.ES256) + + assert ECDSAECKey(pem, ALGORITHMS.ES256).is_public() + + @pytest.mark.cryptography @pytest.mark.skipif(CryptographyECKey is None, reason="pyca/cryptography backend not available") @pytest.mark.parametrize(