src: use automatic memory mgmt in SecretKeyGen

Avoid manual memory management (i.e., calling MallocOpenSSL). This
leaves less room for memory leaks and other bugs.

PR-URL: https://github.com/nodejs/node/pull/44479
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
This commit is contained in:
Tobias Nießen
2022-09-05 22:55:54 +02:00
committed by GitHub
parent 03553c5570
commit 1f54fc25cb
2 changed files with 9 additions and 11 deletions

View File

@@ -54,8 +54,7 @@ EVPKeyCtxPointer NidKeyPairGenTraits::Setup(NidKeyPairGenConfig* params) {
}
void SecretKeyGenConfig::MemoryInfo(MemoryTracker* tracker) const {
if (out != nullptr)
tracker->TrackFieldWithSize("out", length);
if (out) tracker->TrackFieldWithSize("out", length);
}
Maybe<bool> SecretKeyGenTraits::AdditionalConfig(
@@ -80,18 +79,17 @@ KeyGenJobStatus SecretKeyGenTraits::DoKeyGen(
Environment* env,
SecretKeyGenConfig* params) {
CHECK_LE(params->length, INT_MAX);
params->out = MallocOpenSSL<char>(params->length);
EntropySource(reinterpret_cast<unsigned char*>(params->out), params->length);
ByteSource::Builder bytes(params->length);
EntropySource(bytes.data<unsigned char>(), params->length);
params->out = std::move(bytes).release();
return KeyGenJobStatus::OK;
}
Maybe<bool> SecretKeyGenTraits::EncodeKey(
Environment* env,
SecretKeyGenConfig* params,
Local<Value>* result) {
ByteSource out = ByteSource::Allocated(params->out, params->length);
Maybe<bool> SecretKeyGenTraits::EncodeKey(Environment* env,
SecretKeyGenConfig* params,
Local<Value>* result) {
std::shared_ptr<KeyObjectData> data =
KeyObjectData::CreateSecret(std::move(out));
KeyObjectData::CreateSecret(std::move(params->out));
return Just(KeyObjectHandle::Create(env, data).ToLocal(result));
}

View File

@@ -201,7 +201,7 @@ struct KeyPairGenTraits final {
struct SecretKeyGenConfig final : public MemoryRetainer {
size_t length; // In bytes.
char* out = nullptr; // Placeholder for the generated key bytes.
ByteSource out; // Placeholder for the generated key bytes.
void MemoryInfo(MemoryTracker* tracker) const override;
SET_MEMORY_INFO_NAME(SecretKeyGenConfig)