Skip to content

Commit f157f0f

Browse files
Arpan0995dghgit
authored andcommitted
CMS: resolve the RFC 9709 key-derivation wrapper to the content-encryption algorithm it carries before the recipient key-size, allowed-algorithm and tag-size checks, incorporating github PR #2446.
1 parent 8b92def commit f157f0f

14 files changed

Lines changed: 333 additions & 74 deletions

‎CONTRIBUTORS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -542,7 +542,7 @@ We also wish to acknowledge financial and collaborative support from [CISCO](htt
542542
- jmeeder \<https://github.com/jmeeder\> - reporting that RFC 4998 evidence-record generation rejected time stamps from an authority naming the digest with NULL parameters where BC names it with them absent, both of which RFC 5754 requires a receiver to accept (issue #2379).
543543
- rimuln \<https://github.com/rimuln\> - diagnosis and fix for PKCS12 getCertificateAlias returning the alias of an unrelated certificate, tracing it to the alias and certificate enumerations of the keystore's certs table diverging in order once keys() enumerated a copy (issue #2384, PR #2385).
544544
- Yu Bao \<yubao&#064;paypal.com\> - reporting an API gap, on behalf of the PayPal Cyber Security Team, that the high-level OpenPGP message API (OpenPGPMessageProcessor / OpenPGPMessageInputStream) gave a caller no way to bound how far a compressed data packet expands, where the low-level PGPCompressedData it wraps has carried a bounded getDataStream(long) overload all along, and that OpenPGPPolicy exposed no equivalent property to set. Suggesting a protocol whitelist for CRL Distribution Point fetching, which is now the org.bouncycastle.x509.CRLDP_protocols property, and suggesting that an OCSP response was read up to the length the responder declared for itself, now capped by org.bouncycastle.ocsp.max_response_size, and suggesting bounds on the OpenPGP ASCII armor headers, now capped by org.bouncycastle.openpgp.max_armor_header_length and org.bouncycastle.openpgp.max_armor_headers.
545-
- Arpan Sharma \<https://github.com/Arpan0995\> - initial audit of BCPQC provider consistency starting with HQC, which led to the exposure of a number of issues in the JCA provider service interfaces for other BCPQC algorithms. In-depth auditing of PQC signature algorithms in the provider leading to the correction of a number of JCA API compliance issues. Initial implementation of the guard that lets a signature context be set on the composite ML-DSA services before initSign / initVerify, the composite counterpart of the base-engine fix for issue #2396 (issue #2412). Audit of the LMS / HSS stateful private key decoder, establishing that the level count, the one-time index and the persisted tree cache were all accepted without validation (issue #2414); that issue was also the inspiration for the further investigation which found the HSS and XMSS^MT decoders accepting a private key whose declared index disagreed with the traversal state stored beside it, allowing a one-time key to be used twice. Audit of the high-level OpenPGP API (org.bouncycastle.openpgp, org.bouncycastle.openpgp.api) and the bcpg packet layer beneath it, spanning certificate evaluation, message verification, decryption and signature subpacket parsing, which found certificates being used without the certifications RFC 9580 requires of them, malformed but signed content reaching ordinary reader code as unchecked exceptions, a truncated message being read as a clean end of message, and unverified plaintext being released ahead of the integrity check (issues #2417, #2424, #2426). Audit of the recipient side of the CMS RFC 9629 KEMRecipientInfo path, which found three sender-controlled fields leaving methods declared to throw CMSException as unchecked exceptions and the kekLength never being confirmed against the wrap algorithm, and which led to the same translation being added to the neighbouring AuthEnvelopedData constructor and the two streaming parsers (issue #2422). Audit of RSA-PSS parameter handling in the provider, which found Signature.setParameter reporting a rejected trailer field as an unchecked exception and leaving the rejected spec half-applied, so that the parameters reported for a signature were not the ones it had been made with (issue #2421). Audit of the PKCS#12 key store entry-setting boundary, which found setKeyEntry reporting a certificate whose public key the provider cannot resolve as an unchecked exception rather than the KeyStoreException it declares, and which led to the same guard being applied to setCertificateEntry and to the RFC 9579 PBMAC1 store, and to the rejected entry no longer being left behind in the store (issue #2419). Further auditing of the verification and expiration paths of the high-level OpenPGP API, which found a configured algorithm policy not being applied to inline message verification, an expired primary key still offering its subkeys, and a data signature being reported valid past its own expiration time. CMS SignedData and PKIX certification path test coverage for the eighteen Composite ML-DSA parameter sets, which had been reachable through the CMS and cert-path signature algorithm finders with no test exercising either (PR #2437). Identification and fix of the output offset in the AEAD stream cipher data operator that made Grain-128AEAD return corrupted plaintext from a decryption driven in chunks, with the streamed decryption coverage that had been missing (PR #2447).
545+
- Arpan Sharma \<https://github.com/Arpan0995\> - initial audit of BCPQC provider consistency starting with HQC, which led to the exposure of a number of issues in the JCA provider service interfaces for other BCPQC algorithms. In-depth auditing of PQC signature algorithms in the provider leading to the correction of a number of JCA API compliance issues. Initial implementation of the guard that lets a signature context be set on the composite ML-DSA services before initSign / initVerify, the composite counterpart of the base-engine fix for issue #2396 (issue #2412). Audit of the LMS / HSS stateful private key decoder, establishing that the level count, the one-time index and the persisted tree cache were all accepted without validation (issue #2414); that issue was also the inspiration for the further investigation which found the HSS and XMSS^MT decoders accepting a private key whose declared index disagreed with the traversal state stored beside it, allowing a one-time key to be used twice. Audit of the high-level OpenPGP API (org.bouncycastle.openpgp, org.bouncycastle.openpgp.api) and the bcpg packet layer beneath it, spanning certificate evaluation, message verification, decryption and signature subpacket parsing, which found certificates being used without the certifications RFC 9580 requires of them, malformed but signed content reaching ordinary reader code as unchecked exceptions, a truncated message being read as a clean end of message, and unverified plaintext being released ahead of the integrity check (issues #2417, #2424, #2426). Audit of the recipient side of the CMS RFC 9629 KEMRecipientInfo path, which found three sender-controlled fields leaving methods declared to throw CMSException as unchecked exceptions and the kekLength never being confirmed against the wrap algorithm, and which led to the same translation being added to the neighbouring AuthEnvelopedData constructor and the two streaming parsers (issue #2422). Audit of RSA-PSS parameter handling in the provider, which found Signature.setParameter reporting a rejected trailer field as an unchecked exception and leaving the rejected spec half-applied, so that the parameters reported for a signature were not the ones it had been made with (issue #2421). Audit of the PKCS#12 key store entry-setting boundary, which found setKeyEntry reporting a certificate whose public key the provider cannot resolve as an unchecked exception rather than the KeyStoreException it declares, and which led to the same guard being applied to setCertificateEntry and to the RFC 9579 PBMAC1 store, and to the rejected entry no longer being left behind in the store (issue #2419). Further auditing of the verification and expiration paths of the high-level OpenPGP API, which found a configured algorithm policy not being applied to inline message verification, an expired primary key still offering its subkeys, and a data signature being reported valid past its own expiration time. CMS SignedData and PKIX certification path test coverage for the eighteen Composite ML-DSA parameter sets, which had been reachable through the CMS and cert-path signature algorithm finders with no test exercising either (PR #2437). Identification and fix of the output offset in the AEAD stream cipher data operator that made Grain-128AEAD return corrupted plaintext from a decryption driven in chunks, with the streamed decryption coverage that had been missing (PR #2447). Identification and fix of the RFC 9709 content-encryption algorithm being left wrapped at the CMS recipient key-size, allowed-algorithm and tag-size checks, so that none of them applied to the algorithm the content was encrypted under (PR #2446).
546546
- Flowdalic \<https://github.com/Flowdalic\> - initial implementation of an AnimalSniffer-based Android API-level compatibility check for the Gradle build (PR #336).
547547
- hannesa2 \<https://github.com/hannesa2\> - initial Dependabot configuration for the Gradle and GitHub Actions ecosystems (PR #883).
548548
- vladhuma \<https://github.com/vladhuma\> - initial implementation of server-side OCSP stapling for the BCJSSE provider, on behalf of Thales Group (PR #1740).

‎docs/releasenotes.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ Date: 2026, TBD
2929
- ERSArchiveTimeStampGenerator rebuilt its reduced hash tree from the data objects on every call, so the usual generateTimeStampRequest() followed by generateArchiveTimeStamp() or generateArchiveTimeStamps() built it twice. The leaves are now built once and dropped when data or a previous chain is added. A Set of the data groups it had been given, which nothing ever read, has gone with it.
3030
- Grain-128AEAD returned corrupted plaintext from a decryption driven in chunks. The stream cipher data operator splits a processBytes() call that spans the buffered authentication tag into two output segments, the bytes released from the tag buffer and then the bytes taken straight from the caller's input, and wrote the second segment at the caller's output offset instead of after the first, so the second segment overwrote the head of the first and the tail of the reported output was never written at all. The call still returned the full byte count, and because the engine's state update depends on the input and the keystream rather than on where the output lands, the tag still verified: the wrong plaintext came back with no error raised. Any chunk after the first that carried more than the 8 byte tag length was affected. Grain-128AEAD is the only engine that uses this operator, and one shot decryption, the encryption path and every other AEAD engine were unaffected. The second segment is now written at the advanced offset, matching the equivalent step of the general decryption path (github PR #2447).
3131
- The AEAD stream cipher data operator, which Grain-128AEAD alone uses, wrote its output without first checking that the caller's buffer was long enough, so a short output buffer surfaced as an ArrayIndexOutOfBoundsException from inside the engine rather than as the OutputLengthException the general path reports for every other AEAD engine. Both directions of processBytes(), and processByte(), now check before anything is written or buffered, and only when the call releases output, as the general path does.
32+
- The RFC 9709 content-encryption AlgorithmIdentifier, which carries the real algorithm inside the parameters of an outer id-alg-cek-hkdf-sha256, was unwrapped at only one of the points where a CMS recipient makes a decision about it. Key-size validation was corrected for plain key transport in 1.86, but the same call in the KEK, RSA-KTS and KEM recipients, and in the key-transport recipient's own ORI-KEM branch, still compared the recovered key against the outer identifier, which registers no key size, so setKeySizeValidation(true) silently checked nothing there; the setAllowedContentAlgorithms allow-list and the setMinimumTagSize floor were applied to the outer identifier on every recipient family, including the one already corrected, so neither constrained an RFC 9709 message. The unwrap now happens once for the key-size check and once for the two policy checks, and every recipient polices and validates the content-encryption algorithm the message actually carries. A recipient with no allow-list, no tag floor and no key-size validation configured behaves exactly as before; a caller who listed id-alg-cek-hkdf-sha256 in an allow-list in order to admit RFC 9709 messages must now list the content-encryption algorithms themselves (github PR #2446).
3233

3334
### 2.1.3 Additional Features and Functionality
3435

‎pkix/src/main/java/org/bouncycastle/cms/AbstractRecipient.java‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import java.util.Set;
55

66
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
7+
import org.bouncycastle.asn1.cms.CMSObjectIdentifiers;
78
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
89

910
/**
@@ -52,4 +53,38 @@ protected final void checkTagSize(AlgorithmIdentifier contentAlgorithm)
5253
}
5354
}
5455
}
56+
57+
/**
58+
* Apply both of the recipient's restrictions to the content-encryption algorithm the message
59+
* names, resolving an RFC 9709 key-derivation wrapper to the content-encryption algorithm it
60+
* carries first, so that the restrictions are applied to the algorithm the content is actually
61+
* encrypted under.
62+
*
63+
* @param contentAlgorithm the content-encryption AlgorithmIdentifier taken from the message.
64+
* @throws CMSAlgorithmNotAllowedException if the content algorithm is not in the allowed set.
65+
* @throws CMSTagLengthException if the tag size is below the configured minimum.
66+
*/
67+
protected final void checkContentAlgorithm(AlgorithmIdentifier contentAlgorithm)
68+
throws CMSException
69+
{
70+
AlgorithmIdentifier encAlgId;
71+
72+
// RFC 9709: the EncryptedContentInfo carries an outer id-alg-cek-hkdf-sha256 wrapping the
73+
// real inner content-encryption AlgorithmIdentifier - it is the inner one these checks apply to.
74+
if (contentAlgorithm.getAlgorithm().equals(CMSObjectIdentifiers.id_alg_cek_hkdf_sha256))
75+
{
76+
encAlgId = AlgorithmIdentifier.getInstance(contentAlgorithm.getParameters());
77+
}
78+
else
79+
{
80+
encAlgId = contentAlgorithm;
81+
}
82+
83+
if (!isContentAlgorithmAllowed(encAlgId.getAlgorithm()))
84+
{
85+
throw new CMSAlgorithmNotAllowedException("content-encryption algorithm not in recipient's allowed set: " + encAlgId.getAlgorithm());
86+
}
87+
88+
checkTagSize(encAlgId);
89+
}
5590
}

