Skip to content

Commit a8c7d72

Browse files
committed
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.
1 parent e155d96 commit a8c7d72

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

src/node_crypto.cc

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5710,21 +5710,20 @@ void ECDH::SetPrivateKey(const FunctionCallbackInfo<Value>& args) {
57105710
return env->ThrowError("Private key is not valid for specified curve.");
57115711
}
57125712

5713-
int result = EC_KEY_set_private_key(ecdh->key_.get(), priv.get());
5713+
ECKeyPointer new_key(EC_KEY_dup(ecdh->key_.get()));
5714+
CHECK(new_key);
5715+
5716+
int result = EC_KEY_set_private_key(new_key.get(), priv.get());
57145717
priv.reset();
57155718

57165719
if (!result) {
57175720
return env->ThrowError("Failed to convert BN to a private key");
57185721
}
57195722

5720-
// To avoid inconsistency, clear the current public key in-case computing
5721-
// the new one fails for some reason.
5722-
EC_KEY_set_public_key(ecdh->key_.get(), nullptr);
5723-
57245723
MarkPopErrorOnReturn mark_pop_error_on_return;
57255724
USE(&mark_pop_error_on_return);
57265725

5727-
const BIGNUM* priv_key = EC_KEY_get0_private_key(ecdh->key_.get());
5726+
const BIGNUM* priv_key = EC_KEY_get0_private_key(new_key.get());
57285727
CHECK_NOT_NULL(priv_key);
57295728

57305729
ECPointPointer pub(EC_POINT_new(ecdh->group_));
@@ -5735,8 +5734,11 @@ void ECDH::SetPrivateKey(const FunctionCallbackInfo<Value>& args) {
57355734
return env->ThrowError("Failed to generate ECDH public key");
57365735
}
57375736

5738-
if (!EC_KEY_set_public_key(ecdh->key_.get(), pub.get()))
5737+
if (!EC_KEY_set_public_key(new_key.get(), pub.get()))
57395738
return env->ThrowError("Failed to set generated public key");
5739+
5740+
EC_KEY_copy(ecdh->key_.get(), new_key.get());
5741+
ecdh->group_ = EC_KEY_get0_group(ecdh->key_.get());
57405742
}
57415743

57425744

0 commit comments

Comments
 (0)