GeezerVison is showing github.com — crypto: prevent stale OpenSSL errors · nodejs/node@0c4d131
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: deps/ncrypto/ncrypto.cc +4Lines changed: 4 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -933,6 +933,7 @@ int64_t PortableTimeGM(struct tm* t) { | 933 | 933 | // SPKAC | 934 | 934 |
| 935 | 935 | bool VerifySpkac(const char* input, size_t length) { | | 936 | + ClearErrorOnReturn clear_error_on_return; | 936 | 937 | #ifdef OPENSSL_IS_BORINGSSL | 937 | 938 | // OpenSSL uses EVP_DecodeBlock, which explicitly removes trailing characters, | 938 | 939 | // while BoringSSL uses EVP_DecodedLength and EVP_DecodeBase64, which do not. | @@ -951,6 +952,7 @@ bool VerifySpkac(const char* input, size_t length) { | 951 | 952 | } | 952 | 953 |
| 953 | 954 | BIOPointer ExportPublicKey(const char* input, size_t length) { | | 955 | + ClearErrorOnReturn clear_error_on_return; | 954 | 956 | BIOPointer bio(BIO_new(BIO_s_mem())); | 955 | 957 | if (!bio) return {}; | 956 | 958 |
| @@ -972,6 +974,7 @@ BIOPointer ExportPublicKey(const char* input, size_t length) { | 972 | 974 | } | 973 | 975 |
| 974 | 976 | Buffer<char> ExportChallenge(const char* input, size_t length) { | | 977 | + ClearErrorOnReturn clear_error_on_return; | 975 | 978 | #ifdef OPENSSL_IS_BORINGSSL | 976 | 979 | // OpenSSL uses EVP_DecodeBlock, which explicitly removes trailing characters, | 977 | 980 | // while BoringSSL uses EVP_DecodedLength and EVP_DecodeBase64, which do not. | @@ -4542,6 +4545,7 @@ bool ECKeyHasMissingOid(const EVPKeyPointer& key) { | 4542 | 4545 | EVPKeyPointer::ParseKeyResult EVPKeyPointer::TryParsePrivateKey( | 4543 | 4546 | const PrivateKeyEncodingConfig& config, | 4544 | 4547 | const Buffer<const unsigned char>& buffer) { | | 4548 | + ERR_clear_error(); | 4545 | 4549 | static constexpr auto keyOrError = [](EVPKeyPointer pkey, | 4546 | 4550 | bool had_passphrase = false) { | 4547 | 4551 | if (unsigned long err = ERR_peek_error()) { // NOLINT(runtime/int) | |
Collapse file Copy file name to clipboardExpand all lines: src/crypto/crypto_keys.cc +3Lines changed: 3 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -21,6 +21,7 @@ namespace node { | 21 | 21 |
| 22 | 22 | using ncrypto::BignumPointer; | 23 | 23 | using ncrypto::BIOPointer; | | 24 | +using ncrypto::ClearErrorOnReturn; | 24 | 25 | using ncrypto::ECKeyPointer; | 25 | 26 | using ncrypto::ECPointPointer; | 26 | 27 | using ncrypto::EVPKeyCtxPointer; | @@ -680,6 +681,7 @@ static KeyObjectData ImportRawKey(Environment* env, | 680 | 681 | // Shared helper for importing a JWK asymmetric key. Extracts kty from the | 681 | 682 | // JWK object and dispatches to the appropriate importer. | 682 | 683 | static KeyObjectData ImportJWKFromArgs(Environment* env, Local<Object> jwk) { | | 684 | + ClearErrorOnReturn clear_error_on_return; | 683 | 685 | Local<Value> kty; | 684 | 686 | if (!jwk->Get(env->context(), env->jwk_kty_string()).ToLocal(&kty) || | 685 | 687 | !kty->IsString()) { | @@ -1311,6 +1313,7 @@ void KeyObjectHandle::Equals(const FunctionCallbackInfo<Value>& args) { | 1311 | 1313 | case kKeyTypePublic: | 1312 | 1314 | // Fall through | 1313 | 1315 | case kKeyTypePrivate: { | | 1316 | + ClearErrorOnReturn clear_error_on_return; | 1314 | 1317 | EVP_PKEY* pkey = key.GetAsymmetricKey().get(); | 1315 | 1318 | EVP_PKEY* pkey2 = key2.GetAsymmetricKey().get(); | 1316 | 1319 | #ifndef OPENSSL_IS_BORINGSSL | |
Collapse file Copy file name to clipboardExpand all lines: src/crypto/crypto_tls.cc +26Lines changed: 26 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -73,6 +73,20 @@ namespace crypto { | 73 | 73 |
| 74 | 74 | namespace { | 75 | 75 |
| | 76 | +void InjectOpenSSLErrorForTesting(const FunctionCallbackInfo<Value>&) { | | 77 | +#if NCRYPTO_USE_OPENSSL_PROVIDER | | 78 | + ERR_raise(ERR_LIB_USER, ERR_R_INTERNAL_ERROR); | | 79 | +#elif NCRYPTO_USE_BORINGSSL | | 80 | + ERR_put_error(ERR_LIB_USER, 0, ERR_R_INTERNAL_ERROR, __FILE__, __LINE__); | | 81 | +#else | | 82 | +#error "Unsupported crypto backend" | | 83 | +#endif | | 84 | +} | | 85 | + | | 86 | +void HasOpenSSLErrorForTesting(const FunctionCallbackInfo<Value>& args) { | | 87 | + args.GetReturnValue().Set(ERR_peek_error() != 0); | | 88 | +} | | 89 | + | 76 | 90 | // Our custom implementation of the certificate verify callback | 77 | 91 | // used when establishing a TLS handshake. Because we cannot perform | 78 | 92 | // I/O quickly enough with X509_STORE_CTX_ APIs in this callback, | @@ -883,6 +897,7 @@ void TLSWrap::ClearOut() { | 883 | 897 | for (;;) { | 884 | 898 | { | 885 | 899 | SSLLibraryCallScope ssl_library_call_scope(this); | | 900 | + if (ERR_set_mark() != 0) ERR_clear_error(); | 886 | 901 | read = SSL_read(ssl_.get(), out + length, kClearOutChunkSize - length); | 887 | 902 | } | 888 | 903 | Debug(this, "Read %d bytes of cleartext output", read); | @@ -1016,6 +1031,7 @@ void TLSWrap::ClearIn() { | 1016 | 1031 | int written; | 1017 | 1032 | { | 1018 | 1033 | SSLLibraryCallScope ssl_library_call_scope(this); | | 1034 | + if (ERR_set_mark() != 0) ERR_clear_error(); | 1019 | 1035 | written = SSL_write(ssl_.get(), bs->Data(), bs->ByteLength()); | 1020 | 1036 | } | 1021 | 1037 | Debug(this, "Writing %zu bytes, written = %d", bs->ByteLength(), written); | @@ -1214,6 +1230,7 @@ int TLSWrap::DoWrite(WriteWrap* w, | 1214 | 1230 | NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(length); | 1215 | 1231 | { | 1216 | 1232 | SSLLibraryCallScope ssl_library_call_scope(this); | | 1233 | + if (ERR_set_mark() != 0) ERR_clear_error(); | 1217 | 1234 | written = SSL_write(ssl_.get(), bs->Data(), length); | 1218 | 1235 | } | 1219 | 1236 | } else { | @@ -1222,6 +1239,7 @@ int TLSWrap::DoWrite(WriteWrap* w, | 1222 | 1239 | NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(buf->len); | 1223 | 1240 | { | 1224 | 1241 | SSLLibraryCallScope ssl_library_call_scope(this); | | 1242 | + if (ERR_set_mark() != 0) ERR_clear_error(); | 1225 | 1243 | written = SSL_write(ssl_.get(), buf->base, buf->len); | 1226 | 1244 | } | 1227 | 1245 |
| @@ -2351,6 +2369,12 @@ void TLSWrap::Initialize( | 2351 | 2369 | Isolate* isolate = env->isolate(); | 2352 | 2370 |
| 2353 | 2371 | SetMethod(context, target, "wrap", TLSWrap::Wrap); | | 2372 | + SetMethod(context, | | 2373 | + target, | | 2374 | + "injectOpenSSLErrorForTesting", | | 2375 | + InjectOpenSSLErrorForTesting); | | 2376 | + SetMethodNoSideEffect( | | 2377 | + context, target, "hasOpenSSLErrorForTesting", HasOpenSSLErrorForTesting); | 2354 | 2378 |
| 2355 | 2379 | NODE_DEFINE_CONSTANT(target, HAVE_SSL_TRACE); | 2356 | 2380 |
| @@ -2445,6 +2469,8 @@ void TLSWrap::Initialize( | 2445 | 2469 | void TLSWrap::RegisterExternalReferences(ExternalReferenceRegistry* registry) { | 2446 | 2470 | registry->Register(TLSWrap::Wrap); | 2447 | 2471 | registry->Register(GetWriteQueueSize); | | 2472 | + registry->Register(InjectOpenSSLErrorForTesting); | | 2473 | + registry->Register(HasOpenSSLErrorForTesting); | 2448 | 2474 |
| 2449 | 2475 | registry->Register(CertCbDone); | 2450 | 2476 | registry->Register(ClientHelloDone); | |
Collapse file Copy file name to clipboardExpand all lines: test/cctest/test_node_crypto.cc +54Lines changed: 54 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -71,6 +71,16 @@ std::string BioContents(const ncrypto::BIOPointer& bio) { | 71 | 71 | return std::string(mem->data, mem->length); | 72 | 72 | } | 73 | 73 |
| | 74 | +void RaiseTestError() { | | 75 | +#if NCRYPTO_USE_OPENSSL_PROVIDER | | 76 | + ERR_raise(ERR_LIB_USER, ERR_R_INTERNAL_ERROR); | | 77 | +#elif NCRYPTO_USE_BORINGSSL | | 78 | + ERR_put_error(ERR_LIB_USER, 0, ERR_R_INTERNAL_ERROR, __FILE__, __LINE__); | | 79 | +#else | | 80 | +#error "Unsupported crypto backend" | | 81 | +#endif | | 82 | +} | | 83 | + | 74 | 84 | } // namespace | 75 | 85 |
| 76 | 86 | /* | @@ -102,6 +112,50 @@ TEST(NodeCrypto, TryGetIntCipherOutputLength) { | 102 | 112 | 0, static_cast<size_t>(INT_MAX) + 1, &output_len)); | 103 | 113 | } | 104 | 114 |
| | 115 | +TEST(NodeCrypto, SpkacOperationsClearErrorQueue) { | | 116 | + ncrypto::ClearErrorOnReturn clear_errors; | | 117 | + constexpr std::string_view invalid = "garbage"; | | 118 | + | | 119 | + EXPECT_FALSE(ncrypto::VerifySpkac(invalid.data(), invalid.size())); | | 120 | + EXPECT_EQ(ERR_peek_error(), 0UL); | | 121 | + | | 122 | + EXPECT_FALSE(ncrypto::ExportPublicKey(invalid.data(), invalid.size())); | | 123 | + EXPECT_EQ(ERR_peek_error(), 0UL); | | 124 | + | | 125 | + const auto challenge = | | 126 | + ncrypto::ExportChallenge(invalid.data(), invalid.size()); | | 127 | + EXPECT_EQ(challenge.data, nullptr); | | 128 | + EXPECT_EQ(challenge.len, 0UL); | | 129 | + EXPECT_EQ(ERR_peek_error(), 0UL); | | 130 | +} | | 131 | + | | 132 | +TEST(NodeCrypto, PrivateKeyParsingIgnoresUnrelatedErrors) { | | 133 | + ncrypto::ClearErrorOnReturn clear_errors; | | 134 | + auto ctx = EVPKeyCtxPointer::NewFromAlgorithm(KeyAlgorithm::RSA); | | 135 | + ASSERT_TRUE(ctx); | | 136 | + ASSERT_TRUE(ctx.initForKeygen()); | | 137 | + ASSERT_TRUE(ctx.setRsaKeygenBits(2048)); | | 138 | + EVP_PKEY* raw = nullptr; | | 139 | + ASSERT_EQ(EVP_PKEY_keygen(ctx.get(), &raw), 1); | | 140 | + EVPKeyPointer key(raw); | | 141 | + | | 142 | + const EVPKeyPointer::PrivateKeyEncodingConfig config( | | 143 | + false, | | 144 | + EVPKeyPointer::PKFormatType::PEM, | | 145 | + EVPKeyPointer::PKEncodingType::PKCS8); | | 146 | + auto encoded = key.writePrivateKey(config); | | 147 | + ASSERT_TRUE(encoded); | | 148 | + const BUF_MEM* mem = encoded.value; | | 149 | + ASSERT_NE(mem, nullptr); | | 150 | + | | 151 | + RaiseTestError(); | | 152 | + ASSERT_NE(ERR_peek_error(), 0UL); | | 153 | + auto parsed = EVPKeyPointer::TryParsePrivateKey( | | 154 | + config, {reinterpret_cast<const unsigned char*>(mem->data), mem->length}); | | 155 | + EXPECT_TRUE(parsed); | | 156 | + EXPECT_EQ(ERR_peek_error(), 0UL); | | 157 | +} | | 158 | + | 105 | 159 | TEST(NodeCrypto, KeyAlgorithmNames) { | 106 | 160 | EXPECT_EQ(KeyAlgorithm::FromName("rsa-pss"), &KeyAlgorithm::RSA_PSS); | 107 | 161 | EXPECT_EQ(KeyAlgorithm::FromName("ML-DSA-44"), &KeyAlgorithm::ML_DSA_44); | |
Collapse file Copy file name to clipboardExpand all lines: test/cctest/test_node_crypto_env.cc +50Lines changed: 50 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -35,6 +35,56 @@ TEST_F(NodeCryptoEnv, LoadBIO) { | 35 | 35 | "any errors on the OpenSSL error stack\n"; | 36 | 36 | } | 37 | 37 |
| | 38 | +TEST_F(NodeCryptoEnv, KeyObjectEqualsClearsErrorQueue) { | | 39 | + v8::HandleScope handle_scope(isolate_); | | 40 | + Argv argv; | | 41 | + Env env{handle_scope, argv}; | | 42 | + | | 43 | + ERR_clear_error(); | | 44 | + auto result = node::LoadEnvironment(*env, R"JS( | | 45 | + const { generateKeyPairSync } = require('node:crypto'); | | 46 | + const rsa = generateKeyPairSync('rsa', { modulusLength: 2048 }); | | 47 | + const ec = generateKeyPairSync('ec', { namedCurve: 'P-256' }); | | 48 | + return rsa.publicKey.equals(ec.publicKey); | | 49 | + )JS") | | 50 | + .ToLocalChecked(); | | 51 | + EXPECT_TRUE(result->IsFalse()); | | 52 | + EXPECT_EQ(ERR_peek_error(), 0UL); | | 53 | +} | | 54 | + | | 55 | +TEST_F(NodeCryptoEnv, InvalidEcJwkClearsErrorQueue) { | | 56 | + v8::HandleScope handle_scope(isolate_); | | 57 | + Argv argv; | | 58 | + Env env{handle_scope, argv}; | | 59 | + | | 60 | + ERR_clear_error(); | | 61 | + auto result = node::LoadEnvironment(*env, R"JS( | | 62 | + const { diffieHellman, generateKeyPairSync } = require('node:crypto'); | | 63 | + const { privateKey } = generateKeyPairSync( | | 64 | + 'ec', { namedCurve: 'P-256' }); | | 65 | + try { | | 66 | + diffieHellman({ | | 67 | + privateKey, | | 68 | + publicKey: { | | 69 | + key: { | | 70 | + kty: 'EC', | | 71 | + crv: 'P-256', | | 72 | + x: 'AAAA', | | 73 | + y: 'AAAA', | | 74 | + }, | | 75 | + format: 'jwk', | | 76 | + }, | | 77 | + }); | | 78 | + return false; | | 79 | + } catch (error) { | | 80 | + return error.code === 'ERR_CRYPTO_INVALID_JWK'; | | 81 | + } | | 82 | + )JS") | | 83 | + .ToLocalChecked(); | | 84 | + EXPECT_TRUE(result->IsTrue()); | | 85 | + EXPECT_EQ(ERR_peek_error(), 0UL); | | 86 | +} | | 87 | + | 38 | 88 | #if NCRYPTO_USE_OPENSSL_PROVIDER | 39 | 89 | TEST_F(NodeCryptoEnv, ExportIncompleteRsaPrivateKeyAsJwk) { | 40 | 90 | v8::HandleScope handle_scope(isolate_); | |
Collapse file Copy file name to clipboardExpand all lines: test/parallel/test-crypto-encap-decap.js +1-1Lines changed: 1 addition & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -111,7 +111,7 @@ for (const [name, { | 111 | 111 | }] of Object.entries(keys)) { | 112 | 112 | if (!supported) { | 113 | 113 | assert.throws(() => crypto.encapsulate(publicKey), | 114 | | - { code: /ERR_OSSL_EVP_DECODE_ERROR|ERR_OSSL_EVP_UNSUPPORTED_ALGORITHM|ERR_CRYPTO_OPERATION_FAILED/ }); | | 114 | + { code: /ERR_OSSL_UNSUPPORTED|ERR_OSSL_PEM_NO_START_LINE|ERR_CRYPTO_OPERATION_FAILED/ }); | 115 | 115 | continue; | 116 | 116 | } | 117 | 117 |
| |
Collapse file Copy file name to clipboard +46Lines changed: 46 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +'use strict'; | | 2 | + | | 3 | +const common = require('../common'); | | 4 | +if (!common.hasCrypto) | | 5 | + common.skip('missing crypto'); | | 6 | + | | 7 | +const assert = require('node:assert'); | | 8 | +const { | | 9 | + Certificate, | | 10 | + createPrivateKey, | | 11 | + createPublicKey, | | 12 | + diffieHellman, | | 13 | + generateKeyPairSync, | | 14 | +} = require('node:crypto'); | | 15 | +const fixtures = require('../common/fixtures'); | | 16 | + | | 17 | +const privateKeyPem = fixtures.readKey('rsa_private.pem'); | | 18 | +const rsaPublicKey = createPublicKey(fixtures.readKey('rsa_public.pem')); | | 19 | +const ec = generateKeyPairSync('ec', { namedCurve: 'P-256' }); | | 20 | + | | 21 | +function parseValidPrivateKey() { | | 22 | + // This must not pick up an error from the preceding operation. | | 23 | + createPrivateKey(privateKeyPem); | | 24 | +} | | 25 | + | | 26 | +assert.strictEqual(rsaPublicKey.equals(ec.publicKey), false); | | 27 | +parseValidPrivateKey(); | | 28 | + | | 29 | +for (const method of ['verifySpkac', 'exportPublicKey', 'exportChallenge']) { | | 30 | + Certificate[method](Buffer.from('garbage')); | | 31 | + parseValidPrivateKey(); | | 32 | +} | | 33 | + | | 34 | +assert.throws(() => diffieHellman({ | | 35 | + privateKey: ec.privateKey, | | 36 | + publicKey: { | | 37 | + key: { | | 38 | + kty: 'EC', | | 39 | + crv: 'P-256', | | 40 | + x: 'AAAA', | | 41 | + y: 'AAAA', | | 42 | + }, | | 43 | + format: 'jwk', | | 44 | + }, | | 45 | +}), { code: 'ERR_CRYPTO_INVALID_JWK' }); | | 46 | +parseValidPrivateKey(); |
Collapse file Copy file name to clipboardExpand all lines: test/parallel/test-crypto-pqc-key-objects-ml-dsa.js +1-1Lines changed: 1 addition & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -102,7 +102,7 @@ for (const [asymmetricKeyType, pubLen] of [ | 102 | 102 |
| 103 | 103 | if (!hasOpenSSL(3, 5) && !isBoringSSL) { | 104 | 104 | assert.throws(() => createPublicKey(keys.public), { | 105 | | - code: 'ERR_OSSL_EVP_DECODE_ERROR', | | 105 | + code: 'ERR_OSSL_UNSUPPORTED', | 106 | 106 | }); | 107 | 107 |
| 108 | 108 | for (const pem of [keys.private, keys.private_seed_only, keys.private_priv_only]) { | |
Collapse file Copy file name to clipboardExpand all lines: test/parallel/test-crypto-pqc-key-objects-ml-kem.js +2-2Lines changed: 2 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -102,7 +102,7 @@ for (const [asymmetricKeyType, pubLen] of [ | 102 | 102 |
| 103 | 103 | if (!hasOpenSSL(3, 5) && !isBoringSSL) { | 104 | 104 | assert.throws(() => createPublicKey(keys.public), { | 105 | | - code: 'ERR_OSSL_EVP_DECODE_ERROR', | | 105 | + code: 'ERR_OSSL_UNSUPPORTED', | 106 | 106 | }); | 107 | 107 |
| 108 | 108 | for (const pem of [keys.private, keys.private_seed_only, keys.private_priv_only]) { | @@ -113,7 +113,7 @@ for (const [asymmetricKeyType, pubLen] of [ | 113 | 113 | } else if (isBoringSSL && asymmetricKeyType === 'ml-kem-512') { | 114 | 114 | // BoringSSL does not support ML-KEM-512. | 115 | 115 | assert.throws(() => createPublicKey(keys.public), | 116 | | - { code: 'ERR_OSSL_EVP_UNSUPPORTED_ALGORITHM' }); | | 116 | + { code: 'ERR_OSSL_PEM_NO_START_LINE' }); | 117 | 117 | for (const pem of [keys.private, keys.private_seed_only, keys.private_priv_only]) { | 118 | 118 | assert.throws(() => createPrivateKey(pem), | 119 | 119 | { code: 'ERR_OSSL_EVP_UNSUPPORTED_ALGORITHM' }); | |
Collapse file Copy file name to clipboardExpand all lines: test/parallel/test-crypto-pqc-key-objects-slh-dsa.js +1-1Lines changed: 1 addition & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -101,7 +101,7 @@ for (const asymmetricKeyType of [ | 101 | 101 |
| 102 | 102 | if (!hasOpenSSL(3, 5)) { | 103 | 103 | assert.throws(() => createPublicKey(keys.public), { | 104 | | - code: isBoringSSL ? 'ERR_OSSL_EVP_UNSUPPORTED_ALGORITHM' : 'ERR_OSSL_EVP_DECODE_ERROR', | | 104 | + code: isBoringSSL ? 'ERR_OSSL_PEM_NO_START_LINE' : 'ERR_OSSL_UNSUPPORTED', | 105 | 105 | }); | 106 | 106 |
| 107 | 107 | assert.throws(() => createPrivateKey(keys.private), { | |
|