Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.
  • Loading branch information
tniessen committed Sep 1, 2022
commit 8d19d390932c29b2c1e08ce663a6c1350dc55e79
18 changes: 8 additions & 10 deletions src/crypto/crypto_keygen.cc
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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