Skip to content

Commit 500a692

Browse files
author
gefeili
committed
Build FrodoKEMEngine's SHAKE instance per call rather than holding one in a field, as CMCEEngine already does, so that an engine reached concurrently no longer produces wrong results. It is reached that way through FrodoKEMExtractor, which holds one engine for its lifetime: two threads extracting through a single extractor interleaved the digest's absorb and squeeze phases, so extractSecret returned shared secrets that silently did not match the sender's, or threw IllegalStateException "attempt to absorb while squeezing". Encapsulation was unaffected, since FrodoKEMGenerator builds an engine per call. Single-threaded results are unchanged and the reference KAT vectors are byte-identical.
1 parent e6b360d commit 500a692

4 files changed

Lines changed: 173 additions & 2 deletions

File tree

‎core/src/main/java/org/bouncycastle/crypto/kems/frodo/FrodoKEMEngine.java‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,6 @@ public class FrodoKEMEngine
5656
private final int len_ss_bytes;
5757
private final int len_salt_bytes;
5858
//
59-
private final Xof digest;
6059
private final FrodoMatrixGenerator gen;
6160

6261
public static FrodoKEMEngine getInstance(FrodoKEMParameters params)
@@ -110,7 +109,6 @@ public int getPublicKeySize()
110109
this.len_sk_bytes = len_s_bytes + len_pk_bytes + (2*n*nbar + len_pkh_bytes);
111110

112111
this.T_chi = (n == 976) ? cdf_table976 : cdf_table1344;
113-
this.digest = new SHAKEDigest(256);
114112
this.gen = useAes
115113
? (FrodoMatrixGenerator)new FrodoMatrixGenerator.Aes128MatrixGenerator(n, q)
116114
: new FrodoMatrixGenerator.Shake128MatrixGenerator(n, q);
@@ -227,6 +225,10 @@ private byte[] pack(short[] C)
227225

