Skip to content

Commit 1a7b6d7

Browse files
committed
Bound the C509 validity fields to the X.509 time domain when parsing and route every seconds-to-milliseconds conversion through one checked helper, so that a validityNotAfter displaced by 2^61 seconds - which reconstructs the same DER TBSCertificate and so leaves the issuer signature intact - is refused rather than read back as an expiry the holder's isValidOn and its own getters disagree about.
1 parent 97ae51f commit 1a7b6d7

5 files changed

Lines changed: 235 additions & 6 deletions

File tree

‎CONTRIBUTORS.html‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -608,6 +608,7 @@
608608
<li>Flowdalic &lt;https://github.com/Flowdalic&gt; - initial implementation of an AnimalSniffer-based Android API-level compatibility check for the Gradle build (PR #336).</li>
609609
<li>hannesa2 &lt;https://github.com/hannesa2&gt; - initial Dependabot configuration for the Gradle and GitHub Actions ecosystems (PR #883).</li>
610610
<li>vladhuma &lt;https://github.com/vladhuma&gt; - initial implementation of server-side OCSP stapling for the BCJSSE provider, on behalf of Thales Group (PR #1740).</li>
611+
<li>Bhargava Shastry &lt;bshastry@posteo.de&gt; - reporting, with a self-checking reproducer, that the C509 validity fields were read as unbounded seconds and then given two meanings: displacing a type-3 certificate's validityNotAfter by 2^61 seconds left the reconstructed DER TBSCertificate and the issuer signature untouched, while C509CertificateHolder.isValidOn took the raw value and read an expired certificate as valid.</li>
611612
</ul>
612613
</body>
613614
</html>

‎pkix/src/main/java/org/bouncycastle/cert/c509/C509CertificateHolder.java‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ public X500Name getSubject()
9090

9191
public Date getNotBefore()
9292
{
93-
return new Date(certificate.getNotBefore() * 1000);
93+
return C509Certificate.toDate(certificate.getNotBefore());
9494
}
9595

9696
/**
@@ -99,7 +99,7 @@ public Date getNotBefore()
9999
*/
100100
public Date getNotAfter()
101101
{
102-
return new Date(certificate.getNotAfter() * 1000);
102+
return C509Certificate.toDate(certificate.getNotAfter());
103103
}
104104

