From 61a8fa47bd9e2d0446696f699419e26e77a80442 Mon Sep 17 00:00:00 2001 From: Alex Gaynor Date: Mon, 19 Feb 2024 11:16:45 -0500 Subject: [PATCH] Fixes #10422 -- don't crash when a PKCS#12 key and cert don't match --- .../hazmat/backends/openssl/backend.py | 9 +++++++++ tests/hazmat/primitives/test_pkcs12.py | 14 ++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/cryptography/hazmat/backends/openssl/backend.py b/src/cryptography/hazmat/backends/openssl/backend.py index 45888f36168a..6a4aeca7521f 100644 --- a/src/cryptography/hazmat/backends/openssl/backend.py +++ b/src/cryptography/hazmat/backends/openssl/backend.py @@ -623,6 +623,15 @@ def serialize_key_and_certificates_to_pkcs12( mac_iter, 0, ) + if p12 == self._ffi.NULL: + errors = self._consume_errors() + raise ValueError( + ( + "Failed to create PKCS12 (does the key match the " + "certificate?)" + ), + errors, + ) if ( self._lib.Cryptography_HAS_PKCS12_SET_MAC diff --git a/tests/hazmat/primitives/test_pkcs12.py b/tests/hazmat/primitives/test_pkcs12.py index f49c98a4ed3d..9aea832d5663 100644 --- a/tests/hazmat/primitives/test_pkcs12.py +++ b/tests/hazmat/primitives/test_pkcs12.py @@ -660,6 +660,20 @@ def test_key_serialization_encryption_set_mac_unsupported( b"name", cakey, cacert, [], algorithm ) + def test_set_mac_key_certificate_mismatch(self, backend): + cacert, _ = _load_ca(backend) + key = ec.generate_private_key(ec.SECP256R1()) + encryption = ( + serialization.PrivateFormat.PKCS12.encryption_builder() + .hmac_hash(hashes.SHA256()) + .build(b"password") + ) + + with pytest.raises(ValueError): + serialize_key_and_certificates( + b"name", key, cacert, [], encryption + ) + @pytest.mark.skip_fips( reason="PKCS12 unsupported in FIPS mode. So much bad crypto in it."