crypto: split OpenSSL 3, BoringSSL, and legacy backends

This separates the native crypto backend paths for OpenSSL >= 3,
BoringSSL, and legacy OpenSSL. The OpenSSL >= 3 path now builds with
`OPENSSL_API_COMPAT=30000` and `OPENSSL_NO_DEPRECATED`, moving normal
crypto/TLS code away from APIs that OpenSSL 3.0.0 marks deprecated.
BoringSSL remains on its own branch, and OpenSSL < 3 remains the legacy
fallback.

The exception is ENGINE support. ENGINE APIs are isolated into a
dedicated compatibility target so they can remain available while the
JS-facing engine APIs are runtime-deprecated in 27.x. That gives us a
clear removal point for 28.x, without letting ENGINE usage leak back
into the strict OpenSSL 3 path.

The split also makes the eventual OpenSSL 1.1.1 removal easier to reason
about. Once support for OpenSSL < 3 is dropped, the legacy branch can be
removed in a focused follow-up, possibly targeting 27.x, instead of
untangling mixed version guards throughout the crypto implementation.

No public crypto or TLS API behavior is intentionally changed.

Assisted-by: Codex:gpt-5
Signed-off-by: Filip Skokan <panva.ip@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/64211
Refs: https://github.com/nodejs/node/issues/56733
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Richard Lau <richard.lau@ibm.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Filip Skokan authored and Antoine du Hamel committed 2026-07-30 13:23:58 +02:00
1 parent d2c8acd764
commit 195f103e87
23 files changed
+2456 -206

No files matched your search

