Skip to content

Commit 1a269ca

Browse files
committed
Require the signed-message envelope handed to AIMerSigner.verifySignature to be exactly the message plus the parameter set's signature size, so that a short signature is reported as a failed verification rather than indexed past its end, and a valid one with data appended to it no longer verifies, relates to github #2401.
1 parent 1eca2e8 commit 1a269ca

4 files changed

Lines changed: 89 additions & 1 deletion

File tree

‎CONTRIBUTORS.html‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -594,7 +594,7 @@
594594
<li>subbudvk &lt;https://github.com/subbudvk&gt; - initial author on S2K parser hardening work for OpenPGP API.</li>
595595
<li>mkarasik &lt;https://github.com/mkarasik&gt; - initial work on EST server-side key generation (RFC 7030 4.4).</li>
596596
<li>Bernd Pr&uuml;nster (A-SIT Plus) &lt;bernd.pruenster&#064;a-sit.at&gt; - reported lenient ASN.1 UTCTime/GeneralizedTime parsing accepting structurally malformed content, with fuzzing-derived test cases.</li>
597-
<li>Naveed Khan &lt;https://github.com/rootvector2&gt; - constant time comparison of membership and confirmation tags in the MLS API. Reported unbounded array allocation in the BKS/UBER keystore load path (OutOfMemoryError DoS from a crafted keystore) and introduction of a capped decompression limit in PGPCompressedData.getDataStream(), both with POC. Original submission creating S/MIME backing temp files with owner-only permissions (PR #2326). Rejecting empty sequences in the X.509 extension parsers whose RFC 5280 syntax is SEQUENCE SIZE (1..MAX) - CRLDistPoint, CertificatePolicies, ExtendedKeyUsage, PolicyMappings, and SubjectDirectoryAttributes (PR #2331). Hardening asn1.cms.SignerInfo decode to reject a non-INTEGER version or non-tagged unsignedAttrs via getInstance rather than leaking a ClassCastException (PR #2342). Fixing an off-by-4 header-length guard in the OpenPGP NotationData signature subpacket parser (PR #2346). Rejecting CR/LF in the S/MIME streaming writer header names and values (SMIMEEnvelopedWriter/SMIMESignedWriter withHeader) to prevent MIME header injection (PR #2348). Adding minimum-length guards to the SM2 decrypt and GOST28147/DSTU7624/DESede/RC2 key-wrap unwrap paths (PR #2359). Guarding the ECDH session-key length in the JCE OpenPGP decryptor (PR #2383). Fixing the identity fast-path type guards in the OER getInstance factories and the transposed isInstance arguments in OEROptional.getObject (PR #2373).</li>
597+
<li>Naveed Khan &lt;https://github.com/rootvector2&gt; - constant time comparison of membership and confirmation tags in the MLS API. Reported unbounded array allocation in the BKS/UBER keystore load path (OutOfMemoryError DoS from a crafted keystore) and introduction of a capped decompression limit in PGPCompressedData.getDataStream(), both with POC. Original submission creating S/MIME backing temp files with owner-only permissions (PR #2326). Rejecting empty sequences in the X.509 extension parsers whose RFC 5280 syntax is SEQUENCE SIZE (1..MAX) - CRLDistPoint, CertificatePolicies, ExtendedKeyUsage, PolicyMappings, and SubjectDirectoryAttributes (PR #2331). Hardening asn1.cms.SignerInfo decode to reject a non-INTEGER version or non-tagged unsignedAttrs via getInstance rather than leaking a ClassCastException (PR #2342). Fixing an off-by-4 header-length guard in the OpenPGP NotationData signature subpacket parser (PR #2346). Rejecting CR/LF in the S/MIME streaming writer header names and values (SMIMEEnvelopedWriter/SMIMESignedWriter withHeader) to prevent MIME header injection (PR #2348). Adding minimum-length guards to the SM2 decrypt and GOST28147/DSTU7624/DESede/RC2 key-wrap unwrap paths (PR #2359). Guarding the ECDH session-key length in the JCE OpenPGP decryptor (PR #2383). Fixing the identity fast-path type guards in the OER getInstance factories and the transposed isInstance arguments in OEROptional.getObject (PR #2373). Requiring the signed-message envelope handed to AIMerSigner.verifySignature to be exactly the message plus the parameter set's signature size (PR #2401).</li>
598598
<li>suraj0208 &lt;https://github.com/suraj0208&gt; - initial work on auto-detecting private key reader (JcaPrivateKeyReader).</li>
599599
<li>liamgilligan &lt;https://github.com/liamgilligan&gt; - noticing the BIP-340 step numbering in the BIP340Signer signing comments was incorrect (PR #2340).</li>
600600
<li>digi-scrypt &lt;https://github.com/digi-scrypt&gt; - disabling DTD and external-entity resolution in KMIPInputStream to close an XXE (local file disclosure / SSRF) exposure in KMIP XML parsing (PR #2315).</li>

