Skip to content

Commit 53fccd9

Browse files
alexclaude
andauthored
Don't leak how PKCS#7 encryptedKey decryption failed (#15369)
* Don't leak how PKCS#7 encryptedKey decryption failed pkcs7_decrypt_der and its PEM and S/MIME variants reported invalid RSA PKCS#1 v1.5 padding, a recovered key of the wrong length, and a wrong key as three distinct errors, and the middle one disclosed the exact recovered length. That is a Bleichenbacher oracle for any caller that decrypts untrusted messages. The wrong-length case also returned before the AES-CBC pass, so the same distinction was observable by timing, proportional to a content size the attacker chooses. Substitute a random key of the expected length on failure, per RFC 3218, and continue down an identical path so that every outcome looks alike. EnvelopedData still authenticates nothing, so revealing whether decryption succeeded remains a CBC padding oracle regardless. That is a property of PKCS#7 rather than of this implementation, and is now documented instead. Co-Authored-By: Claude Opus 5 <[email protected]> * Cover the non-ValueError path out of encryptedKey decryption Only a ValueError from unwrapping the key is attacker controlled and so deliberately silenced. A private key implemented outside of this library can fail in other ways, and those still reach the caller -- but nothing exercised that arm, leaving it uncovered. Add a DummyRSAPrivateKey double whose decrypt() raises a TypeError, and tests for each of its methods. Co-Authored-By: Claude Opus 5 <[email protected]> * fix? * error message --------- Co-authored-by: Claude Opus 5 <[email protected]>
1 parent d472f97 commit 53fccd9

7 files changed

Lines changed: 237 additions & 37 deletions

File tree

‎CHANGELOG.rst‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,13 @@ Changelog
88

99
.. note:: This version is not yet released and is under active development.
1010

11+
* **SECURITY ISSUE**:
12+
:func:`~cryptography.hazmat.primitives.serialization.pkcs7.pkcs7_decrypt_der`
13+
and its PEM and S/MIME variants no longer expose distinguishable errors or
14+
timing when unwrapping a ``RecipientInfo``'s ``encryptedKey``, which could
15+
act as a Bleichenbacher oracle for callers that decrypt untrusted messages.
16+
A random key is now substituted on failure, as described in :rfc:`3218`.
17+
Credit to **@X1AOxiang** for reporting the issue
1118
* Deprecated Diffie-Hellman key exchange over finite fields (FFDH).
1219
Everything FFDH is deprecated, including the types in
1320
``cryptography.hazmat.primitives.asymmetric.dh`` and loading FFDH keys or

‎docs/hazmat/primitives/asymmetric/serialization.rst‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1445,6 +1445,15 @@ contain certificates, CRLs, and much more. PKCS7 files commonly have a ``p7b``,
14451445
most of this implementation follows S/MIME 2.0 (RFC 2311). A small subset of :rfc:`2632`,
14461446
also known as S/MIME version 3 is supported.
14471447

1448+
.. warning::
1449+
1450+
``EnvelopedData`` does not authenticate its content. An application
1451+
that decrypts attacker-supplied messages and reveals whether
1452+
decryption succeeded -- through an error, a status code, or timing --
1453+
gives the attacker a CBC padding oracle sufficient to recover the
1454+
plaintext. This is a property of PKCS#7 and cannot be fixed here,
1455+
so avoid decrypting untrusted ``EnvelopedData``.
1456+
14481457
:param data: The data, encoded in DER format.
14491458
:type data: bytes
14501459

@@ -1502,6 +1511,12 @@ contain certificates, CRLs, and much more. PKCS7 files commonly have a ``p7b``,
15021511
most of this implementation follows S/MIME 2.0 (RFC 2311). A small subset of :rfc:`2632`,
15031512
also known as S/MIME version 3 is supported.
15041513

1514+
.. warning::
1515+
1516+
The padding oracle described in
1517+
:func:`~cryptography.hazmat.primitives.serialization.pkcs7.pkcs7_decrypt_der`
1518+
applies equally here.
1519+
15051520
:param data: The data, encoded in PEM format.
15061521
:type data: bytes
15071522

@@ -1560,6 +1575,12 @@ contain certificates, CRLs, and much more. PKCS7 files commonly have a ``p7b``,
15601575
most of this implementation follows S/MIME 2.0 (RFC 2311). A small subset of :rfc:`2632`,
15611576
also known as S/MIME version 3 is supported.
15621577

1578+
.. warning::
1579+
1580+
The padding oracle described in
1581+
:func:`~cryptography.hazmat.primitives.serialization.pkcs7.pkcs7_decrypt_der`
1582+
applies equally here.
1583+
15631584
:param data: The data. It should be in S/MIME format, meaning MIME with content type
15641585
``application/pkcs7-mime`` or ``application/x-pkcs7-mime``.
15651586
:type data: bytes

