Skip to content

Commit a2155e1

Browse files
bnoordhuisBethGriggs
authored andcommitted
crypto: harden bignum-to-binary conversions
PR-URL: #24719 Refs: #24645 Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent b72bc11 commit a2155e1

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

src/node_crypto.cc

+10-10
Original file line numberDiff line numberDiff line change
@@ -4115,9 +4115,11 @@ void DiffieHellman::GenerateKeys(const FunctionCallbackInfo<Value>& args) {
41154115

41164116
const BIGNUM* pub_key;
41174117
DH_get0_key(diffieHellman->dh_.get(), &pub_key, nullptr);
4118-
size_t size = BN_num_bytes(pub_key);
4118+
const int size = BN_num_bytes(pub_key);
4119+
CHECK_GE(size, 0);
41194120
char* data = Malloc(size);
4120-
BN_bn2bin(pub_key, reinterpret_cast<unsigned char*>(data));
4121+
CHECK_EQ(size,
4122+
BN_bn2binpad(pub_key, reinterpret_cast<unsigned char*>(data), size));
41214123
args.GetReturnValue().Set(Buffer::New(env, data, size).ToLocalChecked());
41224124
}
41234125

@@ -4133,9 +4135,11 @@ void DiffieHellman::GetField(const FunctionCallbackInfo<Value>& args,
41334135
const BIGNUM* num = get_field(dh->dh_.get());
41344136
if (num == nullptr) return env->ThrowError(err_if_null);
41354137

4136-
size_t size = BN_num_bytes(num);
4138+
const int size = BN_num_bytes(num);
4139+
CHECK_GE(size, 0);
41374140
char* data = Malloc(size);
4138-
BN_bn2bin(num, reinterpret_cast<unsigned char*>(data));
4141+
CHECK_EQ(size,
4142+
BN_bn2binpad(num, reinterpret_cast<unsigned char*>(data), size));
41394143
args.GetReturnValue().Set(Buffer::New(env, data, size).ToLocalChecked());
41404144
}
41414145

@@ -4470,13 +4474,9 @@ void ECDH::GetPrivateKey(const FunctionCallbackInfo<Value>& args) {
44704474
if (b == nullptr)
44714475
return env->ThrowError("Failed to get ECDH private key");
44724476

4473-
int size = BN_num_bytes(b);
4477+
const int size = BN_num_bytes(b);
44744478
unsigned char* out = node::Malloc<unsigned char>(size);
4475-
4476-
if (size != BN_bn2bin(b, out)) {
4477-
free(out);
4478-
return env->ThrowError("Failed to convert ECDH private key to Buffer");
4479-
}
4479+
CHECK_EQ(size, BN_bn2binpad(b, out, size));
44804480

44814481
Local<Object> buf =
44824482
Buffer::New(env, reinterpret_cast<char*>(out), size).ToLocalChecked();

0 commit comments

Comments
 (0)