diff --git a/deps/ncrypto/ncrypto.cc b/deps/ncrypto/ncrypto.cc index aff6f873ec03..001f366ce120 100644 --- a/deps/ncrypto/ncrypto.cc +++ b/deps/ncrypto/ncrypto.cc @@ -8,7 +8,7 @@ #include #include #include -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL #include #include #endif @@ -29,14 +29,14 @@ #include #include #include -#if OPENSSL_WITH_ARGON2 +#if defined(OSSL_KDF_PARAM_ARGON2_LANES) #include #endif #endif // Ubuntu 22.04's default libssl-dev still lacks EVP_PKEY_PRIVATE_KEY when // fully updated. The macro was added upstream in OpenSSL 3.0.12. -#if NCRYPTO_USE_OPENSSL_PROVIDER && !defined(EVP_PKEY_PRIVATE_KEY) +#if !NCRYPTO_USE_BORINGSSL && !defined(EVP_PKEY_PRIVATE_KEY) #define EVP_PKEY_PRIVATE_KEY \ (EVP_PKEY_KEY_PARAMETERS | OSSL_KEYMGMT_SELECT_PRIVATE_KEY) #endif @@ -56,7 +56,7 @@ struct ASN1SequenceDeleter final { using ASN1SequencePointer = std::unique_ptr; -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL using X509PubKeyPointer = DeleteFnPtr; // OSSL_STORE_close() returns int, so it needs a void-returning adapter to be // usable as a DeleteFnPtr deleter. @@ -81,7 +81,7 @@ const EVP_MD* GetDigestCtxMd(const EVP_MD_CTX* ctx) { return EVP_MD_CTX_get0_md(ctx); } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL using ASN1StringPointer = DeleteFnPtr; using OSSLParamBldPointer = DeleteFnPtr; using RsaPssParamsPointer = DeleteFnPtr; @@ -135,7 +135,7 @@ constexpr std::array kRsaOtherPrimeParamNames = {{ static constexpr int kX509NameFlagsRFC2253WithinUtf8JSON = XN_FLAG_RFC2253 & ~ASN1_STRFLGS_ESC_MSB & ~ASN1_STRFLGS_ESC_CTRL; -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL template bool GetPKeyBnParam(const EVP_PKEY* pkey, const char* name, Pointer* out) { BIGNUM* bn = nullptr; @@ -411,7 +411,7 @@ DataPointer DataPointer::Alloc(size_t len) { } DataPointer DataPointer::SecureAlloc(size_t len) { -#ifndef OPENSSL_IS_BORINGSSL +#if NCRYPTO_USE_OPENSSL_PROVIDER auto ptr = OPENSSL_secure_zalloc(len); if (ptr == nullptr) return {}; // OPENSSL_secure_zalloc transparently falls back to a regular allocation @@ -426,6 +426,8 @@ DataPointer DataPointer::SecureAlloc(size_t len) { if (ptr == nullptr) return {}; memset(ptr, 0, len); return DataPointer(ptr, len); +#else +#error "Unsupported crypto backend" #endif } @@ -524,10 +526,12 @@ namespace { std::atomic fips_state_generation{0}; bool isFipsEnabledRaw() { -#ifndef OPENSSL_IS_BORINGSSL +#if NCRYPTO_USE_OPENSSL_PROVIDER return EVP_default_properties_is_fips_enabled(nullptr) == 1; #elif defined(OPENSSL_IS_BORINGSSL) return FIPS_mode() == 1; +#else +#error "Unsupported crypto backend" #endif } } // namespace @@ -541,11 +545,13 @@ bool setFipsEnabled(bool enable, CryptoErrorList* errors) { const bool was_enabled = isFipsEnabled(); if (was_enabled == enable) return true; ClearErrorOnReturn clearErrorOnReturn(errors); -#ifndef OPENSSL_IS_BORINGSSL +#if NCRYPTO_USE_OPENSSL_PROVIDER const bool success = EVP_default_properties_enable_fips(nullptr, enable ? 1 : 0) == 1; #elif defined(OPENSSL_IS_BORINGSSL) const bool success = FIPS_mode_set(enable ? 1 : 0) == 1; +#else +#error "Unsupported crypto backend" #endif if (success && isFipsEnabledRaw() != was_enabled) { fips_state_generation.fetch_add(1, std::memory_order_release); @@ -559,7 +565,7 @@ uint64_t getFipsStateGeneration() { bool testFipsEnabled() { ClearErrorOnReturn clear_error_on_return; -#ifndef OPENSSL_IS_BORINGSSL +#if NCRYPTO_USE_OPENSSL_PROVIDER OSSL_PROVIDER* fips_provider = nullptr; if (OSSL_PROVIDER_available(nullptr, "fips")) { fips_provider = OSSL_PROVIDER_load(nullptr, "fips"); @@ -574,6 +580,8 @@ bool testFipsEnabled() { #else // OPENSSL_FIPS return false; #endif // OPENSSL_FIPS +#else +#error "Unsupported crypto backend" #endif } @@ -833,7 +841,7 @@ bool CSPRNG(void* buffer, size_t length) { auto buf = reinterpret_cast(buffer); do { if (1 == RAND_status()) { -#ifndef OPENSSL_IS_BORINGSSL +#if NCRYPTO_USE_OPENSSL_PROVIDER if (1 == RAND_bytes_ex(nullptr, buf, length, 0)) { return true; } @@ -844,6 +852,8 @@ bool CSPRNG(void* buffer, size_t length) { } if (length <= INT_MAX && 1 == RAND_bytes(buf, static_cast(length))) return true; +#else +#error "Unsupported crypto backend" #endif } #ifndef OPENSSL_IS_BORINGSSL @@ -883,7 +893,7 @@ int PasswordCallback(char* buf, int size, int rwflag, void* u) { return -1; } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL namespace { struct StorePassphraseData { Buffer passphrase{.data = nullptr, .len = 0}; @@ -1234,7 +1244,7 @@ bool PrintGeneralName(const BIOPointer& out, const GENERAL_NAME* gen) { const char* prefix = nullptr; // BoringSSL does not support othername in GENERAL_NAME_print and may // not define these NIDs. -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL int nid = OBJ_obj2nid(gen->d.otherName->type_id); switch (nid) { case NID_id_on_SmtpUTF8Mailbox: @@ -1254,7 +1264,7 @@ bool PrintGeneralName(const BIOPointer& out, const GENERAL_NAME* gen) { prefix = "NAIRealm"; break; } -#endif // NCRYPTO_USE_OPENSSL_PROVIDER +#endif // !NCRYPTO_USE_BORINGSSL int val_type = gen->d.otherName->value->type; if (prefix == nullptr || (unicode && val_type != V_ASN1_UTF8STRING) || (!unicode && val_type != V_ASN1_IA5STRING)) { @@ -1833,13 +1843,7 @@ X509View::CheckKeyResult X509View::checkPrivateKey( return CheckKeyResult::UNSUPPORTED_OPERATION; } #endif -#if NCRYPTO_USE_OPENSSL_PROVIDER const int result = EVP_PKEY_eq(certificate_key.get(), pkey.get()); -#elif NCRYPTO_USE_BORINGSSL - const int result = EVP_PKEY_cmp(certificate_key.get(), pkey.get()); -#else -#error "Unsupported crypto backend" -#endif switch (result) { case 1: return CheckKeyResult::MATCH; @@ -1860,7 +1864,7 @@ Result X509View::checkPublicKey(const EVPKeyPointer& pkey) const { if (result >= 0) return Result(result == 1); const auto error = ERR_peek_last_error(); -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL // A wrong key type or malformed signature BIT STRING cannot verify. if (ERR_GET_LIB(error) == ERR_LIB_ASN1 && (ERR_GET_REASON(error) == ASN1_R_WRONG_PUBLIC_KEY_TYPE || @@ -2181,8 +2185,10 @@ BIOPointer BIOPointer::NewSecMem() { #ifdef OPENSSL_IS_BORINGSSL // Boringssl does not implement the BIO_s_secmem API. return BIOPointer(BIO_new(BIO_s_mem())); -#else +#elif NCRYPTO_USE_OPENSSL_PROVIDER return BIOPointer(BIO_new(BIO_s_secmem())); +#else +#error "Unsupported crypto backend" #endif } @@ -2230,7 +2236,7 @@ bool BIOPointer::WriteAll(const BIOPointer& bio, std::string_view message) { // DHPointer namespace { -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL const char* GetOpenSSLDhGroupName(const std::string_view name, DHPointer::FindGroupOption option) { if (option != DHPointer::FindGroupOption::NO_SMALL_PRIMES && @@ -2446,7 +2452,7 @@ void DHPointer::reset( #endif ) { dh_.reset(dh); -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL p_.reset(); g_.reset(); pub_key_.reset(); @@ -3084,7 +3090,7 @@ DataPointer DHPointer::stateless(const EVPKeyPointer& ourKey, // ============================================================================ // KDF -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL KDF::KDF(EVP_KDF* kdf) : kdf_(kdf) {} KDF KDF::Fetch(const char* algorithm, OSSL_LIB_CTX* libctx) { @@ -3101,11 +3107,15 @@ bool KDF::derive(const Buffer& out, const EVP_MD* getDigestByName(const char* name) { #if NCRYPTO_USE_BORINGSSL - // BoringSSL exposes SHA-3 through EVP_MD descriptors without registering - // their names or assigning them NIDs. + // BoringSSL exposes SHA-3 and SHAKE256 through EVP_MD descriptors without + // registering their names or assigning them NIDs. if (CaseInsensitiveNameEqual()(name, "sha3-256")) return EVP_sha3_256(); if (CaseInsensitiveNameEqual()(name, "sha3-384")) return EVP_sha3_384(); if (CaseInsensitiveNameEqual()(name, "sha3-512")) return EVP_sha3_512(); + if (CaseInsensitiveNameEqual()(name, "shake256") || + CaseInsensitiveNameEqual()(name, "shake-256")) { + return EVP_shake256(); + } #endif return EVP_get_digestbyname(name); } @@ -3206,7 +3216,7 @@ DataPointer hkdf(const Digest& md, return buf; } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL namespace { bool ScryptDerive(const Buffer& pass, const Buffer& salt, @@ -3363,7 +3373,7 @@ DataPointer pbkdf2(const Digest& md, return {}; } -#if OPENSSL_WITH_ARGON2 +#if defined(OSSL_KDF_PARAM_ARGON2_LANES) DataPointer argon2(const Buffer& pass, const Buffer& salt, uint32_t lanes, @@ -3522,7 +3532,7 @@ const KeyAlgorithm KeyAlgorithm::SLH_DSA_SHAKE_256S("SLH-DSA-SHAKE-256s", Family // clang-format on namespace { -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL constexpr char kSignatureContextString[] = "context-string"; constexpr char kSignatureInstance[] = "instance"; #endif @@ -3626,6 +3636,8 @@ const BoringSSLKeyAlgorithm kBoringSSLKeyAlgorithms[] = { {KeyAlgorithm::ML_DSA_87.name(), EVP_PKEY_ML_DSA_87, EVP_pkey_ml_dsa_87}, {KeyAlgorithm::ML_KEM_768.name(), EVP_PKEY_ML_KEM_768, EVP_pkey_ml_kem_768}, {KeyAlgorithm::ML_KEM_1024.name(), EVP_PKEY_ML_KEM_1024, EVP_pkey_ml_kem_1024}, + {KeyAlgorithm::SLH_DSA_SHA2_128S.name(), EVP_PKEY_SLH_DSA_SHA2_128S, EVP_pkey_slh_dsa_sha2_128s}, + {KeyAlgorithm::SLH_DSA_SHAKE_256F.name(), EVP_PKEY_SLH_DSA_SHAKE_256F, EVP_pkey_slh_dsa_shake_256f}, }; // NOLINTEND(whitespace/line_length) // clang-format on @@ -3653,21 +3665,31 @@ const EVP_PKEY_ALG* GetBoringSSLKeyAlgorithm(const KeyAlgorithm& algorithm) { } // namespace void ConfigurePqcEncoding() { -#if NCRYPTO_USE_OPENSSL_PROVIDER && OPENSSL_VERSION_PREREQ(3, 5) - // Configure all loaded providers to prefer seed-only format for ML-KEM and - // ML-DSA private keys in PKCS#8 export, falling back to priv-only when a - // seed is not available. The provider encoder reads these parameters at - // encoding time via ossl_prov_ctx_get_param(). - OSSL_PROVIDER_do_all( - nullptr, - [](OSSL_PROVIDER* provider, void*) -> int { - OSSL_PROVIDER_add_conf_parameter( - provider, "ml-kem.output_formats", "seed-only,priv-only"); - OSSL_PROVIDER_add_conf_parameter( - provider, "ml-dsa.output_formats", "seed-only,priv-only"); - return 1; - }, - nullptr); +#if NCRYPTO_USE_OPENSSL_PROVIDER + [](T*) { + if constexpr (requires(T * provider) { + OSSL_PROVIDER_add_conf_parameter(provider, "", ""); + }) { + // Configure all loaded providers to prefer seed-only format for ML-KEM + // and ML-DSA private keys in PKCS#8 export, falling back to priv-only + // when a seed is not available. The provider encoder reads these + // parameters at encoding time via ossl_prov_ctx_get_param(). + OSSL_PROVIDER_do_all( + nullptr, + [](T* provider, void*) -> int { + OSSL_PROVIDER_add_conf_parameter( + provider, "ml-kem.output_formats", "seed-only,priv-only"); + OSSL_PROVIDER_add_conf_parameter( + provider, "ml-dsa.output_formats", "seed-only,priv-only"); + return 1; + }, + nullptr); + } + }(static_cast(nullptr)); +#elif defined(OPENSSL_IS_BORINGSSL) + // BoringSSL already serializes ML-KEM and ML-DSA private keys in seed form. +#else +#error "Unsupported crypto backend" #endif } @@ -3859,7 +3881,7 @@ bool EVPKeyPointer::isA(const EVP_PKEY* key, const char* name) { // Returns true unless the key is known not to be SM2, so that a key whose curve // cannot be determined opts out of the prehashed fallback rather than into it. bool EVPKeyPointer::mayBeSM2() const { -#if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_NO_SM2) +#if defined(OPENSSL_NO_SM2) return false; #else if (isA(KeyAlgorithm::SM2)) return true; @@ -4294,12 +4316,12 @@ bool EVPKeyPointer::set(const ECKeyPointer& eckey) { #endif } -#if NCRYPTO_USE_LEGACY_KEY_TYPES +#if NCRYPTO_USE_BORINGSSL EVPKeyPointer::operator const EC_KEY*() const { if (!pkey_) return nullptr; return EVP_PKEY_get0_EC_KEY(pkey_.get()); } -#endif // NCRYPTO_USE_LEGACY_KEY_TYPES +#endif // NCRYPTO_USE_BORINGSSL namespace { @@ -4515,7 +4537,7 @@ Buffer GetPassphrase( return pass; } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL using OSSLEncoderCtxPointer = DeleteFnPtr; @@ -4851,7 +4873,7 @@ Result EVPKeyPointer::writePrivateKey( } case PKEncodingType::PKCS8: { EVP_PKEY* export_key = get(); -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL // OpenSSL's provider EC PKCS8 encoders temporarily change encoding flags. // Use an independent key so concurrent exports do not change the source. EVPKeyPointer key_copy; @@ -5008,7 +5030,7 @@ Result EVPKeyPointer::writePublicKey( #endif } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL if (ECKeyHasMissingOid(*this)) { ERR_raise(ERR_LIB_EC, EC_R_MISSING_OID); return Result(false, @@ -5144,11 +5166,13 @@ EVPKeyPointer::operator Dsa() const { bool EVPKeyPointer::validateDsaParameters() const { if (!pkey_) return false; -#ifndef OPENSSL_IS_BORINGSSL +#if NCRYPTO_USE_OPENSSL_PROVIDER if (EVP_default_properties_is_fips_enabled(nullptr) && isA(KeyAlgorithm::DSA)) { #elif defined(OPENSSL_IS_BORINGSSL) if (FIPS_mode() && isA(KeyAlgorithm::DSA)) { +#else +#error "Unsupported crypto backend" #endif // Validate DSA2 parameters from FIPS 186-4. #if NCRYPTO_USE_OPENSSL_PROVIDER @@ -5318,9 +5342,14 @@ EVPKeyPointer SSLPointer::getPeerTempKey() const { } std::optional SSLPointer::getNegotiatedGroup() const { -#if OPENSSL_VERSION_PREREQ(3, 5) +#if NCRYPTO_USE_OPENSSL_PROVIDER if (!ssl_) return std::nullopt; - const char* group = SSL_get0_group_name(get()); + const char* group = [](T* ssl) -> const char* { + if constexpr (requires { SSL_get0_group_name(ssl); }) { + return SSL_get0_group_name(ssl); + } + return nullptr; + }(get()); if (group == nullptr) return std::nullopt; return group; #elif defined(OPENSSL_IS_BORINGSSL) @@ -5331,7 +5360,7 @@ std::optional SSLPointer::getNegotiatedGroup() const { if (group == nullptr) return std::nullopt; return group; #else - return std::nullopt; +#error "Unsupported crypto backend" #endif } @@ -5359,11 +5388,13 @@ std::optional SSLPointer::getSecurityLevel() { #ifdef OPENSSL_IS_BORINGSSL return SSL_CTX_get_security_level(ctx.get()); -#else +#elif NCRYPTO_USE_OPENSSL_PROVIDER auto ssl = SSLPointer::New(ctx); if (!ssl) return std::nullopt; return SSL_get_security_level(ssl); +#else +#error "Unsupported crypto backend" #endif } @@ -5412,7 +5443,7 @@ bool SSLCtxPointer::setGroups(const char* groups) { bool SSLCtxPointer::setCipherSuites(const char* ciphers) { if (!ctx_) return false; -#ifndef OPENSSL_IS_BORINGSSL +#if NCRYPTO_USE_OPENSSL_PROVIDER return SSL_CTX_set_ciphersuites(ctx_.get(), ciphers); #elif defined(OPENSSL_IS_BORINGSSL) constexpr std::array supported = { @@ -5462,6 +5493,8 @@ bool SSLCtxPointer::setCipherSuites(const char* ciphers) { // TLS API expands empty cipher strings to Node's defaults before this call. return SSL_CTX_set1_tls13_ciphers( get(), cipher_ids.data(), flags.data(), cipher_ids.size()) == 1; +#else +#error "Unsupported crypto backend" #endif } @@ -5472,7 +5505,7 @@ constexpr char AsciiToLower(char c) { return c >= 'A' && c <= 'Z' ? c + ('a' - 'A') : c; } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL constexpr auto kUnsupportedCipherFlags = EVP_CIPH_FLAG_CIPHER_WITH_MAC | EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK; @@ -5514,7 +5547,7 @@ void PushAlgorithmAlias(const char* name, void* arg) { #endif } // namespace -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL Cipher::Cipher(DeleteFnPtr cipher) : cipher_(cipher.get()), fetched_cipher_(std::move(cipher)) {} #endif @@ -5603,7 +5636,7 @@ DigestCache::Result DigestCache::insert(const char* name, DigestCache::~DigestCache() = default; void DigestCache::reset(uint64_t generation) { -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL if (generation_ == generation) return; aliases_.clear(); hmac_templates_.clear(); @@ -5613,7 +5646,7 @@ void DigestCache::reset(uint64_t generation) { generation_ = generation; } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL const HMACCtxPointer* DigestCache::getHmacTemplate(const EVP_MD* digest, uint64_t generation) { if (generation_ != generation || digest == nullptr) return nullptr; @@ -5665,7 +5698,7 @@ const EVP_CIPHER* CipherCache::lookup(const char* name, uint64_t generation) { #endif } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL const EVP_CIPHER* CipherCache::insert( const char* name, DeleteFnPtr&& cipher, @@ -5702,7 +5735,7 @@ const EVP_CIPHER* CipherCache::insert( #endif Cipher::Cipher(const Cipher& other) : cipher_(other.cipher_) { -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL if (other.fetched_cipher_ != nullptr) { if (EVP_CIPHER_up_ref(other.fetched_cipher_.get()) == 1) { fetched_cipher_.reset(other.fetched_cipher_.get()); @@ -5715,7 +5748,7 @@ Cipher::Cipher(const Cipher& other) : cipher_(other.cipher_) { Cipher& Cipher::operator=(const Cipher& other) { if (this == &other) return *this; -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL if (other.fetched_cipher_ != nullptr) { if (EVP_CIPHER_up_ref(other.fetched_cipher_.get()) == 1) { fetched_cipher_.reset(other.fetched_cipher_.get()); @@ -5735,7 +5768,7 @@ Cipher& Cipher::operator=(const Cipher& other) { const Cipher Cipher::FromName(const char* name, CipherCache* cache) { const EVP_CIPHER* cipher = EVP_get_cipherbyname(name); if (cipher != nullptr) { -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL if (!IsSupportedLegacyCipher(cipher)) return Cipher(); #endif return Cipher(cipher); @@ -5776,7 +5809,7 @@ const Cipher Cipher::FromName(const char* name, CipherCache* cache) { const Cipher Cipher::FromNameForKeyEncoding(const char* name) { // Key serializers have their own cipher restrictions. Preserve their policy // instead of applying the filters used by the general cipher operations. -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL MarkPopErrorOnReturn mark_pop_error_on_return; DeleteFnPtr fetched( EVP_CIPHER_fetch(nullptr, name, nullptr)); @@ -5789,7 +5822,7 @@ const Cipher Cipher::FromNameForKeyEncoding(const char* name) { const Cipher Cipher::FromNid(int nid, CipherCache* cache) { const EVP_CIPHER* cipher = EVP_get_cipherbynid(nid); if (cipher != nullptr) { -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL if (!IsSupportedLegacyCipher(cipher)) return Cipher(); #endif return Cipher(cipher); @@ -5923,7 +5956,7 @@ bool Cipher::isOcbMode() const { bool Cipher::isSivMode() const { if (!cipher_) return false; -#if OPENSSL_WITH_AES_SIV +#if NCRYPTO_USE_OPENSSL_PROVIDER return getMode() == EVP_CIPH_SIV_MODE; #elif NCRYPTO_USE_BORINGSSL return false; @@ -5934,7 +5967,7 @@ bool Cipher::isSivMode() const { bool Cipher::isGcmSivMode() const { if (!cipher_) return false; -#if OPENSSL_WITH_AES_GCM_SIV +#ifdef EVP_CIPH_GCM_SIV_MODE return getMode() == EVP_CIPH_GCM_SIV_MODE; #else return false; @@ -5995,11 +6028,11 @@ std::string_view Cipher::getModeLabel() const { return "ocb"; case EVP_CIPH_OFB_MODE: return "ofb"; -#if OPENSSL_WITH_AES_SIV +#if !NCRYPTO_USE_BORINGSSL case EVP_CIPH_SIV_MODE: return "siv"; #endif -#if OPENSSL_WITH_AES_GCM_SIV +#ifdef EVP_CIPH_GCM_SIV_MODE case EVP_CIPH_GCM_SIV_MODE: return "gcm-siv"; #endif @@ -6035,13 +6068,11 @@ bool Cipher::isSupportedAuthenticatedMode() const { switch (getMode()) { case EVP_CIPH_CCM_MODE: case EVP_CIPH_GCM_MODE: -#ifndef OPENSSL_NO_OCB case EVP_CIPH_OCB_MODE: -#endif -#if OPENSSL_WITH_AES_SIV +#if !NCRYPTO_USE_BORINGSSL case EVP_CIPH_SIV_MODE: #endif -#if OPENSSL_WITH_AES_GCM_SIV +#ifdef EVP_CIPH_GCM_SIV_MODE case EVP_CIPH_GCM_SIV_MODE: #endif return true; @@ -6121,7 +6152,7 @@ bool CipherCtxPointer::setAeadTagLength(size_t length) { ctx_.get(), EVP_CTRL_AEAD_SET_TAG, length, nullptr); } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL namespace { // OSSL_CIPHER_PARAM_XTS_STANDARD is not defined by OpenSSL 3.0. Use its // parameter name directly so custom providers can advertise it too. @@ -6218,7 +6249,7 @@ bool CipherCtxPointer::isWrapMode() const { bool CipherCtxPointer::isSivMode() const { if (!ctx_) return false; -#if OPENSSL_WITH_AES_SIV +#if NCRYPTO_USE_OPENSSL_PROVIDER return getMode() == EVP_CIPH_SIV_MODE; #elif NCRYPTO_USE_BORINGSSL return false; @@ -6229,11 +6260,7 @@ bool CipherCtxPointer::isSivMode() const { bool CipherCtxPointer::isGcmSivMode() const { if (!ctx_) return false; -#if OPENSSL_WITH_AES_GCM_SIV - return getMode() == EVP_CIPH_GCM_SIV_MODE; -#else - return false; -#endif + return Cipher::FromCtx(*this).isGcmSivMode(); } bool CipherCtxPointer::isChaCha20Poly1305() const { @@ -6922,7 +6949,7 @@ int EVPKeyCtxPointer::initForSign() { } bool EVPKeyCtxPointer::setDhParameters(int prime_size, uint32_t generator) { -#ifndef OPENSSL_IS_BORINGSSL +#if NCRYPTO_USE_OPENSSL_PROVIDER if (!ctx_) return false; return EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx_.get(), prime_size) == 1 && EVP_PKEY_CTX_set_dh_paramgen_generator(ctx_.get(), generator) == 1; @@ -6930,6 +6957,8 @@ bool EVPKeyCtxPointer::setDhParameters(int prime_size, uint32_t generator) { // TODO(jasnell): Boringssl appears not to support this operation. // Is there an alternative approach that Boringssl does support? return false; +#else +#error "Unsupported crypto backend" #endif } @@ -7051,7 +7080,7 @@ bool EVPKeyCtxPointer::setRsaPssSaltlen(int salt_len) { } bool EVPKeyCtxPointer::setRsaImplicitRejection() { -#ifndef OPENSSL_IS_BORINGSSL +#if NCRYPTO_USE_OPENSSL_PROVIDER if (!ctx_) return false; return EVP_PKEY_CTX_ctrl_str( ctx_.get(), "rsa_pkcs1_implicit_rejection", "1") > 0; @@ -7066,6 +7095,8 @@ bool EVPKeyCtxPointer::setRsaImplicitRejection() { // TODO(jasnell): Boringssl appears not to support this operation. // Is there an alternative approach that Boringssl does support? return true; +#else +#error "Unsupported crypto backend" #endif } @@ -7119,25 +7150,29 @@ EVPKeyPointer EVPKeyCtxPointer::paramgen() const { bool EVPKeyCtxPointer::publicCheck() const { if (!ctx_) return false; -#ifndef OPENSSL_IS_BORINGSSL +#if NCRYPTO_USE_OPENSSL_PROVIDER return EVP_PKEY_public_check_quick(ctx_.get()) == 1; #elif defined(OPENSSL_IS_BORINGSSL) // Boringssl appears not to support this operation. // TODO(jasnell): Is there an alternative approach that Boringssl does // support? return true; +#else +#error "Unsupported crypto backend" #endif } bool EVPKeyCtxPointer::privateCheck() const { if (!ctx_) return false; -#ifndef OPENSSL_IS_BORINGSSL +#if NCRYPTO_USE_OPENSSL_PROVIDER return EVP_PKEY_check(ctx_.get()) == 1; #elif defined(OPENSSL_IS_BORINGSSL) // Boringssl appears not to support this operation. // TODO(jasnell): Is there an alternative approach that Boringssl does // support? return true; +#else +#error "Unsupported crypto backend" #endif } @@ -7478,7 +7513,7 @@ const Rsa::PrivateKey Rsa::getPrivateKey() const { const Rsa::OtherPrimeInfos Rsa::getOtherPrimeInfos() const { OtherPrimeInfos infos; -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL infos.reserve(other_prime_infos_.size()); for (const auto& info : other_prime_infos_) { infos.push_back({info.r.get(), info.d.get(), info.t.get()}); @@ -7812,7 +7847,7 @@ void Cipher::ForEach(Cipher::CipherNameCallback callback) { #error "Unsupported crypto backend" #endif &context); -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL EVP_CIPHER_do_all_provided(nullptr, array_push_back_provider, &context); #endif #endif @@ -7932,7 +7967,7 @@ BIOPointer Ec::ExportPrivatePkcs8(const EVPKeyPointer& key) { if (!key || !key.isA(KeyAlgorithm::EC)) return {}; auto ec = ECKeyPointer(key).clone(); if (!ec) return {}; -#if NCRYPTO_USE_LEGACY_KEY_TYPES +#if NCRYPTO_USE_BORINGSSL // Decoding an ECPrivateKey without publicKey reconstructs the public point // but retains a flag that omits it from subsequent encodings. EC_KEY_set_enc_flags(ec.get(), @@ -7948,7 +7983,7 @@ BIOPointer Ec::ExportPrivatePkcs8(const EVPKeyPointer& key) { DataPointer Ec::TryExportPublic(const EVPKeyPointer& key, point_conversion_form_t form) { if (!key || form != POINT_CONVERSION_UNCOMPRESSED) return {}; -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL { MarkPopErrorOnReturn pop_errors; size_t length = 0; @@ -7972,7 +8007,7 @@ DataPointer Ec::TryExportPublic(const EVPKeyPointer& key, DataPointer Ec::ExportPrivate(const EVPKeyPointer& key) { if (!key) return {}; -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL { MarkPopErrorOnReturn pop_errors; BignumPointer priv; @@ -7997,7 +8032,7 @@ bool Ec::GetKeyComponents(const EVPKeyPointer& key, BignumPointer* priv, int* degree) { if (!key) return false; -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL const int nid = GetCurveId(key); switch (nid) { case NID_X9_62_prime256v1: @@ -8101,7 +8136,7 @@ std::optional Ec::GetCurveName(const EVPKeyPointer& key) { #endif } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL namespace { bool IsAvailableEcGroup(const char* name) { MarkPopErrorOnReturn mark; @@ -8151,7 +8186,7 @@ bool Ec::GetCurves(Ec::GetCurveCallback callback) { } for (const auto& curve : curves) { const char* name = OBJ_nid2sn(curve.nid); -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL if (!IsAvailableEcGroup(name)) continue; #endif if (!callback(name)) return false; @@ -8190,7 +8225,7 @@ bool EVPMDCtxPointer::digestInit(const EVP_MD* digest) { return EVP_DigestInit_ex(ctx_.get(), digest, nullptr) > 0; } -#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(4, 0) +#if !NCRYPTO_USE_BORINGSSL bool EVPMDCtxPointer::digestInit(const EVP_MD* digest, const OSSL_PARAM* params) { if (!ctx_) return false; @@ -8248,8 +8283,7 @@ const EVP_MD* EVPMDCtxPointer::getDigest() const { } bool EVPMDCtxPointer::hasXofFlag() const { - if (!ctx_) return false; - return (EVP_MD_flags(getDigest()) & EVP_MD_FLAG_XOF) == EVP_MD_FLAG_XOF; + return Digest(getDigest()).isXof(); } bool EVPMDCtxPointer::copyTo(const EVPMDCtxPointer& other) const { @@ -8290,7 +8324,7 @@ std::optional EVPMDCtxPointer::signInitWithContext( return std::nullopt; } return ctx; -#else +#elif NCRYPTO_USE_OPENSSL_PROVIDER EVP_PKEY_CTX* ctx = nullptr; // Ed25519 requires the INSTANCE param to switch into Ed25519ctx mode. @@ -8324,6 +8358,8 @@ std::optional EVPMDCtxPointer::signInitWithContext( return std::nullopt; } return ctx; +#else +#error "Unsupported crypto backend" #endif } @@ -8341,7 +8377,7 @@ std::optional EVPMDCtxPointer::verifyInitWithContext( return std::nullopt; } return ctx; -#else +#elif NCRYPTO_USE_OPENSSL_PROVIDER EVP_PKEY_CTX* ctx = nullptr; // Ed25519 requires the INSTANCE param to switch into Ed25519ctx mode. @@ -8375,6 +8411,8 @@ std::optional EVPMDCtxPointer::verifyInitWithContext( return std::nullopt; } return ctx; +#else +#error "Unsupported crypto backend" #endif } @@ -8510,7 +8548,7 @@ HMACCtxPointer HMACCtxPointer::New() { } #endif // NCRYPTO_USE_BORINGSSL -#if OPENSSL_WITH_EVP_MAC +#if !NCRYPTO_USE_BORINGSSL EVPMacPointer::EVPMacPointer(EVP_MAC* mac) : mac_(mac) {} EVPMacPointer::EVPMacPointer(EVPMacPointer&& other) noexcept @@ -8813,7 +8851,7 @@ HMACCtxPointer HMACCtxPointer::New(const Digest& md) { result.md_size_ = md.size(); return result; } -#endif // OPENSSL_WITH_EVP_MAC +#endif // !NCRYPTO_USE_BORINGSSL DataPointer hashDigest(const Buffer& buf, const EVP_MD* md) { @@ -9021,13 +9059,25 @@ size_t Digest::size() const { return EVP_MD_size(md_); } +bool Digest::isXof() const { + if (md_ == nullptr) return false; #if NCRYPTO_USE_OPENSSL_PROVIDER + return (EVP_MD_flags(md_) & EVP_MD_FLAG_XOF) != 0; +#elif defined(OPENSSL_IS_BORINGSSL) + // BoringSSL does not set EVP_MD_FLAG_XOF on its SHAKE256 descriptor. + return md_ == EVP_shake256(); +#else +#error "Unsupported crypto backend" +#endif +} + +#if !NCRYPTO_USE_BORINGSSL Digest::Digest(DeleteFnPtr md) : md_(md.get()), fetched_md_(std::move(md)) {} #endif Digest::Digest(const Digest& other) : md_(other.md_) { -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL if (other.fetched_md_ != nullptr) { if (EVP_MD_up_ref(other.fetched_md_.get()) == 1) { fetched_md_.reset(other.fetched_md_.get()); @@ -9040,7 +9090,7 @@ Digest::Digest(const Digest& other) : md_(other.md_) { Digest& Digest::operator=(const Digest& other) { if (this == &other) return *this; -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL if (other.fetched_md_ != nullptr) { if (EVP_MD_up_ref(other.fetched_md_.get()) == 1) { fetched_md_.reset(other.fetched_md_.get()); @@ -9063,7 +9113,7 @@ const Digest Digest::SHA256 = Digest(EVP_sha256()); const Digest Digest::SHA384 = Digest(EVP_sha384()); const Digest Digest::SHA512 = Digest(EVP_sha512()); -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL namespace { bool IsSupportedDigest(const EVP_MD* md) { if (md == nullptr || EVP_MD_is_a(md, "NULL")) return false; @@ -9081,7 +9131,7 @@ bool IsSupportedDigest(const EVP_MD* md) { const Digest Digest::FromName(const char* name) { const EVP_MD* md = ncrypto::getDigestByName(name); if (md != nullptr) { -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL if (md == EVP_md_null()) return Digest(); #endif return Digest(md); @@ -9091,7 +9141,7 @@ const Digest Digest::FromName(const char* name) { } const Digest Digest::Fetch(const char* name) { -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL MarkPopErrorOnReturn mark_pop_error_on_return; DeleteFnPtr fetched( EVP_MD_fetch(nullptr, name, nullptr)); @@ -9104,7 +9154,7 @@ const Digest Digest::Fetch(const char* name) { } const Digest Digest::Ref(const EVP_MD* md) { -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL if (md != nullptr && EVP_MD_get0_provider(md) != nullptr) { if (EVP_MD_up_ref(const_cast(md)) != 1) return Digest(); return Digest(DeleteFnPtr(const_cast(md))); @@ -9115,8 +9165,7 @@ const Digest Digest::Ref(const EVP_MD* md) { // ============================================================================ // KEM Implementation -#if OPENSSL_WITH_KEM -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL bool KEM::SetOperationParameter(EVP_PKEY_CTX* ctx, const EVPKeyPointer& key) { const OSSL_PARAM* settable = EVP_PKEY_CTX_settable_params(ctx); if (settable == nullptr || @@ -9149,7 +9198,7 @@ std::optional KEM::Encapsulate( return std::nullopt; } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL if (!SetOperationParameter(ctx.get(), public_key)) { return std::nullopt; } @@ -9190,7 +9239,7 @@ DataPointer KEM::Decapsulate(const EVPKeyPointer& private_key, return {}; } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL if (!SetOperationParameter(ctx.get(), private_key)) { return {}; } @@ -9220,6 +9269,4 @@ DataPointer KEM::Decapsulate(const EVPKeyPointer& private_key, return shared_key; } -#endif // OPENSSL_WITH_KEM - } // namespace ncrypto diff --git a/deps/ncrypto/ncrypto.h b/deps/ncrypto/ncrypto.h index c814cc1acdf4..3e2ec9918823 100644 --- a/deps/ncrypto/ncrypto.h +++ b/deps/ncrypto/ncrypto.h @@ -28,22 +28,14 @@ (OPENSSL_VERSION_NUMBER >= (((maj) << 28) | ((min) << 20))) #endif -// BoringSSL reports itself as OpenSSL 1.1.1, so it has to be excluded here. -#if !defined(OPENSSL_IS_BORINGSSL) && !OPENSSL_VERSION_PREREQ(3, 0) -#error "OpenSSL 1.x is no longer supported, v3.0.0 or later is required." -#endif - // BoringSSL declares the EVP_*_do_all* APIs, but their implementation may // live in libdecrepit. This matches standalone ncrypto's build flag. #ifndef NCRYPTO_BSSL_LIBDECREPIT_MISSING #define NCRYPTO_BSSL_LIBDECREPIT_MISSING 0 #endif -#if defined(OPENSSL_IS_BORINGSSL) && NCRYPTO_BSSL_LIBDECREPIT_MISSING -#define NCRYPTO_USE_BORINGSSL_EVP_DO_ALL_FALLBACK 1 -#else -#define NCRYPTO_USE_BORINGSSL_EVP_DO_ALL_FALLBACK 0 -#endif +#define NCRYPTO_USE_BORINGSSL_EVP_DO_ALL_FALLBACK \ + (NCRYPTO_USE_BORINGSSL && NCRYPTO_BSSL_LIBDECREPIT_MISSING) // Backend split: // - OpenSSL uses provider APIs and hides deprecated low-level objects. @@ -59,71 +51,18 @@ #error "Unsupported crypto backend" #endif -#define NCRYPTO_USE_LEGACY_KEY_TYPES NCRYPTO_USE_BORINGSSL - -// OpenSSL 4 makes ASN1_STRING opaque and provides a checked BIT STRING length -// accessor. Earlier OpenSSL releases and pinned BoringSSL expose the decoded -// unused-bit count through ASN1_STRING::flags. -#if NCRYPTO_USE_OPENSSL_PROVIDER && OPENSSL_VERSION_PREREQ(4, 0) -#define NCRYPTO_HAS_ASN1_BIT_STRING_GET_LENGTH 1 -#elif NCRYPTO_USE_OPENSSL_PROVIDER || NCRYPTO_USE_BORINGSSL -#define NCRYPTO_HAS_ASN1_BIT_STRING_GET_LENGTH 0 -#else -#error "Unsupported crypto backend" -#endif - -// BoringSSL's X.509 signer can encode only its restricted RSA-PSS parameter -// profile. Other supported backends accept the full runtime signing profile. -#if NCRYPTO_USE_BORINGSSL -#define NCRYPTO_HAS_X509_RSA_PSS_FLEXIBLE_PARAMETERS 0 -#elif NCRYPTO_USE_OPENSSL_PROVIDER -#define NCRYPTO_HAS_X509_RSA_PSS_FLEXIBLE_PARAMETERS 1 -#else -#error "Unsupported crypto backend" -#endif - -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL #include #include #include #endif -#if !defined(OPENSSL_IS_BORINGSSL) -#define OPENSSL_WITH_AES_OCB 1 -#elif defined(OPENSSL_IS_BORINGSSL) -#define OPENSSL_WITH_AES_OCB 0 -#endif - -#if !defined(OPENSSL_NO_ARGON2) && OPENSSL_VERSION_PREREQ(3, 2) -#define OPENSSL_WITH_ARGON2 1 -#else -#define OPENSSL_WITH_ARGON2 0 -#endif - -#define OPENSSL_WITH_KEM 1 - -#if !defined(OPENSSL_IS_BORINGSSL) -#define OPENSSL_WITH_EVP_MAC 1 -#elif defined(OPENSSL_IS_BORINGSSL) -#define OPENSSL_WITH_EVP_MAC 0 -#endif - -#if !defined(OPENSSL_IS_BORINGSSL) -#define OPENSSL_WITH_AES_SIV 1 -#elif defined(OPENSSL_IS_BORINGSSL) -#define OPENSSL_WITH_AES_SIV 0 -#endif - -#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(3, 2) -#define OPENSSL_WITH_AES_GCM_SIV 1 -#else -#define OPENSSL_WITH_AES_GCM_SIV 0 -#endif - -#if !defined(OPENSSL_IS_BORINGSSL) +#if NCRYPTO_USE_OPENSSL_PROVIDER #define OSSL3_CONST const #elif defined(OPENSSL_IS_BORINGSSL) #define OSSL3_CONST +#else +#error "Unsupported crypto backend" #endif #ifdef __GNUC__ @@ -136,8 +75,10 @@ // Boringssl has opted to use size_t for some size related // APIs while Openssl is still using ints using OPENSSL_SIZE_T = size_t; -#else +#elif NCRYPTO_USE_OPENSSL_PROVIDER using OPENSSL_SIZE_T = int; +#else +#error "Unsupported crypto backend" #endif namespace ncrypto { @@ -307,7 +248,7 @@ template using DeleteFnPtr = typename FunctionDeleter::Pointer; using PKCS8Pointer = DeleteFnPtr; -#if NCRYPTO_USE_LEGACY_KEY_TYPES +#if NCRYPTO_USE_BORINGSSL using RSAPointer = DeleteFnPtr; #endif using SSLSessionPointer = DeleteFnPtr; @@ -359,7 +300,7 @@ class Digest final { Digest(const Digest& other); Digest& operator=(const Digest& other); inline Digest& operator=(const EVP_MD* md) { -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL fetched_md_.reset(); #endif md_ = md; @@ -368,6 +309,7 @@ class Digest final { NCRYPTO_DISALLOW_MOVE(Digest) size_t size() const; + bool isXof() const; inline const EVP_MD* get() const { return md_; } inline operator const EVP_MD*() const { return md_; } @@ -387,7 +329,7 @@ class Digest final { private: const EVP_MD* md_ = nullptr; -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL explicit Digest(DeleteFnPtr md); DeleteFnPtr fetched_md_; #endif @@ -439,7 +381,7 @@ class DigestCache final { Result insert(const char* name, const EVP_MD* digest, uint64_t generation); void reset(uint64_t generation); const AliasMap& aliases() const; -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL // Returns an HMAC context for the cached digest that has no key yet. // Duplicating it avoids fetching HMAC and the digest for every context. const HMACCtxPointer* getHmacTemplate(const EVP_MD* digest, @@ -448,7 +390,7 @@ class DigestCache final { private: uint64_t generation_ = 0; -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL using EVPMDPointer = DeleteFnPtr; // IDs are not reused across generations because JavaScript caches them @@ -475,14 +417,14 @@ class CipherCache final { NCRYPTO_DISALLOW_COPY_AND_MOVE(CipherCache) const EVP_CIPHER* lookup(const char* name, uint64_t generation); -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL const EVP_CIPHER* insert(const char* name, DeleteFnPtr&& cipher, uint64_t generation); #endif private: -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL using EVPCipherPointer = DeleteFnPtr; uint64_t generation_ = 0; @@ -516,7 +458,7 @@ class Cipher final { Cipher(const Cipher& other); Cipher& operator=(const Cipher& other); inline Cipher& operator=(const EVP_CIPHER* cipher) { -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL fetched_cipher_.reset(); #endif cipher_ = cipher; @@ -612,7 +554,7 @@ class Cipher final { private: const EVP_CIPHER* cipher_ = nullptr; -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL explicit Cipher(DeleteFnPtr cipher); DeleteFnPtr fetched_cipher_; #endif @@ -642,7 +584,7 @@ class Dsa final { #else #error "Unsupported crypto backend" #endif -#if NCRYPTO_USE_LEGACY_KEY_TYPES +#if NCRYPTO_USE_BORINGSSL inline operator OSSL3_CONST DSA*() const { return dsa_; } #endif @@ -689,7 +631,7 @@ class Rsa final { #else #error "Unsupported crypto backend" #endif -#if NCRYPTO_USE_LEGACY_KEY_TYPES +#if NCRYPTO_USE_BORINGSSL inline operator OSSL3_CONST RSA*() const { return rsa_; } #endif @@ -794,7 +736,7 @@ class Ec final { int getCurve() const; inline operator bool() const { return ec_ != nullptr; } -#if NCRYPTO_USE_LEGACY_KEY_TYPES +#if NCRYPTO_USE_BORINGSSL inline operator OSSL3_CONST EC_KEY*() const { return ec_; } #endif @@ -1358,7 +1300,7 @@ class EVPKeyPointer final { bool assign(const ECKeyPointer& eckey); bool set(const ECKeyPointer& eckey); -#if NCRYPTO_USE_LEGACY_KEY_TYPES +#if NCRYPTO_USE_BORINGSSL operator const EC_KEY*() const; #endif @@ -1903,7 +1845,7 @@ class ECKeyPointer final { public: ECKeyPointer(); explicit ECKeyPointer(const EVPKeyPointer& key); -#if NCRYPTO_USE_LEGACY_KEY_TYPES +#if NCRYPTO_USE_BORINGSSL explicit ECKeyPointer(EC_KEY* key); #endif ECKeyPointer(ECKeyPointer&& other) noexcept; @@ -1951,7 +1893,7 @@ class ECKeyPointer final { static ECKeyPointer New(const EC_GROUP* group); static ECKeyPointer NewByCurveName(int nid); -#if NCRYPTO_USE_LEGACY_KEY_TYPES +#if NCRYPTO_USE_BORINGSSL static const EC_POINT* GetPublicKey(const EC_KEY* key); static const BIGNUM* GetPrivateKey(const EC_KEY* key); static const EC_GROUP* GetGroup(const EC_KEY* key); @@ -1991,7 +1933,7 @@ class EVPMDCtxPointer final { inline bool digestInit(const Digest& digest) { return digestInit(digest.get()); } -#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(4, 0) +#if !NCRYPTO_USE_BORINGSSL bool digestInit(const EVP_MD* digest, const OSSL_PARAM* params); inline bool digestInit(const Digest& digest, const OSSL_PARAM* params) { return digestInit(digest.get(), params); @@ -2065,7 +2007,7 @@ class HMACCtxPointer final { }; #endif // NCRYPTO_USE_BORINGSSL -#if OPENSSL_WITH_EVP_MAC +#if !NCRYPTO_USE_BORINGSSL class EVPMacPointer final { public: EVPMacPointer() = default; @@ -2202,7 +2144,7 @@ class HMACCtxPointer final { const EVP_MD* md_ = nullptr; size_t md_size_ = 0; }; -#endif // OPENSSL_WITH_EVP_MAC +#endif // !NCRYPTO_USE_BORINGSSL #if NCRYPTO_USE_BORINGSSL class MacCache final { @@ -2256,7 +2198,7 @@ Buffer ExportChallenge(const char* input, size_t length); // ============================================================================ // KDF -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL class KDF final { public: KDF() = default; @@ -2311,7 +2253,7 @@ DataPointer pbkdf2(const Digest& md, uint32_t iterations, size_t length); -#if OPENSSL_WITH_ARGON2 +#if defined(OSSL_KDF_PARAM_ARGON2_LANES) enum class Argon2Type { ARGON2D, ARGON2I, ARGON2ID }; DataPointer argon2(const Buffer& pass, @@ -2328,7 +2270,6 @@ DataPointer argon2(const Buffer& pass, // ============================================================================ // KEM (Key Encapsulation Mechanism) -#if OPENSSL_WITH_KEM class KEM final { public: @@ -2352,14 +2293,12 @@ class KEM final { const Buffer& ciphertext); private: -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL static bool SetOperationParameter(EVP_PKEY_CTX* ctx, const EVPKeyPointer& key); #endif }; -#endif // OPENSSL_WITH_KEM - // ============================================================================ // Version metadata #define NCRYPTO_VERSION "0.0.1" diff --git a/lib/internal/crypto/util.js b/lib/internal/crypto/util.js index 52445eab767c..b56c41404e91 100644 --- a/lib/internal/crypto/util.js +++ b/lib/internal/crypto/util.js @@ -49,6 +49,7 @@ const { getFipsCrypto, getFipsCryptoGeneration, KmacJob, + isKdfAlgorithmAvailable, isKeyAlgorithmAvailable, } = internalBinding('crypto'); @@ -498,9 +499,9 @@ function getConditionalAlgorithms() { (has(ciphers, 'aes-128-ocb') || has(ciphers, 'aes-192-ocb') || has(ciphers, 'aes-256-ocb')), - 'Argon2d': !!Argon2Job && !fips, - 'Argon2i': !!Argon2Job && !fips, - 'Argon2id': !!Argon2Job && !fips, + 'Argon2d': !!Argon2Job && isKdfAlgorithmAvailable('ARGON2D'), + 'Argon2i': !!Argon2Job && isKdfAlgorithmAvailable('ARGON2I'), + 'Argon2id': !!Argon2Job && isKdfAlgorithmAvailable('ARGON2ID'), 'ChaCha20-Poly1305': isBoringSSL || has(ciphers, 'chacha20-poly1305'), 'cSHAKE128': has(hashes, 'shake128'), diff --git a/src/crypto/crypto_aes.h b/src/crypto/crypto_aes.h index bea409da94a8..3fd5e41d06ef 100644 --- a/src/crypto/crypto_aes.h +++ b/src/crypto/crypto_aes.h @@ -31,20 +31,24 @@ constexpr unsigned kNoAuthTagLength = static_cast(-1); V(KW_128, AES_KW_Cipher, static_cast(nullptr)) \ V(KW_192, AES_KW_Cipher, static_cast(nullptr)) \ V(KW_256, AES_KW_Cipher, static_cast(nullptr)) -#else +#elif NCRYPTO_USE_OPENSSL_PROVIDER #define VARIANTS_KW(V) \ V(KW_128, AES_Cipher, ncrypto::Cipher::AES_128_KW()) \ V(KW_192, AES_Cipher, ncrypto::Cipher::AES_192_KW()) \ V(KW_256, AES_Cipher, ncrypto::Cipher::AES_256_KW()) +#else +#error "Unsupported crypto backend" #endif -#if OPENSSL_WITH_AES_OCB +#if NCRYPTO_USE_OPENSSL_PROVIDER #define VARIANTS_OCB(V) \ V(OCB_128, AES_Cipher, ncrypto::Cipher::AES_128_OCB()) \ V(OCB_192, AES_Cipher, ncrypto::Cipher::AES_192_OCB()) \ V(OCB_256, AES_Cipher, ncrypto::Cipher::AES_256_OCB()) #elif defined(OPENSSL_IS_BORINGSSL) #define VARIANTS_OCB(V) +#else +#error "Unsupported crypto backend" #endif #define VARIANTS(V) \ diff --git a/src/crypto/crypto_argon2.cc b/src/crypto/crypto_argon2.cc index fdc0b38235ee..fb0ea02756ef 100644 --- a/src/crypto/crypto_argon2.cc +++ b/src/crypto/crypto_argon2.cc @@ -5,7 +5,7 @@ #include "memory_tracker-inl.h" #include "threadpoolwork-inl.h" -#if OPENSSL_WITH_ARGON2 +#if defined(OSSL_KDF_PARAM_ARGON2_LANES) #include namespace node::crypto { diff --git a/src/crypto/crypto_argon2.h b/src/crypto/crypto_argon2.h index 846da0e6f675..be0ceeb192bf 100644 --- a/src/crypto/crypto_argon2.h +++ b/src/crypto/crypto_argon2.h @@ -7,7 +7,7 @@ #include "crypto/crypto_util.h" namespace node::crypto { -#if OPENSSL_WITH_ARGON2 +#if defined(OSSL_KDF_PARAM_ARGON2_LANES) // Argon2 is a password-based key derivation algorithm // defined in https://datatracker.ietf.org/doc/html/rfc9106 @@ -75,11 +75,6 @@ void Initialize(Environment* env, v8::Local target); void RegisterExternalReferences(ExternalReferenceRegistry* registry); } // namespace Argon2 -#else -// If there is no Argon2 support, Argon2Job becomes a non-op -struct Argon2Job { - static void Initialize(Environment* env, v8::Local target) {} -}; #endif } // namespace node::crypto diff --git a/src/crypto/crypto_chacha20_poly1305.cc b/src/crypto/crypto_chacha20_poly1305.cc index 56ba78be7ccd..19f6e6a0247a 100644 --- a/src/crypto/crypto_chacha20_poly1305.cc +++ b/src/crypto/crypto_chacha20_poly1305.cc @@ -214,7 +214,7 @@ WebCryptoCipherStatus ChaCha20Poly1305CipherTraits::DoCipher( *out = ByteSource::Allocated(buf.release()); } return WebCryptoCipherStatus::OK; -#else +#elif NCRYPTO_USE_OPENSSL_PROVIDER auto ctx = CipherCtxPointer::New(); if (!ctx) { return WebCryptoCipherStatus::FAILED; @@ -325,7 +325,9 @@ WebCryptoCipherStatus ChaCha20Poly1305CipherTraits::DoCipher( *out = ByteSource::Allocated(buf.release()); return WebCryptoCipherStatus::OK; -#endif // OPENSSL_IS_BORINGSSL +#else +#error "Unsupported crypto backend" +#endif } void ChaCha20Poly1305::Initialize(Environment* env, Local target) { diff --git a/src/crypto/crypto_client_hello.cc b/src/crypto/crypto_client_hello.cc index 75ecc3cc8748..cf9c933a023f 100644 --- a/src/crypto/crypto_client_hello.cc +++ b/src/crypto/crypto_client_hello.cc @@ -7,19 +7,23 @@ namespace node::crypto { SSL* ClientHelloContext::ssl() const { #ifdef OPENSSL_IS_BORINGSSL return handle_->ssl; -#else +#elif NCRYPTO_USE_OPENSSL_PROVIDER return handle_; +#else +#error "Unsupported crypto backend" #endif } std::span ClientHelloContext::session_id() const { #ifdef OPENSSL_IS_BORINGSSL return {handle_->session_id, handle_->session_id_len}; -#else +#elif NCRYPTO_USE_OPENSSL_PROVIDER const uint8_t* id = nullptr; size_t len = SSL_client_hello_get0_session_id(handle_, &id); if (id == nullptr) return {}; return {id, len}; +#else +#error "Unsupported crypto backend" #endif } @@ -66,10 +70,12 @@ std::optional> ClientHelloContext::extension( if (!SSL_early_callback_ctx_extension_get(handle_, type, &data, &len)) { return std::nullopt; } -#else +#elif NCRYPTO_USE_OPENSSL_PROVIDER if (SSL_client_hello_get0_ext(handle_, type, &data, &len) != 1) { return std::nullopt; } +#else +#error "Unsupported crypto backend" #endif return std::span(data, len); } diff --git a/src/crypto/crypto_client_hello.h b/src/crypto/crypto_client_hello.h index 37b8124e8cc7..9c238660c7ad 100644 --- a/src/crypto/crypto_client_hello.h +++ b/src/crypto/crypto_client_hello.h @@ -9,6 +9,7 @@ #include #include #include +#include "ncrypto.h" namespace node::crypto { @@ -35,12 +36,14 @@ class ClientHelloContext final { static constexpr Result kContinueResult = ssl_select_cert_success; static constexpr Result kRetryResult = ssl_select_cert_retry; static constexpr Result kFailResult = ssl_select_cert_error; -#else +#elif NCRYPTO_USE_OPENSSL_PROVIDER using Handle = SSL*; using Result = int; static constexpr Result kContinueResult = SSL_CLIENT_HELLO_SUCCESS; static constexpr Result kRetryResult = SSL_CLIENT_HELLO_RETRY; static constexpr Result kFailResult = SSL_CLIENT_HELLO_ERROR; +#else +#error "Unsupported crypto backend" #endif explicit ClientHelloContext(Handle handle, int* alert = nullptr) @@ -89,10 +92,12 @@ struct ClientHelloCallback final { static ssl_select_cert_result_t Invoke(const SSL_CLIENT_HELLO* hello) { return ClientHelloContext::Encode(Fn(ClientHelloContext(hello))); } -#else +#elif NCRYPTO_USE_OPENSSL_PROVIDER static int Invoke(SSL* ssl, int* alert, void* arg) { return ClientHelloContext::Encode(Fn(ClientHelloContext(ssl, alert))); } +#else +#error "Unsupported crypto backend" #endif }; @@ -101,8 +106,10 @@ template inline void SetClientHelloCallback(SSL_CTX* ctx) { #ifdef OPENSSL_IS_BORINGSSL SSL_CTX_set_select_certificate_cb(ctx, ClientHelloCallback::Invoke); -#else +#elif NCRYPTO_USE_OPENSSL_PROVIDER SSL_CTX_set_client_hello_cb(ctx, ClientHelloCallback::Invoke, nullptr); +#else +#error "Unsupported crypto backend" #endif } diff --git a/src/crypto/crypto_context.cc b/src/crypto/crypto_context.cc index 21decb34e111..fe2a872a2ba0 100644 --- a/src/crypto/crypto_context.cc +++ b/src/crypto/crypto_context.cc @@ -1561,9 +1561,11 @@ int CertVerifyCallback(X509_STORE_CTX* ctx, void*) { // recorded there. (void)depth; (void)offender; -#else +#elif NCRYPTO_USE_OPENSSL_PROVIDER X509_STORE_CTX_set_error_depth(ctx, depth); X509_STORE_CTX_set_current_cert(ctx, offender); +#else +#error "Unsupported crypto backend" #endif // The per-certificate callback is the one carried by the SSL object; it is // what the library installs on the store context before calling this hook. @@ -2134,7 +2136,7 @@ void SecureContext::SetDHParam(const FunctionCallbackInfo& args) { return THROW_ERR_CRYPTO_OPERATION_FAILED( env, "Error setting temp DH parameter"); } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL dh_pkey.release(); #endif } diff --git a/src/crypto/crypto_dh.cc b/src/crypto/crypto_dh.cc index a65cc2e12e56..862c79cb1ce8 100644 --- a/src/crypto/crypto_dh.cc +++ b/src/crypto/crypto_dh.cc @@ -81,8 +81,10 @@ MaybeLocal DataPointerToBuffer(Environment* env, DataPointer&& data) { void PutDhError(int reason) { #ifdef OPENSSL_IS_BORINGSSL OPENSSL_PUT_ERROR(DH, reason); -#else +#elif NCRYPTO_USE_OPENSSL_PROVIDER ERR_raise(ERR_LIB_DH, reason); +#else +#error "Unsupported crypto backend" #endif } @@ -116,11 +118,13 @@ void New(const FunctionCallbackInfo& args) { if (args[0]->IsInt32()) { int32_t bits = args[0].As()->Value(); if (bits < 2) { -#ifndef OPENSSL_IS_BORINGSSL +#if NCRYPTO_USE_OPENSSL_PROVIDER PutDhError(DH_R_MODULUS_TOO_SMALL); #elif defined(OPENSSL_IS_BORINGSSL) PutBnError(BN_R_BITS_TOO_SMALL); -#endif // OPENSSL_IS_BORINGSSL +#else +#error "Unsupported crypto backend" +#endif return ThrowCryptoError(env, ERR_get_error(), "Invalid prime length"); } @@ -185,7 +189,7 @@ void New(const FunctionCallbackInfo& args) { } } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL if (BN_num_bits(bn_p.get()) >= 512 && BN_cmp(bn_g.get(), bn_p.get()) >= 0) { PutDhError(DH_R_BAD_GENERATOR); return ThrowCryptoError(env, ERR_get_error(), "Invalid generator"); diff --git a/src/crypto/crypto_hash.cc b/src/crypto/crypto_hash.cc index b0ea75e88b27..6b30b947e7a4 100644 --- a/src/crypto/crypto_hash.cc +++ b/src/crypto/crypto_hash.cc @@ -76,7 +76,7 @@ constexpr BoringSSLDigest kBoringSSLDigests[] = { void ResetHashCache(Environment* env, uint64_t generation, Local algorithm_cache = Local()) { -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL ncrypto::DigestCache* cache = env->provider_digest_cache.get(); CHECK_NOT_NULL(cache); if (!algorithm_cache.IsEmpty()) { @@ -261,8 +261,10 @@ const std::vector& GetSupportedHashAlgorithms(Environment* env) { #error "Unsupported crypto backend" #endif #if NCRYPTO_USE_BORINGSSL - // SHA-3 descriptors are not included in BoringSSL's name registry. - for (const char* name : {"sha3-256", "sha3-384", "sha3-512"}) { + // SHA-3 and SHAKE256 descriptors are absent from BoringSSL's name + // registry. + for (const char* name : + {"sha3-256", "sha3-384", "sha3-512", "shake256", "shake-256"}) { env->supported_hash_algorithms.emplace_back(name); } #endif @@ -294,7 +296,7 @@ void Hash::GetCachedAliases(const FunctionCallbackInfo& args) { size_t size = 0; LocalVector names(isolate); LocalVector values(isolate); -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL const auto& aliases = env->provider_digest_cache->aliases(); size = aliases.size(); names.reserve(size); @@ -372,6 +374,8 @@ const ncrypto::Digest GetDigest(Environment* env, const char* name) { return result.digest; #elif NCRYPTO_USE_BORINGSSL return ncrypto::Digest::FromName(name); +#else +#error "Unsupported crypto backend" #endif } @@ -384,7 +388,7 @@ const ncrypto::Digest GetDigestForJob(Environment* env, ncrypto::HMACCtxPointer NewHmacContext(Environment* env, const ncrypto::Digest& md) { -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL SynchronizeHashCache(env); if (const auto* hmac_template = env->provider_digest_cache->getHmacTemplate( md, env->hash_cache_generation)) { @@ -415,9 +419,7 @@ bool IsShakeDigest(const EVP_MD* md) { #if NCRYPTO_USE_OPENSSL_PROVIDER return EVP_MD_is_a(md, "SHAKE128") || EVP_MD_is_a(md, "SHAKE256"); #elif NCRYPTO_USE_BORINGSSL - const char* name = OBJ_nid2sn(EVP_MD_type(md)); - return name != nullptr && - (strcmp(name, "SHAKE128") == 0 || strcmp(name, "SHAKE256") == 0); + return md == EVP_shake256(); #else #error "Unsupported crypto backend" #endif @@ -449,7 +451,7 @@ void OneShotDigestWithMD(Environment* env, enum encoding output_enc = ParseEncoding(isolate, args[4], args[5], HEX); - bool is_xof = (EVP_MD_flags(md) & EVP_MD_FLAG_XOF) != 0; + const bool is_xof = ncrypto::Digest(md).isXof(); OPENSSL_SIZE_T output_length = EVP_MD_size(md); // This is to cause hash() to fail when an incorrect @@ -656,7 +658,7 @@ void Hash::New(const FunctionCallbackInfo& args) { xof_md_len = Just(args[1].As()->Value()); } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL // This is the common path after the first lookup. Avoid constructing a // digest owner when the Environment already owns the cached implementation. if (args.Length() == 4 && args[0]->IsString()) { @@ -804,6 +806,10 @@ void Hash::HashDigest(const FunctionCallbackInfo& args) { unsigned int len = hash->md_len_; +#if NCRYPTO_USE_BORINGSSL + const bool is_xof = hash->mdctx_.hasXofFlag(); +#endif + // TODO(tniessen): SHA3_squeeze does not work for zero-length outputs on all // platforms and will cause a segmentation fault if called. This workaround // causes hash.digest() to correctly return an empty buffer / string. @@ -824,6 +830,12 @@ void Hash::HashDigest(const FunctionCallbackInfo& args) { hash->digest_ = ByteSource::Allocated(data.release()); } +#if NCRYPTO_USE_BORINGSSL + // BoringSSL consumes XOF contexts during finalization. Release the context + // so update() and copy() after a stream flush cannot reuse that state. + if (is_xof) hash->mdctx_.reset(); +#endif + Local ret; if (StringBytes::Encode( env->isolate(), hash->digest_.data(), len, encoding) @@ -894,8 +906,7 @@ Maybe HashTraits::AdditionalConfig( static_cast(args[offset + 2].As()->Value()) / CHAR_BIT; if (params->length != expected) { - if ((EVP_MD_flags(params->digest.get()) & EVP_MD_FLAG_XOF) == 0) - [[unlikely]] { + if (!params->digest.isXof()) [[unlikely]] { THROW_ERR_CRYPTO_INVALID_DIGEST(env, "Digest method not supported"); return Nothing(); } diff --git a/src/crypto/crypto_kem.cc b/src/crypto/crypto_kem.cc index 7d3f309157df..17a100a83943 100644 --- a/src/crypto/crypto_kem.cc +++ b/src/crypto/crypto_kem.cc @@ -1,7 +1,5 @@ #include "crypto/crypto_kem.h" -#if OPENSSL_WITH_KEM - #include "async_wrap-inl.h" #include "base_object-inl.h" #include "crypto/crypto_keys.h" @@ -261,5 +259,3 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) { } // namespace crypto } // namespace node - -#endif diff --git a/src/crypto/crypto_kem.h b/src/crypto/crypto_kem.h index bdc99499204b..7fcfb7d4af12 100644 --- a/src/crypto/crypto_kem.h +++ b/src/crypto/crypto_kem.h @@ -10,8 +10,6 @@ #include "memory_tracker.h" #include "node_external_reference.h" -#if OPENSSL_WITH_KEM - namespace node { namespace crypto { @@ -110,22 +108,5 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry); } // namespace crypto } // namespace node -#else - -// Provide stub implementations when KEM is unavailable. -namespace node { -namespace crypto { -namespace KEM { -inline void Initialize(Environment* env, v8::Local target) { - // No-op when KEM is unavailable. -} -inline void RegisterExternalReferences(ExternalReferenceRegistry* registry) { - // No-op when KEM is unavailable. -} -} // namespace KEM -} // namespace crypto -} // namespace node - -#endif #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS #endif // SRC_CRYPTO_CRYPTO_KEM_H_ diff --git a/src/crypto/crypto_keys.cc b/src/crypto/crypto_keys.cc index 35c01a5e9e68..ca4f86de08c1 100644 --- a/src/crypto/crypto_keys.cc +++ b/src/crypto/crypto_keys.cc @@ -653,7 +653,7 @@ static KeyObjectData ImportRawKey(Environment* env, throw_invalid(); return {}; } -#if NCRYPTO_USE_LEGACY_KEY_TYPES +#if NCRYPTO_USE_BORINGSSL eckey.release(); #endif return KeyObjectData::CreateAsymmetric(target_type, std::move(pkey)); @@ -1316,11 +1316,7 @@ void KeyObjectHandle::Equals(const FunctionCallbackInfo& args) { ClearErrorOnReturn clear_error_on_return; EVP_PKEY* pkey = key.GetAsymmetricKey().get(); EVP_PKEY* pkey2 = key2.GetAsymmetricKey().get(); -#ifndef OPENSSL_IS_BORINGSSL int ok = EVP_PKEY_eq(pkey, pkey2); -#elif defined(OPENSSL_IS_BORINGSSL) - int ok = EVP_PKEY_cmp(pkey, pkey2); -#endif if (ok == -2) { Environment* env = Environment::GetCurrent(args); return THROW_ERR_CRYPTO_UNSUPPORTED_OPERATION(env); diff --git a/src/crypto/crypto_kmac.cc b/src/crypto/crypto_kmac.cc index 40b39990737f..b29225c4bc55 100644 --- a/src/crypto/crypto_kmac.cc +++ b/src/crypto/crypto_kmac.cc @@ -3,7 +3,7 @@ #include "node_internals.h" #include "threadpoolwork-inl.h" -#if OPENSSL_WITH_EVP_MAC +#if !NCRYPTO_USE_BORINGSSL #include #include #include @@ -209,4 +209,4 @@ void Kmac::RegisterExternalReferences(ExternalReferenceRegistry* registry) { } // namespace node::crypto -#endif // OPENSSL_WITH_EVP_MAC +#endif // !NCRYPTO_USE_BORINGSSL diff --git a/src/crypto/crypto_kmac.h b/src/crypto/crypto_kmac.h index 7698a0dfaa15..91bfeb667394 100644 --- a/src/crypto/crypto_kmac.h +++ b/src/crypto/crypto_kmac.h @@ -10,7 +10,7 @@ namespace node::crypto { -#if OPENSSL_WITH_EVP_MAC +#if NCRYPTO_USE_OPENSSL_PROVIDER enum class KmacVariant { KMAC128, KMAC256 }; @@ -70,7 +70,9 @@ namespace Kmac { void Initialize(Environment* env, v8::Local target) {} void RegisterExternalReferences(ExternalReferenceRegistry* registry) {} } // namespace Kmac -#endif // OPENSSL_WITH_EVP_MAC +#else +#error "Unsupported crypto backend" +#endif // NCRYPTO_USE_OPENSSL_PROVIDER } // namespace node::crypto diff --git a/src/crypto/crypto_mac.cc b/src/crypto/crypto_mac.cc index ba34211275f2..85575f791426 100644 --- a/src/crypto/crypto_mac.cc +++ b/src/crypto/crypto_mac.cc @@ -7,7 +7,7 @@ #include "string_bytes.h" #include "v8.h" -#if OPENSSL_WITH_EVP_MAC +#if !NCRYPTO_USE_BORINGSSL #include #include #include @@ -39,7 +39,7 @@ using v8::Value; namespace crypto { -#if OPENSSL_WITH_EVP_MAC +#if !NCRYPTO_USE_BORINGSSL namespace { struct InitializedMac final { @@ -495,9 +495,9 @@ const std::vector& GetSupportedMacAlgorithms(Environment* env) { } } // namespace -#endif // OPENSSL_WITH_EVP_MAC +#endif // !NCRYPTO_USE_BORINGSSL -#if OPENSSL_WITH_EVP_MAC +#if NCRYPTO_USE_OPENSSL_PROVIDER bool Mac::MacUpdate(const char* data, size_t length) { if (!context_) return false; if (length == 0) return true; @@ -526,13 +526,17 @@ Mac::Mac(Environment* env, Mac::Mac(Environment* env, Local wrap) : BaseObject(env, wrap) { MakeWeak(); } +#else +#error "Unsupported crypto backend" #endif void Mac::MemoryInfo(MemoryTracker* tracker) const { -#if OPENSSL_WITH_EVP_MAC +#if NCRYPTO_USE_OPENSSL_PROVIDER tracker->TrackFieldWithSize("context", context_ ? kSizeOf_EVP_MAC_CTX : 0); #elif defined(OPENSSL_IS_BORINGSSL) static_cast(tracker); +#else +#error "Unsupported crypto backend" #endif } @@ -560,7 +564,7 @@ void Mac::RegisterExternalReferences(ExternalReferenceRegistry* registry) { void Mac::New(const FunctionCallbackInfo& args) { CHECK(args.IsConstructCall()); -#if OPENSSL_WITH_EVP_MAC +#if NCRYPTO_USE_OPENSSL_PROVIDER CHECK(args.Length() == 5 || args.Length() == 10); Environment* env = Environment::GetCurrent(args); InitializedMac initialized; @@ -573,11 +577,13 @@ void Mac::New(const FunctionCallbackInfo& args) { #elif defined(OPENSSL_IS_BORINGSSL) THROW_ERR_CRYPTO_MAC_NOT_SUPPORTED(Environment::GetCurrent(args), "MAC is not supported"); +#else +#error "Unsupported crypto backend" #endif } void Mac::MacUpdate(const FunctionCallbackInfo& args) { -#if OPENSSL_WITH_EVP_MAC +#if NCRYPTO_USE_OPENSSL_PROVIDER Decode(args, [](Mac* mac, const FunctionCallbackInfo& args, @@ -588,11 +594,13 @@ void Mac::MacUpdate(const FunctionCallbackInfo& args) { #elif defined(OPENSSL_IS_BORINGSSL) THROW_ERR_CRYPTO_MAC_NOT_SUPPORTED(Environment::GetCurrent(args), "MAC is not supported"); +#else +#error "Unsupported crypto backend" #endif } void Mac::MacFinal(const FunctionCallbackInfo& args) { -#if OPENSSL_WITH_EVP_MAC +#if NCRYPTO_USE_OPENSSL_PROVIDER Mac* mac; ASSIGN_OR_RETURN_UNWRAP(&mac, args.This()); Environment* env = mac->env(); @@ -616,11 +624,13 @@ void Mac::MacFinal(const FunctionCallbackInfo& args) { #elif defined(OPENSSL_IS_BORINGSSL) THROW_ERR_CRYPTO_MAC_NOT_SUPPORTED(Environment::GetCurrent(args), "MAC is not supported"); +#else +#error "Unsupported crypto backend" #endif } void Mac::GetMacs(const FunctionCallbackInfo& args) { -#if OPENSSL_WITH_EVP_MAC +#if NCRYPTO_USE_OPENSSL_PROVIDER Local context = args.GetIsolate()->GetCurrentContext(); Environment* env = Environment::GetCurrent(context); Local result; @@ -629,6 +639,8 @@ void Mac::GetMacs(const FunctionCallbackInfo& args) { } #elif defined(OPENSSL_IS_BORINGSSL) args.GetReturnValue().Set(Array::New(args.GetIsolate(), 0)); +#else +#error "Unsupported crypto backend" #endif } @@ -636,7 +648,7 @@ void Mac::GetCachedAliases(const FunctionCallbackInfo& args) { Isolate* isolate = args.GetIsolate(); LocalVector names(isolate); LocalVector values(isolate); -#if OPENSSL_WITH_EVP_MAC +#if !NCRYPTO_USE_BORINGSSL Environment* env = Environment::GetCurrent(args); SynchronizeMacCache(env); const auto& aliases = env->provider_mac_cache->aliases(); diff --git a/src/crypto/crypto_mac.h b/src/crypto/crypto_mac.h index 4da9dcef2dc7..43dd6012cc95 100644 --- a/src/crypto/crypto_mac.h +++ b/src/crypto/crypto_mac.h @@ -28,7 +28,7 @@ class Mac final : public BaseObject { static void GetMacs(const v8::FunctionCallbackInfo& args); static void GetCachedAliases(const v8::FunctionCallbackInfo& args); -#if OPENSSL_WITH_EVP_MAC +#if NCRYPTO_USE_OPENSSL_PROVIDER Mac(Environment* env, v8::Local wrap, ncrypto::EVPMacCtxPointer&& context, @@ -41,6 +41,8 @@ class Mac final : public BaseObject { bool has_output_length_ = false; #elif defined(OPENSSL_IS_BORINGSSL) Mac(Environment* env, v8::Local wrap); +#else +#error "Unsupported crypto backend" #endif }; diff --git a/src/crypto/crypto_rsa.cc b/src/crypto/crypto_rsa.cc index 353148d3cdd6..107d2c84cdb1 100644 --- a/src/crypto/crypto_rsa.cc +++ b/src/crypto/crypto_rsa.cc @@ -20,7 +20,7 @@ using ncrypto::Digest; using ncrypto::EVPKeyCtxPointer; using ncrypto::EVPKeyPointer; using ncrypto::KeyAlgorithm; -#if NCRYPTO_USE_LEGACY_KEY_TYPES +#if NCRYPTO_USE_BORINGSSL using ncrypto::RSAPointer; #endif using v8::Array; diff --git a/src/crypto/crypto_sig.cc b/src/crypto/crypto_sig.cc index b5fb9572c742..fbae8aeddbbd 100644 --- a/src/crypto/crypto_sig.cc +++ b/src/crypto/crypto_sig.cc @@ -8,7 +8,7 @@ #include "env-inl.h" #include "memory_tracker-inl.h" #include "openssl/ec.h" -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL #include #include #endif diff --git a/src/crypto/crypto_util.cc b/src/crypto/crypto_util.cc index f601685fadae..09f5353d52f3 100644 --- a/src/crypto/crypto_util.cc +++ b/src/crypto/crypto_util.cc @@ -20,18 +20,15 @@ #include "math.h" #ifndef OPENSSL_IS_BORINGSSL +#include +#include #include "openssl/provider.h" #endif -#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(3, 4) +#if defined(OSSL_ALG_PARAM_FIPS_APPROVED_INDICATOR) #include #endif -#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(4, 0) -#include -#include -#endif - namespace node { using ncrypto::BignumPointer; @@ -107,7 +104,7 @@ bool CShakeOptions::Initialize(ncrypto::EVPMDCtxPointer* ctx, if (!ctx || !*ctx || digest == nullptr) return false; if (empty()) return ctx->digestInit(digest); -#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(4, 0) +#if NCRYPTO_USE_OPENSSL_PROVIDER const bool is_cshake = EVP_MD_is_a(digest, "CSHAKE-128") || EVP_MD_is_a(digest, "CSHAKE-256"); if (!is_cshake) return false; @@ -116,20 +113,23 @@ bool CShakeOptions::Initialize(ncrypto::EVPMDCtxPointer* ctx, size_t count = 0; if (has(kFunctionName)) { params[count++] = OSSL_PARAM_construct_utf8_string( - OSSL_DIGEST_PARAM_FUNCTION_NAME, + "function-name", const_cast(function_name.c_str()), function_name.size()); } if (has(kCustomization)) { params[count++] = OSSL_PARAM_construct_utf8_string( - OSSL_DIGEST_PARAM_CUSTOMIZATION, + "customization", const_cast(customization.c_str()), customization.size()); } params[count] = OSSL_PARAM_construct_end(); return ctx->digestInit(digest, params); -#else +#elif defined(OPENSSL_IS_BORINGSSL) + // BoringSSL does not support these cSHAKE parameters. return false; +#else +#error "Unsupported crypto backend" #endif } @@ -211,7 +211,7 @@ int NoPasswordCallback(char* buf, int size, int rwflag, void* u) { return 0; } -#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(3, 4) +#if defined(OSSL_ALG_PARAM_FIPS_APPROVED_INDICATOR) namespace { constexpr size_t kMaxPendingFipsIndicatorEvents = 256; @@ -421,7 +421,7 @@ class FipsIndicatorState final { #endif void InstallFipsIndicatorCallback() { -#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(3, 4) +#if defined(OSSL_ALG_PARAM_FIPS_APPROVED_INDICATOR) const auto& options = per_process::cli_options; const bool strict = options->force_fips_crypto && options->force_fips_crypto_policy == "strict"; @@ -432,7 +432,7 @@ void InstallFipsIndicatorCallback() { } void SetupFipsIndicatorChannel(const FunctionCallbackInfo& args) { -#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(3, 4) +#if defined(OSSL_ALG_PARAM_FIPS_APPROVED_INDICATOR) Environment* env = Environment::GetCurrent(args); if (env->owns_process_state() && per_process::cli_options->enable_fips_indicator_events) { @@ -913,7 +913,7 @@ Maybe Decorate(Environment* env, #ifdef OPENSSL_IS_BORINGSSL #define OSSL_ERROR_CODES_MAP_OPENSSL_ONLY(V) -#else +#elif NCRYPTO_USE_OPENSSL_PROVIDER #define OSSL_ERROR_CODES_MAP_OPENSSL_ONLY(V) \ V(PKCS12) \ V(DSO) \ @@ -924,6 +924,8 @@ Maybe Decorate(Environment* env, V(ASYNC) \ V(KDF) \ V(SM2) +#else +#error "Unsupported crypto backend" #endif #define OSSL_ERROR_CODES_MAP(V) \ @@ -1146,6 +1148,20 @@ void SecureHeapUsed(const FunctionCallbackInfo& args) { args.GetReturnValue().Set( BigInt::New(args.GetIsolate(), DataPointer::GetSecureHeapUsed())); } + +void IsKdfAlgorithmAvailable(const FunctionCallbackInfo& args) { + CHECK(args[0]->IsString()); +#if NCRYPTO_USE_OPENSSL_PROVIDER + const Utf8Value name(args.GetIsolate(), args[0]); + ncrypto::MarkPopErrorOnReturn mark_pop_error_on_return; + args.GetReturnValue().Set(static_cast(ncrypto::KDF::Fetch(*name))); +#elif NCRYPTO_USE_BORINGSSL + // BoringSSL does not provide the provider KDF API. + args.GetReturnValue().Set(false); +#else +#error "Unsupported crypto backend" +#endif +} } // namespace namespace Util { @@ -1168,6 +1184,8 @@ void Initialize(Environment* env, Local target) { SetMethodNoSideEffect( context, target, "getOpenSSLSecLevelCrypto", GetOpenSSLSecLevelCrypto); + SetMethodNoSideEffect( + context, target, "isKdfAlgorithmAvailable", IsKdfAlgorithmAvailable); } void RegisterExternalReferences(ExternalReferenceRegistry* registry) { registry->Register(GetFipsCrypto); @@ -1178,6 +1196,7 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) { registry->Register(SecureBuffer); registry->Register(SecureHeapUsed); registry->Register(GetOpenSSLSecLevelCrypto); + registry->Register(IsKdfAlgorithmAvailable); } } // namespace Util diff --git a/src/crypto/crypto_util.h b/src/crypto/crypto_util.h index 060f77fc3627..816ca62f65e4 100644 --- a/src/crypto/crypto_util.h +++ b/src/crypto/crypto_util.h @@ -22,7 +22,7 @@ #include #include -#if OPENSSL_VERSION_NUMBER >= 0x30200000L && !defined(OPENSSL_NO_COMP_ALG) +#if defined(TLSEXT_comp_cert_limit) && !defined(OPENSSL_NO_COMP_ALG) #define NODE_OPENSSL_HAS_CERT_COMP 1 #endif diff --git a/src/crypto/crypto_x509.cc b/src/crypto/crypto_x509.cc index b66e80e16338..32eaf3af84e0 100644 --- a/src/crypto/crypto_x509.cc +++ b/src/crypto/crypto_x509.cc @@ -749,7 +749,14 @@ MaybeLocal CreateSignature(Environment* env, if (native_length < 0 || (native_length > 0 && native_data == nullptr)) { return {}; } -#if NCRYPTO_HAS_ASN1_BIT_STRING_GET_LENGTH + // Exposed ASN1_STRING flags encode the unused-bit count in the low + // three bits. Opaque values provide a checked accessor instead. +#if defined(ASN1_STRING_FLAG_BITS_LEFT) + if ((native_signature->flags & ASN1_STRING_FLAG_BITS_LEFT) != 0 && + (native_signature->flags & 0x07) != 0) { + return {}; + } +#else size_t byte_length = 0; int unused_bits = 0; if (ASN1_BIT_STRING_get_length( @@ -757,13 +764,6 @@ MaybeLocal CreateSignature(Environment* env, unused_bits != 0 || byte_length != static_cast(native_length)) { return {}; } -#elif NCRYPTO_USE_OPENSSL_PROVIDER || NCRYPTO_USE_BORINGSSL - if ((native_signature->flags & ASN1_STRING_FLAG_BITS_LEFT) != 0 && - (native_signature->flags & 0x07) != 0) { - return {}; - } -#else -#error "Unsupported crypto backend" #endif const ncrypto::Buffer signature{ diff --git a/src/crypto/crypto_x509_gen.cc b/src/crypto/crypto_x509_gen.cc index b797b2183601..36edf9df2589 100644 --- a/src/crypto/crypto_x509_gen.cc +++ b/src/crypto/crypto_x509_gen.cc @@ -122,7 +122,7 @@ X509Pointer NewCertificate() { #elif NCRYPTO_USE_BORINGSSL return X509Pointer(X509_new()); #else -#error "Unsupported ncrypto backend" +#error "Unsupported crypto backend" #endif } @@ -895,7 +895,8 @@ Maybe X509GenerateTraits::AdditionalConfig( params->padding = args[padding_offset].As()->Value(); } -#if !NCRYPTO_HAS_X509_RSA_PSS_FLEXIBLE_PARAMETERS + // BoringSSL's X.509 signer supports only restricted RSA-PSS parameters. +#if NCRYPTO_USE_BORINGSSL const EVPKeyPointer& native_signing_key = signing_key.GetAsymmetricKey(); if (native_signing_key.isRsaVariant()) { const int padding = diff --git a/src/env.cc b/src/env.cc index 5f8e22073fa7..46a71f3f1256 100644 --- a/src/env.cc +++ b/src/env.cc @@ -995,12 +995,10 @@ Environment::Environment(IsolateData* isolate_data, : thread_id.id), thread_name_(thread_name) { isolate_data->AddEnvironment(); -#if HAVE_OPENSSL && NCRYPTO_USE_OPENSSL_PROVIDER +#if HAVE_OPENSSL && !NCRYPTO_USE_BORINGSSL provider_digest_cache = std::make_unique(); provider_cipher_cache = std::make_unique(); -#if OPENSSL_WITH_EVP_MAC provider_mac_cache = std::make_unique(); -#endif #endif if (!is_main_thread()) { @@ -1301,7 +1299,7 @@ Environment::~Environment() { // environment-owned methods before unloading any addon DSOs. provider_digest_cache.reset(); provider_cipher_cache.reset(); -#if OPENSSL_WITH_EVP_MAC +#if !NCRYPTO_USE_BORINGSSL provider_mac_cache.reset(); #endif #endif diff --git a/src/node_config.cc b/src/node_config.cc index 2de1ee244ddb..61fcdb3fca81 100644 --- a/src/node_config.cc +++ b/src/node_config.cc @@ -13,6 +13,7 @@ namespace node { +using v8::Boolean; using v8::Context; using v8::FunctionCallbackInfo; using v8::Isolate; @@ -52,15 +53,13 @@ static void InitConfig(Local target, READONLY_FALSE_PROPERTY(target, "isDebugBuild"); #endif // defined(DEBUG) && DEBUG -#ifdef OPENSSL_IS_BORINGSSL - READONLY_TRUE_PROPERTY(target, "openSSLIsBoringSSL"); -#else - READONLY_FALSE_PROPERTY(target, "openSSLIsBoringSSL"); -#endif // OPENSSL_IS_BORINGSSL - #if HAVE_OPENSSL + READONLY_PROPERTY(target, + "openSSLIsBoringSSL", + Boolean::New(isolate, NCRYPTO_USE_BORINGSSL)); READONLY_TRUE_PROPERTY(target, "hasOpenSSL"); #else + READONLY_FALSE_PROPERTY(target, "openSSLIsBoringSSL"); READONLY_FALSE_PROPERTY(target, "hasOpenSSL"); #endif // HAVE_OPENSSL diff --git a/src/node_crypto.cc b/src/node_crypto.cc index f043d18ab3f1..6b15eb47340b 100644 --- a/src/node_crypto.cc +++ b/src/node_crypto.cc @@ -46,6 +46,7 @@ namespace crypto { V(Hash) \ V(HKDFJob) \ V(Hmac) \ + V(KEM) \ V(Keygen) \ V(Keys) \ V(Mac) \ @@ -65,23 +66,19 @@ namespace crypto { V(X509Generation) \ V(X509GenerateJob) -#if OPENSSL_WITH_ARGON2 +#if defined(OSSL_KDF_PARAM_ARGON2_LANES) #define ARGON2_NAMESPACE_LIST(V) V(Argon2) #else #define ARGON2_NAMESPACE_LIST(V) -#endif // OPENSSL_WITH_ARGON2 - -#if OPENSSL_WITH_KEM -#define KEM_NAMESPACE_LIST(V) V(KEM) -#else -#define KEM_NAMESPACE_LIST(V) #endif -#if OPENSSL_WITH_EVP_MAC +#if NCRYPTO_USE_OPENSSL_PROVIDER #define KMAC_NAMESPACE_LIST(V) V(Kmac) #elif defined(OPENSSL_IS_BORINGSSL) #define KMAC_NAMESPACE_LIST(V) -#endif // OPENSSL_WITH_EVP_MAC +#else +#error "Unsupported crypto backend" +#endif // NCRYPTO_USE_OPENSSL_PROVIDER #define TURBOSHAKE_NAMESPACE_LIST(V) V(TurboShake) @@ -94,7 +91,6 @@ namespace crypto { #define CRYPTO_NAMESPACE_LIST(V) \ CRYPTO_NAMESPACE_LIST_BASE(V) \ ARGON2_NAMESPACE_LIST(V) \ - KEM_NAMESPACE_LIST(V) \ KMAC_NAMESPACE_LIST(V) \ SCRYPT_NAMESPACE_LIST(V) \ TURBOSHAKE_NAMESPACE_LIST(V) diff --git a/src/node_crypto.h b/src/node_crypto.h index 4518336fde28..2bc988607828 100644 --- a/src/node_crypto.h +++ b/src/node_crypto.h @@ -40,10 +40,8 @@ #include "crypto/crypto_hash.h" #include "crypto/crypto_hkdf.h" #include "crypto/crypto_hmac.h" -#if OPENSSL_WITH_KEM #include "crypto/crypto_kem.h" -#endif -#if OPENSSL_WITH_EVP_MAC +#if !NCRYPTO_USE_BORINGSSL #include "crypto/crypto_kmac.h" #endif #include "crypto/crypto_keygen.h" diff --git a/src/node_options.cc b/src/node_options.cc index 2be14c7ffb53..d0e34fd3d176 100644 --- a/src/node_options.cc +++ b/src/node_options.cc @@ -10,7 +10,7 @@ #include "permission/env_permission.h" #include "uv.h" #if HAVE_OPENSSL -#include "ncrypto.h" // Defines OPENSSL_VERSION_PREREQ for BoringSSL. +#include "ncrypto.h" #include "quic/guard.h" #endif @@ -142,7 +142,7 @@ void PerProcessOptions::CheckOptions(std::vector* errors, "invalid value for --force-fips; expected 'provider' or 'strict'"); } -#if defined(OPENSSL_IS_BORINGSSL) || !OPENSSL_VERSION_PREREQ(3, 4) +#if !defined(OSSL_ALG_PARAM_FIPS_APPROVED_INDICATOR) if (enable_fips_indicator_events) { errors->push_back( "--enable-fips-indicator-events requires OpenSSL 3.4 or later"); diff --git a/test/cctest/test_node_crypto.cc b/test/cctest/test_node_crypto.cc index ea601d14c67d..03f49fd715a6 100644 --- a/test/cctest/test_node_crypto.cc +++ b/test/cctest/test_node_crypto.cc @@ -17,7 +17,7 @@ #include #include -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL #include #include #include @@ -174,7 +174,7 @@ TEST(NodeCrypto, KeyAlgorithmNames) { EXPECT_FALSE(empty.isA(static_cast(nullptr))); } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL TEST(NodeCrypto, DhNamedGroupCheckDoesNotRequireRandomness) { ncrypto::ClearErrorOnReturn clear_errors; ncrypto::DeleteFnPtr libctx( @@ -491,7 +491,7 @@ TEST(NodeCrypto, RsaPrimeProduct) { EXPECT_FALSE(rsa.checkPrimeProduct()); } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL namespace { constexpr int kMinimumPrimeChecks = 64; @@ -690,7 +690,7 @@ TEST(NodeCrypto, ResolveKeyAlgorithm) { key.reset(); EXPECT_EQ(key.getAlgorithm(), nullptr); } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL // Legacy keys must resolve even without provider-backed key material. key = EVPKeyPointer::New(); ASSERT_EQ(EVP_PKEY_set_type(key.get(), NID_rsaEncryption), 1); @@ -714,7 +714,7 @@ TEST(NodeCrypto, PublicKeyTypeNames) { EXPECT_STREQ(key.getKeyTypeName(), "ed25519"); } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL TEST(NodeCrypto, LegacyKeyAlgorithmResolution) { ncrypto::ClearErrorOnReturn clear_errors; auto key = EVPKeyPointer::New(); @@ -760,7 +760,7 @@ TEST(NodeCrypto, EcGroupNames) { } } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL namespace { // Deliberately longer than the fixed-size group buffer formerly used by // ncrypto. @@ -950,7 +950,7 @@ TEST(NodeCrypto, NamedRawKey) { EXPECT_TRUE(key.supportsRawPublic()); EXPECT_TRUE(key.supportsRawPrivate()); EXPECT_EQ(key.getAlgorithm()->seedSize(), 0); -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL // Provider aliases are recognized without comparing the primary type name. EXPECT_TRUE(key.isA("1.3.101.112")); auto ctx = ncrypto::EVPKeyCtxPointer::NewFromName("1.3.101.112"); @@ -1005,7 +1005,7 @@ TEST(NodeCrypto, ProviderPqcKeyWithoutLegacyId) { algorithm->seedSize()}; auto key = EVPKeyPointer::NewRawSeed(*algorithm, input); ASSERT_TRUE(key); -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL EXPECT_EQ(EVP_PKEY_id(key.get()), -1); #endif EXPECT_TRUE(key.isA(*algorithm)); @@ -1082,7 +1082,7 @@ TEST(NodeCrypto, UnavailableBoringSSLKeyAlgorithms) { } #endif -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL TEST(NodeCrypto, PrivateKeyEncodingOwnsFetchedCipher) { ncrypto::ClearErrorOnReturn clear_errors; EVPKeyPointer::PrivateKeyEncodingConfig assigned; diff --git a/test/cctest/test_node_crypto_env.cc b/test/cctest/test_node_crypto_env.cc index d83118d969dc..276471ce6ac1 100644 --- a/test/cctest/test_node_crypto_env.cc +++ b/test/cctest/test_node_crypto_env.cc @@ -85,7 +85,7 @@ TEST_F(NodeCryptoEnv, InvalidEcJwkClearsErrorQueue) { EXPECT_EQ(ERR_peek_error(), 0UL); } -#if NCRYPTO_USE_OPENSSL_PROVIDER +#if !NCRYPTO_USE_BORINGSSL TEST_F(NodeCryptoEnv, ExportIncompleteRsaPrivateKeyAsJwk) { v8::HandleScope handle_scope(isolate_); Argv argv; diff --git a/test/parallel/test-crypto-pqc-key-objects-slh-dsa.js b/test/parallel/test-crypto-pqc-key-objects-slh-dsa.js index 3f0dbc73ba5d..9aae5cacbfc1 100644 --- a/test/parallel/test-crypto-pqc-key-objects-slh-dsa.js +++ b/test/parallel/test-crypto-pqc-key-objects-slh-dsa.js @@ -107,13 +107,21 @@ for (const asymmetricKeyType of [ assert.throws(() => createPrivateKey(keys.private), { code: isBoringSSL ? 'ERR_OSSL_EVP_UNSUPPORTED_ALGORITHM' : 'ERR_OSSL_UNSUPPORTED', }); - } else { - const publicKey = createPublicKey(keys.public); + } + + const supported = hasOpenSSL(3, 5) || + (isBoringSSL && (asymmetricKeyType === 'slh-dsa-sha2-128s' || + asymmetricKeyType === 'slh-dsa-shake-256f')); + if (supported) { + const publicKey = createPublicKey(isBoringSSL ? + { format: 'jwk', key: keys.jwk } : keys.public); + const privateKey = createPrivateKey(isBoringSSL ? + { format: 'jwk', key: keys.jwk } : keys.private); assertPublicKey(publicKey); - const pubFromPriv = createPublicKey(keys.private); + const pubFromPriv = createPublicKey(isBoringSSL ? privateKey : keys.private); assertPublicKey(pubFromPriv); - assertPrivateKey(createPrivateKey(keys.private)); + assertPrivateKey(privateKey); assert.strictEqual(pubFromPriv.equals(publicKey), true); // JWK import error tests diff --git a/test/parallel/test-crypto-pqc-keygen-slh-dsa.js b/test/parallel/test-crypto-pqc-keygen-slh-dsa.js index a8e480818cd1..2d3fc3c578bf 100644 --- a/test/parallel/test-crypto-pqc-keygen-slh-dsa.js +++ b/test/parallel/test-crypto-pqc-keygen-slh-dsa.js @@ -4,31 +4,27 @@ const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); -const { hasOpenSSL } = require('../common/crypto'); +const { hasOpenSSL, isBoringSSL } = require('../common/crypto'); const assert = require('assert'); const { generateKeyPair, } = require('crypto'); -if (!hasOpenSSL(3, 5)) { - for (const asymmetricKeyType of [ - 'slh-dsa-sha2-128f', 'slh-dsa-sha2-128s', 'slh-dsa-sha2-192f', 'slh-dsa-sha2-192s', - 'slh-dsa-sha2-256f', 'slh-dsa-sha2-256s', 'slh-dsa-shake-128f', 'slh-dsa-shake-128s', - 'slh-dsa-shake-192f', 'slh-dsa-shake-192s', 'slh-dsa-shake-256f', 'slh-dsa-shake-256s', - ]) { +for (const asymmetricKeyType of [ + 'slh-dsa-sha2-128f', 'slh-dsa-sha2-128s', 'slh-dsa-sha2-192f', 'slh-dsa-sha2-192s', + 'slh-dsa-sha2-256f', 'slh-dsa-sha2-256s', 'slh-dsa-shake-128f', 'slh-dsa-shake-128s', + 'slh-dsa-shake-192f', 'slh-dsa-shake-192s', 'slh-dsa-shake-256f', 'slh-dsa-shake-256s', +]) { + const supported = hasOpenSSL(3, 5) || + (isBoringSSL && (asymmetricKeyType === 'slh-dsa-sha2-128s' || + asymmetricKeyType === 'slh-dsa-shake-256f')); + if (!supported) { assert.throws(() => generateKeyPair(asymmetricKeyType, common.mustNotCall()), { code: 'ERR_INVALID_ARG_VALUE', message: /The argument 'type' must be a supported key type/ }); - } -} else { - for (const asymmetricKeyType of [ - 'slh-dsa-sha2-128f', 'slh-dsa-sha2-128s', 'slh-dsa-sha2-192f', 'slh-dsa-sha2-192s', - 'slh-dsa-sha2-256f', 'slh-dsa-sha2-256s', 'slh-dsa-shake-128f', 'slh-dsa-shake-128s', - 'slh-dsa-shake-192f', 'slh-dsa-shake-192s', 'slh-dsa-shake-256f', 'slh-dsa-shake-256s', - ]) { - + } else { function assertJwk(jwk) { assert.strictEqual(jwk.kty, 'AKP'); // SLH-DSA algorithm names keep the last character (f/s) lowercase. diff --git a/test/parallel/test-crypto-shake256-stream.js b/test/parallel/test-crypto-shake256-stream.js new file mode 100644 index 000000000000..66a7ede5040d --- /dev/null +++ b/test/parallel/test-crypto-shake256-stream.js @@ -0,0 +1,34 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const { createHash } = require('crypto'); +const { isBoringSSL } = require('../common/crypto'); + +const expected = + '483366601360a8771c6863080cc4114d8db44530f8f1e1ee4f94ea37e78b5739' + + 'd5a15bef186a5386c75744c0527e1faa9f8726e462a12a4feb06bd8801e751e4'; + +for (const outputLength of [32, 64]) { + const stream = createHash('shake256', { outputLength }); + stream.end('abc'); + const digest = expected.slice(0, outputLength * 2); + assert.strictEqual(stream.read().toString('hex'), digest); + + // A stream flush caches the digest without setting Hash's JavaScript + // finalized state. Reusing BoringSSL's cleared context used to hang or crash. + if (isBoringSSL) { + assert.throws(() => stream.update('def'), { + code: 'ERR_CRYPTO_HASH_UPDATE_FAILED', + }); + assert.throws(() => stream.copy({ outputLength }), { + name: 'Error', + message: 'Digest method not supported', + }); + } + + assert.strictEqual(stream.digest('hex'), digest); +} diff --git a/test/parallel/test-webcrypto-kem-hybrids.js b/test/parallel/test-webcrypto-kem-hybrids.js index 0d1ec410c160..8738f27c4fb5 100644 --- a/test/parallel/test-webcrypto-kem-hybrids.js +++ b/test/parallel/test-webcrypto-kem-hybrids.js @@ -5,10 +5,10 @@ const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); -const { hasFIPS, hasOpenSSL } = require('../common/crypto'); +const { hasFIPS, hasOpenSSL, isBoringSSL } = require('../common/crypto'); -if (!hasOpenSSL(3, 5)) - common.skip('requires OpenSSL >= 3.5'); +if (!hasOpenSSL(3, 5) && !isBoringSSL) + common.skip('requires OpenSSL >= 3.5 or BoringSSL'); const assert = require('assert'); const { once } = require('events'); diff --git a/test/pummel/test-crypto-pqc-sign-verify-slh-dsa.mjs b/test/pummel/test-crypto-pqc-sign-verify-slh-dsa.mjs index 52b018e7028d..98c6ef837e7a 100644 --- a/test/pummel/test-crypto-pqc-sign-verify-slh-dsa.mjs +++ b/test/pummel/test-crypto-pqc-sign-verify-slh-dsa.mjs @@ -3,14 +3,14 @@ import * as common from '../common/index.mjs'; if (!common.hasCrypto) common.skip('missing crypto'); -import { hasOpenSSL } from '../common/crypto.js'; +import { hasOpenSSL, isBoringSSL } from '../common/crypto.js'; -if (!hasOpenSSL(3, 5)) - common.skip('requires OpenSSL >= 3.5'); +if (!hasOpenSSL(3, 5) && !isBoringSSL) + common.skip('requires OpenSSL >= 3.5 or BoringSSL'); import * as assert from 'node:assert'; import { promisify } from 'node:util'; -import { randomBytes, sign, verify } from 'node:crypto'; +import { createPrivateKey, createPublicKey, randomBytes, sign, verify } from 'node:crypto'; import fixtures from '../common/fixtures.js'; const pSign = promisify(sign); @@ -34,10 +34,20 @@ for (const [asymmetricKeyType, sigLen] of [ ['slh-dsa-shake-256f', 49856], ['slh-dsa-shake-256s', 29792], ]) { + if (isBoringSSL && asymmetricKeyType !== 'slh-dsa-sha2-128s' && + asymmetricKeyType !== 'slh-dsa-shake-256f') { + common.printSkipMessage(`Skipping unsupported ${asymmetricKeyType}`); + continue; + } const keys = { public: fixtures.readKey(getKeyFileName(asymmetricKeyType, 'public'), 'ascii'), private: fixtures.readKey(getKeyFileName(asymmetricKeyType, 'private'), 'ascii'), }; + if (isBoringSSL) { + const jwk = JSON.parse(fixtures.readKey(`${asymmetricKeyType}.json`)); + keys.public = createPublicKey({ format: 'jwk', key: jwk }); + keys.private = createPrivateKey({ format: 'jwk', key: jwk }); + } const data = randomBytes(32); // Start the async signature before the sync work to overlap the two. @@ -59,8 +69,10 @@ for (const [asymmetricKeyType, sigLen] of [ assert.strictEqual(await pVerify(undefined, data, keys.public, signature), true); } - assert.throws(() => sign('sha256', data, keys.private), { code: 'ERR_OSSL_INVALID_DIGEST' }); + const code = isBoringSSL ? + 'ERR_OSSL_EVP_COMMAND_NOT_SUPPORTED' : 'ERR_OSSL_INVALID_DIGEST'; + assert.throws(() => sign('sha256', data, keys.private), { code }); assert.throws( () => verify('sha256', data, keys.public, Buffer.alloc(sigLen)), - { code: 'ERR_OSSL_INVALID_DIGEST' }); + { code }); } diff --git a/test/wpt/status/WebCryptoAPI.cjs b/test/wpt/status/WebCryptoAPI.cjs index be5ee9c9e543..f11d2888c822 100644 --- a/test/wpt/status/WebCryptoAPI.cjs +++ b/test/wpt/status/WebCryptoAPI.cjs @@ -80,32 +80,28 @@ if (isBoringSSL) { skip( 'secure-curves/derive_bits_keys/cfrg_curves_bits_curve448.https.any.js', 'secure-curves/derive_bits_keys/cfrg_curves_keys_curve448.https.any.js', - 'modern-algos/digest/cshake.https.any.js', 'secure-curves/generateKey/failures_Ed448.https.any.js', - 'modern-algos/generateKey/failures_Hybrid-KEM.https.any.js', 'secure-curves/generateKey/failures_X448.https.any.js', 'secure-curves/generateKey/successes_Ed448.https.any.js', - 'modern-algos/generateKey/successes_Hybrid-KEM.https.any.js', 'secure-curves/generateKey/successes_X448.https.any.js', - 'modern-algos/import_export/Hybrid-KEM_importKey.https.any.js', 'secure-curves/import_export/okp_importKey_Ed448.https.any.js', 'secure-curves/import_export/okp_importKey_failures_Ed448.https.any.js', 'secure-curves/import_export/okp_importKey_failures_X448.https.any.js', 'secure-curves/import_export/okp_importKey_X448.https.any.js', 'secure-curves/serialization/ed448.https.any.js', - 'modern-algos/serialization/hybridkem.https.window.js', 'secure-curves/serialization/x448.https.any.js', 'secure-curves/sign_verify/eddsa_curve448.https.any.js'); skipSubtests( - ['modern-algos/encap_decap/encap_decap_bits.https.any.js', /(?:ml-kem-512|mlkem)/i], - ['modern-algos/encap_decap/encap_decap_keys.https.any.js', /(?:ml-kem-512|mlkem)/i], + ['modern-algos/digest/cshake.https.any.js', /cSHAKE128/i], + ['modern-algos/encap_decap/encap_decap_bits.https.any.js', /ml-kem-512/i], + ['modern-algos/encap_decap/encap_decap_keys.https.any.js', /ml-kem-512/i], ['modern-algos/generateKey/failures_ML-KEM.https.any.js', /ml-kem-512/i], ['modern-algos/generateKey/successes_ML-KEM.https.any.js', /ml-kem-512/i], - ['modern-algos/getPublicKey.https.any.js', /(?:ed448|x448|ml-kem-512|mlkem)/i], + ['modern-algos/getPublicKey.https.any.js', /(?:ed448|x448|ml-kem-512)/i], ['modern-algos/import_export/ML-KEM_importKey.https.any.js', /ml-kem-512/i], ['modern-algos/serialization/mlkem.https.any.js', /ml-kem-512/i], - ['modern-algos/supports-modern.https.any.js', /(?:ml-kem-512|mlkem)/i]); + ['modern-algos/supports-modern.https.any.js', /ml-kem-512/i]); } if (hasFIPS(3)) { diff --git a/tools/cpplint.py b/tools/cpplint.py index 1e26e3ded396..338bbbce3e4a 100755 --- a/tools/cpplint.py +++ b/tools/cpplint.py @@ -300,6 +300,7 @@ _ERROR_CATEGORIES = [ "build/c++11", "build/c++17", + "build/crypto_backend", "build/deprecated", "build/endif_comment", "build/explicit_make_pair", @@ -7466,6 +7467,62 @@ def CheckThreadLocalUsage(filename, lines, error): 'NOLINTNEXTLINE(runtime/thread_local).') +def CheckCryptoBackendUsage(filename, clean_lines, error): + """Require explicit BoringSSL guards and unsupported-backend fallbacks. + + Gates excluding BoringSSL must name it instead of using the provider + selector. Backend alternatives must explicitly reject unsupported backends; + other feature checks remain valid. + """ + provider = re.compile(r'\bNCRYPTO_USE_OPENSSL_PROVIDER\b') + boring = re.compile(r'\b(?:NCRYPTO_USE_BORINGSSL|OPENSSL_IS_BORINGSSL)\b') + directives = re.compile( + r'^\s*#\s*(if|ifdef|ifndef|elif|elifdef|elifndef|else|endif|error)\b(.*)$') + stack = [] + lines = iter(enumerate(clean_lines.lines)) + for linenum, line in lines: + # Preprocessor conditions can span multiple physical lines. + while line.endswith('\\'): + line = line[:-1] + next(lines, (0, ''))[1] + match = directives.match(line) + if not match: + continue + directive, condition = match.groups() + if directive in ('if', 'ifdef', 'ifndef'): + stack.append({ + 'linenum': linenum, + 'provider': bool(provider.search(condition)), + 'boring': bool(boring.search(condition)), + 'alternative': False, + 'else': False, + 'error': False, + }) + elif stack: + group = stack[-1] + if directive in ('elif', 'elifdef', 'elifndef'): + group['provider'] |= bool(provider.search(condition)) + group['boring'] |= bool(boring.search(condition)) + group['alternative'] = True + elif directive == 'else': + group['alternative'] = True + group['else'] = True + elif directive == 'error' and group['else']: + if condition.strip() == '"Unsupported crypto backend"': + group['error'] = True + elif directive == 'endif': + stack.pop() + if group['provider'] and not group['boring']: + error(filename, group['linenum'], 'build/crypto_backend', 5, + 'Crypto backend guards must name BoringSSL explicitly; ' + 'use #if !NCRYPTO_USE_BORINGSSL for BoringSSL exclusions.') + elif ((group['provider'] or group['boring']) and group['alternative'] and + not (group['else'] and group['error'])): + error(filename, group['linenum'], 'build/crypto_backend', 5, + 'Crypto backend alternatives must end with ' + '#else and #error "Unsupported crypto backend"; ' + 'use an explicit #elif for each supported backend.') + + def ProcessLine( filename, file_extension, @@ -7631,6 +7688,8 @@ def ProcessFileData(filename, file_extension, lines, error, extra_check_function CheckThreadLocalUsage(filename, lines, error) + CheckCryptoBackendUsage(filename, clean_lines, error) + def ProcessConfigOverrides(filename): """Loads the configuration files and processes the config overrides. diff --git a/tools/nix/pkgs-26.05.nix b/tools/nix/pkgs-26.05.nix index 9a410b7fce91..3cedbc08a7d0 100644 --- a/tools/nix/pkgs-26.05.nix +++ b/tools/nix/pkgs-26.05.nix @@ -1,10 +1,10 @@ arg: let repo = "https://github.com/NixOS/nixpkgs"; - rev = "57f1c8965649ce5bcac5118a0d2e41f1fbdc56e5"; + rev = "f4244ef33645badc8157562b5e80748929b396c2"; nixpkgs = import (builtins.fetchTarball { url = "${repo}/archive/${rev}.tar.gz"; - sha256 = "08gxbi52psc9wvflpfsli9fjvcv1jvzd70w6c8pxl4swjvfcsq3d"; + sha256 = "0qyfd0iwdxb9cn36dn90y6z1jbc0fbl9al96hdrmw13m7262ibb1"; }) arg; in # Unstable channel no longer supports Intel architecture for macOS. We can use the 26.05 channel diff --git a/tools/nix/pkgs.nix b/tools/nix/pkgs.nix index 6ed279484a52..8b36eb17801e 100644 --- a/tools/nix/pkgs.nix +++ b/tools/nix/pkgs.nix @@ -1,10 +1,10 @@ arg: let repo = "https://github.com/NixOS/nixpkgs"; - rev = "085af13c1607f4f73ab1e7a51071faf6577a7e87"; + rev = "2074cc672349f14240fb7ea90d509e0b643e9dd4"; nixpkgs = import (builtins.fetchTarball { url = "${repo}/archive/${rev}.tar.gz"; - sha256 = "0wwdfxvwc19qymmjshf8qzw39dqyav1kgxna2ady9l7akqzanm1i"; + sha256 = "0x2cbp7qi17ll07dlns0bq6401r6563bvkv3bqvd6lia5ai5hj0k"; }) arg; in # Unstable channel no longer supports Intel architecture for macOS. We can use the 26.05 channel diff --git a/typings/internalBinding/crypto.d.ts b/typings/internalBinding/crypto.d.ts index 061e838824fe..d663b7755f90 100644 --- a/typings/internalBinding/crypto.d.ts +++ b/typings/internalBinding/crypto.d.ts @@ -1071,6 +1071,7 @@ export interface CryptoBinding { certificate: InternalCryptoBinding.X509CertificateHandle, ): InternalCryptoBinding.Buffer[]; isCryptoKey(key: unknown): boolean; + isKdfAlgorithmAvailable(name: string): boolean; isKeyAlgorithmAvailable(name: string): boolean; isKeyObject(key: unknown): boolean; isX509Certificate(value: unknown): boolean;