From fad87284e820366c5134a8679081c3999ed443c4 Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Thu, 3 Dec 2026 23:47:45 +0100 Subject: [PATCH 1/2] quic,dtls: share groups configuration with node:tls Signed-off-by: Tim Perry --- doc/api/dtls.md | 2 + doc/api/quic.md | 14 +--- lib/internal/dtls/dtls.js | 9 +- lib/internal/quic/quic.js | 12 +-- lib/internal/tls/negotiation.js | 39 +++++++++ lib/internal/tls/secure-context.js | 16 ++-- lib/quic.js | 2 - node.gyp | 2 + src/crypto/crypto_context.cc | 3 +- src/crypto/crypto_tls_negotiation.cc | 12 +++ src/crypto/crypto_tls_negotiation.h | 16 ++++ src/dtls/dtls_context.cc | 9 +- src/quic/session.cc | 2 - src/quic/tlscontext.cc | 3 +- src/quic/tlscontext.h | 5 +- test/parallel/test-dtls-tls-defaults.mjs | 82 +++++++++++++++++++ ...test-quic-connect-first-flight-failure.mjs | 11 ++- test/parallel/test-quic-exports-constants.mjs | 5 +- test/parallel/test-quic-exports.mjs | 1 - test/parallel/test-quic-tls-defaults.mjs | 68 +++++++++++++++ test/parallel/test-quic-tls-options.mjs | 6 +- test/parallel/test-tls-default-ecdh-curve.js | 33 ++++++++ 22 files changed, 297 insertions(+), 55 deletions(-) create mode 100644 lib/internal/tls/negotiation.js create mode 100644 src/crypto/crypto_tls_negotiation.cc create mode 100644 src/crypto/crypto_tls_negotiation.h create mode 100644 test/parallel/test-dtls-tls-defaults.mjs create mode 100644 test/parallel/test-quic-tls-defaults.mjs create mode 100644 test/parallel/test-tls-default-ecdh-curve.js diff --git a/doc/api/dtls.md b/doc/api/dtls.md index a3012026cebb..f489bac99115 100644 --- a/doc/api/dtls.md +++ b/doc/api/dtls.md @@ -277,6 +277,7 @@ changes: select DTLS 1.3 cipher suites; the rest select DTLS 1.2 cipher suites. See [Protocol versions][]. * `ecdhCurve` {string} Named curve or curve list for ECDH. + **Default:** [`tls.DEFAULT_ECDH_CURVE`][]. * `isServer` {boolean} Build a context for a server. **Default:** `false`. * `key` {string|Buffer} Private key in PEM format. * `maxVersion` {string} Newest protocol version to offer. See @@ -1448,6 +1449,7 @@ The minimum allowed MTU is 256 bytes. The maximum is 65535. [`session.reused`]: #sessionreused [`session.send()`]: #sessionsenddata [`session.session`]: #sessionsession +[`tls.DEFAULT_ECDH_CURVE`]: tls.md#tlsdefault_ecdh_curve [`tls.TLSSocket.getPeerCertificate()`]: tls.md#tlssocketgetpeercertificatedetailed [`tls.TLSSocket.getPeerX509Certificate()`]: tls.md#tlssocketgetpeerx509certificate [`tls.createSecureContext()`]: tls.md#tlscreatesecurecontextoptions diff --git a/doc/api/quic.md b/doc/api/quic.md index 1cf4f86c2479..c8b1a76a33c5 100644 --- a/doc/api/quic.md +++ b/doc/api/quic.md @@ -597,13 +597,6 @@ Congestion control algorithm identifiers, for use with the The default TLS 1.3 cipher suite list used when [`sessionOptions.ciphers`][] is not specified. -### `quic.constants.DEFAULT_GROUPS` - -* {string} - -The default TLS 1.3 key-exchange group list used when -[`sessionOptions.groups`][] is not specified. - ## Class: `QuicEndpoint` A `QuicEndpoint` encapsulates the local UDP-port binding for QUIC. It can be @@ -3282,9 +3275,10 @@ is available. Set to `false` to disable early data support. added: v23.8.0 --> -* Type: {string} +* Type: {string} **Default:** [`tls.DEFAULT_ECDH_CURVE`][] -The list of supported TLS 1.3 cipher groups. +A colon-separated list of supported key exchange groups, in order of +preference, or `'auto'` for OpenSSL's default list. #### `sessionOptions.keylog` @@ -4919,7 +4913,6 @@ throughput issues caused by flow control. [`sessionOptions.cc`]: #sessionoptionscc [`sessionOptions.ciphers`]: #sessionoptionsciphers [`sessionOptions.datagramDropPolicy`]: #sessionoptionsdatagramdroppolicy -[`sessionOptions.groups`]: #sessionoptionsgroups [`sessionOptions.keylog`]: #sessionoptionskeylog [`sessionOptions.qlog`]: #sessionoptionsqlog [`sessionOptions.sessionTicket`]: #sessionoptionssessionticket @@ -4943,6 +4936,7 @@ throughput issues caused by flow control. [`stream.setPriority()`]: #streamsetpriorityoptions [`stream.stopSending()`]: #streamstopsendingcode [`stream.writer`]: #streamwriter +[`tls.DEFAULT_ECDH_CURVE`]: tls.md#tlsdefault_ecdh_curve [`writer.fail()`]: #streamwriter [`writer.fail(reason)`]: #streamwriter [minimal HTTP/3 server]: #minimal-http3-server diff --git a/lib/internal/dtls/dtls.js b/lib/internal/dtls/dtls.js index 7102bc84fa36..458b0efbd32c 100644 --- a/lib/internal/dtls/dtls.js +++ b/lib/internal/dtls/dtls.js @@ -99,6 +99,10 @@ const { kSessionTicket, } = require('internal/dtls/symbols'); +const { + resolveGroups, +} = require('internal/tls/negotiation'); + const { DTLSContext: DTLSContext_, DTLSEndpoint: DTLSEndpoint_, @@ -939,10 +943,7 @@ function createContext(options = kEmptyObject) { context.setProtocolVersions(kProtocolVersionValues[versions.min], kProtocolVersionValues[versions.max]); - // ECDH curve (default: 'auto' = OpenSSL default selection) - const ecdhCurve = options.ecdhCurve || 'auto'; - validateString(ecdhCurve, 'options.ecdhCurve'); - context.setECDHCurve(ecdhCurve); + context.setECDHCurve(resolveGroups(options.ecdhCurve, 'options.ecdhCurve')); // ALPN protocols if (options.alpn !== undefined) { diff --git a/lib/internal/quic/quic.js b/lib/internal/quic/quic.js index 729000fdd935..ec2e4536dffc 100644 --- a/lib/internal/quic/quic.js +++ b/lib/internal/quic/quic.js @@ -58,7 +58,6 @@ const { CC_ALGO_CUBIC_STR: CC_ALGO_CUBIC, CC_ALGO_BBR_STR: CC_ALGO_BBR, DEFAULT_CIPHERS, - DEFAULT_GROUPS, // Internal constants for use by the implementation. // These are not exposed to end users. @@ -151,6 +150,10 @@ const { InternalX509Certificate, } = require('internal/crypto/x509'); +const { + resolveGroups, +} = require('internal/tls/negotiation'); + const { FileHandle, kHandle: kFileHandle, @@ -4910,7 +4913,7 @@ function processTlsOptions(tls, forServer) { servername, alpn, ciphers = DEFAULT_CIPHERS, - groups = DEFAULT_GROUPS, + groups: groupsOption, keylog = false, verifyClient = false, rejectUnauthorized = true, @@ -4932,9 +4935,7 @@ function processTlsOptions(tls, forServer) { if (ciphers !== undefined) { validateString(ciphers, 'options.ciphers'); } - if (groups !== undefined) { - validateString(groups, 'options.groups'); - } + const groups = resolveGroups(groupsOption, 'options.groups'); validateBoolean(keylog, 'options.keylog'); validateBoolean(verifyClient, 'options.verifyClient'); validateBoolean(rejectUnauthorized, 'options.rejectUnauthorized'); @@ -5469,7 +5470,6 @@ module.exports = { CC_ALGO_CUBIC, CC_ALGO_BBR, DEFAULT_CIPHERS, - DEFAULT_GROUPS, // These are exported only for internal testing purposes. getQuicStreamState, getQuicSessionState, diff --git a/lib/internal/tls/negotiation.js b/lib/internal/tls/negotiation.js new file mode 100644 index 000000000000..e385c8970362 --- /dev/null +++ b/lib/internal/tls/negotiation.js @@ -0,0 +1,39 @@ +'use strict'; + +const { + StringPrototypeTrim, +} = primordials; + +const { + codes: { + ERR_INVALID_ARG_VALUE, + }, +} = require('internal/errors'); + +const { + validateString, +} = require('internal/validators'); + +// The process-wide default for every (D)TLS and QUIC context. It can be +// changed at runtime, so is read when each context is created. +function getDefaultEcdhCurve() { + return require('tls').DEFAULT_ECDH_CURVE || 'auto'; +} + +// The option's value, or the process-wide default when it is omitted. OpenSSL +// accepts an empty list, leaving no groups and so no key exchange; only +// node:tls, for compatibility, passes allowEmpty. +function resolveGroups(groups, name, allowEmpty = false) { + if (groups === undefined) { + groups = getDefaultEcdhCurve(); + name = 'tls.DEFAULT_ECDH_CURVE'; + } + validateString(groups, name); + if (!allowEmpty && StringPrototypeTrim(groups) === '') + throw new ERR_INVALID_ARG_VALUE(name, groups, 'must name at least one group'); + return groups; +} + +module.exports = { + resolveGroups, +}; diff --git a/lib/internal/tls/secure-context.js b/lib/internal/tls/secure-context.js index a4336c98026c..9c92cedc5acc 100644 --- a/lib/internal/tls/secure-context.js +++ b/lib/internal/tls/secure-context.js @@ -37,6 +37,10 @@ const { toBuf, } = require('internal/crypto/util'); +const { + resolveGroups, +} = require('internal/tls/negotiation'); + const { crypto: { TLS1_2_VERSION, @@ -44,13 +48,6 @@ const { }, } = internalBinding('constants'); -function getDefaultEcdhCurve() { - // We do it this way because DEFAULT_ECDH_CURVE can be - // changed by users, so we need to grab the current - // value, but we want the evaluation to be lazy. - return require('tls').DEFAULT_ECDH_CURVE || 'auto'; -} - function getDefaultCiphers() { // We do it this way because DEFAULT_CIPHERS can be // changed by users, so we need to grab the current @@ -156,7 +153,7 @@ function configSecureContext(context, options = kEmptyObject, name = 'options') ciphers = getDefaultCiphers(), crl, dhparam, - ecdhCurve = getDefaultEcdhCurve(), + ecdhCurve, key, passphrase, pfx, @@ -270,8 +267,7 @@ function configSecureContext(context, options = kEmptyObject, name = 'options') context.setSigalgs(sigalgs); } - validateString(ecdhCurve, `${name}.ecdhCurve`); - context.setECDHCurve(ecdhCurve); + context.setECDHCurve(resolveGroups(ecdhCurve, `${name}.ecdhCurve`, true)); if (dhparam !== undefined && dhparam !== null) { validateKeyOrCertOption(`${name}.dhparam`, dhparam); diff --git a/lib/quic.js b/lib/quic.js index 90f3a6addf0d..cf42263ec271 100644 --- a/lib/quic.js +++ b/lib/quic.js @@ -17,7 +17,6 @@ const { CC_ALGO_CUBIC, CC_ALGO_BBR, DEFAULT_CIPHERS, - DEFAULT_GROUPS, } = require('internal/quic/quic'); const cc = { @@ -29,7 +28,6 @@ const cc = { const constants = { get cc() { return cc; }, get DEFAULT_CIPHERS() { return DEFAULT_CIPHERS; }, - get DEFAULT_GROUPS() { return DEFAULT_GROUPS; }, }; module.exports = { diff --git a/node.gyp b/node.gyp index 3d7c29c6bdb8..2666f2a9de1e 100644 --- a/node.gyp +++ b/node.gyp @@ -410,6 +410,7 @@ 'src/crypto/crypto_client_hello.cc', 'src/crypto/crypto_context.cc', 'src/crypto/crypto_tls_certificates.cc', + 'src/crypto/crypto_tls_negotiation.cc', 'src/crypto/crypto_ec.cc', 'src/crypto/crypto_kem.cc', 'src/crypto/crypto_hmac.cc', @@ -451,6 +452,7 @@ 'src/crypto/crypto_tls.h', 'src/crypto/crypto_context.h', 'src/crypto/crypto_tls_certificates.h', + 'src/crypto/crypto_tls_negotiation.h', 'src/crypto/crypto_ec.h', 'src/crypto/crypto_hkdf.h', 'src/crypto/crypto_pbkdf2.h', diff --git a/src/crypto/crypto_context.cc b/src/crypto/crypto_context.cc index 6010b90d581f..3e4a0f68ae42 100644 --- a/src/crypto/crypto_context.cc +++ b/src/crypto/crypto_context.cc @@ -4,6 +4,7 @@ #include "crypto/crypto_common.h" #include "crypto/crypto_pkcs12.h" #include "crypto/crypto_tls_certificates.h" +#include "crypto/crypto_tls_negotiation.h" #include "crypto/crypto_util.h" #include "env-inl.h" #include "memory_tracker-inl.h" @@ -2067,7 +2068,7 @@ void SecureContext::SetECDHCurve(const FunctionCallbackInfo& args) { Utf8Value curve(env->isolate(), args[0]); - if (curve != "auto" && !SSL_CTX_set1_curves_list(sc->ctx_.get(), *curve)) { + if (!SetGroups(sc->ctx_, *curve)) { return THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Failed to set ECDH curve"); } } diff --git a/src/crypto/crypto_tls_negotiation.cc b/src/crypto/crypto_tls_negotiation.cc new file mode 100644 index 000000000000..ebb1661b7568 --- /dev/null +++ b/src/crypto/crypto_tls_negotiation.cc @@ -0,0 +1,12 @@ +#include "crypto/crypto_tls_negotiation.h" + +#include + +namespace node::crypto { + +bool SetGroups(const ncrypto::SSLCtxPointer& ctx, const char* groups) { + if (strcmp(groups, "auto") == 0) return true; + return SSL_CTX_set1_groups_list(ctx.get(), groups) == 1; +} + +} // namespace node::crypto diff --git a/src/crypto/crypto_tls_negotiation.h b/src/crypto/crypto_tls_negotiation.h new file mode 100644 index 000000000000..beb4295e7d72 --- /dev/null +++ b/src/crypto/crypto_tls_negotiation.h @@ -0,0 +1,16 @@ +#ifndef SRC_CRYPTO_CRYPTO_TLS_NEGOTIATION_H_ +#define SRC_CRYPTO_CRYPTO_TLS_NEGOTIATION_H_ + +#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#include "ncrypto.h" + +namespace node::crypto { + +// Set the supported key exchange groups. "auto" keeps OpenSSL's default list. +bool SetGroups(const ncrypto::SSLCtxPointer& ctx, const char* groups); + +} // namespace node::crypto + +#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +#endif // SRC_CRYPTO_CRYPTO_TLS_NEGOTIATION_H_ diff --git a/src/dtls/dtls_context.cc b/src/dtls/dtls_context.cc index ef2e7b5d891d..cbbfab75be7c 100644 --- a/src/dtls/dtls_context.cc +++ b/src/dtls/dtls_context.cc @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -1081,14 +1082,12 @@ void DTLSContext::SetECDHCurve(const FunctionCallbackInfo& args) { ASSIGN_OR_RETURN_UNWRAP(&ctx, args.This()); Environment* env = ctx->env(); + ncrypto::ClearErrorOnReturn clear_error_on_return; CHECK(args[0]->IsString()); Utf8Value curve(env->isolate(), args[0]); - // "auto" means use OpenSSL's default curve selection. - if (strcmp(*curve, "auto") != 0) { - if (!SSL_CTX_set1_curves_list(ctx->ctx_.get(), *curve)) { - return THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Failed to set ECDH curve"); - } + if (!crypto::SetGroups(ctx->ctx_, *curve)) { + return THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Failed to set ECDH curve"); } } diff --git a/src/quic/session.cc b/src/quic/session.cc index c1b803b3f205..074a623521c6 100644 --- a/src/quic/session.cc +++ b/src/quic/session.cc @@ -4541,8 +4541,6 @@ void Session::InitPerContext(Realm* realm, Local target) { NODE_DEFINE_STRING_CONSTANT( target, "DEFAULT_CIPHERS", TLSContext::DEFAULT_CIPHERS); - NODE_DEFINE_STRING_CONSTANT( - target, "DEFAULT_GROUPS", TLSContext::DEFAULT_GROUPS); #define V(name, _) IDX_STATS_SESSION_##name, enum SessionStatsIdx { SESSION_STATS(V) IDX_STATS_SESSION_COUNT }; diff --git a/src/quic/tlscontext.cc b/src/quic/tlscontext.cc index 267e9fe02dde..5468a1019598 100644 --- a/src/quic/tlscontext.cc +++ b/src/quic/tlscontext.cc @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -592,7 +593,7 @@ SSLCtxPointer TLSContext::Initialize(Environment* env) { return SSLCtxPointer(); } - if (SSL_CTX_set1_groups_list(ctx.get(), options_.groups.c_str()) != 1) { + if (!crypto::SetGroups(ctx, options_.groups.c_str())) { validation_error_ = "Invalid cipher groups"; return SSLCtxPointer(); } diff --git a/src/quic/tlscontext.h b/src/quic/tlscontext.h index db4c7e97843c..07437e7a3abb 100644 --- a/src/quic/tlscontext.h +++ b/src/quic/tlscontext.h @@ -211,7 +211,6 @@ class TLSContext final : public MemoryRetainer, "TLS_AES_256_GCM_SHA384:" "TLS_CHACHA20_POLY1305_" "SHA256:TLS_AES_128_CCM_SHA256"; - static constexpr auto DEFAULT_GROUPS = "X25519:P-256:P-384:P-521"; struct Options final : public MemoryRetainer { // The SNI servername to use for this session. This option is only used by @@ -226,8 +225,8 @@ class TLSContext final : public MemoryRetainer, // The list of TLS ciphers to use for this session. std::string ciphers = DEFAULT_CIPHERS; - // The list of TLS groups to use for this session. - std::string groups = DEFAULT_GROUPS; + // The key exchange groups. "auto" keeps OpenSSL's defaults. + std::string groups = "auto"; // TLS certificate compression (RFC 8879) preference, packed by the JS // layer as (length | alg0<<8 | alg1<<16 | alg2<<24). Algorithm IDs match diff --git a/test/parallel/test-dtls-tls-defaults.mjs b/test/parallel/test-dtls-tls-defaults.mjs new file mode 100644 index 000000000000..025dd234be10 --- /dev/null +++ b/test/parallel/test-dtls-tls-defaults.mjs @@ -0,0 +1,82 @@ +// Flags: --experimental-dtls --no-warnings + +// Test: DTLS takes its curve default from node:tls, reading it when each +// context is created. + +import { hasCrypto, mustCall, mustNotCall, skip } from '../common/index.mjs'; +import * as fixtures from '../common/fixtures.mjs'; +import assert from 'node:assert'; +import tls from 'node:tls'; + +if (!hasCrypto) { + skip('missing crypto'); +} + +if (!process.features.dtls) { + skip('DTLS is not enabled'); +} + +const { connect, createSecureContext, listen } = await import('node:dtls'); + +const HOST = '127.0.0.1'; +const cert = fixtures.readKey('agent1-cert.pem').toString(); +const key = fixtures.readKey('agent1-key.pem').toString(); + +const V13 = { minVersion: 'DTLSv1.3', maxVersion: 'DTLSv1.3' }; + +async function handshake(serverOptions, clientOptions) { + const endpoint = listen((session) => { + session.onerror = () => {}; + }, { cert, key, host: HOST, port: 0, ...serverOptions }); + const client = connect(HOST, endpoint.address.port, { + rejectUnauthorized: false, handshakeTimeout: 2000, ...clientOptions, + }); + try { + await client.opened; + const cipher = client.cipher.name; + await client.close(); + return cipher; + } finally { + client.destroy(); + await endpoint.close(); + } +} + +async function withDefault(name, value, fn) { + const saved = tls[name]; + tls[name] = value; + try { + return await fn(); + } finally { + tls[name] = saved; + } +} + +// The server's groups come from the default; a client offering none of them +// cannot complete a handshake. DTLS 1.3 is used as every handshake needs a key +// share, whereas DTLS 1.2 can fall back to a suite without ECDHE. +await withDefault('DEFAULT_ECDH_CURVE', 'P-384', mustCall(async () => { + const server = { ...V13 }; + assert.ok(await handshake(server, { ...V13, ecdhCurve: 'P-384' })); + await assert.rejects(handshake(server, { ...V13, ecdhCurve: 'P-256' }), + /handshake failure/); +})); + +// OpenSSL accepts an empty group list, which leaves no key exchange at all. +for (const ecdhCurve of ['', ' ']) { + assert.throws(() => createSecureContext({ ecdhCurve }), { + code: 'ERR_INVALID_ARG_VALUE', + }); +} +assert.throws(() => createSecureContext({ ecdhCurve: null }), { + code: 'ERR_INVALID_ARG_TYPE', +}); + +await withDefault('DEFAULT_ECDH_CURVE', 'not-a-curve', mustCall(async () => { + assert.throws(() => createSecureContext(), { + code: 'ERR_CRYPTO_OPERATION_FAILED', + }); + assert.throws(() => listen(mustNotCall(), { + cert, key, host: HOST, port: 0, + }), { code: 'ERR_CRYPTO_OPERATION_FAILED' }); +})); diff --git a/test/parallel/test-quic-connect-first-flight-failure.mjs b/test/parallel/test-quic-connect-first-flight-failure.mjs index aab291bb72bb..16247810b2de 100644 --- a/test/parallel/test-quic-connect-first-flight-failure.mjs +++ b/test/parallel/test-quic-connect-first-flight-failure.mjs @@ -11,9 +11,14 @@ if (!hasQuic) { const { connect } = await import('../common/quic.mjs'); -// An empty list leaves the ClientHello without a cipher suite or a group, and -// a handshakeTimeout of 0 has already expired once the first flight is out. -const cases = [{ ciphers: '' }, { groups: '' }, { handshakeTimeout: 0 }]; +// An empty cipher list leaves the ClientHello without a cipher suite, +// brainpoolP256r1 is a TLS 1.2 group so leaves it without a key share, and a +// handshakeTimeout of 0 has already expired once the first flight is out. +const cases = [ + { ciphers: '' }, + { groups: 'brainpoolP256r1' }, + { handshakeTimeout: 0 }, +]; for (const options of cases) { await assert.rejects(connect('127.0.0.1:1', options), { code: 'ERR_QUIC_CONNECTION_FAILED', diff --git a/test/parallel/test-quic-exports-constants.mjs b/test/parallel/test-quic-exports-constants.mjs index c176e980e250..c9e225a219d9 100644 --- a/test/parallel/test-quic-exports-constants.mjs +++ b/test/parallel/test-quic-exports-constants.mjs @@ -29,9 +29,8 @@ assert.strictEqual(typeof quic.constants.DEFAULT_CIPHERS, 'string'); assert.ok(quic.constants.DEFAULT_CIPHERS.length > 0); assert.ok(quic.constants.DEFAULT_CIPHERS.includes('TLS_AES_128_GCM_SHA256')); -// DEFAULT_GROUPS. -assert.strictEqual(typeof quic.constants.DEFAULT_GROUPS, 'string'); -assert.ok(quic.constants.DEFAULT_GROUPS.length > 0); +// The group default is node:tls's, so QUIC exports none of its own. +assert.strictEqual(quic.constants.DEFAULT_GROUPS, undefined); // QuicEndpoint can be constructed directly. // QuicSession and QuicStream cannot — they throw ERR_ILLEGAL_CONSTRUCTOR. diff --git a/test/parallel/test-quic-exports.mjs b/test/parallel/test-quic-exports.mjs index 71771624e31e..f4a8b99eb1aa 100644 --- a/test/parallel/test-quic-exports.mjs +++ b/test/parallel/test-quic-exports.mjs @@ -27,7 +27,6 @@ assert.strictEqual(quic.constants.cc.BBR, 'bbr'); assert.strictEqual(quic.constants.DEFAULT_CIPHERS, 'TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:' + 'TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_CCM_SHA256'); -assert.strictEqual(quic.constants.DEFAULT_GROUPS, 'X25519:P-256:P-384:P-521'); // Ensure the constants are.. well, constant. assert.throws(() => { quic.constants.cc.RENO = 'foo'; }, TypeError); diff --git a/test/parallel/test-quic-tls-defaults.mjs b/test/parallel/test-quic-tls-defaults.mjs new file mode 100644 index 000000000000..39688b41577e --- /dev/null +++ b/test/parallel/test-quic-tls-defaults.mjs @@ -0,0 +1,68 @@ +// Flags: --experimental-quic --no-warnings + +// Test: QUIC takes its key exchange group default from node:tls. + +import { hasQuic, skip, mustCall } from '../common/index.mjs'; +import assert from 'node:assert'; +import tls from 'node:tls'; + +if (!hasQuic) { + skip('QUIC is not enabled'); +} + +const { listen, connect } = await import('../common/quic.mjs'); + +async function handshake(serverOptions = {}, clientOptions = {}) { + const endpoint = await listen(mustCall(async (session) => { + await session.opened; + session.close(); + }), serverOptions); + const session = await connect(endpoint.address, { + servername: 'localhost', + ...clientOptions, + }); + await session.opened; + const { ephemeralKeyInfo } = session; + await session.closed; + await endpoint.close(); + return { ephemeralKeyInfo }; +} + +async function withDefault(name, value, fn) { + const saved = tls[name]; + tls[name] = value; + try { + return await fn(); + } finally { + tls[name] = saved; + } +} + +// By default, key exchange uses a hybrid post-quantum group. +{ + const { ephemeralKeyInfo } = await handshake(); + assert.strictEqual(ephemeralKeyInfo.name, 'X25519MLKEM768'); +} + +// The default is read from node:tls when each context is created. +await withDefault('DEFAULT_ECDH_CURVE', 'P-256', mustCall(async () => { + const { ephemeralKeyInfo } = await handshake(); + assert.strictEqual(ephemeralKeyInfo.name, 'prime256v1'); +})); + +const unreachable = '127.0.0.1:1'; + +// OpenSSL accepts an empty group list, which leaves no key exchange at all. +await assert.rejects(connect(unreachable, { groups: '' }), { + code: 'ERR_INVALID_ARG_VALUE', +}); +await assert.rejects(connect(unreachable, { groups: 'not-a-group' }), { + code: 'ERR_INVALID_STATE', + message: /Invalid cipher groups/, +}); +await withDefault('DEFAULT_ECDH_CURVE', 'not-a-group', mustCall(async () => { + await assert.rejects(connect(unreachable), { + code: 'ERR_INVALID_STATE', + message: /Invalid cipher groups/, + }); +})); diff --git a/test/parallel/test-quic-tls-options.mjs b/test/parallel/test-quic-tls-options.mjs index 36adc5799336..4d37de49f287 100644 --- a/test/parallel/test-quic-tls-options.mjs +++ b/test/parallel/test-quic-tls-options.mjs @@ -3,7 +3,7 @@ // Test: custom TLS ciphers and groups. // Custom ciphers option on the server/client. // Custom groups option on the server/client. -// Default ciphers/groups used when not specified. +// Default ciphers used when not specified. import { hasQuic, skip, mustCall } from '../common/index.mjs'; import assert from 'node:assert'; @@ -73,10 +73,8 @@ const cert = fixtures.readKey('agent1-cert.pem'); await serverEndpoint.close(); } -// Default ciphers/groups are non-empty strings from constants. +// The default ciphers are a non-empty string from constants. { assert.strictEqual(typeof constants.DEFAULT_CIPHERS, 'string'); assert.ok(constants.DEFAULT_CIPHERS.length > 0); - assert.strictEqual(typeof constants.DEFAULT_GROUPS, 'string'); - assert.ok(constants.DEFAULT_GROUPS.length > 0); } diff --git a/test/parallel/test-tls-default-ecdh-curve.js b/test/parallel/test-tls-default-ecdh-curve.js new file mode 100644 index 000000000000..091bca8b235f --- /dev/null +++ b/test/parallel/test-tls-default-ecdh-curve.js @@ -0,0 +1,33 @@ +'use strict'; + +// Test: tls.DEFAULT_ECDH_CURVE behaves as an ordinary assignable export, and +// is read when each context is created. + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const tls = require('tls'); + +assert.strictEqual(tls.DEFAULT_ECDH_CURVE, 'auto'); +assert.ok(Object.keys(tls).includes('DEFAULT_ECDH_CURVE')); + +for (const value of ['P-256', '', 'auto']) { + tls.DEFAULT_ECDH_CURVE = value; + assert.strictEqual(tls.DEFAULT_ECDH_CURVE, value); + tls.createSecureContext(); +} + +tls.DEFAULT_ECDH_CURVE = 'not-a-curve'; +assert.throws(() => tls.createSecureContext(), { + code: 'ERR_CRYPTO_OPERATION_FAILED', + message: 'Failed to set ECDH curve', +}); +tls.createSecureContext({ ecdhCurve: 'P-256' }); + +tls.DEFAULT_ECDH_CURVE = 42; +assert.throws(() => tls.createSecureContext(), { + code: 'ERR_INVALID_ARG_TYPE', + message: /tls\.DEFAULT_ECDH_CURVE/, +}); From 75a0e9718417ea61b7a3fc2b451300982146e044 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Thu, 3 Dec 2026 16:41:53 +0000 Subject: [PATCH 2/2] deps: buffer 0-RTT packets until the ClientHello is processed ngtcp2 discarded a 0-RTT packet that arrived after the first Initial packet but before the 0-RTT key was installed. That happens when the ClientHello spans several Initial packets, or when the handshake is interrupted, as the QUIC server does to emit the new session. Buffer the packet until the Handshake key is installed instead. Assisted-by: Claude Opus 5.5 --- deps/ngtcp2/ngtcp2/lib/ngtcp2_conn.c | 12 +++- .../test-quic-zero-rtt-split-client-hello.mjs | 61 +++++++++++++++++++ 2 files changed, 71 insertions(+), 2 deletions(-) create mode 100644 test/parallel/test-quic-zero-rtt-split-client-hello.mjs diff --git a/deps/ngtcp2/ngtcp2/lib/ngtcp2_conn.c b/deps/ngtcp2/ngtcp2/lib/ngtcp2_conn.c index 374274b567c2..61f1ebe1d40d 100644 --- a/deps/ngtcp2/ngtcp2/lib/ngtcp2_conn.c +++ b/deps/ngtcp2/ngtcp2/lib/ngtcp2_conn.c @@ -6808,10 +6808,18 @@ conn_recv_handshake_pkt(ngtcp2_conn *conn, const ngtcp2_path *path, if (nread2 < 0) { return nread2; } + + return (ngtcp2_ssize)pktlen; } - /* Discard 0-RTT packet if we don't have a key to decrypt it. */ - return (ngtcp2_ssize)pktlen; + /* Discard 0-RTT packet if we don't have a key to decrypt it and + the ClientHello has been processed. Until then (the + ClientHello spans several Initial packets, or the TLS stack + interrupted the handshake), the 0-RTT key might still be + installed, so buffer the packet. */ + if (!conn->hs_pktns || conn->hs_pktns->crypto.rx.ckm) { + return (ngtcp2_ssize)pktlen; + } } /* Buffer re-ordered 0-RTT packet. */ diff --git a/test/parallel/test-quic-zero-rtt-split-client-hello.mjs b/test/parallel/test-quic-zero-rtt-split-client-hello.mjs new file mode 100644 index 000000000000..66126c4f8d3e --- /dev/null +++ b/test/parallel/test-quic-zero-rtt-split-client-hello.mjs @@ -0,0 +1,61 @@ +// Flags: --experimental-quic --no-warnings + +// Test: 0-RTT data is accepted when the ClientHello spans more than one +// Initial packet. The X25519MLKEM768 key share makes the ClientHello too +// large for one packet, and the 0-RTT packet is coalesced with the last +// Initial packet while the server's handshake is paused for the new +// session callback. A datagram is used because it is not retransmitted. + +import { hasQuic, skip, mustCall } from '../common/index.mjs'; +import assert from 'node:assert'; + +if (!hasQuic) { + skip('QUIC is not enabled'); +} + +const { listen, connect } = await import('../common/quic.mjs'); + +const groups = 'X25519MLKEM768'; +const transportParams = { maxDatagramFrameSize: 1200 }; + +const gotTicket = Promise.withResolvers(); +const gotToken = Promise.withResolvers(); +const serverGotDatagram = Promise.withResolvers(); + +let serverSessionCount = 0; +const serverEndpoint = await listen(mustCall((serverSession) => { + if (++serverSessionCount === 2) { + serverSession.ondatagram = mustCall((data, early) => { + serverGotDatagram.resolve({ data: Buffer.from(data), early }); + }); + } +}, 2), { groups, transportParams }); + +const cs1 = await connect(serverEndpoint.address, { + groups, + transportParams, + onsessionticket: mustCall((ticket) => gotTicket.resolve(ticket)), + onnewtoken: mustCall((token) => gotToken.resolve(token)), +}); +await cs1.opened; +const [sessionTicket, token] = + await Promise.all([gotTicket.promise, gotToken.promise]); +await cs1.close(); + +const cs2 = await connect(serverEndpoint.address, { + groups, + transportParams, + sessionTicket, + token, +}); +await cs2.sendDatagram(new Uint8Array([0xCA, 0xFE])); + +const info = await cs2.opened; +assert.strictEqual(info.earlyDataAccepted, true); + +const { data, early } = await serverGotDatagram.promise; +assert.deepStrictEqual(data, Buffer.from([0xCA, 0xFE])); +assert.strictEqual(early, true); + +await cs2.close(); +await serverEndpoint.close();