GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — tls: don't allow TLS resumption to change SNI · nodejs/node@05e452f

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • src/crypto
    • crypto_context.cc
    • crypto_context.h
    • crypto_tls.cc
    • crypto_tls.h
  • test/parallel
    • test-tls-resume-servername.js
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎src/crypto/crypto_context.cc‎

Copy file name to clipboardExpand all lines: src/crypto/crypto_context.cc
+12-1Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1776,6 +1776,14 @@ void SecureContext::SetSelectSNIContextCallback(SelectSNIContextCb cb) {
17761776
SSL_CTX_set_tlsext_servername_callback(ctx_.get(), cb);
17771777
}
17781778

1779+
void SecureContext::SetClientHelloCallback(ClientHelloCb cb) {
1780+
#ifdef OPENSSL_IS_BORINGSSL
1781+
SSL_CTX_set_select_certificate_cb(ctx_.get(), cb);
1782+
#else
1783+
SSL_CTX_set_client_hello_cb(ctx_.get(), cb, nullptr);
1784+
#endif
1785+
}
1786+
17791787
void SecureContext::SetKeylogCallback(KeylogCb cb) {
17801788
SSL_CTX_set_keylog_callback(ctx_.get(), cb);
17811789
}
@@ -2197,8 +2205,11 @@ void SecureContext::SetSessionIdContext(
21972205
reinterpret_cast<const unsigned char*>(*sessionIdContext);
21982206
unsigned int sid_ctx_len = sessionIdContext.length();
21992207

2200-
if (SSL_CTX_set_session_id_context(sc->ctx_.get(), sid_ctx, sid_ctx_len) == 1)
2208+
int ok = SSL_CTX_set_session_id_context(sc->ctx_.get(), sid_ctx, sid_ctx_len);
2209+
if (ok == 1) {
2210+
sc->session_id_context_.assign(*sessionIdContext, sid_ctx_len);
22012211
return;
2212+
}
22022213

22032214
Local<String> message;
22042215

Collapse file

‎src/crypto/crypto_context.h‎

Copy file name to clipboardExpand all lines: src/crypto/crypto_context.h
+10Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,11 @@ class SecureContext final : public BaseObject {
3737
using KeylogCb = void (*)(const SSL*, const char*);
3838
using NewSessionCb = int (*)(SSL*, SSL_SESSION*);
3939
using SelectSNIContextCb = int (*)(SSL*, int*, void*);
40+
#ifdef OPENSSL_IS_BORINGSSL
41+
using ClientHelloCb = ssl_select_cert_result_t (*)(const SSL_CLIENT_HELLO*);
42+
#else
43+
using ClientHelloCb = int (*)(SSL*, int*, void*);
44+
#endif
4045

4146
~SecureContext() override;
4247

@@ -51,6 +56,9 @@ class SecureContext final : public BaseObject {
5156
// True if CA certificates were added with addCACert(), as opposed to the
5257
// context relying on the default root store.
5358
bool has_own_ca() const { return has_own_ca_; }
59+
const std::string& session_id_context() const {
60+
return session_id_context_;
61+
}
5462

5563
// Non-const ctx() that allows for non-default initialization of
5664
// the SecureContext.
@@ -62,6 +70,7 @@ class SecureContext final : public BaseObject {
6270
void SetKeylogCallback(KeylogCb cb);
6371
void SetNewSessionCallback(NewSessionCb cb);
6472
void SetSelectSNIContextCallback(SelectSNIContextCb cb);
73+
void SetClientHelloCallback(ClientHelloCb cb);
6574

6675
inline const ncrypto::X509Pointer& issuer() const { return issuer_; }
6776
inline const ncrypto::X509Pointer& cert() const { return cert_; }
@@ -168,6 +177,7 @@ class SecureContext final : public BaseObject {
168177
// Non-owning cache for SSL_CTX_get_cert_store(ctx_.get())
169178
X509_STORE* own_cert_store_cache_ = nullptr;
170179
bool has_own_ca_ = false;
180+
std::string session_id_context_;
171181
#ifndef OPENSSL_NO_ENGINE
172182
bool client_cert_engine_provided_ = false;
173183
ncrypto::EnginePointer private_key_engine_;
Collapse file

‎src/crypto/crypto_tls.cc‎

Copy file name to clipboardExpand all lines: src/crypto/crypto_tls.cc
+114-2Lines changed: 114 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,11 @@
2020
// USE OR OTHER DEALINGS IN THE SOFTWARE.
2121

2222
#include "crypto/crypto_tls.h"
23+
#include <algorithm>
2324
#include <cstdio>
25+
#include <optional>
26+
#include <span>
27+
#include <string_view>
2428
#include "async_wrap-inl.h"
2529
#include "crypto/crypto_bio.h"
2630
#include "crypto/crypto_clienthello-inl.h"
@@ -101,6 +105,93 @@ SSL_SESSION* GetSessionCallback(
101105
return w->ReleaseSession();
102106
}
103107

108+
// Reads a 16-bit length prefixed vector from the front of data. Returns
109+
// nothing if the length does not fit within data.
110+
std::optional<std::span<const uint8_t>> ReadVector16(
111+
std::span<const uint8_t> data) {
112+
if (data.size() < 2) return std::nullopt;
113+
const size_t len = (static_cast<size_t>(data[0]) << 8) | data[1];
114+
if (data.size() < 2 + len) return std::nullopt;
115+
return data.subspan(2, len);
116+
}
117+
118+
// The host name from the server_name extension, empty if the client sent
119+
// none. Nothing at all if it sent one that cannot be used, in which case the
120+
// handshake should fail.
121+
std::optional<std::string_view> ServerName(
122+
std::optional<std::span<const uint8_t>> ext) {
123+
if (!ext.has_value()) return std::string_view();
124+
// RFC 6066: a 16-bit list length, then one entry of an 8-bit name type,
125+
// a 16-bit name length and that many name bytes. The constraints applied
126+
// here are the ones the TLS stack's own parser applies: exactly one
127+
// entry, of type host_name, of a sane length and free of NULs.
128+
auto list = ReadVector16(*ext);
129+
if (!list.has_value() || list->size() < 3) return std::nullopt;
130+
if ((*list)[0] != TLSEXT_NAMETYPE_host_name) return std::nullopt;
131+
auto name = ReadVector16(list->subspan(1));
132+
if (!name.has_value()) return std::nullopt;
133+
if (name->size() + 3 != list->size()) return std::nullopt;
134+
if (name->empty() || name->size() > TLSEXT_MAXLEN_host_name) {
135+
return std::nullopt;
136+
}
137+
if (std::find(name->begin(), name->end(), 0) != name->end()) {
138+
return std::nullopt;
139+
}
140+
return std::string_view(reinterpret_cast<const char*>(name->data()),
141+
name->size());
142+
}
143+
144+
// The TLS library invokes this before version negotiation and before session
145+
// or ticket resumption.
146+
#ifdef OPENSSL_IS_BORINGSSL
147+
ssl_select_cert_result_t EarlyClientHelloCallback(const SSL_CLIENT_HELLO* ch) {
148+
TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(ch->ssl));
149+
150+
const uint8_t* ext;
151+
size_t ext_len;
152+
std::optional<std::span<const uint8_t>> sni;
153+
if (SSL_early_callback_ctx_extension_get(
154+
ch, TLSEXT_TYPE_server_name, &ext, &ext_len)) {
155+
sni.emplace(ext, ext_len);
156+
}
157+
auto servername = ServerName(sni);
158+
// If we can't parse the hello SNI, reject it explicitly:
159+
if (!servername.has_value()) return ssl_select_cert_error;
160+
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;
165+
166+
return ssl_select_cert_success;
167+
}
168+
#else
169+
int EarlyClientHelloCallback(SSL* s, int* al, void* arg) {
170+
TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
171+
172+
const unsigned char* ext;
173+
size_t ext_len;
174+
std::optional<std::span<const uint8_t>> sni;
175+
if (SSL_client_hello_get0_ext(s, TLSEXT_TYPE_server_name, &ext, &ext_len) ==
176+
1) {
177+
sni.emplace(ext, ext_len);
178+
}
179+
auto servername = ServerName(sni);
180+
// If we can't parse the hello SNI, reject it explicitly:
181+
if (!servername.has_value()) {
182+
*al = SSL_AD_DECODE_ERROR;
183+
return SSL_CLIENT_HELLO_ERROR;
184+
}
185+
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;
190+
191+
return SSL_CLIENT_HELLO_SUCCESS;
192+
}
193+
#endif
194+
104195
void OnClientHello(
105196
void* arg,
106197
const ClientHelloParser::ClientHello& hello) {
@@ -430,6 +521,7 @@ TLSWrap::TLSWrap(Environment* env,
430521
ssl_ = sc_->CreateSSL();
431522
CHECK(ssl_);
432523

524+
sc_->SetClientHelloCallback(EarlyClientHelloCallback);
433525
sc_->SetGetSessionCallback(GetSessionCallback);
434526
sc_->SetNewSessionCallback(NewSessionCallback);
435527

@@ -1408,8 +1500,8 @@ int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
14081500
Local<Value> ctx = p->object()->Get(env->context(), env->sni_context_string())
14091501
.FromMaybe(Local<Value>());
14101502

1411-
if (ctx.IsEmpty() || !ctx->IsObject()) [[unlikely]]
1412-
return SSL_TLSEXT_ERR_NOACK;
1503+
// Acknowlege the name so it's correctly stored on the session:
1504+
if (ctx.IsEmpty() || !ctx->IsObject()) return SSL_TLSEXT_ERR_OK;
14131505

14141506
if (!env->secure_context_constructor_template()->HasInstance(ctx)) {
14151507
// Failure: incorrect SNI context object
@@ -1429,6 +1521,26 @@ int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
14291521
return SSL_TLSEXT_ERR_OK;
14301522
}
14311523

1524+
bool TLSWrap::BindSessionsToServerName(std::string_view servername) {
1525+
if (sc_->session_id_context().empty()) return true;
1526+
1527+
// Server names can't contain NULs, so a NUL keeps the parts apart.
1528+
std::string input = sc_->session_id_context();
1529+
input += '\0';
1530+
input += servername;
1531+
// Hash this to guarantee the value fits in 32 bytes while keeping
1532+
// values distinct:
1533+
unsigned char digest[EVP_MAX_MD_SIZE];
1534+
unsigned int digest_len;
1535+
return EVP_Digest(input.data(),
1536+
input.size(),
1537+
digest,
1538+
&digest_len,
1539+
EVP_sha256(),
1540+
nullptr) == 1 &&
1541+
SSL_set_session_id_context(ssl_.get(), digest, digest_len) == 1;
1542+
}
1543+
14321544
int TLSWrap::SetCACerts(SecureContext* sc) {
14331545
int err = SSL_set1_verify_cert_store(ssl_.get(),
14341546
SSL_CTX_get_cert_store(sc->ctx().get()));
Collapse file

‎src/crypto/crypto_tls.h‎

Copy file name to clipboardExpand all lines: src/crypto/crypto_tls.h
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
#include <openssl/ssl.h>
3535

3636
#include <string>
37+
#include <string_view>
3738
#include <vector>
3839

3940
namespace node {
@@ -64,6 +65,7 @@ class TLSWrap : public AsyncWrap,
6465
void set_cert_cb_running(bool on = true) { cert_cb_running_ = on; }
6566
void set_awaiting_new_session(bool on = true) { awaiting_new_session_ = on; }
6667
void enable_session_callbacks() { session_callbacks_ = true; }
68+
bool BindSessionsToServerName(std::string_view servername);
6769
bool is_server() const { return kind_ == Kind::kServer; }
6870
bool is_client() const { return kind_ == Kind::kClient; }
6971
bool is_awaiting_new_session() const { return awaiting_new_session_; }
Collapse file

‎test/parallel/test-tls-resume-servername.js‎

Copy file name to clipboard
+104Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
'use strict';
2+
3+
// A resumed session skips authentication, so it may only be resumed for the
4+
// server name it was authenticated for. Otherwise a client trusted by one host
5+
// could resume into another. Asking for a mismatched name gets a full
6+
// handshake, which authenticates the client from scratch like any other.
7+
8+
const common = require('../common');
9+
10+
if (!common.hasCrypto)
11+
common.skip('missing crypto');
12+
13+
const assert = require('node:assert');
14+
const { isBoringSSL } = require('../common/crypto');
15+
const tls = require('node:tls');
16+
const fixtures = require('../common/fixtures');
17+
18+
// What the server reported for each connection it accepted, in order.
19+
const seen = [];
20+
21+
const server = tls.createServer({
22+
key: fixtures.readKey('agent2-key.pem'),
23+
cert: fixtures.readKey('agent2-cert.pem'),
24+
}, (socket) => {
25+
seen.push({ servername: socket.servername, reused: socket.isSessionReused() });
26+
// End must be deferred on v22.x, or TLS 1.3 session tickets aren't sent:
27+
setImmediate(() => socket.end());
28+
});
29+
30+
// Connects TLS with options, resolves with the raw issued session when the
31+
// conn closes. We need the raw internal session so we can trick Node into
32+
// (ab)using this for the wrong hostname on resumed connections later.
33+
function connect(options) {
34+
return new Promise((resolve) => {
35+
let session;
36+
const socket = tls.connect({
37+
port: server.address().port,
38+
rejectUnauthorized: false,
39+
...options,
40+
});
41+
const { onnewsession } = socket._handle;
42+
socket._handle.onnewsession = function(id, raw) {
43+
session ??= raw;
44+
return onnewsession.call(this, id, raw);
45+
};
46+
socket.on('session', () => {});
47+
socket.on('close', () => resolve(session));
48+
socket.resume();
49+
});
50+
}
51+
52+
// Connecting by IP sends no server name.
53+
const noName = { host: '127.0.0.1' };
54+
55+
server.listen(0, common.mustCall(async () => {
56+
for (const maxVersion of ['TLSv1.2', 'TLSv1.3']) {
57+
seen.length = 0;
58+
const named = await connect({ servername: 'agent1.example', maxVersion });
59+
const unnamed = await connect({ ...noName, maxVersion });
60+
61+
// Resuming as the same name, or with no name both times, is fine.
62+
await connect({ servername: 'agent1.example', maxVersion, session: named });
63+
await connect({ ...noName, maxVersion, session: unnamed });
64+
65+
// Asking for a different name gets a full handshake instead.
66+
await connect({ servername: 'agent3.example', maxVersion, session: named });
67+
// Going from no SNI to any name gets a full handshake instead.
68+
await connect({ servername: 'agent1.example', maxVersion, session: unnamed });
69+
70+
assert.deepStrictEqual(seen, [
71+
{ servername: 'agent1.example', reused: false },
72+
{ servername: false, reused: false },
73+
{ servername: 'agent1.example', reused: true },
74+
{ servername: false, reused: true },
75+
{ servername: 'agent3.example', reused: false },
76+
{ servername: 'agent1.example', reused: false },
77+
], maxVersion);
78+
}
79+
80+
// BoringSSL doesn't support TLS 1.3 external PSK.
81+
if (!isBoringSSL) {
82+
// Make sure fresh PSK & PSK resumption work correctly too - this is risky as
83+
// TLS1.3 PSK works by pretending to be resumption (but it's not).
84+
const secret = Buffer.alloc(32, 1);
85+
const ciphers = 'TLS_AES_128_GCM_SHA256';
86+
const psk = tls.createServer({ ciphers, pskCallback: () => secret },
87+
common.mustCall((socket) => {
88+
assert.strictEqual(socket.servername, 'psk.example');
89+
setImmediate(() => socket.end());
90+
}, 2));
91+
await new Promise((resolve) => psk.listen(0, resolve));
92+
const pskOptions = {
93+
port: psk.address().port,
94+
servername: 'psk.example',
95+
ciphers,
96+
pskCallback: () => ({ psk: secret, identity: 'client' }),
97+
};
98+
const ticket = await connect(pskOptions);
99+
assert.ok(ticket);
100+
await connect({ ...pskOptions, session: ticket });
101+
psk.close();
102+
}
103+
server.close();
104+
}));

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.