Skip to content

Commit ced7851

Browse files
author
royb
committed
Add property to opt-out for malformed ASN.1 time content, fix CMS parser exception, relates to github #2411.
1 parent 83622d5 commit ced7851

8 files changed

Lines changed: 183 additions & 2 deletions

File tree

‎core/src/main/java/org/bouncycastle/asn1/ASN1GeneralizedTime.java‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -508,7 +508,12 @@ static ASN1GeneralizedTime createPrimitive(byte[] contents)
508508
// that getDate() would turn into a nonsensical Date or fail on. Programmatic construction
509509
// (String/Date constructors) and DER re-encoding (toDERObject) do not pass through here.
510510
// The message deliberately omits the raw content (it may carry control characters).
511-
if (!ASN1TimeFormat.isValidGeneralizedTime(contents))
511+
// Setting Properties.ASN1_ALLOW_MALFORMED_TIME restores the pre-1.85 lenient read for data
512+
// already in circulation (github #2411): the constructor's minimal leading-digits check
513+
// still applies, and getDate() then interprets or rejects the content as it always did.
514+
// The property is consulted only on the failure path, so well-formed values cost nothing.
515+
if (!ASN1TimeFormat.isValidGeneralizedTime(contents)
516+
&& !Properties.isOverrideSet(Properties.ASN1_ALLOW_MALFORMED_TIME))
512517
{
513518
throw new IllegalArgumentException("invalid GeneralizedTime format");
514519
}

‎core/src/main/java/org/bouncycastle/asn1/ASN1UTCTime.java‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,12 @@ static ASN1UTCTime createPrimitive(byte[] contents)
335335
// that getDate() would turn into a nonsensical Date or fail on. Programmatic construction
336336
// (String/Date constructors) and DER re-encoding (toDERObject) do not pass through here.
337337
// The message deliberately omits the raw content (it may carry control characters).
338-
if (!ASN1TimeFormat.isValidUTCTime(contents))
338+
// Setting Properties.ASN1_ALLOW_MALFORMED_TIME restores the pre-1.85 lenient read for data
339+
// already in circulation (github #2411): the constructor's minimal leading-digits check
340+
// still applies, and getDate() then interprets or rejects the content as it always did.
341+
// The property is consulted only on the failure path, so well-formed values cost nothing.
342+
if (!ASN1TimeFormat.isValidUTCTime(contents)
343+
&& !Properties.isOverrideSet(Properties.ASN1_ALLOW_MALFORMED_TIME))
339344
{
340345
throw new IllegalArgumentException("invalid UTCTime format");
341346
}

