crypto: make backend requirements explicit

Name OpenSSL and BoringSSL alternatives and add errors for unsupported
backends. This helps catch incomplete backports.

Remove redundant feature aliases and check APIs and constants to detect
capabilities. Retain version checks for behavioral differences.

Determine Argon2 support through provider fetches. Register Argon2Job
based on API availability, including builds configured without Argon2.

Signed-off-by: Filip Skokan <panva.ip@gmail.com>
Assisted-by: Codex
PR-URL: https://github.com/nodejs/node/pull/67472
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
This commit is contained in:
Filip Skokan authored and Node.js GitHub Bot committed 2026-11-16 20:01:15 +00:00
1 parent ca54b1f8e0
commit 95b3edd529
33 files changed
+329 -337

No files matched your search

+140 -110
View File
@@ -8,7 +8,7 @@
#include <openssl/pkcs12.h>
#include <openssl/rand.h>
#include <openssl/x509v3.h>
#if NCRYPTO_USE_OPENSSL_PROVIDER
#if !NCRYPTO_USE_BORINGSSL
#include <openssl/asn1err.h>
#include <openssl/decoder.h>
#endif
@@ -29,14 +29,14 @@
#include <openssl/provider.h>
#include <openssl/store.h>
#include <openssl/ui.h>
#if OPENSSL_WITH_ARGON2
#if defined(OSSL_KDF_PARAM_ARGON2_LANES)
#include <openssl/thread.h>
#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<ASN1_SEQUENCE_ANY, ASN1SequenceDeleter>;
#if NCRYPTO_USE_OPENSSL_PROVIDER
#if !NCRYPTO_USE_BORINGSSL
using X509PubKeyPointer = DeleteFnPtr<X509_PUBKEY, X509_PUBKEY_free>;
// 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<ASN1_STRING, ASN1_STRING_free>;
using OSSLParamBldPointer = DeleteFnPtr<OSSL_PARAM_BLD, OSSL_PARAM_BLD_free>;
using RsaPssParamsPointer = DeleteFnPtr<RSA_PSS_PARAMS, RSA_PSS_PARAMS_free>;
@@ -135,7 +135,7 @@ constexpr std::array<RsaOtherPrimeParamNames, 8> 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 <typename Pointer>
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<uint64_t> 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<unsigned char*>(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<int>(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<char> 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<bool, int> X509View::checkPublicKey(const EVPKeyPointer& pkey) const {
if (result >= 0) return Result<bool, int>(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) {
@@ -3206,7 +3212,7 @@ DataPointer hkdf(const Digest& md,
return buf;
}
#if NCRYPTO_USE_OPENSSL_PROVIDER
#if !NCRYPTO_USE_BORINGSSL
namespace {
bool ScryptDerive(const Buffer<const char>& pass,
const Buffer<const unsigned char>& salt,
@@ -3363,7 +3369,7 @@ DataPointer pbkdf2(const Digest& md,
return {};
}
#if OPENSSL_WITH_ARGON2
#if defined(OSSL_KDF_PARAM_ARGON2_LANES)
DataPointer argon2(const Buffer<const char>& pass,
const Buffer<const unsigned char>& salt,
uint32_t lanes,
@@ -3522,7 +3528,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
@@ -3653,21 +3659,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
[]<typename T>(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<OSSL_PROVIDER*>(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 +3875,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 +4310,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 +4531,7 @@ Buffer<char> GetPassphrase(
return pass;
}
#if NCRYPTO_USE_OPENSSL_PROVIDER
#if !NCRYPTO_USE_BORINGSSL
using OSSLEncoderCtxPointer =
DeleteFnPtr<OSSL_ENCODER_CTX, OSSL_ENCODER_CTX_free>;
@@ -4851,7 +4867,7 @@ Result<BIOPointer, bool> 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 +5024,7 @@ Result<BIOPointer, bool> 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<BIOPointer, bool>(false,
@@ -5144,11 +5160,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 +5336,14 @@ EVPKeyPointer SSLPointer::getPeerTempKey() const {
}
std::optional<std::string_view> 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 = []<typename T>(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 +5354,7 @@ std::optional<std::string_view> SSLPointer::getNegotiatedGroup() const {
if (group == nullptr) return std::nullopt;
return group;
#else
return std::nullopt;
#error "Unsupported crypto backend"
#endif
}
@@ -5359,11 +5382,13 @@ std::optional<int> 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 +5437,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<uint16_t, 3> supported = {
@@ -5462,6 +5487,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 +5499,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 +5541,7 @@ void PushAlgorithmAlias(const char* name, void* arg) {
#endif
} // namespace
#if NCRYPTO_USE_OPENSSL_PROVIDER
#if !NCRYPTO_USE_BORINGSSL
Cipher::Cipher(DeleteFnPtr<EVP_CIPHER, EVP_CIPHER_free> cipher)
: cipher_(cipher.get()), fetched_cipher_(std::move(cipher)) {}
#endif
@@ -5603,7 +5630,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 +5640,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 +5692,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<EVP_CIPHER, EVP_CIPHER_free>&& cipher,
@@ -5702,7 +5729,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 +5742,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 +5762,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 +5803,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<EVP_CIPHER, EVP_CIPHER_free> fetched(
EVP_CIPHER_fetch(nullptr, name, nullptr));
@@ -5789,7 +5816,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 +5950,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 +5961,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 +6022,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 +6062,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 +6146,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 +6243,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 +6254,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 +6943,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 +6951,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 +7074,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 +7089,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 +7144,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 +7507,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 +7841,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 +7961,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 +7977,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 +8001,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 +8026,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 +8130,7 @@ std::optional<std::string> 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 +8180,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 +8219,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;
@@ -8290,7 +8319,7 @@ std::optional<EVP_PKEY_CTX*> 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 +8353,8 @@ std::optional<EVP_PKEY_CTX*> EVPMDCtxPointer::signInitWithContext(
return std::nullopt;
}
return ctx;
#else
#error "Unsupported crypto backend"
#endif
}
@@ -8341,7 +8372,7 @@ std::optional<EVP_PKEY_CTX*> 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 +8406,8 @@ std::optional<EVP_PKEY_CTX*> EVPMDCtxPointer::verifyInitWithContext(
return std::nullopt;
}
return ctx;
#else
#error "Unsupported crypto backend"
#endif
}
@@ -8510,7 +8543,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 +8846,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<const unsigned char>& buf,
const EVP_MD* md) {
@@ -9021,13 +9054,13 @@ size_t Digest::size() const {
return EVP_MD_size(md_);
}
#if NCRYPTO_USE_OPENSSL_PROVIDER
#if !NCRYPTO_USE_BORINGSSL
Digest::Digest(DeleteFnPtr<EVP_MD, EVP_MD_free> 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 +9073,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 +9096,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 +9114,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 +9124,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<EVP_MD, EVP_MD_free> fetched(
EVP_MD_fetch(nullptr, name, nullptr));
@@ -9104,7 +9137,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<EVP_MD*>(md)) != 1) return Digest();
return Digest(DeleteFnPtr<EVP_MD, EVP_MD_free>(const_cast<EVP_MD*>(md)));
@@ -9115,8 +9148,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 +9181,7 @@ std::optional<KEM::EncapsulateResult> 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 +9222,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 +9252,4 @@ DataPointer KEM::Decapsulate(const EVPKeyPointer& private_key,
return shared_key;
}
#endif // OPENSSL_WITH_KEM
} // namespace ncrypto
+30 -92
View File
@@ -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 <openssl/core_names.h>
#include <openssl/encoder.h>
#include <openssl/param_build.h>
#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 <typename T, void (*function)(T*)>
using DeleteFnPtr = typename FunctionDeleter<T, function>::Pointer;
using PKCS8Pointer = DeleteFnPtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_free>;
#if NCRYPTO_USE_LEGACY_KEY_TYPES
#if NCRYPTO_USE_BORINGSSL
using RSAPointer = DeleteFnPtr<RSA, RSA_free>;
#endif
using SSLSessionPointer = DeleteFnPtr<SSL_SESSION, SSL_SESSION_free>;
@@ -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;
@@ -387,7 +328,7 @@ class Digest final {
private:
const EVP_MD* md_ = nullptr;
#if NCRYPTO_USE_OPENSSL_PROVIDER
#if !NCRYPTO_USE_BORINGSSL
explicit Digest(DeleteFnPtr<EVP_MD, EVP_MD_free> md);
DeleteFnPtr<EVP_MD, EVP_MD_free> fetched_md_;
#endif
@@ -439,7 +380,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 +389,7 @@ class DigestCache final {
private:
uint64_t generation_ = 0;
#if NCRYPTO_USE_OPENSSL_PROVIDER
#if !NCRYPTO_USE_BORINGSSL
using EVPMDPointer = DeleteFnPtr<EVP_MD, EVP_MD_free>;
// IDs are not reused across generations because JavaScript caches them
@@ -475,14 +416,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<EVP_CIPHER, EVP_CIPHER_free>&& cipher,
uint64_t generation);
#endif
private:
#if NCRYPTO_USE_OPENSSL_PROVIDER
#if !NCRYPTO_USE_BORINGSSL
using EVPCipherPointer = DeleteFnPtr<EVP_CIPHER, EVP_CIPHER_free>;
uint64_t generation_ = 0;
@@ -516,7 +457,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 +553,7 @@ class Cipher final {
private:
const EVP_CIPHER* cipher_ = nullptr;
#if NCRYPTO_USE_OPENSSL_PROVIDER
#if !NCRYPTO_USE_BORINGSSL
explicit Cipher(DeleteFnPtr<EVP_CIPHER, EVP_CIPHER_free> cipher);
DeleteFnPtr<EVP_CIPHER, EVP_CIPHER_free> fetched_cipher_;
#endif
@@ -642,7 +583,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 +630,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 +735,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 +1299,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 +1844,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 +1892,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 +1932,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 +2006,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 +2143,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 +2197,7 @@ Buffer<char> 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 +2252,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<const char>& pass,
@@ -2328,7 +2269,6 @@ DataPointer argon2(const Buffer<const char>& pass,
// ============================================================================
// KEM (Key Encapsulation Mechanism)
#if OPENSSL_WITH_KEM
class KEM final {
public:
@@ -2352,14 +2292,12 @@ class KEM final {
const Buffer<const void>& 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"
+4 -3
View File
@@ -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'),
+6 -2
View File
@@ -31,20 +31,24 @@ constexpr unsigned kNoAuthTagLength = static_cast<unsigned>(-1);
V(KW_128, AES_KW_Cipher, static_cast<const EVP_CIPHER*>(nullptr)) \
V(KW_192, AES_KW_Cipher, static_cast<const EVP_CIPHER*>(nullptr)) \
V(KW_256, AES_KW_Cipher, static_cast<const EVP_CIPHER*>(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) \
+1 -1
View File
@@ -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 <openssl/core_names.h>
namespace node::crypto {
+1 -6
View File
@@ -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<v8::Object> 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<v8::Object> target) {}
};
#endif
} // namespace node::crypto
+4 -2
View File
@@ -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<Object> target) {
+9 -3
View File
@@ -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<const uint8_t> 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<std::span<const uint8_t>> 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<const uint8_t>(data, len);
}
+10 -3
View File
@@ -9,6 +9,7 @@
#include <optional>
#include <span>
#include <string_view>
#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 <ClientHelloResult (*Fn)(const ClientHelloContext&)>
inline void SetClientHelloCallback(SSL_CTX* ctx) {
#ifdef OPENSSL_IS_BORINGSSL
SSL_CTX_set_select_certificate_cb(ctx, ClientHelloCallback<Fn>::Invoke);
#else
#elif NCRYPTO_USE_OPENSSL_PROVIDER
SSL_CTX_set_client_hello_cb(ctx, ClientHelloCallback<Fn>::Invoke, nullptr);
#else
#error "Unsupported crypto backend"
#endif
}
+4 -2
View File
@@ -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<Value>& 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
}
+8 -4
View File
@@ -81,8 +81,10 @@ MaybeLocal<Value> 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<Value>& args) {
if (args[0]->IsInt32()) {
int32_t bits = args[0].As<Int32>()->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<Value>& 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");
+6 -4
View File
@@ -76,7 +76,7 @@ constexpr BoringSSLDigest kBoringSSLDigests[] = {
void ResetHashCache(Environment* env,
uint64_t generation,
Local<Object> algorithm_cache = Local<Object>()) {
#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()) {
@@ -294,7 +294,7 @@ void Hash::GetCachedAliases(const FunctionCallbackInfo<Value>& args) {
size_t size = 0;
LocalVector<Name> names(isolate);
LocalVector<Value> 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 +372,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 +386,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)) {
@@ -656,7 +658,7 @@ void Hash::New(const FunctionCallbackInfo<Value>& args) {
xof_md_len = Just<unsigned int>(args[1].As<Uint32>()->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()) {
-4
View File
@@ -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
-19
View File
@@ -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<v8::Object> 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_
+1 -5
View File
@@ -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<Value>& 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);
+2 -2
View File
@@ -3,7 +3,7 @@
#include "node_internals.h"
#include "threadpoolwork-inl.h"
#if OPENSSL_WITH_EVP_MAC
#if !NCRYPTO_USE_BORINGSSL
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <utility>
@@ -209,4 +209,4 @@ void Kmac::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
} // namespace node::crypto
#endif // OPENSSL_WITH_EVP_MAC
#endif // !NCRYPTO_USE_BORINGSSL
+4 -2
View File
@@ -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<v8::Object> 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
+22 -10
View File
@@ -7,7 +7,7 @@
#include "string_bytes.h"
#include "v8.h"
#if OPENSSL_WITH_EVP_MAC
#if !NCRYPTO_USE_BORINGSSL
#include <openssl/core_names.h>
#include <openssl/evp.h>
#include <openssl/params.h>
@@ -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<std::string>& 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<Object> 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<void>(tracker);
#else
#error "Unsupported crypto backend"
#endif
}
@@ -560,7 +564,7 @@ void Mac::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
void Mac::New(const FunctionCallbackInfo<Value>& 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<Value>& 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<Value>& args) {
#if OPENSSL_WITH_EVP_MAC
#if NCRYPTO_USE_OPENSSL_PROVIDER
Decode<Mac>(args,
[](Mac* mac,
const FunctionCallbackInfo<Value>& args,
@@ -588,11 +594,13 @@ void Mac::MacUpdate(const FunctionCallbackInfo<Value>& 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<Value>& 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<Value>& 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<Value>& args) {
#if OPENSSL_WITH_EVP_MAC
#if NCRYPTO_USE_OPENSSL_PROVIDER
Local<Context> context = args.GetIsolate()->GetCurrentContext();
Environment* env = Environment::GetCurrent(context);
Local<Value> result;
@@ -629,6 +639,8 @@ void Mac::GetMacs(const FunctionCallbackInfo<Value>& 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<Value>& args) {
Isolate* isolate = args.GetIsolate();
LocalVector<Name> names(isolate);
LocalVector<Value> 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();
+3 -1
View File
@@ -28,7 +28,7 @@ class Mac final : public BaseObject {
static void GetMacs(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetCachedAliases(const v8::FunctionCallbackInfo<v8::Value>& args);
#if OPENSSL_WITH_EVP_MAC
#if NCRYPTO_USE_OPENSSL_PROVIDER
Mac(Environment* env,
v8::Local<v8::Object> 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<v8::Object> wrap);
#else
#error "Unsupported crypto backend"
#endif
};
+1 -1
View File
@@ -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;
+1 -1
View File
@@ -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 <openssl/core_names.h>
#include <openssl/evp.h>
#endif
+33 -14
View File
@@ -20,18 +20,15 @@
#include "math.h"
#ifndef OPENSSL_IS_BORINGSSL
#include <openssl/core_names.h>
#include <openssl/params.h>
#include "openssl/provider.h"
#endif
#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(3, 4)
#if defined(OSSL_ALG_PARAM_FIPS_APPROVED_INDICATOR)
#include <openssl/indicator.h>
#endif
#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(4, 0)
#include <openssl/core_names.h>
#include <openssl/params.h>
#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<char*>(function_name.c_str()),
function_name.size());
}
if (has(kCustomization)) {
params[count++] = OSSL_PARAM_construct_utf8_string(
OSSL_DIGEST_PARAM_CUSTOMIZATION,
"customization",
const_cast<char*>(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<Value>& 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<void> 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<void> 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<Value>& args) {
args.GetReturnValue().Set(
BigInt::New(args.GetIsolate(), DataPointer::GetSecureHeapUsed()));
}
void IsKdfAlgorithmAvailable(const FunctionCallbackInfo<Value>& 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<bool>(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<Object> 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
+1 -1
View File
@@ -22,7 +22,7 @@
#include <string>
#include <vector>
#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
+8 -8
View File
@@ -749,7 +749,14 @@ MaybeLocal<Value> 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<Value> CreateSignature(Environment* env,
unused_bits != 0 || byte_length != static_cast<size_t>(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<const unsigned char> signature{
+3 -2
View File
@@ -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<void> X509GenerateTraits::AdditionalConfig(
params->padding = args[padding_offset].As<v8::Int32>()->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 =
+2 -4
View File
@@ -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<ncrypto::DigestCache>();
provider_cipher_cache = std::make_unique<ncrypto::CipherCache>();
#if OPENSSL_WITH_EVP_MAC
provider_mac_cache = std::make_unique<ncrypto::MacCache>();
#endif
#endif
if (!is_main_thread()) {
@@ -1302,7 +1300,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
+5 -6
View File
@@ -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<Object> 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
+6 -10
View File
@@ -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)
+1 -3
View File
@@ -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"
+2 -2
View File
@@ -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<std::string>* 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");
+9 -9
View File
@@ -17,7 +17,7 @@
#include <string_view>
#include <vector>
#if NCRYPTO_USE_OPENSSL_PROVIDER
#if !NCRYPTO_USE_BORINGSSL
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
@@ -174,7 +174,7 @@ TEST(NodeCrypto, KeyAlgorithmNames) {
EXPECT_FALSE(empty.isA(static_cast<const char*>(nullptr)));
}
#if NCRYPTO_USE_OPENSSL_PROVIDER
#if !NCRYPTO_USE_BORINGSSL
TEST(NodeCrypto, DhNamedGroupCheckDoesNotRequireRandomness) {
ncrypto::ClearErrorOnReturn clear_errors;
ncrypto::DeleteFnPtr<OSSL_LIB_CTX, OSSL_LIB_CTX_free> 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;
+1 -1
View File
@@ -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;
+1
View File
@@ -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;