+1
View File
@@ -24,6 +24,7 @@
'node_module_version%': '',
'node_with_ltcg%': '',
'node_shared_openssl%': 'false',
'openssl_is_boringssl%': 'false',
'node_tag%': '',
'uv_library%': 'static_library',
+51 -33
View File
@@ -1434,6 +1434,48 @@ def get_gas_version(cc):
warn(f'Could not recognize `gas`: {gas_ret}')
return '0.0'
def get_openssl_macros(o):
"""Extract OpenSSL preprocessor macros from the configured headers."""
# Use the C compiler to extract preprocessor macros from OpenSSL headers.
# crypto.h is included because BoringSSL declares OPENSSL_IS_BORINGSSL there.
args = ['-E', '-dM',
'-include', 'openssl/opensslv.h',
'-include', 'openssl/crypto.h',
'-']
if not options.shared_openssl:
args = ['-I', 'deps/openssl/openssl/include'] + args
elif options.shared_openssl_includes:
args = ['-I', options.shared_openssl_includes] + args
else:
for dir in o['include_dirs']:
args = ['-I', dir] + args
proc = subprocess.Popen(
shlex.split(CC) + args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
with proc:
proc.stdin.write(b'\n')
out = to_utf8(proc.communicate()[0])
if proc.returncode != 0:
warn('Failed to extract OpenSSL macros from headers')
return {}
macros = {}
for line in out.split('\n'):
if line.startswith('#define OPENSSL_'):
parts = line.split()
if len(parts) >= 2:
macro_name = parts[1]
macro_value = parts[2] if len(parts) >= 3 else '1'
macros[macro_name] = macro_value
return macros
def get_openssl_version(o):
"""Parse OpenSSL version from opensslv.h header file.
@@ -1443,39 +1485,7 @@ def get_openssl_version(o):
"""
try:
# Use the C compiler to extract preprocessor macros from opensslv.h
args = ['-E', '-dM', '-include', 'openssl/opensslv.h', '-']
if not options.shared_openssl:
args = ['-I', 'deps/openssl/openssl/include'] + args
elif options.shared_openssl_includes:
args = ['-I', options.shared_openssl_includes] + args
else:
for dir in o['include_dirs']:
args = ['-I', dir] + args
proc = subprocess.Popen(
shlex.split(CC) + args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
with proc:
proc.stdin.write(b'\n')
out = to_utf8(proc.communicate()[0])
if proc.returncode != 0:
warn('Failed to extract OpenSSL version from opensslv.h header')
return 0
# Parse the macro definitions
macros = {}
for line in out.split('\n'):
if line.startswith('#define OPENSSL_VERSION_'):
parts = line.split()
if len(parts) >= 3:
macro_name = parts[1]
macro_value = parts[2]
macros[macro_name] = macro_value
macros = get_openssl_macros(o)
# Extract version components
major = int(macros.get('OPENSSL_VERSION_MAJOR', '0'))
@@ -1505,6 +1515,13 @@ def get_openssl_version(o):
warn(f'Failed to determine OpenSSL version from header: {e}')
return 0
def get_openssl_is_boringssl(o):
try:
return b('OPENSSL_IS_BORINGSSL' in get_openssl_macros(o))
except (OSError, ValueError, subprocess.SubprocessError) as e:
warn(f'Failed to determine whether OpenSSL headers are BoringSSL: {e}')
return 'false'
def get_cargo_version(cargo):
try:
proc = subprocess.Popen(shlex.split(cargo) + ['--version'],
@@ -2309,6 +2326,7 @@ def configure_openssl(o):
configure_library('openssl', o)
o['variables']['openssl_version'] = get_openssl_version(o)
o['variables']['openssl_is_boringssl'] = get_openssl_is_boringssl(o)
def configure_lief(o):
if options.without_lief:
+25 -12
View File
@@ -1,12 +1,18 @@
#include "ncrypto.h"
#if !defined(OPENSSL_NO_ENGINE) && \
((defined(NCRYPTO_ENGINE_COMPAT) && NCRYPTO_ENGINE_COMPAT) || \
NCRYPTO_USE_LEGACY_OPENSSL)
#include <openssl/engine.h>
#endif
namespace ncrypto {
// ============================================================================
// Engine
#ifndef OPENSSL_NO_ENGINE
EnginePointer::EnginePointer(ENGINE* engine_, bool finish_on_exit_)
EnginePointer::EnginePointer(void* engine_, bool finish_on_exit_)
: engine(engine_), finish_on_exit(finish_on_exit_) {}
EnginePointer::EnginePointer(EnginePointer&& other) noexcept
@@ -24,21 +30,22 @@ EnginePointer& EnginePointer::operator=(EnginePointer&& other) noexcept {
return *new (this) EnginePointer(std::move(other));
}
void EnginePointer::reset(ENGINE* engine_, bool finish_on_exit_) {
void EnginePointer::reset(void* engine_, bool finish_on_exit_) {
if (engine != nullptr) {
ENGINE* current = static_cast<ENGINE*>(engine);
if (finish_on_exit) {
// This also does the equivalent of ENGINE_free.
ENGINE_finish(engine);
ENGINE_finish(current);
} else {
ENGINE_free(engine);
ENGINE_free(current);
}
}
engine = engine_;
finish_on_exit = finish_on_exit_;
}
ENGINE* EnginePointer::release() {
ENGINE* ret = engine;
void* EnginePointer::release() {
void* ret = engine;
engine = nullptr;
finish_on_exit = false;
return ret;
@@ -52,8 +59,9 @@ EnginePointer EnginePointer::getEngineByName(const char* name,
// Engine not found, try loading dynamically.
engine = EnginePointer(ENGINE_by_id("dynamic"));
if (engine) {
if (!ENGINE_ctrl_cmd_string(engine.get(), "SO_PATH", name, 0) ||
!ENGINE_ctrl_cmd_string(engine.get(), "LOAD", nullptr, 0)) {
ENGINE* current = static_cast<ENGINE*>(engine.engine);
if (!ENGINE_ctrl_cmd_string(current, "SO_PATH", name, 0) ||
!ENGINE_ctrl_cmd_string(current, "LOAD", nullptr, 0)) {
engine.reset();
}
}
@@ -64,19 +72,24 @@ EnginePointer EnginePointer::getEngineByName(const char* name,
bool EnginePointer::setAsDefault(uint32_t flags, CryptoErrorList* errors) {
if (engine == nullptr) return false;
ClearErrorOnReturn clear_error_on_return(errors);
return ENGINE_set_default(engine, flags) != 0;
return ENGINE_set_default(static_cast<ENGINE*>(engine), flags) != 0;
}
bool EnginePointer::init(bool finish_on_exit) {
if (engine == nullptr) return false;
if (finish_on_exit) setFinishOnExit();
return ENGINE_init(engine) == 1;
return ENGINE_init(static_cast<ENGINE*>(engine)) == 1;
}
EVPKeyPointer EnginePointer::loadPrivateKey(const char* key_name) {
if (engine == nullptr) return EVPKeyPointer();
return EVPKeyPointer(
ENGINE_load_private_key(engine, key_name, nullptr, nullptr));
return EVPKeyPointer(ENGINE_load_private_key(
static_cast<ENGINE*>(engine), key_name, nullptr, nullptr));
}
bool EnginePointer::setClientCertEngine(SSL_CTX* ctx) {
if (engine == nullptr || ctx == nullptr) return false;
return SSL_CTX_set_client_cert_engine(ctx, static_cast<ENGINE*>(engine)) == 1;
}
void EnginePointer::initEnginesOnce() {
+1772 -26
View File
File diff suppressed because it is too large. Load diff
+56 -2
View File
@@ -2,10 +2,25 @@
'variables': {
'ncrypto_bssl_libdecrepit_missing%': 1,
'ncrypto_sources': [
'engine.cc',
'ncrypto.cc',
'ncrypto.h',
],
'ncrypto_engine_sources': [
'engine.cc',
'ncrypto.h',
],
'ncrypto_strict_defines': [
'OPENSSL_API_COMPAT=30000',
'OPENSSL_NO_DEPRECATED',
],
'ncrypto_legacy_openssl_defines': [
'OPENSSL_API_COMPAT=0x10100000L',
],
'ncrypto_engine_defines': [
'OPENSSL_API_COMPAT=30000',
'OPENSSL_SUPPRESS_DEPRECATED',
'NCRYPTO_ENGINE_COMPAT=1',
],
},
'targets': [
{
@@ -20,9 +35,25 @@
'defines': [
'NCRYPTO_BSSL_LIBDECREPIT_MISSING=<(ncrypto_bssl_libdecrepit_missing)',
],
'conditions': [
['openssl_is_boringssl=="false" and openssl_version >= 0x3000000f', {
'defines!': [ '<@(ncrypto_legacy_openssl_defines)' ],
'defines': [ '<@(ncrypto_strict_defines)' ],
}],
],
},
'sources': [ '<@(ncrypto_sources)' ],
'conditions': [
['openssl_is_boringssl=="false" and openssl_version >= 0x3000000f', {
'defines!': [ '<@(ncrypto_legacy_openssl_defines)' ],
'defines': [ '<@(ncrypto_strict_defines)' ],
'dependencies': [
'ncrypto_engine',
],
}],
['openssl_is_boringssl=="false" and openssl_version < 0x3000000f', {
'sources': [ '<@(ncrypto_engine_sources)' ],
}],
['node_shared_openssl=="false"', {
'dependencies': [
'../openssl/openssl.gyp:openssl'
@@ -30,5 +61,28 @@
}],
]
},
]
],
'conditions': [
['openssl_is_boringssl=="false" and openssl_version >= 0x3000000f', {
'targets': [
{
'target_name': 'ncrypto_engine',
'type': 'static_library',
'include_dirs': ['.'],
'defines': [
'NCRYPTO_BSSL_LIBDECREPIT_MISSING=<(ncrypto_bssl_libdecrepit_missing)',
'<@(ncrypto_engine_defines)',
],
'sources': [ '<@(ncrypto_engine_sources)' ],
'conditions': [
['node_shared_openssl=="false"', {
'dependencies': [
'../openssl/openssl.gyp:openssl'
]
}],
]
},
],
}],
],
}
+179 -17
View File
@@ -19,9 +19,10 @@
#include <optional>
#include <string>
#include <string_view>
#ifndef OPENSSL_NO_ENGINE
#if defined(NCRYPTO_ENGINE_COMPAT) && NCRYPTO_ENGINE_COMPAT && \
!defined(OPENSSL_NO_ENGINE)
#include <openssl/engine.h>
#endif // !OPENSSL_NO_ENGINE
#endif // NCRYPTO_ENGINE_COMPAT && !OPENSSL_NO_ENGINE
#ifndef OPENSSL_VERSION_PREREQ
#define OPENSSL_VERSION_PREREQ(maj, min) \
@@ -40,6 +41,40 @@
#define NCRYPTO_USE_BORINGSSL_EVP_DO_ALL_FALLBACK 0
#endif
// Backend split:
// - OpenSSL >= 3 uses provider APIs and hides deprecated low-level objects.
// - BoringSSL has its own API-compatible branch.
// - OpenSSL < 3 remains the legacy fallback branch.
#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(3, 0)
#define NCRYPTO_USE_OPENSSL3_PROVIDER 1
#else
#define NCRYPTO_USE_OPENSSL3_PROVIDER 0
#endif
#ifdef OPENSSL_IS_BORINGSSL
#define NCRYPTO_USE_BORINGSSL 1
#else
#define NCRYPTO_USE_BORINGSSL 0
#endif
#if !NCRYPTO_USE_OPENSSL3_PROVIDER && !NCRYPTO_USE_BORINGSSL
#define NCRYPTO_USE_LEGACY_OPENSSL 1
#else
#define NCRYPTO_USE_LEGACY_OPENSSL 0
#endif
#if NCRYPTO_USE_BORINGSSL || NCRYPTO_USE_LEGACY_OPENSSL
#define NCRYPTO_USE_LEGACY_KEY_TYPES 1
#else
#define NCRYPTO_USE_LEGACY_KEY_TYPES 0
#endif
#if NCRYPTO_USE_OPENSSL3_PROVIDER
#include <openssl/core_names.h>
#include <openssl/encoder.h>
#include <openssl/param_build.h>
#endif
// The FIPS-related functions are only available
// when the OpenSSL itself was compiled with FIPS support.
#if defined(OPENSSL_FIPS) && !OPENSSL_VERSION_PREREQ(3, 0)
@@ -112,7 +147,6 @@
#define EVP_PKEY_ML_KEM_512 NID_ML_KEM_512
#define EVP_PKEY_ML_KEM_768 NID_ML_KEM_768
#define EVP_PKEY_ML_KEM_1024 NID_ML_KEM_1024
#include <openssl/core_names.h>
#elif OPENSSL_WITH_BORINGSSL_PQC
#define EVP_PKEY_ML_KEM_768 NID_ML_KEM_768
#define EVP_PKEY_ML_KEM_1024 NID_ML_KEM_1024
@@ -303,7 +337,9 @@ 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
using RSAPointer = DeleteFnPtr<RSA, RSA_free>;
#endif
using SSLSessionPointer = DeleteFnPtr<SSL_SESSION, SSL_SESSION_free>;
class BIOPointer;
@@ -502,11 +538,23 @@ class Cipher final {
class Dsa final {
public:
Dsa();
#if NCRYPTO_USE_OPENSSL3_PROVIDER
explicit Dsa(const EVP_PKEY* pkey);
#else
Dsa(OSSL3_CONST DSA* dsa);
#endif
NCRYPTO_DISALLOW_COPY_AND_MOVE(Dsa)
#if NCRYPTO_USE_OPENSSL3_PROVIDER
inline operator bool() const {
return dsa_;
}
#else
inline operator bool() const { return dsa_ != nullptr; }
#endif
#if NCRYPTO_USE_LEGACY_KEY_TYPES
inline operator OSSL3_CONST DSA*() const { return dsa_; }
#endif
const BIGNUM* getP() const;
const BIGNUM* getQ() const;
@@ -514,7 +562,13 @@ class Dsa final {
size_t getDivisorLength() const;
private:
#if NCRYPTO_USE_OPENSSL3_PROVIDER
bool dsa_ = false;
DeleteFnPtr<BIGNUM, BN_free> p_;
DeleteFnPtr<BIGNUM, BN_free> q_;
#else
OSSL3_CONST DSA* dsa_;
#endif
};
// ============================================================================
@@ -523,11 +577,23 @@ class Dsa final {
class Rsa final {
public:
Rsa();
#if NCRYPTO_USE_OPENSSL3_PROVIDER
explicit Rsa(const EVP_PKEY* pkey);
#else
Rsa(OSSL3_CONST RSA* rsa);
#endif
NCRYPTO_DISALLOW_COPY_AND_MOVE(Rsa)
#if NCRYPTO_USE_OPENSSL3_PROVIDER
inline operator bool() const {
return rsa_;
}
#else
inline operator bool() const { return rsa_ != nullptr; }
#endif
#if NCRYPTO_USE_LEGACY_KEY_TYPES
inline operator OSSL3_CONST RSA*() const { return rsa_; }
#endif
struct PublicKey {
const BIGNUM* n;
@@ -561,6 +627,8 @@ class Rsa final {
using CipherParams = Cipher::CipherParams;
BIOPointer derPublicKey() const;
static DataPointer encrypt(const EVPKeyPointer& key,
const CipherParams& params,
const Buffer<const void> in);
@@ -569,20 +637,41 @@ class Rsa final {
const Buffer<const void> in);
private:
#if NCRYPTO_USE_OPENSSL3_PROVIDER
bool rsa_ = false;
DeleteFnPtr<BIGNUM, BN_free> n_;
DeleteFnPtr<BIGNUM, BN_free> e_;
DeleteFnPtr<BIGNUM, BN_free> d_;
DeleteFnPtr<BIGNUM, BN_free> p_;
DeleteFnPtr<BIGNUM, BN_free> q_;
DeleteFnPtr<BIGNUM, BN_free> dp_;
DeleteFnPtr<BIGNUM, BN_free> dq_;
DeleteFnPtr<BIGNUM, BN_free> qi_;
std::optional<PssParams> pss_params_;
#else
OSSL3_CONST RSA* rsa_;
#endif
};
class Ec final {
public:
Ec();
#if NCRYPTO_USE_OPENSSL3_PROVIDER
explicit Ec(const EVP_PKEY* pkey);
#else
Ec(OSSL3_CONST EC_KEY* key);
#endif
NCRYPTO_DISALLOW_COPY_AND_MOVE(Ec)
const EC_GROUP* getGroup() const;
const EC_POINT* getPublicKey() const;
point_conversion_form_t getPointConversionForm() const;
int getCurve() const;
inline operator bool() const { return ec_ != nullptr; }
#if NCRYPTO_USE_LEGACY_KEY_TYPES
inline operator OSSL3_CONST EC_KEY*() const { return ec_; }
#endif
static int GetCurveIdFromName(const char* name);
@@ -590,7 +679,13 @@ class Ec final {
static bool GetCurves(GetCurveCallback callback);
private:
#if NCRYPTO_USE_OPENSSL3_PROVIDER
DeleteFnPtr<EC_GROUP, EC_GROUP_free> ec_;
DeleteFnPtr<EC_POINT, EC_POINT_free> pub_;
point_conversion_form_t form_ = POINT_CONVERSION_UNCOMPRESSED;
#else
OSSL3_CONST EC_KEY* ec_ = nullptr;
#endif
};
// A managed pointer to a buffer of data. When destroyed the underlying
@@ -926,7 +1021,11 @@ class EVPKeyPointer final {
const Buffer<const unsigned char>& data);
#endif
static EVPKeyPointer NewDH(DHPointer&& dh);
#if NCRYPTO_USE_OPENSSL3_PROVIDER
static EVPKeyPointer NewRSA(const Rsa& rsa);
#else
static EVPKeyPointer NewRSA(RSAPointer&& rsa);
#endif
enum class PKEncodingType {
// RSAPublicKey / RSAPrivateKey according to PKCS#1.
@@ -998,7 +1097,9 @@ class EVPKeyPointer final {
bool assign(const ECKeyPointer& eckey);
bool set(const ECKeyPointer& eckey);
#if NCRYPTO_USE_LEGACY_KEY_TYPES
operator const EC_KEY*() const;
#endif
inline bool operator==(std::nullptr_t) const noexcept {
return pkey_ == nullptr;
@@ -1070,29 +1171,53 @@ class DHPointer final {
static DHPointer New(size_t bits, unsigned int generator);
DHPointer() = default;
#if NCRYPTO_USE_OPENSSL3_PROVIDER
explicit DHPointer(EVPKeyPointer&& key, const char* group_name = nullptr);
DHPointer(BignumPointer&& p, BignumPointer&& g, const char* group_name);
#else
explicit DHPointer(DH* dh);
#endif
DHPointer(DHPointer&& other) noexcept;
DHPointer& operator=(DHPointer&& other) noexcept;
NCRYPTO_DISALLOW_COPY(DHPointer)
~DHPointer();
#if NCRYPTO_USE_OPENSSL3_PROVIDER
inline bool operator==(std::nullptr_t) noexcept {
return !operator bool();
}
inline operator bool() const {
return dh_ != nullptr || (p_ && g_);
}
#else
inline bool operator==(std::nullptr_t) noexcept { return dh_ == nullptr; }
inline operator bool() const { return dh_ != nullptr; }
#endif
#if NCRYPTO_USE_LEGACY_KEY_TYPES
inline DH* get() const { return dh_.get(); }
void reset(DH* dh = nullptr);
DH* release();
#else
inline EVP_PKEY* get() const {
return dh_.get();
}
void reset(EVP_PKEY* dh = nullptr);
EVP_PKEY* release();
#endif
enum class CheckResult {
NONE,
P_NOT_PRIME = DH_CHECK_P_NOT_PRIME,
P_NOT_SAFE_PRIME = DH_CHECK_P_NOT_SAFE_PRIME,
UNABLE_TO_CHECK_GENERATOR = DH_UNABLE_TO_CHECK_GENERATOR,
NOT_SUITABLE_GENERATOR = DH_NOT_SUITABLE_GENERATOR,
Q_NOT_PRIME = DH_CHECK_Q_NOT_PRIME,
P_NOT_PRIME = 0x01,
P_NOT_SAFE_PRIME = 0x02,
UNABLE_TO_CHECK_GENERATOR = 0x04,
NOT_SUITABLE_GENERATOR = 0x08,
Q_NOT_PRIME = 0x10,
#ifndef OPENSSL_IS_BORINGSSL
// Boringssl does not define the DH_CHECK_INVALID_[Q or J]_VALUE
INVALID_Q = DH_CHECK_INVALID_Q_VALUE,
INVALID_J = DH_CHECK_INVALID_J_VALUE,
INVALID_Q = 0x20,
INVALID_J = 0x40,
MODULUS_TOO_SMALL = 0x80,
MODULUS_TOO_LARGE = 0x100,
#endif
CHECK_FAILED = 512,
};
@@ -1114,10 +1239,12 @@ class DHPointer final {
CheckPublicKeyResult checkPublicKey(const BignumPointer& pub_key);
DataPointer getPrime() const;
size_t getPrimeBits() const;
DataPointer getGenerator() const;
DataPointer getPublicKey() const;
DataPointer getPrivateKey() const;
DataPointer generateKeys() const;
bool hasPrivateKey() const;
DataPointer generateKeys();
DataPointer computeSecret(const BignumPointer& peer) const;
bool setPublicKey(BignumPointer&& key);
@@ -1129,7 +1256,16 @@ class DHPointer final {
const EVPKeyPointer& theirKey);
private:
#if NCRYPTO_USE_OPENSSL3_PROVIDER
DeleteFnPtr<EVP_PKEY, EVP_PKEY_free> dh_;
BignumPointer p_;
BignumPointer g_;
BignumPointer pub_key_;
BignumPointer pvt_key_;
const char* group_name_ = nullptr;
#else
DeleteFnPtr<DH, DH_free> dh_;
#endif
};
struct StackOfX509Deleter {
@@ -1438,20 +1574,38 @@ class ECPointPointer final {
};
class ECKeyPointer final {
friend class EVPKeyPointer;
public:
ECKeyPointer();
explicit ECKeyPointer(const EVPKeyPointer& key);
#if NCRYPTO_USE_LEGACY_KEY_TYPES
explicit ECKeyPointer(EC_KEY* key);
#endif
ECKeyPointer(ECKeyPointer&& other) noexcept;
ECKeyPointer& operator=(ECKeyPointer&& other) noexcept;
NCRYPTO_DISALLOW_COPY(ECKeyPointer)
~ECKeyPointer();
#if NCRYPTO_USE_OPENSSL3_PROVIDER
inline bool operator==(std::nullptr_t) noexcept {
return group_ == nullptr;
}
inline operator bool() const {
return group_ != nullptr;
}
#else
inline bool operator==(std::nullptr_t) noexcept { return key_ == nullptr; }
inline operator bool() const { return key_ != nullptr; }
#endif
#if NCRYPTO_USE_LEGACY_KEY_TYPES
inline EC_KEY* get() const { return key_.get(); }
inline operator EC_KEY*() const { return key_.get(); }
void reset(EC_KEY* key = nullptr);
EC_KEY* release();
#else
void reset();
#endif
ECKeyPointer clone() const;
bool setPrivateKey(const BignumPointer& priv);
@@ -1459,6 +1613,7 @@ class ECKeyPointer final {
bool setPublicKeyRaw(const BignumPointer& x, const BignumPointer& y);
bool generate();
bool checkKey() const;
DataPointer computeSecret(const ECPointPointer& peer) const;
const EC_GROUP* getGroup() const;
const BIGNUM* getPrivateKey() const;
@@ -1467,14 +1622,22 @@ class ECKeyPointer final {
static ECKeyPointer New(const EC_GROUP* group);
static ECKeyPointer NewByCurveName(int nid);
#if NCRYPTO_USE_LEGACY_KEY_TYPES
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);
static int GetGroupName(const EC_KEY* key);
static bool Check(const EC_KEY* key);
#endif
private:
#if NCRYPTO_USE_OPENSSL3_PROVIDER
DeleteFnPtr<EC_GROUP, EC_GROUP_free> group_;
DeleteFnPtr<EC_POINT, EC_POINT_free> pub_;
DeleteFnPtr<BIGNUM, BN_free> priv_;
#else
DeleteFnPtr<EC_KEY, EC_KEY_free> key_;
#endif
};
class EVPMDCtxPointer final {
@@ -1641,24 +1804,23 @@ class EnginePointer final {
public:
EnginePointer() = default;
explicit EnginePointer(ENGINE* engine_, bool finish_on_exit = false);
explicit EnginePointer(void* engine_, bool finish_on_exit = false);
EnginePointer(EnginePointer&& other) noexcept;
EnginePointer& operator=(EnginePointer&& other) noexcept;
NCRYPTO_DISALLOW_COPY(EnginePointer)
~EnginePointer();
inline operator bool() const { return engine != nullptr; }
inline ENGINE* get() { return engine; }
inline void setFinishOnExit() { finish_on_exit = true; }
void reset(ENGINE* engine_ = nullptr, bool finish_on_exit_ = false);
void reset(void* engine_ = nullptr, bool finish_on_exit_ = false);
bool setAsDefault(uint32_t flags, CryptoErrorList* errors = nullptr);
bool init(bool finish_on_exit = false);
EVPKeyPointer loadPrivateKey(const char* key_name);
bool setClientCertEngine(SSL_CTX* ctx);
// Release ownership of the ENGINE* pointer.
ENGINE* release();
void* release();
// Retrieve an OpenSSL Engine instance by name. If the name does not
// identify a valid named engine, the returned EnginePointer will be
@@ -1670,7 +1832,7 @@ class EnginePointer final {
static void initEnginesOnce();
private:
ENGINE* engine = nullptr;
void* engine = nullptr;
bool finish_on_exit = false;
};
#endif // !OPENSSL_NO_ENGINE
+5 -1
View File
@@ -26,7 +26,11 @@ template("ncrypto_gn_build") {
source_set(target_name) {
forward_variables_from(invoker, "*")
public_configs = [ ":ncrypto_config" ]
sources = gypi_values.ncrypto_sources
defines = [
"NCRYPTO_ENGINE_COMPAT=1",
"OPENSSL_SUPPRESS_DEPRECATED",
]
sources = gypi_values.ncrypto_sources + gypi_values.ncrypto_engine_sources
deps = [ "$node_openssl_path" ]
}
}
+6 -2
View File
@@ -231,11 +231,15 @@ MaybeLocal<Object> GetEphemeralKey(Environment* env, const SSLPointer& ssl) {
case EVP_PKEY_X448: {
const char* curve_name;
if (kid == EVP_PKEY_EC) {
int nid = ECKeyPointer::GetGroupName(key);
ECKeyPointer ec(key);
if (!ec) break;
int nid = EC_GROUP_get_curve_name(ec.getGroup());
if (nid == NID_undef) break;
curve_name = OBJ_nid2sn(nid);
} else {
curve_name = OBJ_nid2sn(kid);
}
if (curve_name == nullptr) break;
values[0] = env->ecdh_string();
values[1] = OneByteString(env->isolate(), curve_name);
values[2] = Integer::New(env->isolate(), key.bits());
@@ -291,7 +295,7 @@ MaybeLocal<Value> GetPeerCert(
// NOTE: This is because of the odd OpenSSL behavior. On client `cert_chain`
// contains the `peer_certificate`, but on server it doesn't.
X509Pointer cert(is_server ? SSL_get_peer_certificate(ssl.get()) : nullptr);
X509Pointer cert(is_server ? X509Pointer::PeerFrom(ssl) : X509Pointer());
STACK_OF(X509)* ssl_certs = SSL_get_peer_cert_chain(ssl.get());
if (!cert && (ssl_certs == nullptr || sk_X509_num(ssl_certs) == 0))
return Undefined(env->isolate());
+63 -21
View File
@@ -18,9 +18,6 @@
#include <openssl/pkcs12.h>
#include <openssl/rand.h>
#include <openssl/x509.h>
#ifndef OPENSSL_NO_ENGINE
#include <openssl/engine.h>
#endif // !OPENSSL_NO_ENGINE
#ifdef __APPLE__
#include <Security/Security.h>
#endif
@@ -34,7 +31,6 @@
namespace node {
using ncrypto::BignumPointer;
using ncrypto::BIOPointer;
using ncrypto::Cipher;
using ncrypto::ClearErrorOnReturn;
@@ -549,7 +545,7 @@ static bool IsCertificateExpired(X509* cert) {
// -1 if the time is in the past (expired)
// 0 if there was an error
// 1 if the time is in the future (not yet expired)
ASN1_TIME* not_after = X509_get_notAfter(cert);
const ASN1_TIME* not_after = X509_get0_notAfter(cert);
if (not_after == nullptr) {
return false;
}
@@ -1677,7 +1673,12 @@ void SecureContext::Init(const FunctionCallbackInfo<Value>& args) {
return THROW_ERR_CRYPTO_OPERATION_FAILED(
env, "Error generating ticket keys");
}
#if NCRYPTO_USE_OPENSSL3_PROVIDER
SSL_CTX_set_tlsext_ticket_key_evp_cb(sc->ctx_.get(),
TicketCompatibilityCallback);
#else
SSL_CTX_set_tlsext_ticket_key_cb(sc->ctx_.get(), TicketCompatibilityCallback);
#endif
}
SSLPointer SecureContext::CreateSSL() {
@@ -2021,17 +2022,22 @@ void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
if (!bio)
return;
#if NCRYPTO_USE_OPENSSL3_PROVIDER
EVPKeyPointer params(PEM_read_bio_Parameters(bio.get(), nullptr));
if (params && params.id() == EVP_PKEY_DH) dh.reset(params.release());
#else
dh.reset(PEM_read_bio_DHparams(bio.get(), nullptr, nullptr, nullptr));
#endif
}
// Invalid dhparam is silently discarded and DHE is no longer used.
// TODO(tniessen): don't silently discard invalid dhparam.
// TODO(panva): In a semver-major, reject non-DH parameter PEMs instead of
// silently treating them as absent.
if (!dh)
return;
const BIGNUM* p;
DH_get0_pqg(dh.get(), &p, nullptr, nullptr);
const int size = BignumPointer::GetBitCount(p);
const int size = dh.getPrimeBits();
if (size < 1024) {
return THROW_ERR_INVALID_ARG_VALUE(
env, "DH parameter is less than 1024 bits");
@@ -2040,10 +2046,18 @@ void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
env->isolate(), "DH parameter is less than 2048 bits"));
}
#if NCRYPTO_USE_OPENSSL3_PROVIDER
EVPKeyPointer dh_pkey(dh.release());
if (!SSL_CTX_set0_tmp_dh_pkey(sc->ctx_.get(), dh_pkey.get())) {
#else
if (!SSL_CTX_set_tmp_dh(sc->ctx_.get(), dh.get())) {
#endif
return THROW_ERR_CRYPTO_OPERATION_FAILED(
env, "Error setting temp DH parameter");
}
#if NCRYPTO_USE_OPENSSL3_PROVIDER
dh_pkey.release();
#endif
}
void SecureContext::SetMinProto(const FunctionCallbackInfo<Value>& args) {
@@ -2404,7 +2418,7 @@ void SecureContext::SetClientCertEngine(
}
// Note that this takes another reference to `engine`.
if (!SSL_CTX_set_client_cert_engine(sc->ctx_.get(), engine.get()))
if (!engine.setClientCertEngine(sc->ctx_.get()))
return ThrowCryptoError(env, ERR_get_error());
sc->client_cert_engine_provided_ = true;
}
@@ -2449,14 +2463,43 @@ void SecureContext::EnableTicketKeyCallback(
SecureContext* wrap;
ASSIGN_OR_RETURN_UNWRAP(&wrap, args.This());
#if NCRYPTO_USE_OPENSSL3_PROVIDER
SSL_CTX_set_tlsext_ticket_key_evp_cb(wrap->ctx_.get(), TicketKeyCallback);
#else
SSL_CTX_set_tlsext_ticket_key_cb(wrap->ctx_.get(), TicketKeyCallback);
#endif
}
namespace {
#if NCRYPTO_USE_OPENSSL3_PROVIDER
bool InitTicketHmac(EVP_MAC_CTX* hctx,
const unsigned char* key,
size_t key_len) {
const char* md_name = EVP_MD_get0_name(Digest::SHA256);
if (md_name == nullptr) return false;
OSSL_PARAM params[] = {
OSSL_PARAM_construct_utf8_string(
OSSL_MAC_PARAM_DIGEST, const_cast<char*>(md_name), 0),
OSSL_PARAM_construct_end(),
};
return EVP_MAC_init(hctx, key, key_len, params) == 1;
}
#else
bool InitTicketHmac(HMAC_CTX* hctx, const unsigned char* key, size_t key_len) {
return HMAC_Init_ex(hctx, key, key_len, Digest::SHA256, nullptr) == 1;
}
#endif
} // namespace
int SecureContext::TicketKeyCallback(SSL* ssl,
unsigned char* name,
unsigned char* iv,
EVP_CIPHER_CTX* ectx,
#if NCRYPTO_USE_OPENSSL3_PROVIDER
EVP_MAC_CTX* hctx,
#else
HMAC_CTX* hctx,
#endif
int enc) {
static const int kTicketPartSize = 16;
@@ -2529,8 +2572,9 @@ int SecureContext::TicketKeyCallback(SSL* ssl,
}
ArrayBufferViewContents<unsigned char> hmac_buf(hmac);
HMAC_Init_ex(
hctx, hmac_buf.data(), hmac_buf.length(), Digest::SHA256, nullptr);
if (!InitTicketHmac(hctx, hmac_buf.data(), hmac_buf.length())) {
return -1;
}
ArrayBufferViewContents<unsigned char> aes_key(aes.As<ArrayBufferView>());
if (enc) {
@@ -2546,7 +2590,11 @@ int SecureContext::TicketCompatibilityCallback(SSL* ssl,
unsigned char* name,
unsigned char* iv,
EVP_CIPHER_CTX* ectx,
#if NCRYPTO_USE_OPENSSL3_PROVIDER
EVP_MAC_CTX* hctx,
#else
HMAC_CTX* hctx,
#endif
int enc) {
SecureContext* sc = static_cast<SecureContext*>(
SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
@@ -2556,11 +2604,8 @@ int SecureContext::TicketCompatibilityCallback(SSL* ssl,
if (!ncrypto::CSPRNG(iv, 16) ||
EVP_EncryptInit_ex(
ectx, Cipher::AES_128_CBC, nullptr, sc->ticket_key_aes_, iv) <= 0 ||
HMAC_Init_ex(hctx,
sc->ticket_key_hmac_,
sizeof(sc->ticket_key_hmac_),
Digest::SHA256,
nullptr) <= 0) {
!InitTicketHmac(
hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_))) {
return -1;
}
return 1;
@@ -2573,11 +2618,8 @@ int SecureContext::TicketCompatibilityCallback(SSL* ssl,
if (EVP_DecryptInit_ex(
ectx, Cipher::AES_128_CBC, nullptr, sc->ticket_key_aes_, iv) <= 0 ||
HMAC_Init_ex(hctx,
sc->ticket_key_hmac_,
sizeof(sc->ticket_key_hmac_),
Digest::SHA256,
nullptr) <= 0) {
!InitTicketHmac(
hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_))) {
return -1;
}
return 1;
+8
View File
@@ -158,14 +158,22 @@ class SecureContext final : public BaseObject {
unsigned char* name,
unsigned char* iv,
EVP_CIPHER_CTX* ectx,
#if NCRYPTO_USE_OPENSSL3_PROVIDER
EVP_MAC_CTX* hctx,
#else
HMAC_CTX* hctx,
#endif
int enc);
static int TicketCompatibilityCallback(SSL* ssl,
unsigned char* name,
unsigned char* iv,
EVP_CIPHER_CTX* ectx,
#if NCRYPTO_USE_OPENSSL3_PROVIDER
EVP_MAC_CTX* hctx,
#else
HMAC_CTX* hctx,
#endif
int enc);
SecureContext(Environment* env, v8::Local<v8::Object> wrap);
+35 -28
View File
@@ -89,6 +89,26 @@ MaybeLocal<Value> DataPointerToBuffer(Environment* env, DataPointer&& data) {
return Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Value>());
}
void PutDhError(int reason) {
#ifdef OPENSSL_IS_BORINGSSL
OPENSSL_PUT_ERROR(DH, reason);
#elif NCRYPTO_USE_OPENSSL3_PROVIDER
ERR_raise(ERR_LIB_DH, reason);
#else
ERR_put_error(ERR_LIB_DH, 0, reason, __FILE__, __LINE__);
#endif
}
#if defined(OPENSSL_IS_BORINGSSL) || !NCRYPTO_USE_OPENSSL3_PROVIDER
void PutBnError(int reason) {
#ifdef OPENSSL_IS_BORINGSSL
OPENSSL_PUT_ERROR(BN, reason);
#else
ERR_put_error(ERR_LIB_BN, 0, reason, __FILE__, __LINE__);
#endif
}
#endif
void DiffieHellmanGroup(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
CHECK_EQ(args.Length(), 1);
@@ -115,12 +135,12 @@ void New(const FunctionCallbackInfo<Value>& args) {
if (bits < 2) {
#ifndef OPENSSL_IS_BORINGSSL
#if OPENSSL_VERSION_MAJOR >= 3
ERR_put_error(ERR_LIB_DH, 0, DH_R_MODULUS_TOO_SMALL, __FILE__, __LINE__);
PutDhError(DH_R_MODULUS_TOO_SMALL);
#else
ERR_put_error(ERR_LIB_BN, 0, BN_R_BITS_TOO_SMALL, __FILE__, __LINE__);
PutBnError(BN_R_BITS_TOO_SMALL);
#endif // OPENSSL_VERSION_MAJOR >= 3
#else // OPENSSL_IS_BORINGSSL
OPENSSL_PUT_ERROR(BN, BN_R_BITS_TOO_SMALL);
PutBnError(BN_R_BITS_TOO_SMALL);
#endif // OPENSSL_IS_BORINGSSL
return ThrowCryptoError(env, ERR_get_error(), "Invalid prime length");
}
@@ -134,11 +154,7 @@ void New(const FunctionCallbackInfo<Value>& args) {
}
int32_t generator = args[1].As<Int32>()->Value();
if (generator < 2) {
#ifndef OPENSSL_IS_BORINGSSL
ERR_put_error(ERR_LIB_DH, 0, DH_R_BAD_GENERATOR, __FILE__, __LINE__);
#else
OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR);
#endif
PutDhError(DH_R_BAD_GENERATOR);
return ThrowCryptoError(env, ERR_get_error(), "Invalid generator");
}
@@ -167,20 +183,12 @@ void New(const FunctionCallbackInfo<Value>& args) {
if (args[1]->IsInt32()) {
int32_t generator = args[1].As<Int32>()->Value();
if (generator < 2) {
#ifndef OPENSSL_IS_BORINGSSL
ERR_put_error(ERR_LIB_DH, 0, DH_R_BAD_GENERATOR, __FILE__, __LINE__);
#else
OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR);
#endif
PutDhError(DH_R_BAD_GENERATOR);
return ThrowCryptoError(env, ERR_get_error(), "Invalid generator");
}
bn_g = BignumPointer::New();
if (!bn_g.setWord(generator)) {
#ifndef OPENSSL_IS_BORINGSSL
ERR_put_error(ERR_LIB_DH, 0, DH_R_BAD_GENERATOR, __FILE__, __LINE__);
#else
OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR);
#endif
PutDhError(DH_R_BAD_GENERATOR);
return ThrowCryptoError(env, ERR_get_error(), "Invalid generator");
}
} else {
@@ -189,23 +197,22 @@ void New(const FunctionCallbackInfo<Value>& args) {
return THROW_ERR_OUT_OF_RANGE(env, "generator is too big");
bn_g = BignumPointer(reinterpret_cast<uint8_t*>(arg1.data()), arg1.size());
if (!bn_g) {
#ifndef OPENSSL_IS_BORINGSSL
ERR_put_error(ERR_LIB_DH, 0, DH_R_BAD_GENERATOR, __FILE__, __LINE__);
#else
OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR);
#endif
PutDhError(DH_R_BAD_GENERATOR);
return ThrowCryptoError(env, ERR_get_error(), "Invalid generator");
}
if (bn_g.getWord().has_value() && bn_g.getWord().value() < 2) {
#ifndef OPENSSL_IS_BORINGSSL
ERR_put_error(ERR_LIB_DH, 0, DH_R_BAD_GENERATOR, __FILE__, __LINE__);
#else
OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR);
#endif
PutDhError(DH_R_BAD_GENERATOR);
return ThrowCryptoError(env, ERR_get_error(), "Invalid generator");
}
}
#ifndef OPENSSL_IS_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");
}
#endif
auto dh = DHPointer::New(std::move(bn_p), std::move(bn_g));
if (!dh) {
return THROW_ERR_INVALID_ARG_VALUE(env, "Invalid DH parameters");
+25 -19
View File
@@ -187,15 +187,16 @@ void ECDH::ComputeSecret(const FunctionCallbackInfo<Value>& args) {
return;
}
int field_size = EC_GROUP_get_degree(ecdh->group_);
size_t out_len = (field_size + 7) / 8;
auto bs = ArrayBuffer::NewBackingStore(
env->isolate(), out_len, BackingStoreInitializationMode::kUninitialized);
if (!ECDH_compute_key(
bs->Data(), bs->ByteLength(), pub, ecdh->key_.get(), nullptr))
auto secret = ecdh->key_.computeSecret(pub);
if (!secret)
return THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Failed to compute ECDH key");
auto bs = ArrayBuffer::NewBackingStore(
env->isolate(),
secret.size(),
BackingStoreInitializationMode::kUninitialized);
memcpy(bs->Data(), secret.get(), secret.size());
Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
Local<Value> buffer;
if (!Buffer::New(env, ab, 0, ab->ByteLength()).ToLocal(&buffer)) return;
@@ -469,11 +470,14 @@ bool ExportJWKEcKey(Environment* env,
const auto& m_pkey = key.GetAsymmetricKey();
CHECK_EQ(m_pkey.id(), EVP_PKEY_EC);
const EC_KEY* ec = m_pkey;
CHECK_NOT_NULL(ec);
ECKeyPointer ec(m_pkey);
if (!ec) {
THROW_ERR_CRYPTO_INVALID_JWK(env, "Invalid JWK EC key");
return false;
}
const auto pub = ECKeyPointer::GetPublicKey(ec);
const auto group = ECKeyPointer::GetGroup(ec);
const auto pub = ec.getPublicKey();
const auto group = ec.getGroup();
int degree_bits = EC_GROUP_get_degree(group);
int degree_bytes =
@@ -538,7 +542,7 @@ bool ExportJWKEcKey(Environment* env,
}
if (key.GetKeyType() == kKeyTypePrivate) {
auto pvt = ECKeyPointer::GetPrivateKey(ec);
auto pvt = ec.getPrivateKey();
return SetEncodedValue(env, target, env->jwk_d_string(), pvt, degree_bytes)
.IsJust();
}
@@ -751,11 +755,12 @@ bool GetEcKeyDetail(Environment* env,
const auto& m_pkey = key.GetAsymmetricKey();
CHECK_EQ(m_pkey.id(), EVP_PKEY_EC);
const EC_KEY* ec = m_pkey;
CHECK_NOT_NULL(ec);
ECKeyPointer ec(m_pkey);
if (!ec) return true;
const auto group = ECKeyPointer::GetGroup(ec);
const auto group = ec.getGroup();
int nid = EC_GROUP_get_curve_name(group);
if (nid == NID_undef) return true;
return target
->Set(env->context(),
@@ -770,11 +775,12 @@ bool GetEcKeyDetail(Environment* env,
// https://github.com/chromium/chromium/blob/7af6cfd/components/webcrypto/algorithms/ecdsa.cc
size_t GroupOrderSize(const EVPKeyPointer& key) {
const EC_KEY* ec = key;
CHECK_NOT_NULL(ec);
ECKeyPointer ec(key);
if (!ec) return 0;
auto order = BignumPointer::New();
CHECK(order);
CHECK(EC_GROUP_get_order(ECKeyPointer::GetGroup(ec), order.get(), nullptr));
if (!order || !EC_GROUP_get_order(ec.getGroup(), order.get(), nullptr)) {
return 0;
}
return order.byteLength();
}
} // namespace crypto
+8 -1
View File
@@ -246,6 +246,13 @@ const EVP_MD* GetDigestImplementation(Environment* env,
#endif
}
void MarkInvalidXofLength() {
#if NCRYPTO_USE_OPENSSL3_PROVIDER
ERR_raise(ERR_LIB_EVP, EVP_R_NOT_XOF_OR_INVALID_LENGTH);
#else
EVPerr(EVP_F_EVP_DIGESTFINALXOF, EVP_R_NOT_XOF_OR_INVALID_LENGTH);
#endif
}
// crypto.digest(algorithm, algorithmId, algorithmCache,
// input, outputEncoding, outputEncodingId, outputLength)
void Hash::OneShotDigest(const FunctionCallbackInfo<Value>& args) {
@@ -441,7 +448,7 @@ bool Hash::HashInit(const EVP_MD* md, Maybe<unsigned int> xof_md_len) {
// This is a little hack to cause createHash to fail when an incorrect
// hashSize option was passed for a non-XOF hash function.
if (!mdctx_.hasXofFlag()) [[unlikely]] {
EVPerr(EVP_F_EVP_DIGESTFINALXOF, EVP_R_NOT_XOF_OR_INVALID_LENGTH);
MarkInvalidXofLength();
mdctx_.reset();
return false;
}
+45 -22
View File
@@ -385,11 +385,14 @@ bool KeyObjectData::ToEncodedPublicKey(
Mutex::ScopedLock lock(mutex());
const auto& pkey = GetAsymmetricKey();
if (pkey.id() == EVP_PKEY_EC) {
const EC_KEY* ec_key = pkey;
CHECK_NOT_NULL(ec_key);
ECKeyPointer ec_key(pkey);
if (!ec_key) {
THROW_ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS(env);
return false;
}
auto form = static_cast<point_conversion_form_t>(config.ec_point_form);
const auto group = ECKeyPointer::GetGroup(ec_key);
const auto point = ECKeyPointer::GetPublicKey(ec_key);
const auto group = ec_key.getGroup();
const auto point = ec_key.getPublicKey();
return ECPointToBuffer(env, group, point, form).ToLocal(out);
}
const int id = pkey.id();
@@ -431,14 +434,23 @@ bool KeyObjectData::ToEncodedPrivateKey(
Mutex::ScopedLock lock(mutex());
const auto& pkey = GetAsymmetricKey();
if (pkey.id() == EVP_PKEY_EC) {
const EC_KEY* ec_key = pkey;
CHECK_NOT_NULL(ec_key);
const BIGNUM* private_key = ECKeyPointer::GetPrivateKey(ec_key);
CHECK_NOT_NULL(private_key);
const auto group = ECKeyPointer::GetGroup(ec_key);
ECKeyPointer ec_key(pkey);
if (!ec_key) {
THROW_ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS(env);
return false;
}
const BIGNUM* private_key = ec_key.getPrivateKey();
if (private_key == nullptr) {
THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Failed to get EC private key");
return false;
}
const auto group = ec_key.getGroup();
auto order = BignumPointer::New();
CHECK(order);
CHECK(EC_GROUP_get_order(group, order.get(), nullptr));
if (!order || !EC_GROUP_get_order(group, order.get(), nullptr)) {
THROW_ERR_CRYPTO_OPERATION_FAILED(env,
"Failed to export EC private key");
return false;
}
auto buf = BignumPointer::EncodePadded(private_key, order.byteLength());
if (!buf) {
THROW_ERR_CRYPTO_OPERATION_FAILED(env,
@@ -629,7 +641,9 @@ static KeyObjectData ImportRawKey(Environment* env,
throw_invalid();
return {};
}
#if NCRYPTO_USE_LEGACY_KEY_TYPES
eckey.release();
#endif
return KeyObjectData::CreateAsymmetric(target_type, std::move(pkey));
}
@@ -1460,15 +1474,17 @@ void KeyObjectHandle::ExportECPublicRaw(
return THROW_ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS(env);
}
const EC_KEY* ec_key = m_pkey;
CHECK_NOT_NULL(ec_key);
ECKeyPointer ec_key(m_pkey);
if (!ec_key) {
return THROW_ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS(env);
}
CHECK(args[0]->IsInt32());
auto form =
static_cast<point_conversion_form_t>(args[0].As<Int32>()->Value());
const auto group = ECKeyPointer::GetGroup(ec_key);
const auto point = ECKeyPointer::GetPublicKey(ec_key);
const auto group = ec_key.getGroup();
const auto point = ec_key.getPublicKey();
Local<Object> buf;
if (!ECPointToBuffer(env, group, point, form).ToLocal(&buf)) return;
@@ -1491,16 +1507,23 @@ void KeyObjectHandle::ExportECPrivateRaw(
return THROW_ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS(env);
}
const EC_KEY* ec_key = m_pkey;
CHECK_NOT_NULL(ec_key);
ECKeyPointer ec_key(m_pkey);
if (!ec_key) {
return THROW_ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS(env);
}
const BIGNUM* private_key = ECKeyPointer::GetPrivateKey(ec_key);
CHECK_NOT_NULL(private_key);
const BIGNUM* private_key = ec_key.getPrivateKey();
if (private_key == nullptr) {
return THROW_ERR_CRYPTO_OPERATION_FAILED(env,
"Failed to get EC private key");
}
const auto group = ECKeyPointer::GetGroup(ec_key);
const auto group = ec_key.getGroup();
auto order = BignumPointer::New();
CHECK(order);
CHECK(EC_GROUP_get_order(group, order.get(), nullptr));
if (!order || !EC_GROUP_get_order(group, order.get(), nullptr)) {
return THROW_ERR_CRYPTO_OPERATION_FAILED(env,
"Failed to export EC private key");
}
auto buf = BignumPointer::EncodePadded(private_key, order.byteLength());
if (!buf) {
+10
View File
@@ -19,7 +19,9 @@ using ncrypto::DataPointer;
using ncrypto::Digest;
using ncrypto::EVPKeyCtxPointer;
using ncrypto::EVPKeyPointer;
#if NCRYPTO_USE_LEGACY_KEY_TYPES
using ncrypto::RSAPointer;
#endif
using v8::ArrayBuffer;
using v8::BackingStoreInitializationMode;
using v8::FunctionCallbackInfo;
@@ -353,6 +355,9 @@ KeyObjectData ImportJWKRsaKey(Environment* env, Local<Object> jwk) {
KeyType type = d_value->IsString() ? kKeyTypePrivate : kKeyTypePublic;
#if NCRYPTO_USE_OPENSSL3_PROVIDER
ncrypto::Rsa rsa_view;
#else
RSAPointer rsa(RSA_new());
if (!rsa) {
THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Unable to create RSA pointer");
@@ -360,6 +365,7 @@ KeyObjectData ImportJWKRsaKey(Environment* env, Local<Object> jwk) {
}
ncrypto::Rsa rsa_view(rsa.get());
#endif
ByteSource n = ByteSource::FromEncodedString(env, n_value.As<String>());
ByteSource e = ByteSource::FromEncodedString(env, e_value.As<String>());
@@ -421,7 +427,11 @@ KeyObjectData ImportJWKRsaKey(Environment* env, Local<Object> jwk) {
}
}
#if NCRYPTO_USE_OPENSSL3_PROVIDER
auto pkey = EVPKeyPointer::NewRSA(rsa_view);
#else
auto pkey = EVPKeyPointer::NewRSA(std::move(rsa));
#endif
if (!pkey) {
THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Unable to create key pointer");
return {};
+4
View File
@@ -874,7 +874,11 @@ void TLSWrap::ClearOut() {
return;
const char* ls = ERR_lib_error_string(ssl_err);
#if NCRYPTO_USE_OPENSSL3_PROVIDER
const char* fs = nullptr;
#else
const char* fs = ERR_func_error_string(ssl_err);
#endif
const char* rs = ERR_reason_error_string(ssl_err);
if (!Set(env(), obj, env()->library_string(), ls) ||
!Set(env(), obj, env()->function_string(), fs) ||
+4 -4
View File
@@ -12,10 +12,6 @@
#include "util-inl.h"
#include "v8.h"
#ifndef OPENSSL_NO_ENGINE
#include <openssl/engine.h>
#endif // !OPENSSL_NO_ENGINE
#include "math.h"
#if OPENSSL_VERSION_MAJOR >= 3
@@ -544,7 +540,11 @@ Maybe<void> Decorate(Environment* env,
if (err == 0) return JustVoid(); // No decoration necessary.
const char* ls = ERR_lib_error_string(err);
#if NCRYPTO_USE_OPENSSL3_PROVIDER
const char* fs = nullptr;
#else
const char* fs = ERR_func_error_string(err);
#endif
const char* rs = ERR_reason_error_string(err);
Isolate* isolate = env->isolate();
+9 -18
View File
@@ -20,7 +20,6 @@ using ncrypto::BIOPointer;
using ncrypto::ClearErrorOnReturn;
using ncrypto::DataPointer;
using ncrypto::Digest;
using ncrypto::ECKeyPointer;
using ncrypto::SSLPointer;
using ncrypto::X509Name;
using ncrypto::X509Pointer;
@@ -668,17 +667,10 @@ static MaybeLocal<Value> GetX509NameObject(Environment* env,
}
MaybeLocal<Object> GetPubKey(Environment* env, const ncrypto::Rsa& rsa) {
int size = i2d_RSA_PUBKEY(rsa, nullptr);
CHECK_GE(size, 0);
auto bs = ArrayBuffer::NewBackingStore(
env->isolate(), size, BackingStoreInitializationMode::kUninitialized);
auto serialized = reinterpret_cast<unsigned char*>(bs->Data());
CHECK_GE(i2d_RSA_PUBKEY(rsa, &serialized), 0);
auto ab = ArrayBuffer::New(env->isolate(), std::move(bs));
return Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Object>());
auto bio = rsa.derPublicKey();
Local<Value> ret;
if (!ToBuffer(env, &bio).ToLocal(&ret)) return {};
return ret.As<Object>();
}
MaybeLocal<Value> GetModulusString(Environment* env, const BIGNUM* n) {
@@ -698,14 +690,13 @@ MaybeLocal<Value> GetExponentString(Environment* env, const BIGNUM* e) {
return ToV8Value(env->context(), bio);
}
MaybeLocal<Value> GetECPubKey(Environment* env,
const EC_GROUP* group,
OSSL3_CONST EC_KEY* ec) {
const auto pubkey = ECKeyPointer::GetPublicKey(ec);
MaybeLocal<Value> GetECPubKey(Environment* env, const ncrypto::Ec& ec) {
const auto group = ec.getGroup();
const auto pubkey = ec.getPublicKey();
if (pubkey == nullptr) [[unlikely]]
return Undefined(env->isolate());
return ECPointToBuffer(env, group, pubkey, EC_KEY_get_conv_form(ec))
return ECPointToBuffer(env, group, pubkey, ec.getPointConversionForm())
.FromMaybe(Local<Object>());
}
@@ -792,7 +783,7 @@ MaybeLocal<Object> X509ToObject(Environment* env, const X509View& cert) {
cert.ifEc([&](const ncrypto::Ec& ec) {
const auto group = ec.getGroup();
values[7] = GetECPubKey(env, group, ec); // pubkey
values[7] = GetECPubKey(env, ec); // pubkey
values[8] = GetECGroupBits(env, group); // bits
const int nid = ec.getCurve();
if (nid != 0) {
+5
View File
@@ -50,6 +50,11 @@
#if HAVE_OPENSSL
#include "ncrypto.h"
#include "node_crypto.h"
#if OPENSSL_VERSION_MAJOR >= 3 && !defined(CONF_MFLAGS_IGNORE_MISSING_FILE)
// OpenSSL hides this deprecated macro under OPENSSL_NO_DEPRECATED, but the
// non-deprecated OPENSSL_INIT settings API still accepts the flag value.
#define CONF_MFLAGS_IGNORE_MISSING_FILE 0x10
#endif
#endif
#if defined(NODE_HAVE_I18N_SUPPORT)
+50
View File
@@ -39,8 +39,58 @@
#if HAVE_OPENSSL
#include <openssl/ec.h>
#include <openssl/ssl.h>
#if !defined(RSA_PKCS1_PADDING)
#define RSA_PKCS1_PADDING 1
#endif
#if !defined(RSA_SSLV23_PADDING)
#define RSA_SSLV23_PADDING 2
#endif
#if !defined(RSA_NO_PADDING)
#define RSA_NO_PADDING 3
#endif
#if !defined(RSA_PKCS1_OAEP_PADDING)
#define RSA_PKCS1_OAEP_PADDING 4
#endif
#if !defined(RSA_X931_PADDING)
#define RSA_X931_PADDING 5
#endif
#if !defined(RSA_PKCS1_PSS_PADDING)
#define RSA_PKCS1_PSS_PADDING 6
#endif
#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_MAJOR >= 3
// OpenSSL hides these deprecated DH check constants under
// OPENSSL_NO_DEPRECATED, but the numeric verifyError values remain public API.
#if !defined(DH_CHECK_P_NOT_PRIME)
#define DH_CHECK_P_NOT_PRIME 0x01
#endif
#if !defined(DH_CHECK_P_NOT_SAFE_PRIME)
#define DH_CHECK_P_NOT_SAFE_PRIME 0x02
#endif
#if !defined(DH_UNABLE_TO_CHECK_GENERATOR)
#define DH_UNABLE_TO_CHECK_GENERATOR 0x04
#endif
#if !defined(DH_NOT_SUITABLE_GENERATOR)
#define DH_NOT_SUITABLE_GENERATOR 0x08
#endif
#endif
#ifndef OPENSSL_NO_ENGINE
#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_MAJOR >= 3
// Engine constants remain public API while engine implementation lives in the
// dedicated compatibility target.
#define ENGINE_METHOD_RSA (unsigned int)0x0001
#define ENGINE_METHOD_DSA (unsigned int)0x0002
#define ENGINE_METHOD_DH (unsigned int)0x0004
#define ENGINE_METHOD_RAND (unsigned int)0x0008
#define ENGINE_METHOD_CIPHERS (unsigned int)0x0040
#define ENGINE_METHOD_DIGESTS (unsigned int)0x0080
#define ENGINE_METHOD_PKEY_METHS (unsigned int)0x0200
#define ENGINE_METHOD_PKEY_ASN1_METHS (unsigned int)0x0400
#define ENGINE_METHOD_EC (unsigned int)0x0800
#define ENGINE_METHOD_ALL (unsigned int)0xFFFF
#define ENGINE_METHOD_NONE (unsigned int)0x0000
#else
#include <openssl/engine.h>
#endif
#endif // !OPENSSL_NO_ENGINE
#endif // HAVE_OPENSSL
+57
View File
@@ -5,6 +5,11 @@ if (!common.hasCrypto)
const assert = require('assert');
const crypto = require('crypto');
const { hasOpenSSL } = require('../common/crypto');
const {
DH_CHECK_P_NOT_PRIME,
DH_CHECK_P_NOT_SAFE_PRIME,
} = crypto.constants;
// Second OAKLEY group, see
// https://github.com/nodejs/node-v0.x-archive/issues/2338 and
@@ -15,12 +20,64 @@ const p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' +
'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF';
crypto.createDiffieHellman(p, 'hex');
if (!process.features.openssl_is_boringssl) {
const notPrime = Buffer.from(p, 'hex');
notPrime[notPrime.length - 1] = 0xfd;
assert.strictEqual(
crypto.createDiffieHellman(notPrime, Buffer.from([2])).verifyError,
DH_CHECK_P_NOT_PRIME);
const notSafePrime = Buffer.from(
'd2d6d13e1c1e0bbb63c742199dee010411f089ac74f0f7213348388280700fd6' +
'0ef9c1e7b096a4257dcbce61c544a5d1d23db4c49c63ce302f63be5cf5804327',
'hex');
assert.strictEqual(
crypto.createDiffieHellman(notSafePrime, Buffer.from([2])).verifyError,
DH_CHECK_P_NOT_SAFE_PRIME);
const group = crypto.getDiffieHellman('modp14');
const alice = crypto.createDiffieHellman(
group.getPrime(), group.getGenerator());
alice.generateKeys();
const groupPrime = BigInt(`0x${group.getPrime('hex')}`);
assert.throws(
() => alice.computeSecret(Buffer.from([1])),
{
code: 'ERR_CRYPTO_INVALID_KEYLEN',
message: 'Supplied key is too small'
});
assert.throws(
() => alice.computeSecret(group.getPrime()),
{
code: 'ERR_CRYPTO_INVALID_KEYLEN',
message: 'Supplied key is too large'
});
assert.throws(
() => alice.computeSecret(
Buffer.from((groupPrime - 1n).toString(16), 'hex')),
{
code: 'ERR_CRYPTO_INVALID_KEYLEN',
message: 'Supplied key is too large'
});
}
// Confirm DH_check() results are exposed for optional examination.
const bad_dh = process.features.openssl_is_boringssl ?
crypto.createDiffieHellman('abcd', 'hex', 0) :
crypto.createDiffieHellman('02', 'hex');
assert.notStrictEqual(bad_dh.verifyError, 0);
if (hasOpenSSL(3)) {
const smallSafePrime = crypto.createDiffieHellman(
Buffer.from([23]), Buffer.from([2]));
assert.notStrictEqual(smallSafePrime.verifyError, 0);
assert.throws(
() => crypto.createDiffieHellman(Buffer.from(p, 'hex'),
Buffer.from(p, 'hex')),
{ code: 'ERR_OSSL_DH_BAD_GENERATOR' });
}
const availableCurves = new Set(crypto.getCurves());
const availableHashes = new Set(crypto.getHashes());
+35
View File
@@ -909,6 +909,41 @@ if (!process.features.openssl_is_boringssl) {
}
}
}
const der = publicKey.export({ format: 'der', type: 'spki' });
const saltLengthParam = Buffer.from([0xa2, 0x03, 0x02, 0x01, 0x10]);
const saltLengthOffset = der.indexOf(saltLengthParam);
assert.notStrictEqual(saltLengthOffset, -1);
const importMalformedPublicKey = common.mustCall((key) => {
const malformedKey = createPublicKey({
key,
format: 'der',
type: 'spki'
});
assert.strictEqual(malformedKey.asymmetricKeyType, 'rsa-pss');
assert.strictEqual(malformedKey.asymmetricKeyDetails.modulusLength, 2048);
assert.strictEqual(malformedKey.asymmetricKeyDetails.publicExponent,
65537n);
}, 2);
{
const negativeSaltLength = Buffer.from(der);
negativeSaltLength[saltLengthOffset + saltLengthParam.length - 1] = 0x80;
importMalformedPublicKey(negativeSaltLength);
}
{
const oversizedSaltLength = Buffer.concat([
der.subarray(0, saltLengthOffset),
Buffer.from([0xa2, 0x0b, 0x02, 0x09, 1, 0, 0, 0, 0, 0, 0, 0, 0x10]),
der.subarray(saltLengthOffset + saltLengthParam.length),
]);
oversizedSaltLength.writeUInt16BE(der.readUInt16BE(2) + 8, 2);
oversizedSaltLength[5] = der[5] + 8;
oversizedSaltLength[18] = der[18] + 8;
importMalformedPublicKey(oversizedSaltLength);
}
}
{
@@ -23,6 +23,9 @@ connect({
return cleanup();
}));
// Invalid dhparam input is silently discarded for compatibility.
tls.createSecureContext({ dhparam: fixtures.readKey('ec-key.pem') });
connect({
client: {
servername: 'agent1',