‎core/src/main/java/org/bouncycastle/pqc/crypto/aimer/AIMerSigner.java‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,11 @@ public byte[] generateSignature(byte[] message)
7777
@Override
7878
public boolean verifySignature(byte[] message, byte[] signature)
7979
{
80+
// the envelope is message || signature: any other length would be indexed past its end or leave a trailing tail unread.
81+
if (signature.length != message.length + params.getSignatureBytes())
82+
{
83+
return false;
84+
}
8085
byte[] sig = new byte[params.getSignatureBytes()];
8186
AIMerEngine engine = new AIMerEngine(params);
8287
System.arraycopy(signature, message.length, sig, 0, params.getSignatureBytes());

‎core/src/test/java/org/bouncycastle/pqc/crypto/test/AIMerTest.java‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
package org.bouncycastle.pqc.crypto.test;
22

3+
import java.io.BufferedReader;
4+
import java.io.InputStream;
5+
import java.io.InputStreamReader;
36
import java.security.SecureRandom;
7+
import java.util.HashMap;
48

59
import junit.framework.TestCase;
610
import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator;
@@ -14,6 +18,9 @@
1418
import org.bouncycastle.pqc.crypto.aimer.AIMerPrivateKeyParameters;
1519
import org.bouncycastle.pqc.crypto.aimer.AIMerPublicKeyParameters;
1620
import org.bouncycastle.pqc.crypto.aimer.AIMerSigner;
21+
import org.bouncycastle.test.TestResourceFinder;
22+
import org.bouncycastle.util.Arrays;
23+
import org.bouncycastle.util.encoders.Hex;
1724

1825
public class AIMerTest
1926
extends TestCase
@@ -23,6 +30,7 @@ public static void main(String[] args)
2330
{
2431
AIMerTest test = new AIMerTest();
2532
test.testTestVectors();
33+
test.testWrongLengthSignatureRejected();
2634
}
2735

2836
private static final AIMerParameters[] PARAMETER_SETS = new AIMerParameters[]
@@ -94,4 +102,78 @@ public MessageSigner getMessageSigner()
94102
long end = System.currentTimeMillis();
95103
System.out.println("time cost: " + (end - start) + "\n");
96104
}
105+
106+
/**
107+
* verifySignature() is handed the message || signature envelope
108+
* generateSignature() produces, so it has to require exactly that length:
109+
* a shorter buffer used to be indexed past its end, and a longer one had
110+
* its trailing bytes ignored, so a valid signature with data appended
111+
* still verified.
112+
*
113+
* The first KAT vector of each parameter set supplies a public key and a
114+
* valid envelope, which keeps this off the key generation and signing
115+
* paths - a valid envelope is what makes the appended-data cases bite.
116+
*/
117+
public void testWrongLengthSignatureRejected()
118+
throws Exception
119+
{
120+
for (int fileIndex = 0; fileIndex != files.length; fileIndex++)
121+
{
122+
AIMerParameters parameters = PARAMETER_SETS[fileIndex];
123+
String name = parameters.getName();
124+
125+
HashMap vector = readFirstVector(files[fileIndex]);
126+
byte[] message = Hex.decode((String)vector.get("msg"));
127+
byte[] pk = Hex.decode((String)vector.get("pk"));
128+
byte[] signature = Hex.decode((String)vector.get("sm"));
129+
130+
AIMerSigner verifier = new AIMerSigner();
131+
verifier.init(false, new AIMerPublicKeyParameters(parameters, pk));
132+
133+
assertEquals(name, message.length + parameters.getSignatureBytes(), signature.length);
134+
assertTrue(name, verifier.verifySignature(message, signature));
135+
136+
// a short envelope must be rejected rather than indexed past its end
137+
assertFalse(name, verifier.verifySignature(message, new byte[0]));
138+
assertFalse(name, verifier.verifySignature(message, Arrays.copyOf(signature, message.length)));
139+
assertFalse(name, verifier.verifySignature(message, Arrays.copyOf(signature, signature.length - 1)));
140+
141+
// trailing data must not be silently ignored
142+
assertFalse(name, verifier.verifySignature(message, Arrays.append(signature, (byte)0)));
143+
assertFalse(name, verifier.verifySignature(message, Arrays.concatenate(signature, new byte[16])));
144+
}
145+
}
146+
147+
private static HashMap readFirstVector(String name)
148+
throws Exception
149+
{
150+
InputStream src = TestResourceFinder.findTestResource("pqc/crypto/aimer", name);
151+
BufferedReader bin = new BufferedReader(new InputStreamReader(src));
152+
153+
HashMap buf = new HashMap();
154+
String line;
155+
while ((line = bin.readLine()) != null)
156+
{
157+
line = line.trim();
158+
159+
if (line.startsWith("#") || line.length() == 0)
160+
{
161+
// the vectors are separated by a blank line - stop at the end of the first
162+
if (buf.size() > 0)
163+
{
164+
break;
165+
}
166+
continue;
167+
}
168+
169+
int a = line.indexOf('=');
170+
if (a > -1)
171+
{
172+
buf.put(line.substring(0, a).trim(), line.substring(a + 1).trim());
173+
}
174+
}
175+
bin.close();
176+
177+
return buf;
178+
}
97179
}

