diff --git a/lib/internal/tls/wrap.js b/lib/internal/tls/wrap.js index dd6f4ee726d..bb78bbdcdca 100644 --- a/lib/internal/tls/wrap.js +++ b/lib/internal/tls/wrap.js @@ -1159,7 +1159,7 @@ TLSSocket.prototype._finishInit = function() { return; this.alpnProtocol = this._handle.getALPNNegotiatedProtocol(); - // The servername could be set by TLSWrap::SelectSNIContextCallback(). + // On a server, TLSWrap::PinServerName() sets it from the first ClientHello. if (this.servername === null) { this.servername = this._handle.getServername(); } diff --git a/src/crypto/crypto_tls.cc b/src/crypto/crypto_tls.cc index 2ba7f682b19..a3830293ccf 100644 --- a/src/crypto/crypto_tls.cc +++ b/src/crypto/crypto_tls.cc @@ -105,6 +105,12 @@ SSL_SESSION* GetSessionCallback( return w->ReleaseSession(); } +// The server name is handled in EarlyClientHelloCallback, so this only +// acknowledges it, which also has the TLS library store it in new sessions. +int AcknowledgeServerName(SSL* s, int* ad, void* arg) { + return SSL_TLSEXT_ERR_OK; +} + // Reads a 16-bit length prefixed vector from the front of data. Returns // nothing if the length does not fit within data. std::optional> ReadVector16( @@ -158,10 +164,7 @@ ssl_select_cert_result_t EarlyClientHelloCallback(const SSL_CLIENT_HELLO* ch) { // If we can't parse the hello SNI, reject it explicitly: if (!servername.has_value()) return ssl_select_cert_error; - // Session resumption must only be allowed for sessions with exactly the same - // SNI. We use the SNI to derive the session id, so no handshake can resume - // from a mismatched SNI value. Mismatches fall back to full handshakes: - if (!w->BindSessionsToServerName(*servername)) return ssl_select_cert_error; + if (!w->PinServerName(*servername)) return ssl_select_cert_error; return ssl_select_cert_success; } @@ -183,10 +186,10 @@ int EarlyClientHelloCallback(SSL* s, int* al, void* arg) { return SSL_CLIENT_HELLO_ERROR; } - // Session resumption must only be allowed for sessions with exactly the same - // SNI. We use the SNI to derive the session id, so no handshake can resume - // from a mismatched SNI value. Mismatches fall back to full handshakes: - if (!w->BindSessionsToServerName(*servername)) return SSL_CLIENT_HELLO_ERROR; + if (!w->PinServerName(*servername)) { + *al = SSL_AD_ILLEGAL_PARAMETER; + return SSL_CLIENT_HELLO_ERROR; + } return SSL_CLIENT_HELLO_SUCCESS; } @@ -604,8 +607,7 @@ void TLSWrap::InitSSL() { // https://github.com/openssl/openssl/issues/7199#issuecomment-420670544 SSL_set_info_callback(ssl_.get(), SSLInfoCallback); - if (is_server()) - sc_->SetSelectSNIContextCallback(SelectSNIContextCallback); + if (is_server()) sc_->SetSelectSNIContextCallback(AcknowledgeServerName); ConfigureSecureContext(sc_.get()); @@ -1486,39 +1488,34 @@ void TLSWrap::SetServername(const FunctionCallbackInfo& args) { SSL_set_tlsext_host_name(wrap->ssl_.get(), *servername); } -int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) { - TLSWrap* p = static_cast(SSL_get_app_data(s)); - Environment* env = p->env(); - HandleScope handle_scope(env->isolate()); - Context::Scope context_scope(env->context()); +// The connection's server name is fixed by its first ClientHello: later ones (a +// renegotiation, or the second of a HelloRetryRequest) must ask for exactly the +// same, as the connection's secure context was chosen for it. +bool TLSWrap::PinServerName(std::string_view servername) { + if (servername_pinned_) { + if (servername == servername_) return true; + Debug(this, + "ClientHello asked for server name '%s', connection pinned to '%s'", + servername, + servername_); + return false; + } + servername_pinned_ = true; + servername_ = servername; - auto servername = SSLPointer::GetServerName(s); - if (!servername.has_value() || - !Set(env, p->GetOwner(), env->servername_string(), servername.value())) - return SSL_TLSEXT_ERR_NOACK; - - Local ctx = p->object()->Get(env->context(), env->sni_context_string()) - .FromMaybe(Local()); - - // Acknowlege the name so it's correctly stored on the session: - if (ctx.IsEmpty() || !ctx->IsObject()) return SSL_TLSEXT_ERR_OK; - - if (!env->secure_context_constructor_template()->HasInstance(ctx)) { - // Failure: incorrect SNI context object - Local err = Exception::TypeError(env->sni_context_err_string()); - p->MakeCallback(env->onerror_string(), 1, &err); - return SSL_TLSEXT_ERR_NOACK; + if (!servername.empty()) { + HandleScope handle_scope(env()->isolate()); + Context::Scope context_scope(env()->context()); + if (!Set(env(), GetOwner(), env()->servername_string(), servername_)) { + return false; + } } - SecureContext* sc = Unwrap(ctx.As()); - CHECK_NOT_NULL(sc); - p->sni_context_ = BaseObjectPtr(sc); - - ConfigureSecureContext(sc); - CHECK_EQ(SSL_set_SSL_CTX(p->ssl_.get(), sc->ctx().get()), sc->ctx().get()); - p->SetCACerts(sc); - - return SSL_TLSEXT_ERR_OK; + // Session resumption must only be allowed for sessions with exactly the same + // SNI. We use the SNI to derive the session id context, so no handshake can + // resume from a mismatched SNI value. Mismatches fall back to full + // handshakes: + return BindSessionsToServerName(servername); } bool TLSWrap::BindSessionsToServerName(std::string_view servername) { @@ -1699,6 +1696,7 @@ void TLSWrap::MemoryInfo(MemoryTracker* tracker) const { tracker->TrackField("ocsp_response", ocsp_response_); tracker->TrackField("sni_context", sni_context_); tracker->TrackField("error", error_); + tracker->TrackField("servername", servername_); if (pending_cleartext_input_) tracker->TrackField("pending_cleartext_input", pending_cleartext_input_); if (enc_in_ != nullptr) diff --git a/src/crypto/crypto_tls.h b/src/crypto/crypto_tls.h index 4c9f579cabf..2bea41f809d 100644 --- a/src/crypto/crypto_tls.h +++ b/src/crypto/crypto_tls.h @@ -66,6 +66,7 @@ class TLSWrap : public AsyncWrap, void set_awaiting_new_session(bool on = true) { awaiting_new_session_ = on; } void enable_session_callbacks() { session_callbacks_ = true; } bool BindSessionsToServerName(std::string_view servername); + bool PinServerName(std::string_view servername); bool is_server() const { return kind_ == Kind::kServer; } bool is_client() const { return kind_ == Kind::kClient; } bool is_awaiting_new_session() const { return awaiting_new_session_; } @@ -172,8 +173,6 @@ class TLSWrap : public AsyncWrap, int SetCACerts(SecureContext* sc); - static int SelectSNIContextCallback(SSL* s, int* ad, void* arg); - static void CertCbDone(const v8::FunctionCallbackInfo& args); static void DestroySSL(const v8::FunctionCallbackInfo& args); static void EnableCertCb(const v8::FunctionCallbackInfo& args); @@ -256,6 +255,7 @@ class TLSWrap : public AsyncWrap, v8::Global ocsp_response_; BaseObjectPtr sni_context_; BaseObjectPtr sc_; + std::string servername_; // BIO buffers hold encrypted data. BIO* enc_in_ = nullptr; // StreamListener fills this for SSL_read(). @@ -283,6 +283,7 @@ class TLSWrap : public AsyncWrap, // is set to true, so it's likely redundant. bool established_ = false; bool write_callback_scheduled_ = false; + bool servername_pinned_ = false; int cycle_depth_ = 0; diff --git a/test/parallel/test-tls-sni-context-renegotiate.js b/test/parallel/test-tls-sni-context-renegotiate.js new file mode 100644 index 00000000000..756a9ad1e6e --- /dev/null +++ b/test/parallel/test-tls-sni-context-renegotiate.js @@ -0,0 +1,57 @@ +'use strict'; + +// Once a connection's secure context is chosen, later ClientHellos for the +// same name - the second ClientHello of a TLS 1.3 HelloRetryRequest, or a TLS +// 1.2 renegotiation - must leave it as it is. A context with no certificate of +// its own (here one that only sets `ca`) keeps the server's certificate, and +// must keep it for those too. + +const common = require('../common'); + +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('node:assert'); +const tls = require('node:tls'); +const fixtures = require('../common/fixtures'); +const { isBoringSSL } = require('../common/crypto'); + +const server = tls.createServer({ + key: fixtures.readKey('agent2-key.pem'), + cert: fixtures.readKey('agent2-cert.pem'), + // Offering only this group makes the server answer a TLS 1.3 client whose + // first key share is for another one with a HelloRetryRequest. + ecdhCurve: 'P-521', +}, common.mustCall((socket) => { + assert.strictEqual(socket.servername, 'certless.example'); + socket.resume(); +}, isBoringSSL ? 1 : 2)); +server.addContext('certless.example', { ca: fixtures.readKey('ca1-cert.pem') }); + +function connect(maxVersion) { + return new Promise((resolve) => { + const socket = tls.connect({ + port: server.address().port, + servername: 'certless.example', + rejectUnauthorized: false, + maxVersion, + ecdhCurve: 'P-256:P-521', + }, () => resolve(socket)); + }); +} + +server.listen(0, common.mustCall(async () => { + const retried = await connect('TLSv1.3'); + retried.end(); + + // BoringSSL servers don't support renegotiation. + if (!isBoringSSL) { + const renegotiating = await connect('TLSv1.2'); + await new Promise((resolve) => { + renegotiating.renegotiate({}, common.mustSucceed(resolve)); + }); + renegotiating.end(); + } + + server.close(); +}));