105105
/**
@@ -111,6 +111,8 @@ public boolean isValidOn(Date date)
111111
{
112112
throw new NullPointerException("'date' cannot be null");
113113
}
114+
// the validity values are in the X.509 time domain, so this decision, the dates
115+
// the getters return, and the reconstructed X.509 view all agree on their meaning
114116
long seconds = date.getTime() / 1000;
115117
return seconds >= certificate.getNotBefore() && seconds <= certificate.getNotAfter();
116118
}

‎pkix/src/test/java/org/bouncycastle/cert/c509/test/C509CertTest.java‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package org.bouncycastle.cert.c509.test;
22

3+
import java.io.ByteArrayOutputStream;
4+
import java.io.IOException;
35
import java.math.BigInteger;
46
import java.security.KeyPair;
57
import java.security.KeyPairGenerator;
@@ -18,6 +20,8 @@
1820
import org.bouncycastle.asn1.x509.ExtensionsGenerator;
1921
import org.bouncycastle.asn1.x509.KeyUsage;
2022
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
23+
import org.bouncycastle.cbor.CBORDecoder;
24+
import org.bouncycastle.cbor.CBOREncoder;
2125
import org.bouncycastle.cbor.c509.C509Certificate;
2226
import org.bouncycastle.cbor.c509.C509CertificationRequest;
2327
import org.bouncycastle.cbor.c509.C509PrivateKey;
@@ -224,6 +228,80 @@ public void testX509RoundTripThroughType3()
224228
assertTrue(Arrays.areEqual(der, new JcaX509CertificateHolder(jcaCert).getEncoded()));
225229
}
226230

231+
public void testExpiredType3CannotBeRevivedByDisplacingNotAfter()
232+
throws Exception
233+
{
234+
KeyPair issuerKp = generateECKeyPair();
235+
KeyPair subjectKp = generateECKeyPair();
236+
237+
Date notBefore = new Date(1640995200000L); // 2022-01-01T00:00:00Z
238+
Date notAfter = new Date(1672531200000L); // 2023-01-01T00:00:00Z
239+
Date checkTime = new Date(1767225600000L); // 2026-01-01T00:00:00Z, after expiry
240+
241+
X509CertificateHolder x509 = new X509v3CertificateBuilder(new X500Name("CN=C509 test CA"),
242+
BigInteger.valueOf(4712), notBefore, notAfter, new X500Name("CN=C509 test EE"),
243+
SubjectPublicKeyInfo.getInstance(subjectKp.getPublic().getEncoded()))
244+
.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature))
245+
.build(new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(issuerKp.getPrivate()));
246+
247+
C509CertificateHolder holder = new C509CertificateHolder(
248+
C509Certificate.fromX509Certificate(x509.getEncoded()));
249+
assertTrue(holder.isSignatureValid(new JcaC509ContentVerifierProviderBuilder().setProvider("BC")
250+
.build(SubjectPublicKeyInfo.getInstance(issuerKp.getPublic().getEncoded()))));
251+
assertEquals(notAfter, holder.getNotAfter());
252+
assertFalse(holder.isValidOn(checkTime));
253+
254+
// displacing notAfter by 2^61 seconds leaves the reconstructed DER, and so the
255+
// signed bytes and the issuer signature, untouched; the holder must refuse the
256+
// encoding rather than let its validity decision disagree with its own getters
257+
long displaced = (notAfter.getTime() / 1000) + (1L << 61);
258+
assertEquals(notAfter.getTime(), displaced * 1000);
259+
byte[] forged = withValidityField(holder.getEncoded(), 5, displaced);
260+
try
261+
{
262+
new C509CertificateHolder(forged);
263+
fail("accepted a notAfter displaced past 99991231235959Z");
264+
}
265+
catch (IOException e)
266+
{
267+
assertEquals("validityNotAfter is after 99991231235959Z: " + displaced, e.getMessage());
268+
}
269+
}
270+
271+
/**
272+
* Re-encode a C509 certificate with the CBOR item at the given index of the
273+
* certificate array replaced by an unsigned integer, leaving every other item,
274+
* including the issuer signature, exactly as it was.
275+
*/
276+
private static byte[] withValidityField(byte[] encoding, int index, long seconds)
277+
throws IOException
278+
{
279+
CBORDecoder in = new CBORDecoder(encoding);
280+
int count = in.readArrayHeader();
281+
byte[][] items = new byte[count][];
282+
for (int i = 0; i != count; i++)
283+
{
284+
items[i] = in.readEncodedItem();
285+
}
286+
in.expectEnd();
287+
288+
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
289+
CBOREncoder out = new CBOREncoder(bOut);
290+
out.writeArrayHeader(count);
291+
for (int i = 0; i != count; i++)
292+
{
293+
if (i == index)
294+
{
295+
out.writeUnsignedInteger(seconds);
296+
}
297+
else
298+
{
299+
out.writeEncoded(items[i]);
300+
}
301+
}
302+
return bOut.toByteArray();
303+
}
304+
227305
public void testNativeCertificationRequestBuildAndVerify()
228306
throws Exception
229307
{

‎util/src/main/java/org/bouncycastle/cbor/c509/C509Certificate.java‎

Lines changed: 45 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -209,15 +209,15 @@ private static Fields parseTBSFields(CBORDecoder in)
209209
fields.issuer = C509Name.parse(in);
210210
}
211211

