Skip to content

Commit 209c7e4

Browse files
pimterryaduh95
authored andcommitted
tls: don't allow renegotiation or HRR to change SNI
Signed-off-by: Tim Perry <pimterry@gmail.com> Backport-PR-URL: nodejs-private/node-private#1054 Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com> PR-URL: nodejs-private/node-private#1030 CVE-ID: CVE-2026-123872
1 parent 05e452f commit 209c7e4

4 files changed

Lines changed: 99 additions & 43 deletions

File tree

‎lib/internal/tls/wrap.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1159,7 +1159,7 @@ TLSSocket.prototype._finishInit = function() {
11591159
return;
11601160

11611161
this.alpnProtocol = this._handle.getALPNNegotiatedProtocol();
1162-
// The servername could be set by TLSWrap::SelectSNIContextCallback().
1162+
// On a server, TLSWrap::PinServerName() sets it from the first ClientHello.
11631163
if (this.servername === null) {
11641164
this.servername = this._handle.getServername();
11651165
}

‎src/crypto/crypto_tls.cc‎

Lines changed: 38 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,12 @@ SSL_SESSION* GetSessionCallback(
105105
return w->ReleaseSession();
106106
}
107107

108+
// The server name is handled in EarlyClientHelloCallback, so this only
109+
// acknowledges it, which also has the TLS library store it in new sessions.
110+
int AcknowledgeServerName(SSL* s, int* ad, void* arg) {
111+
return SSL_TLSEXT_ERR_OK;
112+
}
113+
108114
// Reads a 16-bit length prefixed vector from the front of data. Returns
109115
// nothing if the length does not fit within data.
110116
std::optional<std::span<const uint8_t>> ReadVector16(
@@ -158,10 +164,7 @@ ssl_select_cert_result_t EarlyClientHelloCallback(const SSL_CLIENT_HELLO* ch) {
158164
// If we can't parse the hello SNI, reject it explicitly:
159165
if (!servername.has_value()) return ssl_select_cert_error;
160166

161-
// Session resumption must only be allowed for sessions with exactly the same
162-
// SNI. We use the SNI to derive the session id, so no handshake can resume
163-
// from a mismatched SNI value. Mismatches fall back to full handshakes:
164-
if (!w->BindSessionsToServerName(*servername)) return ssl_select_cert_error;
167+
if (!w->PinServerName(*servername)) return ssl_select_cert_error;
165168

166169
return ssl_select_cert_success;
167170
}
@@ -183,10 +186,10 @@ int EarlyClientHelloCallback(SSL* s, int* al, void* arg) {
183186
return SSL_CLIENT_HELLO_ERROR;
184187
}
185188

186-
// Session resumption must only be allowed for sessions with exactly the same
187-
// SNI. We use the SNI to derive the session id, so no handshake can resume
188-
// from a mismatched SNI value. Mismatches fall back to full handshakes:
189-
if (!w->BindSessionsToServerName(*servername)) return SSL_CLIENT_HELLO_ERROR;
189+
if (!w->PinServerName(*servername)) {
190+
*al = SSL_AD_ILLEGAL_PARAMETER;
191+
return SSL_CLIENT_HELLO_ERROR;
192+
}
190193

191194
return SSL_CLIENT_HELLO_SUCCESS;
192195
}
@@ -604,8 +607,7 @@ void TLSWrap::InitSSL() {
604607
// https://github.com/openssl/openssl/issues/7199#issuecomment-420670544
605608
SSL_set_info_callback(ssl_.get(), SSLInfoCallback);
606609

607-
if (is_server())
608-
sc_->SetSelectSNIContextCallback(SelectSNIContextCallback);
610+
if (is_server()) sc_->SetSelectSNIContextCallback(AcknowledgeServerName);
609611

610612
ConfigureSecureContext(sc_.get());
611613

@@ -1486,39 +1488,34 @@ void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
14861488
SSL_set_tlsext_host_name(wrap->ssl_.get(), *servername);
14871489
}
14881490

1489-
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
1490-
TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1491-
Environment* env = p->env();
1492-
HandleScope handle_scope(env->isolate());
1493-
Context::Scope context_scope(env->context());
1494-
1495-
auto servername = SSLPointer::GetServerName(s);
1496-
if (!servername.has_value() ||
1497-
!Set(env, p->GetOwner(), env->servername_string(), servername.value()))
1498-
return SSL_TLSEXT_ERR_NOACK;
1499-
1500-
Local<Value> ctx = p->object()->Get(env->context(), env->sni_context_string())
1501-
.FromMaybe(Local<Value>());
1502-
1503-
// Acknowlege the name so it's correctly stored on the session:
1504-
if (ctx.IsEmpty() || !ctx->IsObject()) return SSL_TLSEXT_ERR_OK;
1505-
1506-
if (!env->secure_context_constructor_template()->HasInstance(ctx)) {
1507-
// Failure: incorrect SNI context object
1508-
Local<Value> err = Exception::TypeError(env->sni_context_err_string());
1509-
p->MakeCallback(env->onerror_string(), 1, &err);
1510-
return SSL_TLSEXT_ERR_NOACK;
1491+
// The connection's server name is fixed by its first ClientHello: later ones (a
1492+
// renegotiation, or the second of a HelloRetryRequest) must ask for exactly the
1493+
// same, as the connection's secure context was chosen for it.
1494+
bool TLSWrap::PinServerName(std::string_view servername) {
1495+
if (servername_pinned_) {
1496+
if (servername == servername_) return true;
1497+
Debug(this,
1498+
"ClientHello asked for server name '%s', connection pinned to '%s'",
1499+
servername,
1500+
servername_);
1501+
return false;
15111502
}
1503+
servername_pinned_ = true;
1504+
servername_ = servername;
15121505

1513-
SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
1514-
CHECK_NOT_NULL(sc);
1515-
p->sni_context_ = BaseObjectPtr<SecureContext>(sc);
1516-
1517-
ConfigureSecureContext(sc);
1518-
CHECK_EQ(SSL_set_SSL_CTX(p->ssl_.get(), sc->ctx().get()), sc->ctx().get());
1519-
p->SetCACerts(sc);
1506+
if (!servername.empty()) {
1507+
HandleScope handle_scope(env()->isolate());
1508+
Context::Scope context_scope(env()->context());
1509+
if (!Set(env(), GetOwner(), env()->servername_string(), servername_)) {
1510+
return false;
1511+
}
1512+
}
15201513

1521-
return SSL_TLSEXT_ERR_OK;
1514+
// Session resumption must only be allowed for sessions with exactly the same
1515+
// SNI. We use the SNI to derive the session id context, so no handshake can
1516+
// resume from a mismatched SNI value. Mismatches fall back to full
1517+
// handshakes:
1518+
return BindSessionsToServerName(servername);
15221519
}
15231520

15241521
bool TLSWrap::BindSessionsToServerName(std::string_view servername) {
@@ -1699,6 +1696,7 @@ void TLSWrap::MemoryInfo(MemoryTracker* tracker) const {
16991696
tracker->TrackField("ocsp_response", ocsp_response_);
17001697
tracker->TrackField("sni_context", sni_context_);
17011698
tracker->TrackField("error", error_);
1699+
tracker->TrackField("servername", servername_);
17021700
if (pending_cleartext_input_)
17031701
tracker->TrackField("pending_cleartext_input", pending_cleartext_input_);
17041702
if (enc_in_ != nullptr)

‎src/crypto/crypto_tls.h‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ class TLSWrap : public AsyncWrap,
6666
void set_awaiting_new_session(bool on = true) { awaiting_new_session_ = on; }
6767
void enable_session_callbacks() { session_callbacks_ = true; }
6868
bool BindSessionsToServerName(std::string_view servername);
69+
bool PinServerName(std::string_view servername);
6970
bool is_server() const { return kind_ == Kind::kServer; }
7071
bool is_client() const { return kind_ == Kind::kClient; }
7172
bool is_awaiting_new_session() const { return awaiting_new_session_; }
@@ -172,8 +173,6 @@ class TLSWrap : public AsyncWrap,
172173

173174
int SetCACerts(SecureContext* sc);
174175

175-
static int SelectSNIContextCallback(SSL* s, int* ad, void* arg);
176-
177176
static void CertCbDone(const v8::FunctionCallbackInfo<v8::Value>& args);
178177
static void DestroySSL(const v8::FunctionCallbackInfo<v8::Value>& args);
179178
static void EnableCertCb(const v8::FunctionCallbackInfo<v8::Value>& args);
@@ -256,6 +255,7 @@ class TLSWrap : public AsyncWrap,
256255
v8::Global<v8::ArrayBufferView> ocsp_response_;
257256
BaseObjectPtr<SecureContext> sni_context_;
258257
BaseObjectPtr<SecureContext> sc_;
258+
std::string servername_;
259259

260260
// BIO buffers hold encrypted data.
261261
BIO* enc_in_ = nullptr; // StreamListener fills this for SSL_read().
@@ -283,6 +283,7 @@ class TLSWrap : public AsyncWrap,
283283
// is set to true, so it's likely redundant.
284284
bool established_ = false;
285285
bool write_callback_scheduled_ = false;
286+
bool servername_pinned_ = false;
286287

287288
int cycle_depth_ = 0;
288289

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
'use strict';
2+
3+
// Once a connection's secure context is chosen, later ClientHellos for the
4+
// same name - the second ClientHello of a TLS 1.3 HelloRetryRequest, or a TLS
5+
// 1.2 renegotiation - must leave it as it is. A context with no certificate of
6+
// its own (here one that only sets `ca`) keeps the server's certificate, and
7+
// must keep it for those too.
8+
9+
const common = require('../common');
10+
11+
if (!common.hasCrypto)
12+
common.skip('missing crypto');
13+
14+
const assert = require('node:assert');
15+
const tls = require('node:tls');
16+
const fixtures = require('../common/fixtures');
17+
const { isBoringSSL } = require('../common/crypto');
18+
19+
const server = tls.createServer({
20+
key: fixtures.readKey('agent2-key.pem'),
21+
cert: fixtures.readKey('agent2-cert.pem'),
22+
// Offering only this group makes the server answer a TLS 1.3 client whose
23+
// first key share is for another one with a HelloRetryRequest.
24+
ecdhCurve: 'P-521',
25+
}, common.mustCall((socket) => {
26+
assert.strictEqual(socket.servername, 'certless.example');
27+
socket.resume();
28+
}, isBoringSSL ? 1 : 2));
29+
server.addContext('certless.example', { ca: fixtures.readKey('ca1-cert.pem') });
30+
31+
function connect(maxVersion) {
32+
return new Promise((resolve) => {
33+
const socket = tls.connect({
34+
port: server.address().port,
35+
servername: 'certless.example',
36+
rejectUnauthorized: false,
37+
maxVersion,
38+
ecdhCurve: 'P-256:P-521',
39+
}, () => resolve(socket));
40+
});
41+
}
42+
43+
server.listen(0, common.mustCall(async () => {
44+
const retried = await connect('TLSv1.3');
45+
retried.end();
46+
47+
// BoringSSL servers don't support renegotiation.
48+
if (!isBoringSSL) {
49+
const renegotiating = await connect('TLSv1.2');
50+
await new Promise((resolve) => {
51+
renegotiating.renegotiate({}, common.mustSucceed(resolve));
52+
});
53+
renegotiating.end();
54+
}
55+
56+
server.close();
57+
}));

0 commit comments

Comments
 (0)