‎pkix/src/main/java/org/bouncycastle/cms/bc/BcKEKRecipient.java‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
66
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
77
import org.bouncycastle.cms.AbstractRecipient;
8-
import org.bouncycastle.cms.CMSAlgorithmNotAllowedException;
98
import org.bouncycastle.cms.CMSException;
109
import org.bouncycastle.cms.KEKRecipient;
1110
import org.bouncycastle.crypto.CipherParameters;
@@ -42,12 +41,7 @@ public BcKEKRecipient setAllowedContentAlgorithms(Set<ASN1ObjectIdentifier> allo
4241
protected CipherParameters extractSecretKey(AlgorithmIdentifier keyEncryptionAlgorithm, AlgorithmIdentifier contentEncryptionAlgorithm, byte[] encryptedContentEncryptionKey)
4342
throws CMSException
4443
{
45-
if (!isContentAlgorithmAllowed(contentEncryptionAlgorithm.getAlgorithm()))
46-
{
47-
throw new CMSAlgorithmNotAllowedException("content-encryption algorithm not in recipient's allowed set: " + contentEncryptionAlgorithm.getAlgorithm());
48-
}
49-
50-
checkTagSize(contentEncryptionAlgorithm);
44+
checkContentAlgorithm(contentEncryptionAlgorithm);
5145

5246
try
5347
{

‎pkix/src/main/java/org/bouncycastle/cms/bc/BcKeyTransRecipient.java‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
66
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
77
import org.bouncycastle.cms.AbstractRecipient;
8-
import org.bouncycastle.cms.CMSAlgorithmNotAllowedException;
98
import org.bouncycastle.cms.CMSException;
109
import org.bouncycastle.cms.KeyTransRecipient;
1110
import org.bouncycastle.crypto.CipherParameters;
@@ -43,12 +42,7 @@ public BcKeyTransRecipient setAllowedContentAlgorithms(Set<ASN1ObjectIdentifier>
4342
protected CipherParameters extractSecretKey(AlgorithmIdentifier keyEncryptionAlgorithm, AlgorithmIdentifier encryptedKeyAlgorithm, byte[] encryptedEncryptionKey)
4443
throws CMSException
4544
{
46-
if (!isContentAlgorithmAllowed(encryptedKeyAlgorithm.getAlgorithm()))
47-
{
48-
throw new CMSAlgorithmNotAllowedException("content-encryption algorithm not in recipient's allowed set: " + encryptedKeyAlgorithm.getAlgorithm());
49-
}
50-
51-
checkTagSize(encryptedKeyAlgorithm);
45+
checkContentAlgorithm(encryptedKeyAlgorithm);
5246

5347
AsymmetricKeyUnwrapper unwrapper = new BcRSAAsymmetricKeyUnwrapper(keyEncryptionAlgorithm, recipientKey);
5448

‎pkix/src/main/java/org/bouncycastle/cms/bc/BcPasswordRecipient.java‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
import org.bouncycastle.asn1.pkcs.PBKDF2Params;
99
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
1010
import org.bouncycastle.cms.AbstractRecipient;
11-
import org.bouncycastle.cms.CMSAlgorithmNotAllowedException;
1211
import org.bouncycastle.cms.CMSException;
1312
import org.bouncycastle.cms.PasswordRecipient;
1413
import org.bouncycastle.crypto.InvalidCipherTextException;
@@ -62,12 +61,7 @@ public BcPasswordRecipient setAllowedContentAlgorithms(Set<ASN1ObjectIdentifier>
6261
protected KeyParameter extractSecretKey(AlgorithmIdentifier keyEncryptionAlgorithm, AlgorithmIdentifier contentEncryptionAlgorithm, byte[] derivedKey, byte[] encryptedContentEncryptionKey)
6362
throws CMSException
6463
{
65-
if (!isContentAlgorithmAllowed(contentEncryptionAlgorithm.getAlgorithm()))
66-
{
67-
throw new CMSAlgorithmNotAllowedException("content-encryption algorithm not in recipient's allowed set: " + contentEncryptionAlgorithm.getAlgorithm());
68-
}
69-
70-
checkTagSize(contentEncryptionAlgorithm);
64+
checkContentAlgorithm(contentEncryptionAlgorithm);
7165

7266
Wrapper keyEncryptionCipher = EnvelopedDataHelper.createRFC3211Wrapper(keyEncryptionAlgorithm.getAlgorithm());
7367

‎pkix/src/main/java/org/bouncycastle/cms/jcajce/EnvelopedDataHelper.java‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,21 @@ public Key getJceKey(AlgorithmIdentifier algId, GenericKey key)
260260
public void keySizeCheck(AlgorithmIdentifier keyAlgorithm, Key key)
261261
throws CMSException
262262
{
263-
int expectedKeySize = EnvelopedDataHelper.KEY_SIZE_PROVIDER.getKeySize(keyAlgorithm);
263+
AlgorithmIdentifier encAlgId;
264+
265+
// RFC 9709: the EncryptedContentInfo carries an outer id-alg-cek-hkdf-sha256 wrapping the
266+
// real inner content-encryption AlgorithmIdentifier - it is the inner one that fixes the
267+
// key size the recovered CEK is expected to have.
268+
if (keyAlgorithm.getAlgorithm().equals(CMSObjectIdentifiers.id_alg_cek_hkdf_sha256))
269+
{
270+
encAlgId = AlgorithmIdentifier.getInstance(keyAlgorithm.getParameters());
271+
}
272+
else
273+
{
274+
encAlgId = keyAlgorithm;
275+
}
276+
277+
int expectedKeySize = EnvelopedDataHelper.KEY_SIZE_PROVIDER.getKeySize(encAlgId);
264278
if (expectedKeySize > 0)
265279
{
266280
byte[] keyEnc = null;

‎pkix/src/main/java/org/bouncycastle/cms/jcajce/JceKEKRecipient.java‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
1010
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
1111
import org.bouncycastle.cms.AbstractRecipient;
12-
import org.bouncycastle.cms.CMSAlgorithmNotAllowedException;
1312
import org.bouncycastle.cms.CMSException;
1413
import org.bouncycastle.cms.KEKRecipient;
1514
import org.bouncycastle.operator.OperatorException;
@@ -133,12 +132,7 @@ public JceKEKRecipient setMinimumTagSize(int tagSizeInBits)
133132
protected Key extractSecretKey(AlgorithmIdentifier keyEncryptionAlgorithm, AlgorithmIdentifier encryptedKeyAlgorithm, byte[] encryptedContentEncryptionKey)
134133
throws CMSException
135134
{
136-
if (!isContentAlgorithmAllowed(encryptedKeyAlgorithm.getAlgorithm()))
137-
{
138-
throw new CMSAlgorithmNotAllowedException("content-encryption algorithm not in recipient's allowed set: " + encryptedKeyAlgorithm.getAlgorithm());
139-
}
140-
141-
checkTagSize(encryptedKeyAlgorithm);
135+
checkContentAlgorithm(encryptedKeyAlgorithm);
142136

143137
SymmetricKeyUnwrapper unwrapper = helper.createSymmetricUnwrapper(keyEncryptionAlgorithm, recipientKey);
144138

0 commit comments

Comments
 (0)