‎core/src/main/java/org/bouncycastle/util/Properties.java‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,9 +208,32 @@ public class Properties
208208
* fails (github #1973 / #1986). BER serialization is unaffected. Programmatically
209209
* constructing a time from a {@code Date} always produces DER content, so this setting
210210
* only matters for primitives whose contents arrived non-conformant from the wire.
211+
* <p>
212+
* "Lenient" here means legal-but-non-DER formatting. Structurally malformed content is a
213+
* separate matter, rejected on read since 1.85 unless {@link #ASN1_ALLOW_MALFORMED_TIME} is set.
211214
*/
212215
public static final String ASN1_ALLOW_NON_DER_TIME = "org.bouncycastle.asn1.allow_non_der_time";
213216

217+
/**
218+
* Fall back to the legacy lenient decoding of ASN.1 {@code UTCTime} / {@code GeneralizedTime}
219+
* values. Since 1.85 the decoder rejects structurally malformed time content - non-digit or
220+
* out-of-range fields, an illegal length, a missing or garbage zone terminator - with
221+
* "invalid UTCTime format" / "invalid GeneralizedTime format". That is raised while the
222+
* enclosing structure is being read, so a single such field fails the whole parse: a CMS
223+
* SignedData whose signing-time attribute lacks its trailing "Z" cannot be loaded at all,
224+
* let alone have the rest of its content examined (github #2411). When this property is set
225+
* the pre-1.85 behaviour is restored: any content whose leading year digits are digits decodes
226+
* into a time object, which can be inspected ({@code toString()} / {@code getTimeString()})
227+
* and re-encoded unchanged, while {@code getDate()} interprets it exactly as it always did -
228+
* a zone-less value is taken as GMT, and genuinely nonsensical content throws
229+
* {@code ParseException} or yields a rolled-over date. This is a read-side safety valve for
230+
* processing data already in circulation, not a recommended mode: the legal lenient forms
231+
* (missing seconds, numeric offset, fractional seconds) parse regardless of this setting, and
232+
* generation is unaffected. It is independent of {@link #ASN1_ALLOW_NON_DER_TIME}, which
233+
* governs writing rather than reading. Read via {@link #isOverrideSet(String)}.
234+
*/
235+
public static final String ASN1_ALLOW_MALFORMED_TIME = "org.bouncycastle.asn1.allow_malformed_time";
236+
214237
/**
215238
* Maximum depth of nested constructed ASN.1 objects the parser will descend before failing
216239
* with "maximum nested construction level reached", guarding against stack exhaustion from

‎core/src/main/jdk1.4/org/bouncycastle/util/Properties.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ public class Properties
4343
public static final String DRBG_ENTROPY_THREAD = "org.bouncycastle.drbg.entropy_thread";
4444
public static final String DRBG_GATHER_PAUSE_SECS = "org.bouncycastle.drbg.gather_pause_secs";
4545
public static final String ASN1_ALLOW_NON_DER_TIME = "org.bouncycastle.asn1.allow_non_der_time";
46+
public static final String ASN1_ALLOW_MALFORMED_TIME = "org.bouncycastle.asn1.allow_malformed_time";
4647
public static final String ASN1_MAX_CONS_DEPTH = "org.bouncycastle.asn1.max_cons_depth";
4748
public static final String ASN1_MAX_LIMIT = "org.bouncycastle.asn1.max_limit";
4849
public static final String DH_MAX_SIZE = "org.bouncycastle.dh.max_size";

‎core/src/test/java/org/bouncycastle/asn1/test/RegressionTest.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ public class RegressionTest
1212
new SetTest(),
1313
new ASN1IntegerTest(),
1414
new AllowNonDerTimeTest(),
15+
new AllowMalformedTimeTest(),
1516
new DERUTF8StringTest(),
1617
new CertificateTest(),
1718
new GenerationTest(),

‎docs/releasenotes.html‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,7 @@ <h3>2.1.2 Defects Fixed</h3>
152152
<li>Signature.verify() on a malformed LMS signature threw an unchecked exception out of the lightweight API rather than reporting the problem the way the JCA does, so an empty, truncated or otherwise damaged signature reached the caller as IllegalStateException("cannot parse signature"), and one naming an OTS type other than the verifying key's as IllegalArgumentException. LMSSignatureSpi.engineVerify() now answers false for a signature it cannot parse, as ML-DSA, SLH-DSA, XMSS and XMSS^MT already did, and throws SignatureException for one it can parse but cannot process, which is the OTS type mismatch. Either way the accumulated message is cleared, so the signature object stays usable afterwards (github #2408).</li>
153153
<li>An XMSS signature carrying trailing data was accepted as valid. XMSSSignature.Builder.withSignature() read the index, randomness, WOTS+ signature and authentication path at their fixed offsets and ignored anything past them, so appending arbitrary bytes to a valid signature produced a second, different encoding that still verified. RFC 8391 sec. 4.1.8 fixes an XMSS signature at 4 + n + (len + h) * n bytes, and the builder now rejects any other length the way XMSSMTSignature always has, which also covers the truncated case (github #2408).</li>
154154
<li>KeyPairGenerator.getInstance("XMSSMT").generateKeyPair() without a preceding initialize() threw IllegalArgumentException("layers must divide totalHeight without remainder"): the parameters used when uninitialised were height 10 with 20 layers, which is not a constructible XMSS^MT parameter set, leaving the default unusable. The default is now XMSSMT-SHA2_20/2_512 (RFC 8391 sec. 5.4). The same path in both the XMSS and XMSS^MT generators also left the returned key without a tree digest, so equals(), hashCode() and getTreeDigest() threw NullPointerException on a default-generated key; both now set it (github #2408).</li>
155+
<li>The structural check on decoded ASN.1 UTCTime / GeneralizedTime content introduced in 1.85 had no opt-out, so a single malformed time field - such as a CMS signing-time attribute whose UTCTime lacks its trailing "Z", as found in signatures in circulation - made the enclosing structure unreadable: CMSSignedData and CMSSignedDataParser.getSignerInfos() failed with "invalid UTCTime format" and nothing else in the message could be examined. Setting the new system/security property org.bouncycastle.asn1.allow_malformed_time (Properties.ASN1_ALLOW_MALFORMED_TIME) to "true" restores the pre-1.85 lenient read: such content decodes into a time object that can be inspected and re-encoded unchanged, and getDate() interprets it exactly as it did before - a zone-less value as GMT, genuinely nonsensical content by throwing ParseException. The default stays strict, in line with the JDK's own DER parser and OpenSSL, both of which also reject a zone-less UTCTime; the property is a read-side safety valve for data already in circulation, is consulted only when the check fails, and leaves generation unaffected. Separately, CMSSignedDataParser.getSignerInfos() let a SignerInfo that failed to decode escape as an unchecked IllegalStateException; it now reports it as the CMSException the method declares (github #2411).</li>
155156
</ul>
156157

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

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,13 @@ public SignerInformationStore getSignerInfos()
359359
{
360360
throw new CMSException("io exception: " + e.getMessage(), e);
361361
}
362+
catch (IllegalStateException e)
363+
{
364+
// toASN1Primitive() on a stream parser surfaces the IOException of loading the
365+
// SignerInfo this way - e.g. a malformed time in a signed attribute (github #2411);
366+
// report it as the CMSException this method declares rather than letting it escape.
367+
throw new CMSException("io exception: " + e.getMessage(), e);
368+
}
362369

363370
_signerInfoStore = new SignerInformationStore(signerInfos);
364371
}

‎pkix/src/test/java/org/bouncycastle/cms/test/NewSignedDataTest.java‎

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,15 @@
1919
import java.security.spec.PKCS8EncodedKeySpec;
2020
import java.security.spec.X509EncodedKeySpec;
2121
import java.util.ArrayList;
22+
import java.util.Calendar;
2223
import java.util.Collection;
2324
import java.util.HashMap;
2425
import java.util.HashSet;
2526
import java.util.Iterator;
2627
import java.util.List;
2728
import java.util.Map;
2829
import java.util.Set;
30+
import java.util.TimeZone;
2931

3032
import junit.framework.Assert;
3133
import junit.framework.Test;
@@ -40,6 +42,7 @@
4042
import org.bouncycastle.asn1.ASN1Primitive;
4143
import org.bouncycastle.asn1.ASN1Sequence;
4244
import org.bouncycastle.asn1.ASN1TaggedObject;
45+
import org.bouncycastle.asn1.ASN1UTCTime;
4346
import org.bouncycastle.asn1.ASN1Util;
4447
import org.bouncycastle.asn1.BERTags;
4548
import org.bouncycastle.asn1.DERNull;
@@ -54,6 +57,7 @@
5457
import org.bouncycastle.asn1.cms.ContentInfo;
5558
import org.bouncycastle.asn1.cms.SignedData;
5659
import org.bouncycastle.asn1.cms.SignerInfo;
60+
import org.bouncycastle.asn1.cms.Time;
5761
import org.bouncycastle.asn1.edec.EdECObjectIdentifiers;
5862
import org.bouncycastle.asn1.ess.ESSCertIDv2;
5963
import org.bouncycastle.asn1.ess.SigningCertificateV2;
@@ -116,7 +120,9 @@
116120
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
117121
import org.bouncycastle.test.TestResourceFinder;
118122
import org.bouncycastle.util.CollectionStore;
123+
import org.bouncycastle.util.Properties;
119124
import org.bouncycastle.util.Store;
125+
import org.bouncycastle.util.Strings;
120126
import org.bouncycastle.util.encoders.Base64;
121127
import org.bouncycastle.util.io.Streams;
122128
import org.bouncycastle.util.io.pem.PemObject;
@@ -1534,6 +1540,138 @@ public void testSHA1WithRSAAndAttributeTableSimple()
15341540
verifyRSASignatures(s, md.digest("Hello world!".getBytes()));
15351541
}
15361542

1543+
public void testSigningTimeMalformedUTCTime()
1544+
throws Exception
1545+
{
1546+
// github #2411: a SignedData in circulation carries the zone-less UTCTime "150612153520"
1547+
// (seconds present, no trailing "Z") as its signing-time attribute. Since 1.85 the ASN.1
1548+
// decoder rejects that as structurally malformed while the signerInfos are being read, so
1549+
// the whole message fails to load; Properties.ASN1_ALLOW_MALFORMED_TIME restores the legacy
1550+
// lenient read so the message can still be examined, and getSignerInfos() reports the
1551+
// strict-mode failure as the CMSException it declares rather than an IllegalStateException.
1552+
byte[] rawTime = Strings.toByteArray("150612153520");
1553+
byte[] utcNoZone = new byte[2 + rawTime.length];
1554+
utcNoZone[0] = BERTags.UTC_TIME;
1555+
utcNoZone[1] = (byte)rawTime.length;
1556+
System.arraycopy(rawTime, 0, utcNoZone, 2, rawTime.length);
1557+
1558+
CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes());
1559+
byte[] encoded;
1560+
1561+
// the lenient read is the only way to obtain such a primitive - use it to build the message
1562+
// the way the reporter's producer must have.
1563+
System.setProperty(Properties.ASN1_ALLOW_MALFORMED_TIME, "true");
1564+
try
1565+
{
1566+
ASN1EncodableVector v = new ASN1EncodableVector();
1567+
v.add(new Attribute(CMSAttributes.signingTime,
1568+
new DERSet(Time.getInstance(ASN1UTCTime.getInstance(utcNoZone)))));
1569+
1570+
List certList = new ArrayList();
1571+
certList.add(_origCert);
1572+
certList.add(_signCert);
1573+
1574+
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
1575+
gen.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider(BC)
1576+
.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v)))
1577+
.build("SHA256withRSA", _origKP.getPrivate(), _origCert));
1578+
gen.addCertificates(new JcaCertStore(certList));
1579+
1580+
encoded = gen.generate(msg, true).getEncoded();
1581+
}
1582+
finally
1583+
{
1584+
System.getProperties().remove(Properties.ASN1_ALLOW_MALFORMED_TIME);
1585+
}
1586+
1587+
// the attribute went out exactly as supplied
1588+
assertTrue("zone-less signing time not present in the encoding", indexOf(encoded, utcNoZone) >= 0);
1589+
1590+
// default: the message cannot be loaded, whichever way it is read
1591+
try
1592+
{
1593+
new CMSSignedData(encoded);
1594+
fail("malformed signing time loaded by default");
1595+
}
1596+
catch (CMSException e)
1597+
{
1598+
assertMentions(e, "invalid UTCTime format");
1599+
}
1600+
1601+
CMSSignedDataParser sp = new CMSSignedDataParser(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(), encoded);
1602+
sp.getSignedContent().drain();
1603+
try
1604+
{
1605+
sp.getSignerInfos();
1606+
fail("malformed signing time loaded by default (parser)");
1607+
}
1608+
catch (CMSException e)
1609+
{
1610+
assertMentions(e, "invalid UTCTime format");
1611+
}
1612+
1613+
// property set: the message loads and verifies, and the attribute reads as GMT as it did before 1.85
1614+
System.setProperty(Properties.ASN1_ALLOW_MALFORMED_TIME, "true");
1615+
try
1616+
{
1617+
CMSSignedData s = new CMSSignedData(encoded);
1618+
1619+
// verify against the key rather than the certificate: a certificate-bound verifier also
1620+
// checks validity at the signing time, and 2015 predates the test certificate.
1621+
SignerInformation signer = (SignerInformation)s.getSignerInfos().getSigners().iterator().next();
1622+
assertTrue(signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(_origKP.getPublic())));
1623+
1624+
Attribute attr = signer.getSignedAttributes().get(CMSAttributes.signingTime);
1625+
Time signingTime = Time.getInstance(attr.getAttrValues().getObjectAt(0));
1626+
1627+
assertEquals("150612153520", signingTime.toASN1Primitive().toString());
1628+
assertEquals("20150612153520GMT+00:00", signingTime.getTime());
1629+
1630+
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
1631+
cal.clear();
1632+
cal.set(2015, Calendar.JUNE, 12, 15, 35, 20);
1633+
assertEquals(cal.getTime(), signingTime.getDate());
1634+
1635+
sp = new CMSSignedDataParser(new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(), encoded);
1636+
sp.getSignedContent().drain();
1637+
signer = (SignerInformation)sp.getSignerInfos().getSigners().iterator().next();
1638+
assertTrue(signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(_origKP.getPublic())));
1639+
assertEquals("150612153520", signer.getSignedAttributes().get(CMSAttributes.signingTime).getAttrValues().getObjectAt(0).toString());
1640+
}
1641+
finally
1642+
{
1643+
System.getProperties().remove(Properties.ASN1_ALLOW_MALFORMED_TIME);
1644+
}
1645+
}
1646+
1647+
private static void assertMentions(CMSException e, String text)
1648+
{
1649+
String message = e.getMessage();
1650+
Exception underlying = e.getUnderlyingException();
1651+
if (underlying != null)
1652+
{
1653+
message = message + " / " + underlying.getMessage();
1654+
}
1655+
assertTrue(message, message.indexOf(text) >= 0);
1656+
}
1657+
1658+
private static int indexOf(byte[] data, byte[] pattern)
1659+
{
1660+
for (int i = 0; i + pattern.length <= data.length; i++)
1661+
{
1662+
int j = 0;
1663+
while (j != pattern.length && data[i + j] == pattern[j])
1664+
{
1665+
j++;
1666+
}
1667+
if (j == pattern.length)
1668+
{
1669+
return i;
1670+
}
1671+
}
1672+
return -1;
1673+
}
1674+
15371675
public void testCMSAlgorithmProtection()
15381676
throws Exception
15391677
{

0 commit comments

Comments
 (0)