From 118c40f922ba51b10dcb9ddb805b83a244fa22f0 Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Mon, 16 Nov 2026 12:55:12 +0100 Subject: [PATCH] tls: docs-deprecate TLS renegotiation, add allowRenegotiation opt-in For now this changes very little, but offers an option to directly control whether this is supported. In future, this will default to 'false' (disabling by default) and eventually be mostly removed, except opt-in client support for accepting renegotiation requests from servers. Signed-off-by: Tim Perry --- doc/api/deprecations.md | 52 +++++++ doc/api/errors.md | 4 +- doc/api/https.md | 3 +- doc/api/tls.md | 45 ++++++ lib/https.js | 4 + lib/internal/tls/wrap.js | 48 ++++++ src/crypto/crypto_tls.cc | 29 ++++ src/crypto/crypto_tls.h | 5 + test/doctool/test-doc-api-json.mjs | 2 +- test/parallel/test-https-agent-getname.js | 11 +- test/parallel/test-tls-allow-renegotiation.js | 139 ++++++++++++++++++ ...t-tls-renegotiation-pending-deprecation.js | 106 +++++++++++++ 12 files changed, 441 insertions(+), 7 deletions(-) create mode 100644 test/parallel/test-tls-allow-renegotiation.js create mode 100644 test/parallel/test-tls-renegotiation-pending-deprecation.js diff --git a/doc/api/deprecations.md b/doc/api/deprecations.md index b31bfffc11bc..669d1d276130 100644 --- a/doc/api/deprecations.md +++ b/doc/api/deprecations.md @@ -4861,6 +4861,55 @@ Type: Documentation-only `node:util`'s `util.TextDecoder` and `util.TextEncoder` are deprecated. Use global `TextDecoder` and `TextEncoder` instead. +### DEP0213: TLS renegotiation + + + +Type: Documentation-only (supports [`--pending-deprecation`][]) + +TLS renegotiation is deprecated and will be disabled by default in future. +This functionality will be largely removed in a subsequent release. Only a +client accepting server-initiated renegotiation requests is expected to +remain supported, and on an opt-in basis for legacy server compatibility. + +This only affects TLS 1.2. TLS 1.3 removed renegotiation from the standard, +and so this has never been supported. + +Avoid using TLS renegotiation. A server that needs a client certificate should +request it in the initial configuration, with the `requestCert` option of +[`tls.createServer()`][]. A client that needs to change the configuration of +an existing connection should create a new connection. + +This affects multiple TLS APIs: + +* Node.js TLS clients needing to initiate renegotiation locally, or accept + renegotiation requested by the server, should opt in by setting the + `allowRenegotiation` option of [`tls.connect()`][]. +* Node.js TLS servers needing to initiate renegotiation locally, or accept + renegotiation requested by the client, should opt in by setting the + `allowRenegotiation` option of [`tls.createServer()`][]. + If renegotiation by clients is removed in future, setting this option to + `true` on a server will throw an error. +* In either case, initiating renegotiation ([`tlsSocket.renegotiate()`][]) + should be avoided by using alternative mechanisms. When renegotiation is + disabled by default this method will only work on connections created + with the `allowRenegotiation` option, and will throw an error if not. + If initiating renegotiation is removed in future, this method will throw + an error. +* Using [`tlsSocket.disableRenegotiation()`][] to disable renegotiation will + no longer be necessary when it is disabled by default. This will become a + no-op in most configurations. +* The `tls.CLIENT_RENEG_LIMIT` and `tls.CLIENT_RENEG_WINDOW` properties which + limit renegotiation will become unused in default configurations. + If renegotiation by clients is removed in future these are likely to be + removed. + [DEP0142]: #dep0142-repl_builtinlibs [DEP0156]: #dep0156-aborted-property-and-abort-aborted-event-in-http [NIST SP 800-38D]: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf @@ -4985,8 +5034,11 @@ Use global `TextDecoder` and `TextEncoder` instead. [`tls.SecureContext`]: tls.md#tlscreatesecurecontextoptions [`tls.TLSSocket`]: tls.md#class-tlstlssocket [`tls.checkServerIdentity()`]: tls.md#tlscheckserveridentityhostname-cert +[`tls.connect()`]: tls.md#tlsconnectoptions-callback [`tls.createSecureContext()`]: tls.md#tlscreatesecurecontextoptions [`tls.createServer()`]: tls.md#tlscreateserveroptions-secureconnectionlistener +[`tlsSocket.disableRenegotiation()`]: tls.md#tlssocketdisablerenegotiation +[`tlsSocket.renegotiate()`]: tls.md#tlssocketrenegotiateoptions-callback [`url.format()`]: url.md#urlformaturlobject [`url.format(urlString)`]: url.md#urlformaturlstring [`url.parse()`]: url.md#urlparseurlstring-parsequerystring-slashesdenotehost diff --git a/doc/api/errors.md b/doc/api/errors.md index e6ab55bab058..80bcadab826a 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -3358,8 +3358,8 @@ disabled. ### `ERR_TLS_RENEGOTIATION_UNSUPPORTED` -An attempt was made to renegotiate TLS, but the TLS implementation does not -support caller-initiated renegotiation. +An attempt was made to renegotiate TLS, or to allow renegotiation on a server, +but the TLS implementation does not support it. diff --git a/doc/api/https.md b/doc/api/https.md index d9de65813733..2d3426778eb8 100644 --- a/doc/api/https.md +++ b/doc/api/https.md @@ -474,7 +474,8 @@ Makes a request to a secure web server. The following additional `options` from [`tls.connect()`][] are also accepted: `ca`, `cert`, `ciphers`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`, `pfx`, `rejectUnauthorized`, `secureOptions`, -`secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`. +`secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`, +`allowRenegotiation`. `options` can be an object, a string, or a [`URL`][] object. If `options` is a string, it is automatically parsed with [`new URL()`][]. If it is a [`URL`][] diff --git a/doc/api/tls.md b/doc/api/tls.md index 032aa4764175..08c5e66ef629 100644 --- a/doc/api/tls.md +++ b/doc/api/tls.md @@ -235,6 +235,11 @@ understanding of the implications and risks. TLSv1.3 does not support renegotiation. +Renegotiation is deprecated (see [DEP0213][]). A future version of Node.js will +disable it by default, for servers and clients. The `allowRenegotiation` option +of [`tls.createServer()`][] and [`tls.connect()`][] can be set to `false` to +disable it now, or to `true` to keep it enabled when that default changes. + ### Session resumption Establishing a TLS session can be relatively slow. The process can be sped @@ -901,6 +906,9 @@ connection is open. +> Stability: 0 - Deprecated. See [DEP0213][]. + Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts to renegotiate will trigger an `'error'` event on the `TLSSocket`. +Set `allowRenegotiation: false` when creating the server or connection +instead. This method has no effect on a connection created that way, where the +peer's attempts to renegotiate are refused without an error. + ### `tlsSocket.enableTrace()` +> Stability: 0 - Deprecated. See [DEP0213][]. + * `options` {Object} * `rejectUnauthorized` {boolean} If not `false`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if @@ -1622,6 +1641,12 @@ When running as the server, the socket will be destroyed with an error after For TLSv1.3, renegotiation cannot be initiated, it is not supported by the protocol. +If the connection was created with `allowRenegotiation: false`, this method +returns `false` and `callback` is called with an +[`ERR_TLS_RENEGOTIATION_DISABLED`][] error. A future version of Node.js will +disable renegotiation by default, and this method will then only work on +connections created with `allowRenegotiation: true`. + ### `tlsSocket.servername` * `options` {Object} + * `allowRenegotiation` {boolean} If `true`, connections to the server may be + renegotiated, either when requested by the client or through local calls to + [`tlsSocket.renegotiate()`][]. Renegotiation is deprecated (see + [DEP0213][]) and future versions will set this default to `false`. + Setting this to `true` throws [`ERR_TLS_RENEGOTIATION_UNSUPPORTED`][] + where the TLS library does not support renegotiation on servers. + **Default:** `true`. * `ALPNProtocols` {string\[]|Buffer|TypedArray|DataView} An array of strings, or a single `Buffer`, `TypedArray`, or `DataView` containing the supported ALPN protocols. Buffers should have the format `[len][name][len][name]...` @@ -2585,6 +2626,7 @@ added: v0.11.3 [CVE-2021-44531]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531 [Chrome's 'modern cryptography' setting]: https://www.chromium.org/Home/chromium-security/education/tls#TOC-Cipher-Suites +[DEP0213]: deprecations.md#dep0213-tls-renegotiation [DHE]: https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange [ECDHE]: https://en.wikipedia.org/wiki/Elliptic_curve_Diffie%E2%80%93Hellman [IANA TLS Supported Groups registry]: https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-8 @@ -2617,6 +2659,8 @@ added: v0.11.3 [`--use-openssl-ca`]: cli.md#--use-bundled-ca---use-openssl-ca [`--use-system-ca`]: cli.md#--use-system-ca [`Duplex`]: stream.md#class-streamduplex +[`ERR_TLS_RENEGOTIATION_DISABLED`]: errors.md#err_tls_renegotiation_disabled +[`ERR_TLS_RENEGOTIATION_UNSUPPORTED`]: errors.md#err_tls_renegotiation_unsupported [`NODE_EXTRA_CA_CERTS`]: cli.md#node_extra_ca_certsfile [`NODE_OPTIONS`]: cli.md#node_optionsoptions [`SSL_export_keying_material`]: https://www.openssl.org/docs/man3.0/man3/SSL_export_keying_material.html @@ -2652,6 +2696,7 @@ added: v0.11.3 [`tls.getCACertificates()`]: #tlsgetcacertificatestype [`tls.getCiphers()`]: #tlsgetciphers [`tls.rootCertificates`]: #tlsrootcertificates +[`tlsSocket.renegotiate()`]: #tlssocketrenegotiateoptions-callback [`x509.checkHost()`]: crypto.md#x509checkhostname-options [asn1.js]: https://www.npmjs.com/package/asn1.js [certificate object]: #certificate-object diff --git a/lib/https.js b/lib/https.js index 38623d258a20..649c925daf4f 100644 --- a/lib/https.js +++ b/lib/https.js @@ -700,6 +700,10 @@ Agent.prototype.getName = function getName(options = kEmptyObject) { if (options.session) name += getTlsOptionKey(options.session); + name += ':'; + if (options.allowRenegotiation !== undefined) + name += getTlsOptionKey(options.allowRenegotiation); + if (options[kPerRequestCheckServerIdentity]) name += `:${options[kPerRequestCheckServerIdentity]}`; diff --git a/lib/internal/tls/wrap.js b/lib/internal/tls/wrap.js index 2d5886ea8010..96e48210c14b 100644 --- a/lib/internal/tls/wrap.js +++ b/lib/internal/tls/wrap.js @@ -34,6 +34,8 @@ const { const { assertCrypto, + getDeprecationWarningEmitter, + isPendingDeprecation, kEmptyObject, } = require('internal/util'); @@ -101,10 +103,20 @@ const { const { InternalX509Certificate, } = require('internal/crypto/x509'); +const emitRenegotiationDeprecation = getDeprecationWarningEmitter( + 'DEP0213', + 'TLS renegotiation is deprecated and will be disabled by default. Only ' + + "clients setting allowRenegotiation to accept a server's request will " + + 'remain supported.', + undefined, + false, + isPendingDeprecation, +); const traceTls = getOptionValue('--trace-tls'); const tlsKeylog = getOptionValue('--tls-keylog'); const { appendFile } = require('fs'); const kConnectOptions = Symbol('connect-options'); +const kAllowRenegotiation = Symbol('allowRenegotiation'); const kDisableRenegotiation = Symbol('disable-renegotiation'); const kErrorEmitted = Symbol('error-emitted'); const kHandshakeTimeout = Symbol('handshake-timeout'); @@ -234,6 +246,15 @@ function onhandshakestart(now) { owner._emitTLSError(new ERR_TLS_RENEGOTIATION_DISABLED()); } +function validateAllowRenegotiation(allowRenegotiation, isServer) { + if (allowRenegotiation === undefined) + return; + validateBoolean(allowRenegotiation, 'options.allowRenegotiation'); + // BoringSSL servers always refuse renegotiation. + if (allowRenegotiation && isServer && isBoringSSL) + throw new ERR_TLS_RENEGOTIATION_UNSUPPORTED(); +} + function onhandshakedone() { debug('server onhandshakedone'); @@ -655,6 +676,9 @@ function TLSSocket(socket, opts) { if (tlsOptions.ALPNProtocols) tls.convertALPNProtocols(tlsOptions.ALPNProtocols, tlsOptions); + validateAllowRenegotiation(tlsOptions.allowRenegotiation, + tlsOptions.isServer); + this._tlsOptions = tlsOptions; this._secureEstablished = false; this._securePending = false; @@ -977,6 +1001,9 @@ TLSSocket.prototype._init = function(socket, wrap) { if (requestCert || rejectUnauthorized) ssl.setVerifyMode(requestCert, rejectUnauthorized); + if (options.allowRenegotiation === false) + ssl.disableRenegotiation(); + // Only call .onkeylog if there is a keylog listener. ssl.onkeylog = onkeylog; @@ -1114,6 +1141,8 @@ TLSSocket.prototype.renegotiate = function(options, callback) { validateFunction(callback, 'callback'); } + emitRenegotiationDeprecation(); + debug('%s renegotiate()', this._tlsOptions.isServer ? 'server' : 'client', 'destroyed?', this.destroyed, @@ -1122,6 +1151,13 @@ TLSSocket.prototype.renegotiate = function(options, callback) { if (this.destroyed) return; + if (this._tlsOptions.allowRenegotiation === false) { + if (callback) { + process.nextTick(callback, new ERR_TLS_RENEGOTIATION_DISABLED()); + } + return false; + } + let requestCert = !!this._requestCert; let rejectUnauthorized = !!this._rejectUnauthorized; @@ -1228,6 +1264,13 @@ TLSSocket.prototype._finishInit = function() { 'alpn', this.alpnProtocol, 'servername', this.servername); + // A second completed handshake is a renegotiation. + if (this._secureEstablished && + (this._tlsOptions.isServer || + this._tlsOptions.allowRenegotiation !== true)) { + emitRenegotiationDeprecation(); + } + this._secureEstablished = true; if (this._tlsOptions.handshakeTimeout > 0) this.setTimeout(0, this._handleTimeout); @@ -1412,6 +1455,7 @@ function tlsConnectionListener(rawSocket) { ALPNCallback: this.ALPNCallback, SNICallback: this[kSNICallback] || SNICallback, enableTrace: this[kEnableTrace], + allowRenegotiation: this[kAllowRenegotiation], pauseOnConnect: this.pauseOnConnect, pskCallback: this[kPskCallback], pskIdentityHint: this[kPskIdentityHint], @@ -1532,6 +1576,9 @@ function Server(options, listener) { validateNumber(this[kHandshakeTimeout], 'options.handshakeTimeout'); + validateAllowRenegotiation(options.allowRenegotiation, true); + this[kAllowRenegotiation] = options.allowRenegotiation; + if (this[kSNICallback]) { validateFunction(this[kSNICallback], 'options.SNICallback'); } @@ -1901,6 +1948,7 @@ exports.connect = function connect(...args) { ALPNProtocols: options.ALPNProtocols, requestOCSP: options.requestOCSP, enableTrace: options.enableTrace, + allowRenegotiation: options.allowRenegotiation, pskCallback: options.pskCallback, highWaterMark: options.highWaterMark, onread: options.onread, diff --git a/src/crypto/crypto_tls.cc b/src/crypto/crypto_tls.cc index a0e883f00b49..e092cb244684 100644 --- a/src/crypto/crypto_tls.cc +++ b/src/crypto/crypto_tls.cc @@ -700,6 +700,16 @@ void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) { if (where & SSL_CB_HANDSHAKE_START) { Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_START);"); +#ifndef OPENSSL_IS_BORINGSSL + // The TLS library answers a peer's attempt to renegotiate with a + // no_renegotiation alert when renegotiation is disabled, and then reports + // the handshake as done without having done one. + c->flags_.renegotiation_refused = + c->flags_.established && + (SSL_get_options(ssl) & SSL_OP_NO_RENEGOTIATION) != 0; + if (c->flags_.renegotiation_refused) return; +#endif + // Start is tracked to limit number and frequency of renegotiation attempts, // since excessive renegotiation may be an attack. Local callback; @@ -717,6 +727,10 @@ void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) { if (where & SSL_CB_HANDSHAKE_DONE && !SSL_renegotiate_pending(ssl)) { Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_DONE);"); CHECK(!SSL_renegotiate_pending(ssl)); + if (c->flags_.renegotiation_refused) { + c->flags_.renegotiation_refused = false; + return; + } Local callback; c->flags_.established = true; @@ -1457,6 +1471,19 @@ void TLSWrap::EnableKeylogCallback(const FunctionCallbackInfo& args) { # define HAVE_SSL_TRACE 1 #endif +void TLSWrap::DisableRenegotiation(const FunctionCallbackInfo& args) { + TLSWrap* wrap; + ASSIGN_OR_RETURN_UNWRAP(&wrap, args.This()); + if (!wrap->ssl_) return; +#if NCRYPTO_USE_OPENSSL_PROVIDER + SSL_set_options(wrap->ssl_.get(), SSL_OP_NO_RENEGOTIATION); +#elif NCRYPTO_USE_BORINGSSL + SSL_set_renegotiate_mode(wrap->ssl_.get(), ssl_renegotiate_never); +#else +#error "Unsupported crypto backend" +#endif +} + void TLSWrap::EnableTrace(const FunctionCallbackInfo& args) { TLSWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.This()); @@ -2453,6 +2480,7 @@ void TLSWrap::Initialize( SetProtoMethod(isolate, t, "certCbDone", CertCbDone); SetProtoMethod(isolate, t, "clientHelloDone", ClientHelloDone); SetProtoMethod(isolate, t, "destroySSL", DestroySSL); + SetProtoMethod(isolate, t, "disableRenegotiation", DisableRenegotiation); SetProtoMethod(isolate, t, "enableCertCb", EnableCertCb); SetProtoMethod(isolate, t, "enableALPNCb", EnableALPNCb); SetProtoMethod(isolate, t, "enableKeylogCallback", EnableKeylogCallback); @@ -2528,6 +2556,7 @@ void TLSWrap::RegisterExternalReferences(ExternalReferenceRegistry* registry) { registry->Register(CertCbDone); registry->Register(ClientHelloDone); registry->Register(DestroySSL); + registry->Register(DisableRenegotiation); registry->Register(EnableCertCb); registry->Register(EnableALPNCb); registry->Register(EnableKeylogCallback); diff --git a/src/crypto/crypto_tls.h b/src/crypto/crypto_tls.h index f49a4904f15f..7f5ac201a62c 100644 --- a/src/crypto/crypto_tls.h +++ b/src/crypto/crypto_tls.h @@ -238,6 +238,8 @@ class TLSWrap : public AsyncWrap, static void CertCbDone(const v8::FunctionCallbackInfo& args); static void ClientHelloDone(const v8::FunctionCallbackInfo& args); static void DestroySSL(const v8::FunctionCallbackInfo& args); + static void DisableRenegotiation( + const v8::FunctionCallbackInfo& args); static void EnableCertCb(const v8::FunctionCallbackInfo& args); static void EnableALPNCb(const v8::FunctionCallbackInfo& args); static void EnableKeylogCallback( @@ -358,6 +360,9 @@ class TLSWrap : public AsyncWrap, bool has_active_write_issued_by_prev_listener : 1; bool alpn_callback_enabled : 1; bool servername_pinned : 1; + // The handshake in progress is the peer's attempt to renegotiate, which + // the TLS library is refusing. + bool renegotiation_refused : 1; }; Flags flags_{}; diff --git a/test/doctool/test-doc-api-json.mjs b/test/doctool/test-doc-api-json.mjs index f0e7d2b3425f..ac56a415811c 100644 --- a/test/doctool/test-doc-api-json.mjs +++ b/test/doctool/test-doc-api-json.mjs @@ -158,5 +158,5 @@ for await (const dirent of await fs.opendir(new URL('../../out/doc/api/', import assert.partialDeepStrictEqual(allExpectedKeys, findAllKeys(json)); } -assert.strictEqual(numberOfDeprecatedSections, 49); // Increase this number every time a new API is deprecated. +assert.strictEqual(numberOfDeprecatedSections, 51); // Increase this number every time a new API is deprecated. assert.strictEqual(numberOfRemovedAPIs, 49); // Increase this number every time a section is marked as removed. diff --git a/test/parallel/test-https-agent-getname.js b/test/parallel/test-https-agent-getname.js index 4b6555724b09..7ae5b8479d1c 100644 --- a/test/parallel/test-https-agent-getname.js +++ b/test/parallel/test-https-agent-getname.js @@ -14,13 +14,13 @@ const agent = new https.Agent(); // empty argument assert.strictEqual( agent.getName(), - 'localhost:::::::::::::::::::::::::::' + 'localhost::::::::::::::::::::::::::::' ); // empty options assert.strictEqual( agent.getName({}), - 'localhost:::::::::::::::::::::::::::' + 'localhost::::::::::::::::::::::::::::' ); // Pass all options arguments @@ -50,7 +50,7 @@ assert.strictEqual( '0.0.0.0:443:192.168.1.1:s2:ca:s4:cert:ciphers:s3:key::' + 's3:pfx::false:localhost:::secureProtocol:' + 'a3:7:v1:Yw==:7:v1:cg==:7:v1:bA==:false:ecdhCurve:dhparam:0:' + - 'sessionIdContext:"sigalgs"::::::::' + 'sessionIdContext:"sigalgs":::::::::' ); { @@ -105,6 +105,11 @@ assert.strictEqual( agent.getName({ ...baseOptions, allowPartialTrustChain: false }) ); + assert.notStrictEqual( + agent.getName(baseOptions), + agent.getName({ ...baseOptions, allowRenegotiation: false }) + ); + const secureContext1 = tls.createSecureContext({ ca: agent1 }); const secureContext2 = tls.createSecureContext({ ca: agent6 }); assert.strictEqual( diff --git a/test/parallel/test-tls-allow-renegotiation.js b/test/parallel/test-tls-allow-renegotiation.js new file mode 100644 index 000000000000..5292d794b6f4 --- /dev/null +++ b/test/parallel/test-tls-allow-renegotiation.js @@ -0,0 +1,139 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +// Tests the allowRenegotiation option of tls.createServer() and tls.connect(). + +const assert = require('assert'); +const tls = require('tls'); +const fixtures = require('../common/fixtures'); +const { hasOpenSSL, isBoringSSL } = require('../common/crypto'); + +if (isBoringSSL) { + // BoringSSL servers always refuse renegotiation. + for (const create of [ + () => tls.createServer({ allowRenegotiation: true }), + () => new tls.TLSSocket(null, { isServer: true, allowRenegotiation: true }), + ]) { + assert.throws(create, { code: 'ERR_TLS_RENEGOTIATION_UNSUPPORTED' }); + } + require('../common/boringssl').testRenegotiationUnsupported(); + return; +} + +// Renegotiation as a protocol feature was dropped after TLS1.2. +tls.DEFAULT_MAX_VERSION = 'TLSv1.2'; + +const handshakeFailure = hasOpenSSL(4, 0) ? + 'ERR_SSL_TLS_ALERT_HANDSHAKE_FAILURE' : hasOpenSSL(3, 2) ? + 'ERR_SSL_SSL/TLS_ALERT_HANDSHAKE_FAILURE' : + 'ERR_SSL_SSLV3_ALERT_HANDSHAKE_FAILURE'; + +const idleTimeout = common.platformTimeout(60_000); + +const serverOptions = { + key: fixtures.readKey('rsa_private.pem'), + cert: fixtures.readKey('rsa_cert.crt'), +}; + +for (const allowRenegotiation of [null, 0, 'false', {}]) { + const expected = { code: 'ERR_INVALID_ARG_TYPE' }; + assert.throws(() => tls.createServer({ allowRenegotiation }), expected); + assert.throws(() => tls.connect({ port: 1, allowRenegotiation }), expected); +} + +function connect(server, options, onSecure) { + const client = tls.connect({ + port: server.address().port, + rejectUnauthorized: false, + ...options, + }, () => onSecure(client)); + client.on('close', common.mustCall(() => server.close())); +} + +// A side that does not allow renegotiation cannot start one itself. +function assertCannotRenegotiate(socket) { + assert.strictEqual(socket.renegotiate({}, common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_TLS_RENEGOTIATION_DISABLED'); + })), false); +} + +// A server that does not allow renegotiation refuses the client's attempt, and +// the attempt leaves the server's side of the connection as it was. +function testServerRefuses({ disableRenegotiation }) { + const server = tls.createServer({ + ...serverOptions, + allowRenegotiation: false, + }, common.mustCall((socket) => { + socket.setTimeout(idleTimeout); + // Has no effect: the attempt is refused without an error on this side. + if (disableRenegotiation) socket.disableRenegotiation(); + assertCannotRenegotiate(socket); + socket.on('secure', common.mustNotCall('renegotiation completed')); + // The client gives up on the connection once its attempt is refused. + socket.on('error', common.mustCall((err) => { + assert.strictEqual(err.code, handshakeFailure); + assert.strictEqual(socket.timeout, idleTimeout); + socket.destroy(); + })); + })); + + server.listen(0, common.mustCall(() => { + connect(server, {}, common.mustCall((client) => { + client.on('error', common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_SSL_NO_RENEGOTIATION'); + client.destroy(); + })); + client.on('secure', common.mustNotCall('renegotiation completed')); + assert.strictEqual(client.renegotiate({}), true); + })); + })); +} + +// A client that does not allow renegotiation refuses the server's request. +function testClientRefuses() { + const server = tls.createServer(serverOptions, common.mustCall((socket) => { + socket.on('error', common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_SSL_NO_RENEGOTIATION'); + socket.destroy(); + })); + socket.on('secure', common.mustNotCall('renegotiation completed')); + assert.strictEqual(socket.renegotiate({}), true); + })); + + server.listen(0, common.mustCall(() => { + connect(server, { allowRenegotiation: false }, common.mustCall((client) => { + client.setTimeout(idleTimeout); + assertCannotRenegotiate(client); + client.on('secure', common.mustNotCall('renegotiation completed')); + // The server gives up on the connection once its request is refused. + client.on('error', common.mustCall((err) => { + assert.strictEqual(err.code, handshakeFailure); + assert.strictEqual(client.timeout, idleTimeout); + client.destroy(); + })); + })); + })); +} + +function testAllowed() { + const server = tls.createServer({ + ...serverOptions, + allowRenegotiation: true, + }, common.mustCall((socket) => socket.resume())); + + server.listen(0, common.mustCall(() => { + connect(server, { allowRenegotiation: true }, common.mustCall((client) => { + assert.strictEqual(client.renegotiate({}, common.mustSucceed(() => { + client.end(); + })), true); + })); + })); +} + +testServerRefuses({ disableRenegotiation: false }); +testServerRefuses({ disableRenegotiation: true }); +testClientRefuses(); +testAllowed(); diff --git a/test/parallel/test-tls-renegotiation-pending-deprecation.js b/test/parallel/test-tls-renegotiation-pending-deprecation.js new file mode 100644 index 000000000000..f8f692299cd2 --- /dev/null +++ b/test/parallel/test-tls-renegotiation-pending-deprecation.js @@ -0,0 +1,106 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const { isBoringSSL } = require('../common/crypto'); +if (isBoringSSL) + common.skip('BoringSSL does not support renegotiation'); + +// With --pending-deprecation, renegotiation emits a deprecation warning unless +// it is a client that set allowRenegotiation: true accepting a server's request. + +const assert = require('assert'); +const { fork } = require('child_process'); +const tls = require('tls'); +const fixtures = require('../common/fixtures'); + +tls.DEFAULT_MAX_VERSION = 'TLSv1.2'; + +const serverOptions = { + key: fixtures.readKey('rsa_private.pem'), + cert: fixtures.readKey('rsa_cert.crt'), +}; + +// The endpoint under test runs in a child process, as the warning is emitted +// once per process and the peer would otherwise emit it too. +if (process.argv[2] === 'child') { + const { role, allowRenegotiation, initiate, port } = + JSON.parse(process.argv[3]); + + if (role === 'server') { + const server = tls.createServer({ + ...serverOptions, + allowRenegotiation, + }, common.mustCall((socket) => { + socket.resume(); + socket.on('close', common.mustCall(() => server.close())); + })); + server.listen(0, common.mustCall(() => { + process.send({ port: server.address().port }); + })); + } else { + const client = tls.connect({ + port, + rejectUnauthorized: false, + allowRenegotiation, + }, common.mustCall(() => { + if (initiate) + client.renegotiate({}, common.mustSucceed(() => client.end())); + })); + client.resume(); + } + return; +} + +function start(options, warns) { + const child = fork(__filename, ['child', JSON.stringify(options)], { + execArgv: ['--pending-deprecation'], + stdio: ['ignore', 'inherit', 'pipe', 'ipc'], + }); + let stderr = ''; + child.stderr.setEncoding('utf8'); + child.stderr.on('data', (chunk) => { stderr += chunk; }); + child.on('close', common.mustCall((code) => { + assert.strictEqual(code, 0, stderr); + assert.strictEqual( + stderr.includes('[DEP0213] DeprecationWarning: TLS renegotiation'), + warns, + stderr); + })); + return child; +} + +function testServer(options, warns) { + const child = start({ role: 'server', ...options }, warns); + child.on('message', common.mustCall(({ port }) => { + const client = tls.connect({ + port, + rejectUnauthorized: false, + }, common.mustCall(() => { + client.renegotiate({}, common.mustSucceed(() => client.end())); + })); + client.resume(); + })); +} + +function testClient(options, warns) { + const server = tls.createServer(serverOptions, common.mustCall((socket) => { + socket.resume(); + socket.on('close', common.mustCall(() => server.close())); + if (!options.initiate) + socket.renegotiate({}, common.mustSucceed(() => socket.end())); + })); + server.listen(0, common.mustCall(() => { + start({ role: 'client', port: server.address().port, ...options }, warns); + })); +} + +// A server completing a renegotiation, whether or not it set the option. +testServer({ allowRenegotiation: true }, true); +// Any call to renegotiate(). +testClient({ allowRenegotiation: true, initiate: true }, true); +// A client accepting the server's request, unless it set the option. +testClient({ initiate: false }, true); +testClient({ allowRenegotiation: true, initiate: false }, false);