Skip to content

Commit

Permalink
crypto: fix zero byte allocation assertion failure
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
tniessen authored and targos committed Jan 1, 2019
1 parent b0b1414 commit f3ebc39
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/node_crypto.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2669,7 +2669,7 @@ static bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
template <typename T>
static T* MallocOpenSSL(size_t count) {
void* mem = OPENSSL_malloc(MultiplyWithOverflowCheck(count, sizeof(T)));
CHECK_NOT_NULL(mem);
CHECK_IMPLIES(mem == nullptr, count == 0);
return static_cast<T*>(mem);
}

Expand Down Expand Up @@ -2827,7 +2827,8 @@ static EVPKeyPointer ParsePrivateKey(const PrivateKeyEncodingConfig& config,

if (config.format_ == kKeyFormatPEM) {
BIOPointer bio(BIO_new_mem_buf(key, key_len));
CHECK(bio);
if (!bio)
return pkey;

char* pass = const_cast<char*>(config.passphrase_.get());
pkey.reset(PEM_read_bio_PrivateKey(bio.get(),
Expand All @@ -2842,7 +2843,8 @@ static EVPKeyPointer ParsePrivateKey(const PrivateKeyEncodingConfig& config,
pkey.reset(d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &p, key_len));
} else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
BIOPointer bio(BIO_new_mem_buf(key, key_len));
CHECK(bio);
if (!bio)
return pkey;
char* pass = const_cast<char*>(config.passphrase_.get());
pkey.reset(d2i_PKCS8PrivateKey_bio(bio.get(),
nullptr,
Expand Down
7 changes: 7 additions & 0 deletions test/parallel/test-crypto-key-objects.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,10 @@ const privatePem = fixtures.readSync('test_rsa_privkey.pem', 'ascii');
}
}
}

{
// This should not cause a crash: https://github.com/nodejs/node/issues/25247
assert.throws(() => {
createPrivateKey({ key: '' });
}, /null/);
}

0 comments on commit f3ebc39

Please sign in to comment.