From 2979c58fb073206adc60492e45ce87b46bfdcace Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Mon, 15 Nov 2021 16:50:20 +0100 Subject: [PATCH] crypto: throw errors in SignTraits::DeriveBits Fixes: https://github.com/nodejs/node/issues/40794 PR-URL: https://github.com/nodejs/node/pull/40796 Reviewed-By: Filip Skokan Reviewed-By: James M Snell --- src/crypto/crypto_sig.cc | 19 ++++++++++++++----- test/parallel/test-crypto-sign-verify.js | 14 ++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/src/crypto/crypto_sig.cc b/src/crypto/crypto_sig.cc index be2b3c32d98254..703104d75ace79 100644 --- a/src/crypto/crypto_sig.cc +++ b/src/crypto/crypto_sig.cc @@ -738,19 +738,25 @@ bool SignTraits::DeriveBits( size_t len; unsigned char* data = nullptr; if (IsOneShot(params.key)) { - EVP_DigestSign( + if (!EVP_DigestSign( context.get(), nullptr, &len, params.data.data(), - params.data.size()); + params.data.size())) { + crypto::CheckThrow(env, SignBase::Error::kSignPrivateKey); + return false; + } data = MallocOpenSSL(len); - EVP_DigestSign( + if (!EVP_DigestSign( context.get(), data, &len, params.data.data(), - params.data.size()); + params.data.size())) { + crypto::CheckThrow(env, SignBase::Error::kSignPrivateKey); + return false; + } ByteSource buf = ByteSource::Allocated(reinterpret_cast(data), len); *out = std::move(buf); @@ -760,13 +766,16 @@ bool SignTraits::DeriveBits( params.data.data(), params.data.size()) || !EVP_DigestSignFinal(context.get(), nullptr, &len)) { + crypto::CheckThrow(env, SignBase::Error::kSignPrivateKey); return false; } data = MallocOpenSSL(len); ByteSource buf = ByteSource::Allocated(reinterpret_cast(data), len); - if (!EVP_DigestSignFinal(context.get(), data, &len)) + if (!EVP_DigestSignFinal(context.get(), data, &len)) { + crypto::CheckThrow(env, SignBase::Error::kSignPrivateKey); return false; + } if (UseP1363Encoding(params.key, params.dsa_encoding)) { *out = ConvertSignatureToP1363(env, params.key, buf); diff --git a/test/parallel/test-crypto-sign-verify.js b/test/parallel/test-crypto-sign-verify.js index 6893f0c0e6d49a..b2c14b1efcd68b 100644 --- a/test/parallel/test-crypto-sign-verify.js +++ b/test/parallel/test-crypto-sign-verify.js @@ -742,3 +742,17 @@ assert.throws( } } } + +// The sign function should not swallow OpenSSL errors. +// Regression test for https://github.com/nodejs/node/issues/40794. +{ + assert.throws(() => { + const { privateKey } = crypto.generateKeyPairSync('rsa', { + modulusLength: 512 + }); + crypto.sign('sha512', 'message', privateKey); + }, { + code: 'ERR_OSSL_RSA_DIGEST_TOO_BIG_FOR_RSA_KEY', + message: /digest too big for rsa key/ + }); +}