‎docs/spelling_wordlist.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ unencrypted
173173
unicode
174174
uninstantiated
175175
unpadded
176+
untrusted
176177
unpadding
177178
unsafety
178179
validator

‎src/rust/src/pkcs7.rs‎

Lines changed: 47 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -270,47 +270,16 @@ fn decrypt_der<'p>(
270270
}
271271
};
272272

273-
// Raise error when the key encryption algorithm is not RSA
274-
let key = match recipient_info.key_encryption_algorithm.oid() {
275-
&oid::RSA_OID => {
276-
let padding = types::PKCS1V15.get(py)?.call0()?;
277-
private_key
278-
.call_method1(
279-
pyo3::intern!(py, "decrypt"),
280-
(recipient_info.encrypted_key, &padding),
281-
)?
282-
.extract::<pyo3::pybacked::PyBackedBytes>()?
283-
}
284-
_ => {
285-
return Err(CryptographyError::from(
286-
exceptions::UnsupportedAlgorithm::new_err((
287-
"Only RSA with PKCS #1 v1.5 padding is currently supported for key decryption.",
288-
exceptions::Reasons::UNSUPPORTED_SERIALIZATION,
289-
)),
290-
));
291-
}
292-
};
293-
294273
// The function can decrypt content encrypted with AES-128-CBC, which the S/MIME v3.2
295274
// RFC specifies as MUST support, and AES-256-CBC, which is specified as SHOULD+
296275
// support. More info: https://datatracker.ietf.org/doc/html/rfc5751#section-2.7
297276
// however rest of S/MIME v3.2 is not currently supported
298277
let algorithm_identifier = enveloped_data
299278
.encrypted_content_info
300279
.content_encryption_algorithm;
301-
let (algorithm, mode) = match algorithm_identifier.params {
302-
AlgorithmParameters::Aes128Cbc(iv) => (
303-
types::AES128.get(py)?.call1((key,))?,
304-
types::CBC
305-
.get(py)?
306-
.call1((pyo3::types::PyBytes::new(py, &iv),))?,
307-
),
308-
AlgorithmParameters::Aes256Cbc(iv) => (
309-
types::AES256.get(py)?.call1((key,))?,
310-
types::CBC
311-
.get(py)?
312-
.call1((pyo3::types::PyBytes::new(py, &iv),))?,
313-
),
280+
let (algorithm_type, key_size, iv) = match algorithm_identifier.params {
281+
AlgorithmParameters::Aes128Cbc(iv) => (&types::AES128, 16, iv),
282+
AlgorithmParameters::Aes256Cbc(iv) => (&types::AES256, 32, iv),
314283
_ => {
315284
return Err(CryptographyError::from(
316285
exceptions::UnsupportedAlgorithm::new_err((
@@ -321,6 +290,50 @@ fn decrypt_der<'p>(
321290
}
322291
};
323292

293+
// Raise error when the key encryption algorithm is not RSA
294+
if recipient_info.key_encryption_algorithm.oid() != &oid::RSA_OID {
295+
return Err(CryptographyError::from(
296+
exceptions::UnsupportedAlgorithm::new_err((
297+
"Only RSA with PKCS #1 v1.5 padding is currently supported for key decryption.",
298+
exceptions::Reasons::UNSUPPORTED_SERIALIZATION,
299+
)),
300+
));
301+
}
302+
303+
// Unwrap the content encryption key. RFC 3218 requires that a
304+
// failure to recover a usable key is not distinguishable from
305+
// recovering a key that simply isn't the right one -- otherwise
306+
// this becomes a Bleichenbacher oracle for anything that decrypts
307+
// attacker-supplied data. We substitute a random key of the
308+
// expected size, so that every failure surfaces as the same
309+
// content decryption error.
310+
let padding = types::PKCS1V15.get(py)?.call0()?;
311+
let random_key = crate::backend::rand::get_rand_bytes(py, key_size)?;
312+
let key = match private_key.call_method1(
313+
pyo3::intern!(py, "decrypt"),
314+
(recipient_info.encrypted_key, &padding),
315+
) {
316+
Ok(key) => {
317+
let key = key.extract::<pyo3::Bound<'_, pyo3::types::PyBytes>>()?;
318+
if key.as_bytes().len() == key_size {
319+
key
320+
} else {
321+
random_key
322+
}
323+
}
324+
// A ValueError here is entirely attacker controlled (invalid
325+
// padding, or an encrypted key of the wrong length) and must
326+
// stay silent. Any other exception reflects a caller mistake
327+
// rather than the contents of the message.
328+
Err(e) if e.is_instance_of::<pyo3::exceptions::PyValueError>(py) => random_key,
329+
Err(e) => return Err(e.into()),
330+
};
331+
332+
let algorithm = algorithm_type.get(py)?.call1((key,))?;
333+
let mode = types::CBC
334+
.get(py)?
335+
.call1((pyo3::types::PyBytes::new(py, &iv),))?;
336+
324337
// Decrypt the content using the key and proper algorithm
325338
let encrypted_content = match enveloped_data.encrypted_content_info.encrypted_content {
326339
Some(content) => content,

‎tests/doubles.py‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
33
# for complete details.
44

5+
from __future__ import annotations
56

67
from cryptography.hazmat.primitives import hashes, serialization
7-
from cryptography.hazmat.primitives.asymmetric import ed25519, padding
8+
from cryptography.hazmat.primitives.asymmetric import ed25519, padding, rsa
9+
from cryptography.hazmat.primitives.asymmetric import utils as asym_utils
810
from cryptography.hazmat.primitives.ciphers import (
911
BlockCipherAlgorithm,
1012
CipherAlgorithm,
@@ -86,3 +88,50 @@ def __copy__(self) -> ed25519.Ed25519PublicKey:
8688

8789
def __deepcopy__(self, memo: dict) -> ed25519.Ed25519PublicKey:
8890
raise NotImplementedError
91+
92+
93+
class DummyRSAPrivateKey(rsa.RSAPrivateKey):
94+
"""
95+
A fake RSAPrivateKey whose decrypt() raises a non-ValueError. Used for
96+
testing that a failure originating outside of this library is not
97+
mistaken for an attacker controlled decryption failure.
98+
"""
99+
100+
def decrypt(
101+
self, ciphertext: bytes, padding: padding.AsymmetricPadding
102+
) -> bytes:
103+
raise TypeError("TypeError for testing")
104+
105+
@property
106+
def key_size(self) -> int:
107+
raise NotImplementedError
108+
109+
def public_key(self) -> rsa.RSAPublicKey:
110+
raise NotImplementedError
111+
112+
def sign(
113+
self,
114+
data: bytes,
115+
padding: padding.AsymmetricPadding,
116+
algorithm: asym_utils.Prehashed
117+
| hashes.HashAlgorithm
118+
| asym_utils.NoDigestInfo,
119+
) -> bytes:
120+
raise NotImplementedError
121+
122+
def private_numbers(self) -> rsa.RSAPrivateNumbers:
123+
raise NotImplementedError
124+
125+
def private_bytes(
126+
self,
127+
encoding: serialization.Encoding,
128+
format: serialization.PrivateFormat,
129+
encryption_algorithm: serialization.KeySerializationEncryption,
130+
) -> bytes:
131+
raise NotImplementedError
132+
133+
def __copy__(self) -> rsa.RSAPrivateKey:
134+
raise NotImplementedError
135+
136+
def __deepcopy__(self, memo: dict) -> rsa.RSAPrivateKey:
137+
raise NotImplementedError

‎tests/hazmat/primitives/test_pkcs7.py‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
from cryptography.hazmat.primitives.asymmetric import ed25519, padding, rsa
2424
from cryptography.hazmat.primitives.ciphers import algorithms
2525
from cryptography.hazmat.primitives.serialization import pkcs7
26+
from tests.doubles import DummyRSAPrivateKey
2627
from tests.x509.test_x509 import _generate_ca_and_leaf
2728

2829
from ...hazmat.primitives.fixtures_rsa import (
@@ -1434,6 +1435,67 @@ def test_smime_decrypt_smime_not_encrypted(self, certificate, private_key):
14341435
email_message.as_bytes(), certificate, private_key, []
14351436
)
14361437

1438+
def test_decrypt_encrypted_key_is_not_an_oracle(
1439+
self, data, certificate, private_key
1440+
):
1441+
# An attacker who replaces the encryptedKey must not be able to tell
1442+
# the RSA decryption outcomes apart. Recovering an unusable key, or
1443+
# failing to recover one at all, has to look exactly like recovering
1444+
# a key of the right length that simply isn't the right key. See
1445+
# RFC 3218 and Bleichenbacher's '98 attack.
1446+
enveloped = (
1447+
pkcs7.PKCS7EnvelopeBuilder()
1448+
.set_data(data)
1449+
.add_recipient(certificate)
1450+
)
1451+
der = enveloped.encrypt(serialization.Encoding.DER, [])
1452+
1453+
public_key = certificate.public_key()
1454+
assert isinstance(public_key, rsa.RSAPublicKey)
1455+
1456+
# The encryptedKey is the only OCTET STRING in the structure as long
1457+
# as the RSA modulus, so it can be located by its DER header.
1458+
key_bytes = public_key.key_size // 8
1459+
marker = b"\x04\x82" + key_bytes.to_bytes(2, "big")
1460+
assert der.count(marker) == 1
1461+
offset = der.index(marker) + len(marker)
1462+
1463+
for encrypted_key in [
1464+
# Invalid PKCS#1 v1.5 padding.
1465+
b"\x00" * key_bytes,
1466+
# Valid padding concealing a key of the wrong length.
1467+
public_key.encrypt(b"A" * 15, padding.PKCS1v15()),
1468+
public_key.encrypt(b"A" * 17, padding.PKCS1v15()),
1469+
public_key.encrypt(b"A" * 32, padding.PKCS1v15()),
1470+
# Valid padding concealing a correctly sized but wrong key.
1471+
public_key.encrypt(b"A" * 16, padding.PKCS1v15()),
1472+
]:
1473+
tampered = der[:offset] + encrypted_key + der[offset + key_bytes :]
1474+
try:
1475+
pkcs7.pkcs7_decrypt_der(tampered, certificate, private_key, [])
1476+
except ValueError as exc:
1477+
# Decrypting under a substituted random key leaves plausible
1478+
# PKCS#7 padding roughly one time in 256, in which case the
1479+
# caller gets garbage instead of an error. That is equally
1480+
# uninformative, so it is an acceptable outcome here.
1481+
assert str(exc) == "Invalid padding bytes."
1482+
1483+
def test_decrypt_key_error_is_not_swallowed(self, data, certificate):
1484+
# Only a ValueError from unwrapping the key is attacker controlled and
1485+
# therefore silenced. A private key implemented outside this library
1486+
# can fail in other ways, and those must still reach the caller.
1487+
enveloped = (
1488+
pkcs7.PKCS7EnvelopeBuilder()
1489+
.set_data(data)
1490+
.add_recipient(certificate)
1491+
.encrypt(serialization.Encoding.DER, [])
1492+
)
1493+
1494+
with pytest.raises(TypeError, match="TypeError for testing"):
1495+
pkcs7.pkcs7_decrypt_der(
1496+
enveloped, certificate, DummyRSAPrivateKey(), []
1497+
)
1498+
14371499

14381500
class TestPKCS7SerializeCerts:
14391501
@pytest.mark.parametrize(

‎tests/test_doubles.py‎

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,10 @@
66

77
import pytest
88

9-
from cryptography.hazmat.primitives import serialization
9+
from cryptography.hazmat.primitives import hashes, serialization
10+
from cryptography.hazmat.primitives.asymmetric import padding
1011

11-
from .doubles import DummyEd25519PublicKey
12+
from .doubles import DummyEd25519PublicKey, DummyRSAPrivateKey
1213

1314

1415
class TestDummyEd25519PublicKey:
@@ -46,3 +47,49 @@ def test_deepcopy_not_implemented(self):
4647
key = DummyEd25519PublicKey(b"test data")
4748
with pytest.raises(NotImplementedError):
4849
copy.deepcopy(key)
50+
51+
52+
class TestDummyRSAPrivateKey:
53+
def test_decrypt(self):
54+
key = DummyRSAPrivateKey()
55+
with pytest.raises(TypeError):
56+
key.decrypt(b"ciphertext", padding.PKCS1v15())
57+
58+
def test_key_size_not_implemented(self):
59+
key = DummyRSAPrivateKey()
60+
with pytest.raises(NotImplementedError):
61+
key.key_size
62+
63+
def test_public_key_not_implemented(self):
64+
key = DummyRSAPrivateKey()
65+
with pytest.raises(NotImplementedError):
66+
key.public_key()
67+
68+
def test_sign_not_implemented(self):
69+
key = DummyRSAPrivateKey()
70+
with pytest.raises(NotImplementedError):
71+
key.sign(b"data", padding.PKCS1v15(), hashes.SHA256())
72+
73+
def test_private_numbers_not_implemented(self):
74+
key = DummyRSAPrivateKey()
75+
with pytest.raises(NotImplementedError):
76+
key.private_numbers()
77+
78+
def test_private_bytes_not_implemented(self):
79+
key = DummyRSAPrivateKey()
80+
with pytest.raises(NotImplementedError):
81+
key.private_bytes(
82+
serialization.Encoding.PEM,
83+
serialization.PrivateFormat.PKCS8,
84+
serialization.NoEncryption(),
85+
)
86+
87+
def test_copy_not_implemented(self):
88+
key = DummyRSAPrivateKey()
89+
with pytest.raises(NotImplementedError):
90+
copy.copy(key)
91+
92+
def test_deepcopy_not_implemented(self):
93+
key = DummyRSAPrivateKey()
94+
with pytest.raises(NotImplementedError):
95+
copy.deepcopy(key)

0 commit comments

Comments
 (0)