Skip to content

Commit 501bc12

Browse files
bnoordhuisrefack
authored andcommitted
crypto: harden bignum-to-binary conversions
PR-URL: nodejs#24719 Refs: nodejs#24645 Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 87881b4 commit 501bc12

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
@@ -4211,9 +4211,11 @@ void DiffieHellman::GenerateKeys(const FunctionCallbackInfo<Value>& args) {
42114211

42124212
const BIGNUM* pub_key;
42134213
DH_get0_key(diffieHellman->dh_.get(), &pub_key, nullptr);
4214-
size_t size = BN_num_bytes(pub_key);
4214+
const int size = BN_num_bytes(pub_key);
4215+
CHECK_GE(size, 0);
42154216
char* data = Malloc(size);
4216-
BN_bn2bin(pub_key, reinterpret_cast<unsigned char*>(data));
4217+
CHECK_EQ(size,
4218+
BN_bn2binpad(pub_key, reinterpret_cast<unsigned char*>(data), size));
42174219
args.GetReturnValue().Set(Buffer::New(env, data, size).ToLocalChecked());
42184220
}
42194221

@@ -4229,9 +4231,11 @@ void DiffieHellman::GetField(const FunctionCallbackInfo<Value>& args,
42294231
const BIGNUM* num = get_field(dh->dh_.get());
42304232
if (num == nullptr) return env->ThrowError(err_if_null);
42314233

4232-
size_t size = BN_num_bytes(num);
4234+
const int size = BN_num_bytes(num);
4235+
CHECK_GE(size, 0);
42334236
char* data = Malloc(size);
4234-
BN_bn2bin(num, reinterpret_cast<unsigned char*>(data));
4237+
CHECK_EQ(size,
4238+
BN_bn2binpad(num, reinterpret_cast<unsigned char*>(data), size));
42354239
args.GetReturnValue().Set(Buffer::New(env, data, size).ToLocalChecked());
42364240
}
42374241

@@ -4567,13 +4571,9 @@ void ECDH::GetPrivateKey(const FunctionCallbackInfo<Value>& args) {
45674571
if (b == nullptr)
45684572
return env->ThrowError("Failed to get ECDH private key");
45694573

4570-
int size = BN_num_bytes(b);
4574+
const int size = BN_num_bytes(b);
45714575
unsigned char* out = node::Malloc<unsigned char>(size);
4572-
4573-
if (size != BN_bn2bin(b, out)) {
4574-
free(out);
4575-
return env->ThrowError("Failed to convert ECDH private key to Buffer");
4576-
}
4576+
CHECK_EQ(size, BN_bn2binpad(b, out, size));
45774577

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

0 commit comments

Comments
 (0)