212-
fields.notBefore = in.readUnsignedInteger();
212+
fields.notBefore = checkValiditySeconds(in.readUnsignedInteger(), "validityNotBefore");
213213
if (in.nextIsNull())
214214
{
215215
in.readNull();
216216
fields.notAfter = NO_EXPIRATION_DATE;
217217
}
218218
else
219219
{
220-
fields.notAfter = in.readUnsignedInteger();
220+
fields.notAfter = checkValiditySeconds(in.readUnsignedInteger(), "validityNotAfter");
221221
if (fields.notAfter == NO_EXPIRATION_DATE)
222222
{
223223
throw new IOException("validityNotAfter of 99991231235959Z must be encoded as null");
@@ -234,6 +234,43 @@ private static Fields parseTBSFields(CBORDecoder in)
234234
return fields;
235235
}
236236

237+
/**
238+
* Check a validity value read from an encoding lies in the X.509 time domain. The
239+
* C509 validity fields are unbounded CBOR unsigned integers, but the X.509 view of
240+
* them, a Time, reaches no further than {@link #NO_EXPIRATION_DATE}, so a larger
241+
* value has no X.509 meaning to agree on: converting it to milliseconds overflows,
242+
* and the reconstructed date it lands on collides with that of a legitimate value.
243+
* Values are rejected here rather than clamped so that the encoding a certificate
244+
* was accepted from stays the encoding its X.509 view was built from.
245+
*/
246+
private static long checkValiditySeconds(long seconds, String field)
247+
throws IOException
248+
{
249+
// CBORDecoder.readUnsignedInteger() has already excluded negative values
250+
if (seconds > NO_EXPIRATION_DATE)
251+
{
252+
throw new IOException(field + " is after 99991231235959Z: " + seconds);
253+
}
254+
return seconds;
255+
}
256+
257+
/**
258+
* Convert a C509 validity value in POSIX seconds, as returned by
259+
* {@link #getNotBefore()} and {@link #getNotAfter()}, to a Date.
260+
*
261+
* @param seconds a validity value in POSIX seconds.
262+
* @throws IllegalArgumentException if the value lies outside the X.509 time domain,
263+
* which the validity values of a parsed or generated certificate cannot.
264+
*/
265+
public static Date toDate(long seconds)
266+
{
267+
if (seconds < 0 || seconds > NO_EXPIRATION_DATE)
268+
{
269+
throw new IllegalArgumentException("validity value outside the X.509 time domain: " + seconds);
270+
}
271+
return new Date(seconds * 1000);
272+
}
273+
237274
/**
238275
* Encode the TBSCertificate group for a certificate about to be signed. For a
239276
* natively signed certificate the returned encoding is exactly the byte string
@@ -366,6 +403,10 @@ private static long toEpochSeconds(Date date, String field)
366403
{
367404
throw new IOException(field + " must not be before 1970-01-01T00:00:00Z");
368405
}
406+
if (seconds > NO_EXPIRATION_DATE)
407+
{
408+
throw new IOException(field + " must not be after 9999-12-31T23:59:59Z");
409+
}
369410
return seconds;
370411
}
371412

@@ -485,8 +526,8 @@ public Certificate toX509Certificate()
485526
tbsGen.setSignature(issuerSignatureAlgorithm.toX509AlgorithmIdentifier());
486527
X500Name issuerName = issuer == null ? subject.toX500Name() : issuer.toX500Name();
487528
tbsGen.setIssuer(issuerName);
488-
tbsGen.setStartDate(new Time(new Date(notBefore * 1000), Locale.US));
489-
tbsGen.setEndDate(new Time(new Date(notAfter * 1000), Locale.US));
529+
tbsGen.setStartDate(new Time(toDate(notBefore), Locale.US));
530+
tbsGen.setEndDate(new Time(toDate(notAfter), Locale.US));
490531
tbsGen.setSubject(subject.toX500Name());
491532
tbsGen.setSubjectPublicKeyInfo(subjectPublicKeyInfo);
492533
Extensions x509Extensions = extensions.toX509Extensions();

‎util/src/test/java/org/bouncycastle/cbor/c509/test/C509CertificateTest.java‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
package org.bouncycastle.cbor.c509.test;
22

3+
import java.io.ByteArrayOutputStream;
34
import java.io.IOException;
45
import java.io.InputStream;
56
import java.math.BigInteger;
7+
import java.util.Date;
68

79
import junit.framework.TestCase;
810
import org.bouncycastle.asn1.x509.Certificate;
11+
import org.bouncycastle.asn1.x509.TBSCertificate;
912
import org.bouncycastle.test.TestResourceFinder;
13+
import org.bouncycastle.cbor.CBORDecoder;
14+
import org.bouncycastle.cbor.CBOREncoder;
1015
import org.bouncycastle.cbor.c509.C509AttributeType;
1116
import org.bouncycastle.cbor.c509.C509Certificate;
1217
import org.bouncycastle.cbor.c509.C509ConversionOptions;
@@ -271,6 +276,108 @@ public void testNotAfterMustUseNullFor9999()
271276
expectRejected(modified, "notAfter 99991231235959Z as uint");
272277
}
273278

279+
public void testValidityOutsideX509TimeDomainRejected()
280+
throws Exception
281+
{
282+
byte[] good = vector("a1_c509_reencoded");
283+
C509Certificate cert = C509Certificate.getInstance(good);
284+
285+
// adding 2^61 seconds moves a validity value by 125 * 2^64 milliseconds, so an
286+
// accepted value would convert to the very millisecond the original did: the
287+
// reconstructed X.509 date, the signed DER TBSCertificate and the issuer
288+
// signature would all be unchanged, while a validity decision taken on the raw
289+
// seconds saw an expiry roughly 73 billion years out
290+
long wrapDelta = 1L << 61;
291+
assertEquals(0L, wrapDelta * 1000);
292+
expectRejected(withValidityField(good, 5, cert.getNotAfter() + wrapDelta),
293+
"notAfter displaced by 2^61 seconds");
294+
expectRejected(withValidityField(good, 4, cert.getNotBefore() + wrapDelta),
295+
"notBefore displaced by 2^61 seconds");
296+
297+
// one second past 99991231235959Z is the first value with no X.509 meaning
298+
expectRejected(withValidityField(good, 4, C509Certificate.NO_EXPIRATION_DATE + 1),
299+
"notBefore after 99991231235959Z");
300+
expectRejected(withValidityField(good, 5, C509Certificate.NO_EXPIRATION_DATE + 1),
301+
"notAfter after 99991231235959Z");
302+
303+
// the largest value CBOR can carry, and the largest a Java long can hold
304+
expectRejected(withValidityField(good, 5, Long.MAX_VALUE), "notAfter of 2^63-1");
305+
306+
// 99991231235959Z itself stays representable as a notBefore; as a notAfter it
307+
// must take the null encoding, which testNotAfterMustUseNullFor9999 covers.
308+
// The draft states no ordering requirement, so notBefore > notAfter is left to
309+
// the validity decision, which simply never holds.
310+
C509Certificate atLimit = C509Certificate.getInstance(
311+
withValidityField(good, 4, C509Certificate.NO_EXPIRATION_DATE));
312+
assertEquals(C509Certificate.NO_EXPIRATION_DATE, atLimit.getNotBefore());
313+
assertEquals(253402300799000L, C509Certificate.toDate(C509Certificate.NO_EXPIRATION_DATE).getTime());
314+
}
315+
316+
public void testGeneratedValidityBoundedToX509TimeDomain()
317+
throws Exception
318+
{
319+
// the generation path applies the same bound, so no caller can mint a validity
320+
// value the parse path would refuse to read back
321+
TBSCertificate tbs = Certificate.getInstance(vector("a1_x509")).getTBSCertificate();
322+
try
323+
{
324+
C509Certificate.createTBSCertificate(C509Certificate.TYPE_REENCODED_X509,
325+
tbs.getSerialNumber().getValue(), tbs.getSignature(), tbs.getIssuer(),
326+
new Date((C509Certificate.NO_EXPIRATION_DATE + 1) * 1000L), tbs.getEndDate().getDate(),
327+
tbs.getSubject(), tbs.getSubjectPublicKeyInfo(), tbs.getExtensions(),
328+
C509ConversionOptions.DEFAULT);
329+
fail("accepted a validityNotBefore after 99991231235959Z");
330+
}
331+
catch (IOException e)
332+
{
333+
assertEquals("validityNotBefore must not be after 9999-12-31T23:59:59Z", e.getMessage());
334+
}
335+
336+
try
337+
{
338+
C509Certificate.toDate(C509Certificate.NO_EXPIRATION_DATE + 1);
339+
fail("converted a validity value outside the X.509 time domain");
340+
}
341+
catch (IllegalArgumentException e)
342+
{
343+
assertEquals("validity value outside the X.509 time domain: 253402300800", e.getMessage());
344+
}
345+
}
346+
347+
/**
348+
* Re-encode a C509 certificate with the CBOR item at the given index of the
349+
* certificate array replaced by an unsigned integer, leaving every other item,
350+
* including the issuer signature, exactly as it was.
351+
*/
352+
private static byte[] withValidityField(byte[] encoding, int index, long seconds)
353+
throws IOException
354+
{
355+
CBORDecoder in = new CBORDecoder(encoding);
356+
int count = in.readArrayHeader();
357+
byte[][] items = new byte[count][];
358+
for (int i = 0; i != count; i++)
359+
{
360+
items[i] = in.readEncodedItem();
361+
}
362+
in.expectEnd();
363+
364+
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
365+
CBOREncoder out = new CBOREncoder(bOut);
366+
out.writeArrayHeader(count);
367+
for (int i = 0; i != count; i++)
368+
{
369+
if (i == index)
370+
{
371+
out.writeUnsignedInteger(seconds);
372+
}
373+
else
374+
{
375+
out.writeEncoded(items[i]);
376+
}
377+
}
378+
return bOut.toByteArray();
379+
}
380+
274381
public void testCertificationRequestTemplateRoundTrip()
275382
throws Exception
276383
{

0 commit comments

Comments
 (0)