Skip to content

Commit 5ece6c9

Browse files
author
gefeili
committed
Refuse a KEM KeyGenerator request for more key bits than the mechanism's session key when no KDF is configured, where KdfUtil.makeKeyBytes previously overran the shared secret and threw ArrayIndexOutOfBoundsException out of KeyGenerator.generateKey() - the conventional 256 bit request for FrodoKEM's 976 parameter sets, whose session key is 192 bits, and any request above 256 bits for ML-KEM, Classic McEliece and the composite KEMs, whose session keys are 256 bits. These services take a KEMGenerateSpec or KEMExtractSpec rather than a KTSParameterSpec and so never pass through resolveKemSpec, where the javax.crypto.KEM specs are now validated up front, so the check sits in makeKeyBytes itself and covers them along with any future caller of it. The request is refused rather than quietly met at the shorter length, as a caller that asked for a 256 bit AES key and was handed a 192 bit one has no way of telling, while the Cipher and KTS key wrapping paths go on clamping - there the requested size is only an upper bound on a wrapping key both parties derive the same way from the same secret.
1 parent 0f336b6 commit 5ece6c9

4 files changed

Lines changed: 116 additions & 0 deletions

File tree

‎docs/releasenotes.html‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ <h3>2.1.2 Defects Fixed</h3>
126126
<li>Signature.setParameter(...) on any of the ML-DSA or SLH-DSA services threw NullPointerException when called before initSign / initVerify, out of a method declared to throw InvalidAlgorithmParameterException. The context carried by a ContextParameterSpec is applied by re-initialising the underlying signer with the key the Signature holds, and BaseDeterministicOrRandomSignature.engineSetParameter went straight to that re-initialisation without checking there was a key to re-initialise with. The context may now be set either side of initialisation, as the RSASSA-PSS parameters may be: setting it on a signature that already has a key re-initialises the signer at once as before, and setting it beforehand records it to be applied when the key arrives. Initialising no longer discards a context set beforehand, which it previously did by resetting the context to empty - so a caller who set one first and would have had it silently dropped now gets the signature they asked for. Setting a context after initialisation, which is what the existing tests and examples do, produces exactly the signatures it did before, and setting one in the middle of an update is still refused with a ProviderException. Note the context now also survives a subsequent re-initialisation of the same Signature object, again as the RSASSA-PSS parameters do (github #2396).</li>
127127
<li>An OCSP response carrying no nextUpdate could be cached and reused as though it stated a validity interval, so a response could go on answering for a certificate after the responder had newer information about it - after a revocation, in particular. Any such reuse was bounded only by garbage collection rather than by an interval: OcspCache holds each responder's response map through a WeakReference, itself in a WeakHashMap, and nothing else refers to that map once the call returns, so entries last until the next collection. That is unpredictable rather than long - short on a busy JVM, potentially much longer on a large heap that collects rarely - and it is not a window the responder or the caller had any say in. RFC 6960 sec. 4.2.2.1 says the opposite of what that assumes: "if nextUpdate is not set, the responder is indicating that newer revocation information is available all the time", which is a statement that there is no interval to reuse the response over, not that it never expires. OcspCache now separates the two questions it had been asking with one method: a response arriving from the responder is accepted as before, whether or not it states a nextUpdate, while only a response that states one may be served from the cache afterwards. Nothing is rejected that was previously accepted - a responder that omits nextUpdate simply costs another request per validation, which is what "available all the time" asks for. Additionally, both the cached and the caller-supplied (stapled) paths now apply RFC 6960 sec. 4.2.2.1's other freshness rule, "responses whose thisUpdate time is later than the local system time SHOULD be considered unreliable", which neither had checked: a response dated ahead of the time being validated for by more than a 15 minute clock-skew allowance is treated as unreliable, raising "OCSP response not yet valid" on the stapled path.</li>
128128
<li>None of the javax.crypto.KEM encapsulators destroyed the SecretWithEncapsulation the mechanism handed them, so each left the mechanism's own session key live in the heap for as long as the KEM.Encapsulator object was reachable - ML-KEM, HQC, NTRU, NTRU Prime and SM9 were all affected. Clearing the derived key was not enough to cover it: SecretWithEncapsulationImpl.getSecret() and getEncapsulation() hand back clones of their internal arrays, so KdfUtil.makeKeyBytes clearing the secret clone it is passed never reached the session key inside, and only destroy() does. Each encapsulator now takes the encapsulation and the shared secret and then destroys the SecretWithEncapsulation in a finally block, as the sibling Cipher services in the same packages already did, and as the ISO/IEC 18033-2 FrodoKEM and Classic McEliece encapsulators added in this release do. The order matters, since destroy() clears the encapsulation as well as the session key. Nothing observable changes for a caller - the shared secret and encapsulation returned are the same as before, and are the caller's own copies.</li>
129+
<li>The KEM KeyGenerator services had the same missing key-size check as the javax.crypto.KEM ones described under Additional Features below, and are corrected here for the older API too: a KEMGenerateSpec or KEMExtractSpec built withNoKdf() and given a key size larger than the mechanism's session key overran the shared secret and threw ArrayIndexOutOfBoundsException out of KeyGenerator.generateKey(), which has no way to describe such a failure. The conventional 256-bit request failed that way for FrodoKEM's 976 parameter sets, whose session key is 192 bits, as did any request above 256 bits for ML-KEM, Classic McEliece and the composite KEMs, whose session keys are 256 bits. These services take a KEMKDFSpec rather than a KTSParameterSpec and so never pass through KdfUtil.resolveKemSpec, where the KEM services now have their spec validated up front; the check therefore sits in KdfUtil.makeKeyBytes itself, which covers them and any future caller of it. The request is refused with an IllegalArgumentException naming both sizes rather than quietly met at the shorter length, since a caller that asked for a 256-bit AES key and was handed a 192-bit one has no way of telling. A request the session key can satisfy is unaffected and produces exactly the key material it did before, and the Cipher and KTS key-wrapping paths were never affected - there the requested size is only an upper bound on a wrapping key both parties derive the same way from the same secret, so WrapUtil clamps it to the secret it has.</li>
129130
</ul>
130131

131132
<h3>2.1.3 Additional Features and Functionality</h3>

‎prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/util/KdfUtil.java‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,8 @@ private static boolean isSupportedKdf(AlgorithmIdentifier kdfAlgorithm)
188188
* @param kdfSpec definition of the KDF and the output size to produce.
189189
* @param secret the secret value to initialize the KDF with (erased after secret key generation).
190190
* @return a generated secret key.
191+
* @throws IllegalArgumentException if the spec asks for no KDF and the requested key size is
192+
* larger than the shared secret the mechanism produced.
191193
*/
192194
public static byte[] makeKeyBytes(KEMKDFSpec kdfSpec, byte[] secret)
193195
{
@@ -219,6 +221,22 @@ static byte[] makeKeyBytes(AlgorithmIdentifier kdfAlgorithm, byte[] secret, byte
219221

220222
if (kdfAlgorithm == null)
221223
{
224+
// With no KDF the shared secret is the key material, so a request for more bits than the
225+
// mechanism produced cannot be met. Refuse rather than truncate the request silently: a
226+
// caller that asked for a 256-bit key and was handed FrodoKEM-976's 192-bit secret would
227+
// have no way of telling. (WrapUtil clamps instead, as there the requested size is only an
228+
// upper bound on a wrapping key both sides derive the same way.)
229+
//
230+
// resolveKemSpec above applies the same rule to a KTSParameterSpec before a
231+
// javax.crypto.KEM ever encapsulates, where it can be reported as the spec failure it is.
232+
// This is the backstop for the callers that do not pass through it - the KEM KeyGenerator
233+
// services, which take a KEMGenerateSpec / KEMExtractSpec and reach makeKeyBytes directly.
234+
if (secret.length < keyBytes.length)
235+
{
236+
throw new IllegalArgumentException("no KDF specified and the shared secret is "
237+
+ (secret.length * 8) + " bits, " + keySize + " requested");
238+
}
239+
222240
System.arraycopy(secret, 0, keyBytes, 0, keyBytes.length);
223241
}
224242
else if (X9ObjectIdentifiers.id_kdf_kdf2.equals(kdfAlgorithm.getAlgorithm()))

‎prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/CMCEKEMTest.java‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,37 @@ public void testGenerateAES()
124124
assertTrue(Arrays.areEqual(secEnc1.getEncoded(), secEnc2.getEncoded()));
125125
}
126126

127+
/**
128+
* The no-KDF key size check is not a FrodoKEM speciality - it lives in the shared KdfUtil, so
129+
* every KEM KeyGenerator gets it. CMCE's secret is 256 bits, which covers the conventional
130+
* request but not one above it.
131+
*/
132+
public void testNoKdfRejectsKeySizeAboveSharedSecret()
133+
throws Exception
134+
{
135+
KeyPairGenerator kpg = KeyPairGenerator.getInstance("CMCE", "BC");
136+
kpg.initialize(CMCEParameterSpec.mceliece460896, new SecureRandom());
137+
KeyPair kp = kpg.generateKeyPair();
138+
139+
KeyGenerator keyGen = KeyGenerator.getInstance("CMCE", "BC");
140+
141+
keyGen.init(new KEMGenerateSpec.Builder(kp.getPublic(), "AES", 256).withNoKdf().build(), new SecureRandom());
142+
143+
assertEquals(32, keyGen.generateKey().getEncoded().length);
144+
145+
keyGen.init(new KEMGenerateSpec.Builder(kp.getPublic(), "AES", 512).withNoKdf().build(), new SecureRandom());
146+
147+
try
148+
{
149+
keyGen.generateKey();
150+
fail("no exception on over-long no-KDF generate");
151+
}
152+
catch (IllegalArgumentException e)
153+
{
154+
assertEquals("no KDF specified and the shared secret is 256 bits, 512 requested", e.getMessage());
155+
}
156+
}
157+
127158
/**
128159
* The KEM cipher's data-encapsulation mechanism is caller-selectable; the non-AES wrap
129160
* algorithms the removed round-3 tests exercised have to keep working here too.

‎prov/src/test/java/org/bouncycastle/pqc/jcajce/provider/test/FrodoKEMTest.java‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,72 @@ public void testGenerateAES()
143143
assertTrue(Arrays.areEqual(secEnc1.getEncoded(), secEnc2.getEncoded()));
144144
}
145145

146+
/**
147+
* With {@link KEMGenerateSpec.Builder#withNoKdf()} the shared secret is the key material, so a
148+
* request for more bits than the parameter set produces cannot be met - frodokem976shake's
149+
* secret is 192 bits. Both the generate and the extract side have to say so, rather than
150+
* overrunning the secret (which surfaced as an ArrayIndexOutOfBoundsException out of KdfUtil)
151+
* and rather than quietly handing back a 192-bit key the caller never asked for.
152+
*/
153+
public void testNoKdfRejectsKeySizeAboveSharedSecret()
154+
throws Exception
155+
{
156+
String expected = "no KDF specified and the shared secret is 192 bits, 256 requested";
157+
158+
KeyPairGenerator kpg = KeyPairGenerator.getInstance("FRODOKEM", "BC");
159+
kpg.initialize(FrodoKEMParameterSpec.frodokem976shake, new SecureRandom());
160+
161+
KeyPair kp = kpg.generateKeyPair();
162+
163+
KeyGenerator keyGen = KeyGenerator.getInstance("FRODOKEM", "BC");
164+
165+
keyGen.init(new KEMGenerateSpec.Builder(kp.getPublic(), "AES", 256).withNoKdf().build(), new SecureRandom());
166+
167+
try
168+
{
169+
keyGen.generateKey();
170+
fail("no exception on over-long no-KDF generate");
171+
}
172+
catch (IllegalArgumentException e)
173+
{
174+
assertEquals(expected, e.getMessage());
175+
}
176+
177+
// a request the secret can satisfy is untouched, and both sides still agree on the key.
178+
keyGen.init(new KEMGenerateSpec.Builder(kp.getPublic(), "AES", 192).withNoKdf().build(), new SecureRandom());
179+
180+
SecretKeyWithEncapsulation secEnc1 = (SecretKeyWithEncapsulation)keyGen.generateKey();
181+
182+
assertEquals(24, secEnc1.getEncoded().length);
183+
184+
keyGen.init(new KEMExtractSpec.Builder(kp.getPrivate(), secEnc1.getEncapsulation(), "AES", 192).withNoKdf().build());
185+
186+
SecretKeyWithEncapsulation secEnc2 = (SecretKeyWithEncapsulation)keyGen.generateKey();
187+
188+
assertTrue(Arrays.areEqual(secEnc1.getEncoded(), secEnc2.getEncoded()));
189+
190+
keyGen.init(new KEMExtractSpec.Builder(kp.getPrivate(), secEnc1.getEncapsulation(), "AES", 256).withNoKdf().build());
191+
192+
try
193+
{
194+
keyGen.generateKey();
195+
fail("no exception on over-long no-KDF extract");
196+
}
197+
catch (IllegalArgumentException e)
198+
{
199+
assertEquals(expected, e.getMessage());
200+
}
201+
202+
// frodokem1344shake's 256-bit secret does satisfy the conventional 256-bit request.
203+
kpg.initialize(FrodoKEMParameterSpec.frodokem1344shake, new SecureRandom());
204+
205+
KeyPair kp1344 = kpg.generateKeyPair();
206+
207+
keyGen.init(new KEMGenerateSpec.Builder(kp1344.getPublic(), "AES", 256).withNoKdf().build(), new SecureRandom());
208+
209+
assertEquals(32, keyGen.generateKey().getEncoded().length);
210+
}
211+
146212
/**
147213
* The KEM cipher's data-encapsulation mechanism is caller-selectable; the non-AES wrap
148214
* algorithms the removed round-3 tests exercised have to keep working here too.

0 commit comments

Comments
 (0)