Skip to content

Commit f3ebc39

Browse files
tniessentargos
authored andcommitted
crypto: fix zero byte allocation assertion failure
When an empty string was passed, malloc might have returned a nullptr depending on the platform, causing an assertion failure. This change makes private key parsing behave as public key parsing does, causing a BIO error instead that can be caught in JS. Fixes: #25247 PR-URL: #25248 Reviewed-By: Ujjwal Sharma <usharma1998@gmail.com> Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl> Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: Anna Henningsen <anna@addaleax.net>
1 parent b0b1414 commit f3ebc39

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

src/node_crypto.cc

+5-3
Original file line numberDiff line numberDiff line change
@@ -2669,7 +2669,7 @@ static bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
26692669
template <typename T>
26702670
static T* MallocOpenSSL(size_t count) {
26712671
void* mem = OPENSSL_malloc(MultiplyWithOverflowCheck(count, sizeof(T)));
2672-
CHECK_NOT_NULL(mem);
2672+
CHECK_IMPLIES(mem == nullptr, count == 0);
26732673
return static_cast<T*>(mem);
26742674
}
26752675

@@ -2827,7 +2827,8 @@ static EVPKeyPointer ParsePrivateKey(const PrivateKeyEncodingConfig& config,
28272827

28282828
if (config.format_ == kKeyFormatPEM) {
28292829
BIOPointer bio(BIO_new_mem_buf(key, key_len));
2830-
CHECK(bio);
2830+
if (!bio)
2831+
return pkey;
28312832

28322833
char* pass = const_cast<char*>(config.passphrase_.get());
28332834
pkey.reset(PEM_read_bio_PrivateKey(bio.get(),
@@ -2842,7 +2843,8 @@ static EVPKeyPointer ParsePrivateKey(const PrivateKeyEncodingConfig& config,
28422843
pkey.reset(d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &p, key_len));
28432844
} else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
28442845
BIOPointer bio(BIO_new_mem_buf(key, key_len));
2845-
CHECK(bio);
2846+
if (!bio)
2847+
return pkey;
28462848
char* pass = const_cast<char*>(config.passphrase_.get());
28472849
pkey.reset(d2i_PKCS8PrivateKey_bio(bio.get(),
28482850
nullptr,

test/parallel/test-crypto-key-objects.js

+7
Original file line numberDiff line numberDiff line change
@@ -105,3 +105,10 @@ const privatePem = fixtures.readSync('test_rsa_privkey.pem', 'ascii');
105105
}
106106
}
107107
}
108+
109+
{
110+
// This should not cause a crash: https://github.com/nodejs/node/issues/25247
111+
assert.throws(() => {
112+
createPrivateKey({ key: '' });
113+
}, /null/);
114+
}

0 commit comments

Comments
 (0)