From 5c3164aea04b6b84e1be9de0b6d0338f09bcebe7 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 --- src/crypto/crypto_random.cc | 6 ++++++ test/parallel/test-crypto-prime.js | 13 +++++++++++++ 2 files changed, 19 insertions(+) diff --git a/src/crypto/crypto_random.cc b/src/crypto/crypto_random.cc index a6a206455b52c3..b985c07ef54859 100644 --- a/src/crypto/crypto_random.cc +++ b/src/crypto/crypto_random.cc @@ -176,6 +176,12 @@ Maybe CheckPrimeTraits::AdditionalConfig( ArrayBufferOrViewContents candidate(args[offset]); params->candidate = BignumPointer(candidate.data(), candidate.size()); + if (params->candidate.get() == nullptr) { + 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..c32f63ae432b0d 100644 --- a/test/parallel/test-crypto-prime.js +++ b/test/parallel/test-crypto-prime.js @@ -12,6 +12,7 @@ const { generatePrimeSync, checkPrime, checkPrimeSync, + randomBytes, } = require('crypto'); const { Worker } = require('worker_threads'); @@ -254,6 +255,18 @@ for (const checks of [-(2 ** 31), -1, 2 ** 31, 2 ** 32 - 1, 2 ** 32, 2 ** 50]) { }); } +{ + const bytes = randomBytes(67108864); + 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])));