GeezerVison is showing github.com — crypto: remove key mutexes by panva · Pull Request #66413 · nodejs/node
crypto: remove key mutexes
#66413
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter
Filter by extension
.cc
(5)
.h
(1)
.js
(3)
All 3 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -479,7 +479,6 @@ Maybe<void> EcKeyGenTraits::AdditionalConfig(
bool ExportJWKEcKey (Environment* env,
const KeyObjectData& key,
Local<Object> target) {
Mutex::ScopedLock lock (key.mutex ());
const auto & m_pkey = key.GetAsymmetricKey ();
DCHECK (m_pkey.isA (KeyAlgorithm::EC ));
Expand Down
Expand Up
@@ -624,7 +623,6 @@ KeyObjectData ImportJWKEcKey(Environment* env, Local<Object> jwk) {
bool GetEcKeyDetail (Environment* env,
const KeyObjectData& key,
Local<Object> target) {
Mutex::ScopedLock lock (key.mutex ());
const auto & m_pkey = key.GetAsymmetricKey ();
DCHECK (m_pkey.isA (KeyAlgorithm::EC ));
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -117,7 +117,6 @@ KEMEncapsulateJob::KEMEncapsulateJob(Environment* env,
void KEMEncapsulateJob::DoThreadPoolWork () {
ncrypto::ClearErrorOnReturn clear_error_on_return;
AdditionalParams* params = CryptoJob<KEMEncapsulateTraits>::params ();
Mutex::ScopedLock lock (params->key .mutex ());
auto result = ncrypto::KEM::Encapsulate (params->key .GetAsymmetricKey ());
if (result) {
out_.emplace ();
Expand Down
Expand Up
@@ -223,7 +222,6 @@ bool KEMDecapsulateTraits::DeriveBits(Environment* env,
ByteSource* out,
CryptoJobMode mode,
CryptoErrorStore* errors) {
Mutex::ScopedLock lock (params.key .mutex ());
const auto & private_key = params.key .GetAsymmetricKey ();
return DoKEMDecapsulate (
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -187,7 +187,6 @@ KeyObjectData ImportJWKSecretKey(Environment* env, Local<Object> jwk) {
static bool ExportJWKRawKey(Environment* env,
const KeyObjectData& key,
Local<Object> target) {
Mutex::ScopedLock lock(key.mutex());
auto result =
key.GetAsymmetricKey().exportRawJwk(key.GetKeyType() == kKeyTypePrivate);
if (!result) {
Expand Down
Expand Up
@@ -416,7 +415,6 @@ bool KeyObjectData::ToEncodedPublicKey(
return ExportJWKInner(
env, addRefWithType(KeyType::kKeyTypePublic), *out, false);
} else if (config.format == EVPKeyPointer::PKFormatType::RAW_PUBLIC) {
Mutex::ScopedLock lock(mutex());
const auto& pkey = GetAsymmetricKey();
const auto* algorithm = pkey.getAlgorithm();
if (algorithm == &KeyAlgorithm::EC) {
Expand Down
Expand Up
@@ -471,7 +469,6 @@ bool KeyObjectData::ToEncodedPrivateKey(
return ExportJWKInner(
env, addRefWithType(KeyType::kKeyTypePrivate), *out, false);
} else if (config.format == EVPKeyPointer::PKFormatType::RAW_PRIVATE) {
Mutex::ScopedLock lock(mutex());
const auto& pkey = GetAsymmetricKey();
const auto* algorithm = pkey.getAlgorithm();
if (algorithm == &KeyAlgorithm::EC) {
Expand All
@@ -497,7 +494,6 @@ bool KeyObjectData::ToEncodedPrivateKey(
return Buffer::Copy(env, raw_data.get<const char>(), raw_data.size())
.ToLocal(out);
} else if (config.format == EVPKeyPointer::PKFormatType::RAW_SEED) {
Mutex::ScopedLock lock(mutex());
const auto& pkey = GetAsymmetricKey();
auto raw_data = pkey.rawSeed();
if (!raw_data) {
Expand Down
Expand Up
@@ -1053,13 +1049,10 @@ KeyObjectData::KeyObjectData(std::nullptr_t)
KeyObjectData::KeyObjectData(ByteSource symmetric_key)
: key_type_(KeyType::kKeyTypeSecret),
mutex_(std::make_shared<Mutex>()),
data_(std::make_shared<Data>(std::move(symmetric_key))) {}
KeyObjectData::KeyObjectData(KeyType type, EVPKeyPointer&& pkey)
: key_type_(type),
mutex_(std::make_shared<Mutex>()),
data_(std::make_shared<Data>(std::move(pkey))) {}
: key_type_(type), data_(std::make_shared<Data>(std::move(pkey))) {}
void KeyObjectData::Data::MemoryInfo(MemoryTracker* tracker) const {
if (asymmetric_key) {
Expand All
@@ -1076,11 +1069,6 @@ void KeyObjectData::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("data", data_);
}
Mutex& KeyObjectData::mutex() const {
if (!mutex_) mutex_ = std::make_shared<Mutex>();
return *mutex_.get();
}
KeyObjectData KeyObjectData::CreateSecret(ByteSource key) {
return KeyObjectData(std::move(key));
}
Expand Down
Expand Up
@@ -1475,7 +1463,6 @@ void KeyObjectHandle::RawPublicKey(
const KeyObjectData& data = key->Data();
CHECK_NE(data.GetKeyType(), kKeyTypeSecret);
Mutex::ScopedLock lock(data.mutex());
const auto& pkey = data.GetAsymmetricKey();
const bool is_raw_supported = pkey.supportsRawPublic();
Expand Down
Expand Up
@@ -1503,7 +1490,6 @@ void KeyObjectHandle::RawPrivateKey(
const KeyObjectData& data = key->Data();
CHECK_EQ(data.GetKeyType(), kKeyTypePrivate);
Mutex::ScopedLock lock(data.mutex());
const auto& pkey = data.GetAsymmetricKey();
const bool is_raw_supported = pkey.supportsRawPrivate();
Expand Down
Expand Up
@@ -1531,7 +1517,6 @@ void KeyObjectHandle::ExportECPublicRaw(
const KeyObjectData& data = key->Data();
CHECK_NE(data.GetKeyType(), kKeyTypeSecret);
Mutex::ScopedLock lock(data.mutex());
const auto& m_pkey = data.GetAsymmetricKey();
if (!m_pkey.isA(KeyAlgorithm::EC)) {
return THROW_ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS(env);
Expand Down
Expand Up
@@ -1570,7 +1555,6 @@ void KeyObjectHandle::ExportECPrivateRaw(
const KeyObjectData& data = key->Data();
CHECK_EQ(data.GetKeyType(), kKeyTypePrivate);
Mutex::ScopedLock lock(data.mutex());
const auto& m_pkey = data.GetAsymmetricKey();
if (!m_pkey.isA(KeyAlgorithm::EC)) {
return THROW_ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS(env);
Expand All
@@ -1593,7 +1577,6 @@ void KeyObjectHandle::ExportECPrivatePkcs8(
ASSIGN_OR_RETURN_UNWRAP(&key, args.This());
const KeyObjectData& data = key->Data();
CHECK_EQ(data.GetKeyType(), kKeyTypePrivate);
Mutex::ScopedLock lock(data.mutex());
auto encoded = ncrypto::Ec::ExportPrivatePkcs8(data.GetAsymmetricKey());
if (!encoded) {
return THROW_ERR_CRYPTO_OPERATION_FAILED(env,
Expand All
@@ -1612,7 +1595,6 @@ void KeyObjectHandle::RawSeed(const v8::FunctionCallbackInfo<v8::Value>& args) {
const KeyObjectData& data = key->Data();
CHECK_EQ(data.GetKeyType(), kKeyTypePrivate);
Mutex::ScopedLock lock(data.mutex());
const auto& pkey = data.GetAsymmetricKey();
auto raw_data = pkey.rawSeed();
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -54,8 +54,8 @@ class KeyObjectData final : public MemoryRetainer {
KeyType GetKeyType () const ;
// These functions allow unprotected access to the raw key material and should
// only be used to implement cryptographic operations requiring the key .
// The key material is immutable and can be used concurrently by operations
// with separate contexts .
const ncrypto::EVPKeyPointer& GetAsymmetricKey () const ;
const char * GetSymmetricKey () const ;
size_t GetSymmetricKeySize () const ;
Expand All
@@ -64,8 +64,6 @@ class KeyObjectData final : public MemoryRetainer {
SET_MEMORY_INFO_NAME (KeyObjectData)
SET_SELF_SIZE (KeyObjectData)
Mutex& mutex () const ;
static v8::Maybe<ncrypto::EVPKeyPointer::PublicKeyEncodingConfig>
GetPublicKeyEncodingFromJs (const v8::FunctionCallbackInfo<v8::Value>& args,
unsigned int * offset,
Expand Down
Expand Up
@@ -97,11 +95,11 @@ class KeyObjectData final : public MemoryRetainer {
v8::Local<v8::Value>* out);
inline KeyObjectData addRef () const {
return KeyObjectData (key_type_, mutex_, data_);
return KeyObjectData (key_type_, data_);
}
inline KeyObjectData addRefWithType (KeyType type) const {
return KeyObjectData (type, mutex_, data_);
return KeyObjectData (type, data_);
}
private:
Expand All
@@ -115,7 +113,6 @@ class KeyObjectData final : public MemoryRetainer {
const char * default_msg);
KeyType key_type_;
mutable std::shared_ptr<Mutex> mutex_;
struct Data final : public MemoryRetainer {
const ByteSource symmetric_key;
Expand All
@@ -131,10 +128,8 @@ class KeyObjectData final : public MemoryRetainer {
};
std::shared_ptr<Data> data_;
KeyObjectData (KeyType type,
std::shared_ptr<Mutex> mutex,
std::shared_ptr<Data> data)
: key_type_(type), mutex_(std::move(mutex)), data_(std::move(data)) {}
KeyObjectData (KeyType type, std::shared_ptr<Data> data)
: key_type_(type), data_(std::move(data)) {}
};
class KeyObjectHandle : public BaseObject {
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -210,7 +210,6 @@ WebCryptoCipherStatus RSA_Cipher(Environment* env,
const ByteSource& in,
ByteSource* out) {
CHECK_NE(key_data.GetKeyType(), kKeyTypeSecret);
Mutex::ScopedLock lock(key_data.mutex());
const auto& m_pkey = key_data.GetAsymmetricKey();
const ncrypto::Rsa::CipherParams nparams{
.padding = params.padding,
Expand Down
Expand Up
@@ -299,7 +298,6 @@ WebCryptoCipherStatus RSACipherTraits::DoCipher(Environment* env,
bool ExportJWKRsaKey(Environment* env,
const KeyObjectData& key,
Local<Object> target) {
Mutex::ScopedLock lock(key.mutex());
const auto& m_pkey = key.GetAsymmetricKey();
const ncrypto::Rsa rsa = m_pkey;
Expand Down
Expand Up
@@ -527,7 +525,6 @@ KeyObjectData ImportJWKRsaKey(Environment* env, Local<Object> jwk) {
bool GetRsaKeyDetail(Environment* env,
const KeyObjectData& key,
Local<Object> target) {
Mutex::ScopedLock lock(key.mutex());
const auto& m_pkey = key.GetAsymmetricKey();
const auto rsa = ncrypto::Rsa::PublicOnly(m_pkey);
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -712,7 +712,6 @@ Maybe<void> SignTraits::AdditionalConfig(
}
// If this is an EC key (assuming ECDSA) we need to convert the
// the signature from WebCrypto format into DER format...
Mutex::ScopedLock lock (params->key .mutex ());
const auto & akey = params->key .GetAsymmetricKey ();
if (UseP1363Encoding (akey, params->dsa_encoding )) {
params->signature = ConvertSignatureToDER (akey, signature.ToByteSource ());
Expand Down
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,140 @@
'use strict' ;
const common = require ( '../common' ) ;
if ( ! common . hasCrypto )
common . skip ( 'missing crypto' ) ;
const assert = require ( 'assert' ) ;
const {
createPrivateKey,
createPublicKey,
encapsulate,
decapsulate,
} = require ( 'crypto' ) ;
const { once } = require ( 'events' ) ;
const { promisify } = require ( 'util' ) ;
const { Worker, parentPort, workerData } = require ( 'worker_threads' ) ;
const { hasOpenSSL, hasFIPS, isBoringSSL } = require ( '../common/crypto' ) ;
const fixtures = require ( '../common/fixtures' ) ;
const { subtle } = globalThis . crypto ;
if ( ! hasOpenSSL ( 3 ) && ! isBoringSSL )
common . skip ( 'requires OpenSSL >= 3 or BoringSSL' ) ;
const encapsulateAsync = promisify ( encapsulate ) ;
const decapsulateAsync = promisify ( decapsulate ) ;
async function encapsulateKeys ( keys ) {
const operations = Array . from ( { length : 4 } , ( ) =>
encapsulateAsync ( keys . publicKey ) ) ;
operations . push ( encapsulate ( keys . publicKey ) ) ;
if ( keys . publicCryptoKey ) {
operations . push ( subtle . encapsulateBits ( 'ML-KEM-768' , keys . publicCryptoKey ) ) ;
}
const results = await Promise . all ( operations ) ;
for ( const { sharedKey, ciphertext } of results ) {
assert . strictEqual ( sharedKey . byteLength , keys . sharedSecretLength ) ;
assert . strictEqual ( ciphertext . byteLength , keys . ciphertextLength ) ;
}
return results ;
}
async function decapsulateKeys ( keys , results ) {
const operations = results . map ( common . mustCall ( async ( { sharedKey, ciphertext } ) => {
const result = await decapsulateAsync ( keys . privateKey , ciphertext ) ;
assert . deepStrictEqual ( result , Buffer . from ( sharedKey ) ) ;
} , results . length ) ) ;
for ( const { sharedKey, ciphertext } of results ) {
assert . deepStrictEqual (
decapsulate ( keys . privateKey , ciphertext ) , Buffer . from ( sharedKey ) ) ;
if ( keys . privateCryptoKey ) {
operations . push ( subtle . decapsulateBits (
'ML-KEM-768' , keys . privateCryptoKey , ciphertext ,
) . then ( ( result ) => {
assert . deepStrictEqual ( Buffer . from ( result ) , Buffer . from ( sharedKey ) ) ;
} ) ) ;
}
}
await Promise . all ( operations ) ;
}
function waitForStart ( barrier , phase ) {
parentPort . postMessage ( phase ) ;
Atomics . wait ( barrier , phase , 0 ) ;
}
async function runWorker ( ) {
const barrier = new Int32Array ( workerData . barrier ) ;
waitForStart ( barrier , 0 ) ;
const results = await encapsulateKeys ( workerData . keys ) ;
waitForStart ( barrier , 1 ) ;
await decapsulateKeys ( workerData . keys , results ) ;
}
async function testKeys ( keys ) {
const barrier = new Int32Array ( new SharedArrayBuffer ( 8 ) ) ;
const workers = Array . from ( { length : 3 } , ( ) => new Worker ( __filename , {
workerData : { test : 'kem-shared-key' , keys, barrier : barrier . buffer } ,
} ) ) ;
const exits = workers . map ( ( worker ) => once ( worker , 'exit' ) ) ;
// Synchronize each phase before the backing keys have been used for it.
const ready = await Promise . all (
workers . map ( ( worker ) => once ( worker , 'message' ) ) ) ;
for ( const [ phase ] of ready )
assert . strictEqual ( phase , 0 ) ;
const decapsulateReady = workers . map ( ( worker ) => once ( worker , 'message' ) ) ;
Atomics . store ( barrier , 0 , 1 ) ;
Atomics . notify ( barrier , 0 ) ;
const results = await encapsulateKeys ( keys ) ;
for ( const [ phase ] of await Promise . all ( decapsulateReady ) )
assert . strictEqual ( phase , 1 ) ;
Atomics . store ( barrier , 1 , 1 ) ;
Atomics . notify ( barrier , 1 ) ;
await decapsulateKeys ( keys , results ) ;
for ( const [ code ] of await Promise . all ( exits ) )
assert . strictEqual ( code , 0 ) ;
}
async function runMain ( ) {
const types = [ ] ;
if ( hasOpenSSL ( 3 ) ) {
types . push ( [ 'rsa' , 'rsa' , 256 , 256 ] ) ;
}
if ( hasOpenSSL ( 3 , 2 ) && ! hasFIPS ( 3 ) ) {
types . push ( [ 'ec' , 'ec_p256' , 32 , 65 ] , [ 'x25519' , 'x25519' , 32 , 32 ] ) ;
}
if ( hasOpenSSL ( 3 , 5 ) || isBoringSSL ) {
types . push ( [ 'ml-kem-768' , 'ml_kem_768' , 32 , 1088 ] ) ;
}
for ( const [ type , prefix , sharedSecretLength , ciphertextLength ] of types ) {
const suffix = type === 'rsa' ? '_2048' : '' ;
const privateSuffix = type === 'ml-kem-768' ? '_seed_only' : suffix ;
const publicKey = createPublicKey ( fixtures . readKey (
`${ prefix } _public${ suffix } .pem` ) ) ;
const privateKey = createPrivateKey ( fixtures . readKey (
`${ prefix } _private${ privateSuffix } .pem` ) ) ;
const keys = {
publicKey, privateKey, sharedSecretLength, ciphertextLength,
} ;
if ( type === 'ml-kem-768' ) {
keys . publicCryptoKey = publicKey . toCryptoKey (
'ML-KEM-768' , false , [ 'encapsulateBits' ] ) ;
keys . privateCryptoKey = privateKey . toCryptoKey (
'ML-KEM-768' , false , [ 'decapsulateBits' ] ) ;
}
await testKeys ( keys ) ;
}
}
if ( workerData ?. test === 'kem-shared-key' ) {
runWorker ( ) . then ( common . mustCall ( ) ) ;
} else {
runMain ( ) . then ( common . mustCall ( ) ) ;
}
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.