diff --git a/jose/backends/ecdsa_backend.py b/jose/backends/ecdsa_backend.py index 756c7ea..4286460 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 d8602a2..76bca1a 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(