‎docs/releasenotes.html‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@ <h3>2.1.2 Defects Fixed</h3>
137137
<li>A TLS server that answered a client's "status_request" or "status_request_v2" extension stored the echo it sent in the session, along with the rest of its ServerHello extensions, and replayed it on every abbreviated handshake that resumed that session. An abbreviated handshake sends neither a Certificate nor a CertificateStatus message, so the echo announced a message that could not follow - and it was replayed whether or not the resuming ClientHello had offered the extension at all. RFC 5246 sec. 7.4.1.4 requires a client receiving an extension it did not request to abort with an unsupported_extension alert, which is what BouncyCastle's own client does, so a resumption by a client that did not re-offer the extension failed outright. TlsServerProtocol and DTLSServerProtocol now drop both echoes from the extensions they replay on a resumed handshake, through the new TlsExtensionsUtils.removeStatusRequestExtensions; a client that did re-offer the extension is unaffected apart from no longer receiving an echo answering nothing. Servers that never answered a status request - the default for both the low-level API and the JSSE provider - were never affected.</li>
138138
<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>
139139
<li>AbstractTlsServer.notifyHandshakeBeginning() cleared the "status_request" extension recorded from the previous ClientHello but not "status_request_v2" or "trusted_ca_keys", which processClientExtensions assigns only when the ClientHello carries any extensions at all. A TlsServer instance driven through more than one handshake - a renegotiation, say - therefore carried both fields over, and a following ClientHello with no extensions had the server decide whether to echo them from the earlier handshake's values, sending the client an extension it had not offered; RFC 5246 sec. 7.4.1.4 has a client abort with unsupported_extension over exactly that. Both are now cleared alongside "status_request". Reaching this needed a TlsServer overriding allowMultiCertStatus() or allowTrustedCAIndication(), which default to false and, for the JSSE provider, were not previously settable at all.</li>
140+
<li>org.bouncycastle.pqc.crypto.aimer.AIMerSigner.verifySignature() sliced the signature out of the signed-message envelope generateSignature() produces - the message followed by the signature - at offset message.length without first checking the envelope was that long. A truncated or otherwise short signature therefore threw ArrayIndexOutOfBoundsException instead of returning false, which reached the caller unchecked out of Signature.verify() on the BCPQC "AIMer" services, and because only the signature-sized run of bytes at that offset was read, a valid signature with data appended to it still verified, so the accepted encoding was not unique. The envelope is now required to be exactly message.length plus the parameter set's signature size before it is read, and anything else is reported as a failed verification, matching the guard the Falcon, Faest, Mayo, Snova and QRUOV signers already apply. A correctly formed signature is unaffected (github #2401).</li>
140141
</ul>
141142

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

0 commit comments

Comments
 (0)