Skip to content

Commit

Permalink
src: use automatic memory mgmt in SecretKeyGen
Browse files Browse the repository at this point in the history
Avoid manual memory management (i.e., calling MallocOpenSSL). This
leaves less room for memory leaks and other bugs.

PR-URL: #44479
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
  • Loading branch information
tniessen committed Sep 5, 2022
1 parent 03553c5 commit 1f54fc2
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 11 deletions.
18 changes: 8 additions & 10 deletions src/crypto/crypto_keygen.cc
Expand Up @@ -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(
Expand All @@ -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));
}

Expand Down
2 changes: 1 addition & 1 deletion src/crypto/crypto_keygen.h
Expand Up @@ -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)
Expand Down

0 comments on commit 1f54fc2

Please sign in to comment.