228226
public void kem_keypair(byte[] pk, byte[] sk, SecureRandom random)
229227
{
228+
// a SHAKE instance is mutable state, so it is built per call rather than shared -
229+
// an engine may be reached concurrently through a cached extractor or generator
230+
Xof digest = new SHAKEDigest(256);
231+
230232
// 1. Choose uniformly random seeds s || seedSE || z
231233
byte[] s_seedSE_z = new byte[len_s_bytes + len_seedSE_bytes + len_z_bytes];
232234
random.nextBytes(s_seedSE_z);
@@ -355,6 +357,10 @@ private short[] encode(byte[] k)
355357

356358
public void kem_enc(byte[] ct, byte[] ss, byte[] pk, SecureRandom random)
357359
{
360+
// a SHAKE instance is mutable state, so it is built per call rather than shared -
361+
// an engine may be reached concurrently through a cached extractor or generator
362+
Xof digest = new SHAKEDigest(256);
363+
358364
// Parse pk = seedA || b
359365
byte[] b = Arrays.copyOfRange(pk, len_seedA_bytes, len_pk_bytes);
360366

@@ -475,6 +481,10 @@ private byte[] decode(short[] in)
475481

476482
public void kem_dec(byte[] ss, byte[] ct, byte[] sk)
477483
{
484+
// a SHAKE instance is mutable state, so it is built per call rather than shared -
485+
// an engine may be reached concurrently through a cached extractor or generator
486+
Xof digest = new SHAKEDigest(256);
487+
478488
// Parse ct = c1 || c2 || salt
479489
int offset = 0;
480490
int length = mbar * n * D / 8;

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ public static Test suite()
2424
// XMSS tests split out into AllTestsXMSS so they can run as a separate (parallel) fork.
2525
// suite.addTestSuite(SphincsPlusTest.class); -- now deprecated
2626
// CMCE (Classic McEliece) tests split out into AllTestsCMCE so they can run as a separate (parallel) fork.
27+
suite.addTestSuite(FrodoKEMConcurrencyTest.class);
2728
suite.addTestSuite(FrodoKEMVectorTest.class);
2829
suite.addTestSuite(SABERVectorTest.class);
2930
suite.addTestSuite(NTRUTest.class);
Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
package org.bouncycastle.pqc.crypto.test;
2+
3+
import java.security.SecureRandom;
4+
5+
import junit.framework.TestCase;
6+
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
7+
import org.bouncycastle.crypto.SecretWithEncapsulation;
8+
import org.bouncycastle.crypto.generators.FrodoKEMKeyPairGenerator;
9+
import org.bouncycastle.crypto.kems.FrodoKEMExtractor;
10+
import org.bouncycastle.crypto.kems.FrodoKEMGenerator;
11+
import org.bouncycastle.crypto.params.FrodoKEMKeyGenerationParameters;
12+
import org.bouncycastle.crypto.params.FrodoKEMParameters;
13+
import org.bouncycastle.crypto.params.FrodoKEMPrivateKeyParameters;
14+
import org.bouncycastle.crypto.params.FrodoKEMPublicKeyParameters;
15+
import org.bouncycastle.util.Arrays;
16+
17+
/**
18+
* A FrodoKEMExtractor holds one FrodoKEMEngine for its lifetime, so the engine must not carry
19+
* mutable state across a call. It used to keep a single SHAKE instance in a field: two threads
20+
* extracting through one extractor interleaved their absorb/squeeze phases, which produced wrong
21+
* shared secrets and threw {@code IllegalStateException: attempt to absorb while squeezing}. The
22+
* digest is now built per call, as CMCEEngine's already was.
23+
* <p>
24+
* The generator side is exercised too, since FrodoKEMGenerator builds an engine per call but its
25+
* KEM keys and parameters are shared.
26+
*/
27+
public class FrodoKEMConcurrencyTest
28+
extends TestCase
29+
{
30+
private static final int VECTORS = 16;
31+
private static final int THREADS = 4;
32+
33+
public void testConcurrentExtraction()
34+
throws Exception
35+
{
36+
SecureRandom random = new SecureRandom();
37+
38+
FrodoKEMKeyPairGenerator kpg = new FrodoKEMKeyPairGenerator();
39+
kpg.init(new FrodoKEMKeyGenerationParameters(random, FrodoKEMParameters.frodokem976shake));
40+
AsymmetricCipherKeyPair kp = kpg.generateKeyPair();
41+
42+
final FrodoKEMPublicKeyParameters pub = (FrodoKEMPublicKeyParameters)kp.getPublic();
43+
FrodoKEMPrivateKeyParameters priv = (FrodoKEMPrivateKeyParameters)kp.getPrivate();
44+
45+
final byte[][] encapsulations = new byte[VECTORS][];
46+
final byte[][] expected = new byte[VECTORS][];
47+
48+
FrodoKEMGenerator gen = new FrodoKEMGenerator(random);
49+
for (int i = 0; i != VECTORS; i++)
50+
{
51+
SecretWithEncapsulation enc = gen.generateEncapsulated(pub);
52+
encapsulations[i] = enc.getEncapsulation();
53+
expected[i] = enc.getSecret();
54+
}
55+
56+
// one extractor, shared across threads
57+
final FrodoKEMExtractor extractor = new FrodoKEMExtractor(priv);
58+
final Throwable[] failure = new Throwable[1];
59+
final int[] mismatches = new int[1];
60+
61+
Thread[] threads = new Thread[THREADS];
62+
for (int t = 0; t != THREADS; t++)
63+
{
64+
threads[t] = new Thread()
65+
{
66+
public void run()
67+
{
68+
for (int i = 0; i != VECTORS; i++)
69+
{
70+
try
71+
{
72+
byte[] secret = extractor.extractSecret(encapsulations[i]);
73+
if (!Arrays.areEqual(secret, expected[i]))
74+
{
75+
synchronized (mismatches)
76+
{
77+
mismatches[0]++;
78+
}
79+
}
80+
}
81+
catch (Throwable th)
82+
{
83+
failure[0] = th;
84+
}
85+
}
86+
}
87+
};
88+
threads[t].start();
89+
}
90+
for (int t = 0; t != THREADS; t++)
91+
{
92+
threads[t].join();
93+
}
94+
95+
assertNull("shared extractor threw " + failure[0], failure[0]);
96+
assertEquals("shared extractor produced wrong secrets", 0, mismatches[0]);
97+
}
98+
99+
public void testConcurrentEncapsulation()
100+
throws Exception
101+
{
102+
SecureRandom random = new SecureRandom();
103+
104+
FrodoKEMKeyPairGenerator kpg = new FrodoKEMKeyPairGenerator();
105+
kpg.init(new FrodoKEMKeyGenerationParameters(random, FrodoKEMParameters.frodokem976shake));
106+
AsymmetricCipherKeyPair kp = kpg.generateKeyPair();
107+
108+
final FrodoKEMPublicKeyParameters pub = (FrodoKEMPublicKeyParameters)kp.getPublic();
109+
final FrodoKEMExtractor extractor =
110+
new FrodoKEMExtractor((FrodoKEMPrivateKeyParameters)kp.getPrivate());
111+
112+
// one generator, shared across threads - each encapsulation must round trip
113+
final FrodoKEMGenerator gen = new FrodoKEMGenerator(random);
114+
final Throwable[] failure = new Throwable[1];
115+
final int[] mismatches = new int[1];
116+
117+
Thread[] threads = new Thread[THREADS];
118+
for (int t = 0; t != THREADS; t++)
119+
{
120+
threads[t] = new Thread()
121+
{
122+
public void run()
123+
{
124+
for (int i = 0; i != VECTORS; i++)
125+
{
126+
try
127+
{
128+
SecretWithEncapsulation enc = gen.generateEncapsulated(pub);
129+
byte[] secret;
130+
synchronized (extractor)
131+
{
132+
secret = extractor.extractSecret(enc.getEncapsulation());
133+
}
134+
if (!Arrays.areEqual(secret, enc.getSecret()))
135+
{
136+
synchronized (mismatches)
137+
{
138+
mismatches[0]++;
139+
}
140+
}
141+
}
142+
catch (Throwable th)
143+
{
144+
failure[0] = th;
145+
}
146+
}
147+
}
148+
};
149+
threads[t].start();
150+
}
151+
for (int t = 0; t != THREADS; t++)
152+
{
153+
threads[t].join();
154+
}
155+
156+
assertNull("shared generator threw " + failure[0], failure[0]);
157+
assertEquals("shared generator produced unrecoverable encapsulations", 0, mismatches[0]);
158+
}
159+
}

‎docs/releasenotes.html‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ <h2>2.0 Release History</h2>
2323
Date:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2026, TBD
2424
<h3>2.1.2 Defects Fixed</h3>
2525
<ul>
26+
<li>FrodoKEMEngine kept a single SHAKE instance in a field, so an engine reached concurrently produced wrong results. It is reached that way through org.bouncycastle.crypto.kems.FrodoKEMExtractor, which holds one engine for its lifetime: two threads extracting through one extractor interleaved the digest's absorb and squeeze phases, yielding shared secrets that silently did not match the sender's, or an IllegalStateException of "attempt to absorb while squeezing" from inside extractSecret. The digest is now built per call, as CMCEEngine's already was, which makes an extractor safe to share. Encapsulation was unaffected, since FrodoKEMGenerator builds an engine per call. Results for any single-threaded use are unchanged - the reference KAT vectors are byte-identical.</li>
2627
<li>The bcmail module descriptor did not declare its javax.mail/javax.activation dependences, so a modular (module-path) consumer of the jar hit IllegalAccessError/module-resolution failures when the S/MIME classes touched the mail API. The descriptor now requires them optionally (requires static) under all four module names those libraries are known by - the automatic names mail and activation carried by the javax.mail:mail / javax.activation:activation artifacts, and the explicit names java.mail and java.activation carried by the newer com.sun.mail / com.sun.activation ones - a hard requires on any one name would break users of the others (github #2389).</li>
2728
<li>Four type-coercion helpers in the OER / IEEE 1609.2 (ITS) decoder tested the wrong type in the identity fast path that lets a getInstance() factory return an argument that is already of the target type. org.bouncycastle.oer.its.ieee1609dot2.basetypes.UINT32.getInstance and org.bouncycastle.oer.its.etsi102941.basetypes.Version.getInstance guarded on UINT8 - a sibling of UINT32 under UintBase, and unrelated to Version - so passing a UINT8 threw ClassCastException, while passing an actual UINT32 or Version missed the fast path and fell through to ASN1Integer.getInstance, which rejects them: neither factory accepted its own type. org.bouncycastle.oer.its.etsi103097.EtsiTs103097DataEncryptedUnicast.getInstance guarded on its sibling EtsiTs103097DataEncrypted and then cast to the unicast type, so an EtsiTs103097DataEncrypted threw ClassCastException. org.bouncycastle.oer.OEROptional.getObject(Class) called value.getClass().isInstance(type) with the arguments transposed, which is always false because the argument is a java.lang.Class, so the cast path was dead and every optional field was resolved reflectively, failing with IllegalStateException for a target type with no static getInstance. Each guard now names the type it returns, matching the sibling UINT8 / UINT16 / UINT64 and EtsiTs103097DataEncrypted factories (github #2373).</li>
2829
<li>DefaultAlgorithmNameFinder and DefaultSignatureNameFinder had no entries at all for the ShangMi algorithms, so an SM2 signature AlgorithmIdentifier that DefaultSignatureAlgorithmIdentifierFinder itself produces came back named only by its OID string - getAlgorithmName(GMObjectIdentifiers.sm2sign_with_sm3) returned "1.2.156.10197.1.501" and hasAlgorithmName returned false. Both finders now name sm2sign_with_sm3 as SM3WITHSM2 and sm2sign_with_sha256 as SHA256WITHSM2, and DefaultAlgorithmNameFinder additionally names the sm3 digest. All three resolve through the BC provider, as Signature and MessageDigest respectively. The remaining GM arc - the SM4 cipher modes, the sm2encrypt variants, and the SM1 / SM6 / SSF33 ciphers BC does not implement - is still unnamed (github #2377).</li>

0 commit comments

Comments
 (0)