From 7a9d78306b68b15e06eecbf30370c551da18bd90 Mon Sep 17 00:00:00 2001 From: Santiago Gimeno Date: Sat, 11 Jan 2025 14:17:38 +0100 Subject: [PATCH] crypto: fix checkPrime crash with large buffers Fixes: https://github.com/nodejs/node/issues/56512 PR-URL: https://github.com/nodejs/node/pull/56559 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Joyee Cheung --- src/crypto/crypto_random.cc | 5 +++++ test/parallel/test-crypto-prime.js | 13 +++++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/crypto/crypto_random.cc b/src/crypto/crypto_random.cc index a6a206455b52c3..0c26834de3126c 100644 --- a/src/crypto/crypto_random.cc +++ b/src/crypto/crypto_random.cc @@ -176,6 +176,11 @@ Maybe CheckPrimeTraits::AdditionalConfig( ArrayBufferOrViewContents candidate(args[offset]); params->candidate = BignumPointer(candidate.data(), candidate.size()); + if (!params->candidate) { + ThrowCryptoError( + Environment::GetCurrent(args), ERR_get_error(), "BignumPointer"); + return Nothing(); + } CHECK(args[offset + 1]->IsInt32()); // Checks params->checks = args[offset + 1].As()->Value(); diff --git a/test/parallel/test-crypto-prime.js b/test/parallel/test-crypto-prime.js index 2e7edb9074d090..5ffdc1394282be 100644 --- a/test/parallel/test-crypto-prime.js +++ b/test/parallel/test-crypto-prime.js @@ -254,6 +254,19 @@ for (const checks of [-(2 ** 31), -1, 2 ** 31, 2 ** 32 - 1, 2 ** 32, 2 ** 50]) { }); } +{ + const bytes = Buffer.alloc(67108864); + bytes[0] = 0x1; + assert.throws(() => checkPrime(bytes, common.mustNotCall()), { + code: 'ERR_OSSL_BN_BIGNUM_TOO_LONG', + message: /bignum too long/ + }); + assert.throws(() => checkPrimeSync(bytes), { + code: 'ERR_OSSL_BN_BIGNUM_TOO_LONG', + message: /bignum too long/ + }); +} + assert(!checkPrimeSync(Buffer.from([0x1]))); assert(checkPrimeSync(Buffer.from([0x2]))); assert(checkPrimeSync(Buffer.from([0x3])));