Skip to content

Commit e8b5cf1

Browse files
committed
Merge branch 'main' of gitlab.cryptoworkshop.com:root/bc-java
2 parents ae14c98 + b4e2c10 commit e8b5cf1

5 files changed

Lines changed: 118 additions & 154 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ pg/*.bpg
2828
pg/*.txt
2929

3030
.idea/
31+
.vscode/
3132

3233
.DS_Store
3334

‎docs/releasenotes.html‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@ <h3>2.1.2 Defects Fixed</h3>
131131
<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>
132132
<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>
133133
<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>
134+
<li>The PKIX certification path builders - CertPathBuilder "PKIX" / "RFC3280" and the "RFC3281" attribute certificate path builder - kept the failure cause of a build in an instance field that was never cleared, so a CertPathBuilder reused for a further build could report a stale diagnostic: a build that found no certification path while recording no failure of its own, for example with the target certificate excluded or every candidate path cut off by the maximum path length, reported the previous build's failure instead of "Unable to find certificate chain.". The exception type and the result of a successful build were unaffected, as was any build with a freshly obtained CertPathBuilder. The field is now cleared at the start of each build, and the recursive search now removes each certificate from its working path in a finally block, so every exit - a successful build included, the returned certification path being built from a copy of the working path - restores the path for the next candidate, where previously only the exits without a result did.</li>
134135
<li>The BCJSSE provider now only computes active early key share groups for clients offering TLS 1.3+. Previously it was computed for all connections, which was mostly harmless, but could generate misleading log messages (at WARNING level) for servers or pre-TLS1.3 clients where the logged condition was irrelevant (github #2392).</li>
135136
<li>Initialising a BC signature, cipher or key-agreement service with a private key from another provider whose key material is not accessible - a hardware-backed key whose getModulus() / getX() / getS() / getParams() throws, as an IBM CCA RSAPrivateHWKey does with "Hardware error, function getModulus has no meaning in hardware" - let that provider-specific unchecked UnsupportedOperationException escape a method declared to throw only InvalidKeyException, so an mTLS handshake failed with a raw hardware error rather than the documented type. The key-parameter helpers that examine a key through a java.security.interfaces or javax.crypto.interfaces type a foreign provider may implement - RSAUtil, DSAUtil, ECUtil (its java.security.interfaces.ECPrivateKey branch), both DHUtil copies and ElGamalUtil - now catch a failure to read the key's parameters and raise InvalidKeyException with the original exception chained as its cause. A caller, or a JSSE layer that keys its provider fallback on InvalidKeyException, sees the declared type and a clear message. This does not let BC sign or decrypt with a non-exportable hardware key, which is not possible; it makes the refusal in contract. BC's own keys and any exportable key are unaffected (github #1440).</li>
136137
<li>org.bouncycastle.operator.DefaultKemEncapsulationLengthProvider.getEncapsulationLength() looked its argument up in a table of the KEMs whose encapsulation lengths are registered - ML-KEM, NTRU, HQC, FrodoKEM and composite ML-KEM - and dereferenced the result without checking it. A CMS RFC 9629 KEMRecipientInfo recipient using any other KEM which does register a key wrapping cipher, BIKE, NTRU+ or SMAUG-T, got as far as the wrap and then failed with a NullPointerException carrying no indication of which algorithm was at fault. The lookup now throws IllegalArgumentException naming the KEM's OID, as the sibling DefaultKemAlgorithmIdentifierFinder does, and the contract is documented on the KemEncapsulationLengthProvider interface (github #2398).</li>

‎prov/src/main/java/org/bouncycastle/jce/provider/PKIXAttrCertPathBuilderSpi.java‎

Lines changed: 27 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
public class PKIXAttrCertPathBuilderSpi
4343
extends CertPathBuilderSpi
4444
{
45+
private AnnotatedException certPathException;
4546

4647
/**
4748
* Build and validate a CertPath using the given parameter.
@@ -86,6 +87,8 @@ public CertPathBuilderResult engineBuild(CertPathParameters params)
8687
paramsPKIX = (PKIXExtendedBuilderParameters)params;
8788
}
8889

90+
certPathException = null;
91+
8992
Collection targets;
9093
Iterator targetIter;
9194
List certPathList = new ArrayList();
@@ -119,11 +122,9 @@ public CertPathBuilderResult engineBuild(CertPathParameters params)
119122
"No attribute certificate found matching targetConstraints.");
120123
}
121124

122-
CertPathBuilderResult result = null;
123-
124125
// check all potential target certificates
125126
targetIter = targets.iterator();
126-
while (targetIter.hasNext() && result == null)
127+
while (targetIter.hasNext())
127128
{
128129
cert = (X509AttributeCertificate) targetIter.next();
129130

@@ -161,30 +162,24 @@ public CertPathBuilderResult engineBuild(CertPathParameters params)
161162
"Public key certificate for attribute certificate cannot be found.");
162163
}
163164
Iterator it = issuers.iterator();
164-
while (it.hasNext() && result == null)
165+
while (it.hasNext())
165166
{
166-
result = build(cert, (X509Certificate)it.next(), paramsPKIX, certPathList);
167+
CertPathBuilderResult result = build(cert, (X509Certificate)it.next(), paramsPKIX, certPathList);
168+
if (result != null)
169+
{
170+
return result;
171+
}
167172
}
168173
}
169174

170-
if (result == null && certPathException != null)
175+
if (certPathException == null)
171176
{
172-
throw SecurityExceptions.certPathBuilderException(
173-
"Possible certificate chain could not be validated.",
174-
certPathException);
177+
throw new CertPathBuilderException("Unable to find certificate chain.");
175178
}
176179

177-
if (result == null && certPathException == null)
178-
{
179-
throw new CertPathBuilderException(
180-
"Unable to find certificate chain.");
181-
}
182-
183-
return result;
180+
throw new CertPathBuilderException(certPathException.getMessage(), certPathException.getCause());
184181
}
185182

186-
private Exception certPathException;
187-
188183
private CertPathBuilderResult build(X509AttributeCertificate attrCert, X509Certificate tbvCert,
189184
PKIXExtendedBuilderParameters pkixParams, List tbvPath)
190185

@@ -211,12 +206,8 @@ private CertPathBuilderResult build(X509AttributeCertificate attrCert, X509Certi
211206
}
212207
}
213208

214-
tbvPath.add(tbvCert);
215-
216209
CertificateFactory cFact;
217210
CertPathValidator validator;
218-
CertPathBuilderResult builderResult = null;
219-
220211
try
221212
{
222213
cFact = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME);
@@ -225,10 +216,11 @@ private CertPathBuilderResult build(X509AttributeCertificate attrCert, X509Certi
225216
catch (Exception e)
226217
{
227218
// cannot happen
228-
throw new RuntimeException(
229-
"Exception creating support classes.");
219+
throw new RuntimeException("Exception creating support classes.");
230220
}
231221

222+
tbvPath.add(tbvCert);
223+
232224
try
233225
{
234226
// check whether the issuer of <tbvCert> is a TrustAnchor
@@ -298,7 +290,7 @@ private CertPathBuilderResult build(X509AttributeCertificate attrCert, X509Certi
298290
}
299291

300292
Iterator it = issuers.iterator();
301-
while (it.hasNext() && builderResult == null)
293+
while (it.hasNext())
302294
{
303295
X509Certificate issuer = (X509Certificate) it.next();
304296
// TODO Use CertPathValidatorUtilities.isSelfIssued(issuer)?
@@ -307,19 +299,26 @@ private CertPathBuilderResult build(X509AttributeCertificate attrCert, X509Certi
307299
{
308300
continue;
309301
}
310-
builderResult = build(attrCert, issuer, pkixParams, tbvPath);
302+
303+
CertPathBuilderResult builderResult = build(attrCert, issuer, pkixParams, tbvPath);
304+
if (builderResult != null)
305+
{
306+
return builderResult;
307+
}
311308
}
312309
}
313310
}
314311
catch (AnnotatedException e)
315312
{
316313
certPathException = new AnnotatedException("No valid certification path could be build.", e);
317314
}
318-
if (builderResult == null)
315+
finally
319316
{
317+
// Undo the add above on every exit from this frame - including the success path (the CertPath was built
318+
// from a copy of tbvPath).
320319
tbvPath.remove(tbvCert);
321320
}
322-
return builderResult;
321+
return null;
323322
}
324323

325324
protected static Collection findCertificates(X509AttributeCertStoreSelector certSelect, List certStores)

‎prov/src/main/java/org/bouncycastle/jce/provider/PKIXCertPathBuilderSpi.java‎

Lines changed: 39 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ public class PKIXCertPathBuilderSpi
3636
{
3737
private final boolean isForCRLCheck;
3838

39+
private AnnotatedException certPathException;
40+
private int maxNodes;
41+
private int nodesVisited;
42+
3943
public PKIXCertPathBuilderSpi()
4044
{
4145
this(false);
@@ -93,59 +97,41 @@ else if (params instanceof PKIXExtendedBuilderParameters)
9397
+ PKIXExtendedBuilderParameters.class.getName() + ".");
9498
}
9599

96-
Collection targets;
97-
Iterator targetIter;
98-
List certPathList = new ArrayList();
99-
X509Certificate cert;
100-
101-
// search target certificates
102-
targets = CertPathValidatorUtilities.findTargets(paramsPKIX);
103-
104-
CertPathBuilderResult result = null;
105-
100+
certPathException = null;
106101
maxNodes = Properties.asInteger(Properties.X509_MAX_CERT_PATH_BUILD_NODES, 262144);
107102
nodesVisited = 0;
108103

109-
// check all potential target certificates
110-
targetIter = targets.iterator();
111104
try
112105
{
113-
while (targetIter.hasNext() && result == null)
106+
List certPathList = new ArrayList();
107+
108+
// check all potential target certificates
109+
Collection targets = CertPathValidatorUtilities.findTargets(paramsPKIX);
110+
Iterator targetIter = targets.iterator();
111+
while (targetIter.hasNext())
114112
{
115-
cert = (X509Certificate) targetIter.next();
116-
result = build(cert, paramsPKIX, certPathList);
113+
X509Certificate tbvCert = (X509Certificate)targetIter.next();
114+
115+
CertPathBuilderResult result = build(tbvCert, paramsPKIX, certPathList);
116+
if (result != null)
117+
{
118+
return result;
119+
}
117120
}
118121
}
119122
catch (NodeBudgetExceededException e)
120123
{
121124
throw new CertPathBuilderException(e.getMessage());
122125
}
123126

124-
if (result == null && certPathException != null)
125-
{
126-
if (certPathException instanceof AnnotatedException)
127-
{
128-
throw new CertPathBuilderException(certPathException.getMessage(), certPathException.getCause());
129-
}
130-
throw new CertPathBuilderException(
131-
"Possible certificate chain could not be validated.",
132-
certPathException);
133-
}
134-
135-
if (result == null && certPathException == null)
127+
if (certPathException == null)
136128
{
137-
throw new CertPathBuilderException(
138-
"Unable to find certificate chain.");
129+
throw new CertPathBuilderException("Unable to find certificate chain.");
139130
}
140131

141-
return result;
132+
throw new CertPathBuilderException(certPathException.getMessage(), certPathException.getCause());
142133
}
143134

144-
private Exception certPathException;
145-
146-
private int maxNodes;
147-
private int nodesVisited;
148-
149135
protected CertPathBuilderResult build(X509Certificate tbvCert,
150136
PKIXExtendedBuilderParameters pkixParams, List tbvPath)
151137
{
@@ -182,12 +168,8 @@ protected CertPathBuilderResult build(X509Certificate tbvCert,
182168
}
183169
}
184170

185-
tbvPath.add(tbvCert);
186-
187171
CertificateFactory cFact;
188172
PKIXCertPathValidatorSpi validator;
189-
CertPathBuilderResult builderResult = null;
190-
191173
try
192174
{
193175
cFact = new CertificateFactory();
@@ -199,6 +181,8 @@ protected CertPathBuilderResult build(X509Certificate tbvCert,
199181
throw new RuntimeException("Exception creating support classes.");
200182
}
201183

184+
tbvPath.add(tbvCert);
185+
202186
try
203187
{
204188
// check whether the issuer of <tbvCert> is a TrustAnchor
@@ -222,25 +206,19 @@ protected CertPathBuilderResult build(X509Certificate tbvCert,
222206

223207
try
224208
{
225-
result = (PKIXCertPathValidatorResult) validator.engineValidate(
226-
certPath, pkixParams);
209+
result = (PKIXCertPathValidatorResult)validator.engineValidate(certPath, pkixParams);
227210
}
228211
catch (Exception e)
229212
{
230-
throw new AnnotatedException(
231-
"Certification path could not be validated.", e);
213+
throw new AnnotatedException("Certification path could not be validated.", e);
232214
}
233215

234-
return new PKIXCertPathBuilderResult(certPath, result
235-
.getTrustAnchor(), result.getPolicyTree(), result
236-
.getPublicKey());
237-
216+
return new PKIXCertPathBuilderResult(certPath, result.getTrustAnchor(), result.getPolicyTree(),
217+
result.getPublicKey());
238218
}
239219
else
240220
{
241221
List stores = new ArrayList();
242-
243-
244222
stores.addAll(pkixParams.getBaseParameters().getCertificateStores());
245223

246224
// add additional X.509 stores from locations in certificate
@@ -256,8 +234,7 @@ protected CertPathBuilderResult build(X509Certificate tbvCert,
256234
e);
257235
}
258236
Collection issuers = new HashSet();
259-
// try to get the issuer certificate from one
260-
// of the stores
237+
// try to get the issuer certificate from one of the stores
261238
try
262239
{
263240
issuers.addAll(CertPathValidatorUtilities.findIssuerCerts(tbvCert, pkixParams.getBaseParameters().getCertStores(), stores));
@@ -274,23 +251,29 @@ protected CertPathBuilderResult build(X509Certificate tbvCert,
274251
"No issuer certificate for certificate in certification path found.");
275252
}
276253
Iterator it = issuers.iterator();
277-
278-
while (it.hasNext() && builderResult == null)
254+
while (it.hasNext())
279255
{
280256
X509Certificate issuer = (X509Certificate) it.next();
281-
builderResult = build(issuer, pkixParams, tbvPath);
257+
258+
CertPathBuilderResult builderResult = build(issuer, pkixParams, tbvPath);
259+
if (builderResult != null)
260+
{
261+
return builderResult;
262+
}
282263
}
283264
}
284265
}
285266
catch (AnnotatedException e)
286267
{
287268
certPathException = e;
288269
}
289-
if (builderResult == null)
270+
finally
290271
{
272+
// Undo the add above on every exit from this frame - including the success path (the CertPath was built
273+
// from a copy of tbvPath) and an unwinding NodeBudgetExceededException.
291274
tbvPath.remove(tbvCert);
292275
}
293-
return builderResult;
276+
return null;
294277
}
295278

296279
/**
@@ -305,5 +288,4 @@ private static class NodeBudgetExceededException
305288
super(message);
306289
}
307290
}
308-
309291
}

0 commit comments

Comments
 (0)