Skip to content

Commit 73aa358

Browse files
committed
crypto: avoid infinite loops in prime generation
1 parent 8b14046 commit 73aa358

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

src/crypto/crypto_random.cc

+20
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,26 @@ Maybe<bool> RandomPrimeTraits::AdditionalConfig(
127127
return Nothing<bool>();
128128
}
129129

130+
if (params->add) {
131+
if (BN_num_bits(params->add.get()) > bits) {
132+
// If we allowed this, the best case would be returning a static prime
133+
// that wasn't generated randomly. The worst case would be an infinite
134+
// loop within OpenSSL, blocking the main thread or one of the threads
135+
// in the thread pool.
136+
THROW_ERR_OUT_OF_RANGE(env, "invalid options.add");
137+
return Nothing<bool>();
138+
}
139+
140+
if (params->rem) {
141+
if (BN_cmp(params->add.get(), params->rem.get()) != 1) {
142+
// This would definitely lead to an infinite loop if allowed since
143+
// OpenSSL does not check this condition.
144+
THROW_ERR_OUT_OF_RANGE(env, "invalid options.rem");
145+
return Nothing<bool>();
146+
}
147+
}
148+
}
149+
130150
params->bits = bits;
131151
params->safe = safe;
132152
params->prime.reset(BN_secure_new());

test/parallel/test-crypto-prime.js

+38
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,44 @@ generatePrime(
159159
}
160160
}
161161

162+
{
163+
// This is impossible because it implies (prime % 2**64) == 1 and
164+
// prime < 2**64, meaning prime = 1, but 1 is not prime.
165+
for (const add of [2n**64n, 2n**65n]) {
166+
assert.throws(() => {
167+
generatePrimeSync(64, { add });
168+
}, {
169+
code: 'ERR_OUT_OF_RANGE',
170+
message: 'invalid options.add'
171+
});
172+
}
173+
174+
// rem >= add is impossible.
175+
for (const rem of [7n, 8n, 3000n]) {
176+
assert.throws(() => {
177+
generatePrimeSync(64, { add: 7n, rem });
178+
}, {
179+
code: 'ERR_OUT_OF_RANGE',
180+
message: 'invalid options.rem'
181+
});
182+
}
183+
184+
// This is possible, but not allowed. It implies prime == 7, which means that
185+
// we did not actually generate a random prime.
186+
assert.throws(() => {
187+
generatePrimeSync(3, { add: 8n, rem: 7n });
188+
}, {
189+
code: 'ERR_OUT_OF_RANGE'
190+
});
191+
192+
// This is possible and allowed (but makes little sense).
193+
assert.strictEqual(generatePrimeSync(4, {
194+
add: 15n,
195+
rem: 13n,
196+
bigint: true
197+
}), 13n);
198+
}
199+
162200
[1, 'hello', {}, []].forEach((i) => {
163201
assert.throws(() => checkPrime(i), {
164202
code: 'ERR_INVALID_ARG_TYPE'

0 commit comments

Comments
 (0)