Skip to content

Commit 39dc408

Browse files
tniessenaddaleax
authored andcommitted
crypto: avoid unitializing ECDH objects on error
The previous code changed the private key of the ECDH object, but removed the public key if deriving it from the private key failed. Instead, if deriving the public key fails, neither the private nor the public key stored in the ECDH object should be updated. PR-URL: #34302 Reviewed-By: Ben Noordhuis <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Anna Henningsen <[email protected]>
1 parent 9cde4eb commit 39dc408

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

src/node_crypto.cc

+9-7
Original file line numberDiff line numberDiff line change
@@ -5649,21 +5649,20 @@ void ECDH::SetPrivateKey(const FunctionCallbackInfo<Value>& args) {
56495649
return env->ThrowError("Private key is not valid for specified curve.");
56505650
}
56515651

5652-
int result = EC_KEY_set_private_key(ecdh->key_.get(), priv.get());
5652+
ECKeyPointer new_key(EC_KEY_dup(ecdh->key_.get()));
5653+
CHECK(new_key);
5654+
5655+
int result = EC_KEY_set_private_key(new_key.get(), priv.get());
56535656
priv.reset();
56545657

56555658
if (!result) {
56565659
return env->ThrowError("Failed to convert BN to a private key");
56575660
}
56585661

5659-
// To avoid inconsistency, clear the current public key in-case computing
5660-
// the new one fails for some reason.
5661-
EC_KEY_set_public_key(ecdh->key_.get(), nullptr);
5662-
56635662
MarkPopErrorOnReturn mark_pop_error_on_return;
56645663
USE(&mark_pop_error_on_return);
56655664

5666-
const BIGNUM* priv_key = EC_KEY_get0_private_key(ecdh->key_.get());
5665+
const BIGNUM* priv_key = EC_KEY_get0_private_key(new_key.get());
56675666
CHECK_NOT_NULL(priv_key);
56685667

56695668
ECPointPointer pub(EC_POINT_new(ecdh->group_));
@@ -5674,8 +5673,11 @@ void ECDH::SetPrivateKey(const FunctionCallbackInfo<Value>& args) {
56745673
return env->ThrowError("Failed to generate ECDH public key");
56755674
}
56765675

5677-
if (!EC_KEY_set_public_key(ecdh->key_.get(), pub.get()))
5676+
if (!EC_KEY_set_public_key(new_key.get(), pub.get()))
56785677
return env->ThrowError("Failed to set generated public key");
5678+
5679+
EC_KEY_copy(ecdh->key_.get(), new_key.get());
5680+
ecdh->group_ = EC_KEY_get0_group(ecdh->key_.get());
56795681
}
56805682

56815683

0 commit comments

Comments
 (0)