Skip to content

Commit 82dc287

Browse files
committed
Merge the FrodoKEM and NTRU+ engine thread-safety fix (build the SHAKE instance per call rather than holding one in a field).
2 parents 33e9e85 + 0e67365 commit 82dc287

6 files changed

Lines changed: 343 additions & 3 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/main/java/org/bouncycastle/pqc/crypto/ntruplus/NTRUPlusEngine.java‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ class NTRUPlusEngine
3131
public short polyBytes;
3232
public short[] zetas;
3333
private final NTRUPlusParameters params;
34-
private final SHAKEDigest shakeDigest = new SHAKEDigest(256);
3534

3635
public NTRUPlusEngine(NTRUPlusParameters params)
3736
{
@@ -325,6 +324,10 @@ public int baseinv(short[] r, int rOff, short[] a, int aOff, short zeta)
325324

326325
public void shake256(byte[] output, int outOff, int outLen, byte[] input, int inLen)
327326
{
327+
// a SHAKE instance is mutable state, so it is built per call rather than shared -
328+
// an engine may be reached concurrently through a cached extractor
329+
SHAKEDigest shakeDigest = new SHAKEDigest(256);
330+
328331
shakeDigest.update(input, 0, inLen);
329332
shakeDigest.doFinal(output, outOff, outLen);
330333
}
@@ -683,6 +686,10 @@ public void crypto_kem_enc_derand(byte[] ct, int ctPos, byte[] ss, int ssPos,
683686
*/
684687
private void shake256(byte[] output, int outOff, int outLen, byte domainSeperation, byte[] input, int inOff, int inLen)
685688
{
689+
// a SHAKE instance is mutable state, so it is built per call rather than shared -
690+
// an engine may be reached concurrently through a cached extractor
691+
SHAKEDigest shakeDigest = new SHAKEDigest(256);
692+
686693
shakeDigest.update(domainSeperation);
687694
shakeDigest.update(input, inOff, inLen);
688695
shakeDigest.doFinal(output, outOff, outLen);

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ 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);
28+
suite.addTestSuite(NTRUPlusConcurrencyTest.class);
29+
suite.addTestSuite(NTRUPlusTest.class);
2730
suite.addTestSuite(FrodoKEMVectorTest.class);
2831
suite.addTestSuite(SABERVectorTest.class);
2932
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+
}

0 commit comments

Comments
 (0)