Skip to content

Commit 12feb9e

Browse files
bnoordhuisBridgeAR
authored andcommitted
crypto: harden bignum-to-binary conversions
PR-URL: #24719 Refs: #24645 Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent 6b71099 commit 12feb9e

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

41874187
const BIGNUM* pub_key;
41884188
DH_get0_key(diffieHellman->dh_.get(), &pub_key, nullptr);
4189-
size_t size = BN_num_bytes(pub_key);
4189+
const int size = BN_num_bytes(pub_key);
4190+
CHECK_GE(size, 0);
41904191
char* data = Malloc(size);
4191-
BN_bn2bin(pub_key, reinterpret_cast<unsigned char*>(data));
4192+
CHECK_EQ(size,
4193+
BN_bn2binpad(pub_key, reinterpret_cast<unsigned char*>(data), size));
41924194
args.GetReturnValue().Set(Buffer::New(env, data, size).ToLocalChecked());
41934195
}
41944196

@@ -4204,9 +4206,11 @@ void DiffieHellman::GetField(const FunctionCallbackInfo<Value>& args,
42044206
const BIGNUM* num = get_field(dh->dh_.get());
42054207
if (num == nullptr) return env->ThrowError(err_if_null);
42064208

4207-
size_t size = BN_num_bytes(num);
4209+
const int size = BN_num_bytes(num);
4210+
CHECK_GE(size, 0);
42084211
char* data = Malloc(size);
4209-
BN_bn2bin(num, reinterpret_cast<unsigned char*>(data));
4212+
CHECK_EQ(size,
4213+
BN_bn2binpad(num, reinterpret_cast<unsigned char*>(data), size));
42104214
args.GetReturnValue().Set(Buffer::New(env, data, size).ToLocalChecked());
42114215
}
42124216

@@ -4542,13 +4546,9 @@ void ECDH::GetPrivateKey(const FunctionCallbackInfo<Value>& args) {
45424546
if (b == nullptr)
45434547
return env->ThrowError("Failed to get ECDH private key");
45444548

4545-
int size = BN_num_bytes(b);
4549+
const int size = BN_num_bytes(b);
45464550
unsigned char* out = node::Malloc<unsigned char>(size);
4547-
4548-
if (size != BN_bn2bin(b, out)) {
4549-
free(out);
4550-
return env->ThrowError("Failed to convert ECDH private key to Buffer");
4551-
}
4551+
CHECK_EQ(size, BN_bn2binpad(b, out, size));
45524552

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

0 commit comments

Comments
 (0)