Skip to content

Commit fe5b8dc

Browse files
tniessenaddaleax
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 <[email protected]> Reviewed-By: Ben Noordhuis <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Anna Henningsen <[email protected]>
1 parent 54fa59c commit fe5b8dc

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

src/node_crypto.cc

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2696,7 +2696,7 @@ static bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
26962696
template <typename T>
26972697
static T* MallocOpenSSL(size_t count) {
26982698
void* mem = OPENSSL_malloc(MultiplyWithOverflowCheck(count, sizeof(T)));
2699-
CHECK_NOT_NULL(mem);
2699+
CHECK_IMPLIES(mem == nullptr, count == 0);
27002700
return static_cast<T*>(mem);
27012701
}
27022702

@@ -2854,7 +2854,8 @@ static EVPKeyPointer ParsePrivateKey(const PrivateKeyEncodingConfig& config,
28542854

28552855
if (config.format_ == kKeyFormatPEM) {
28562856
BIOPointer bio(BIO_new_mem_buf(key, key_len));
2857-
CHECK(bio);
2857+
if (!bio)
2858+
return pkey;
28582859

28592860
char* pass = const_cast<char*>(config.passphrase_.get());
28602861
pkey.reset(PEM_read_bio_PrivateKey(bio.get(),
@@ -2869,7 +2870,8 @@ static EVPKeyPointer ParsePrivateKey(const PrivateKeyEncodingConfig& config,
28692870
pkey.reset(d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &p, key_len));
28702871
} else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
28712872
BIOPointer bio(BIO_new_mem_buf(key, key_len));
2872-
CHECK(bio);
2873+
if (!bio)
2874+
return pkey;
28732875
char* pass = const_cast<char*>(config.passphrase_.get());
28742876
pkey.reset(d2i_PKCS8PrivateKey_bio(bio.get(),
28752877
nullptr,

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

Lines changed: 7 additions & 0 deletions
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)