GeezerVison is showing github.com — tls: don't allow TLS resumption to change SNI · nodejs/node@05e452f
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: src/crypto/crypto_context.cc +12-1Lines changed: 12 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -1776,6 +1776,14 @@ void SecureContext::SetSelectSNIContextCallback(SelectSNIContextCb cb) { | 1776 | 1776 | SSL_CTX_set_tlsext_servername_callback(ctx_.get(), cb); | 1777 | 1777 | } | 1778 | 1778 |
| | 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 | + | 1779 | 1787 | void SecureContext::SetKeylogCallback(KeylogCb cb) { | 1780 | 1788 | SSL_CTX_set_keylog_callback(ctx_.get(), cb); | 1781 | 1789 | } | @@ -2197,8 +2205,11 @@ void SecureContext::SetSessionIdContext( | 2197 | 2205 | reinterpret_cast<const unsigned char*>(*sessionIdContext); | 2198 | 2206 | unsigned int sid_ctx_len = sessionIdContext.length(); | 2199 | 2207 |
| 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); | 2201 | 2211 | return; | | 2212 | + } | 2202 | 2213 |
| 2203 | 2214 | Local<String> message; | 2204 | 2215 |
| |
Collapse file Copy file name to clipboardExpand all lines: src/crypto/crypto_context.h +10Lines changed: 10 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -37,6 +37,11 @@ class SecureContext final : public BaseObject { | 37 | 37 | using KeylogCb = void (*)(const SSL*, const char*); | 38 | 38 | using NewSessionCb = int (*)(SSL*, SSL_SESSION*); | 39 | 39 | 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 | 40 | 45 |
| 41 | 46 | ~SecureContext() override; | 42 | 47 |
| @@ -51,6 +56,9 @@ class SecureContext final : public BaseObject { | 51 | 56 | // True if CA certificates were added with addCACert(), as opposed to the | 52 | 57 | // context relying on the default root store. | 53 | 58 | bool has_own_ca() const { return has_own_ca_; } | | 59 | + const std::string& session_id_context() const { | | 60 | + return session_id_context_; | | 61 | + } | 54 | 62 |
| 55 | 63 | // Non-const ctx() that allows for non-default initialization of | 56 | 64 | // the SecureContext. | @@ -62,6 +70,7 @@ class SecureContext final : public BaseObject { | 62 | 70 | void SetKeylogCallback(KeylogCb cb); | 63 | 71 | void SetNewSessionCallback(NewSessionCb cb); | 64 | 72 | void SetSelectSNIContextCallback(SelectSNIContextCb cb); | | 73 | + void SetClientHelloCallback(ClientHelloCb cb); | 65 | 74 |
| 66 | 75 | inline const ncrypto::X509Pointer& issuer() const { return issuer_; } | 67 | 76 | inline const ncrypto::X509Pointer& cert() const { return cert_; } | @@ -168,6 +177,7 @@ class SecureContext final : public BaseObject { | 168 | 177 | // Non-owning cache for SSL_CTX_get_cert_store(ctx_.get()) | 169 | 178 | X509_STORE* own_cert_store_cache_ = nullptr; | 170 | 179 | bool has_own_ca_ = false; | | 180 | + std::string session_id_context_; | 171 | 181 | #ifndef OPENSSL_NO_ENGINE | 172 | 182 | bool client_cert_engine_provided_ = false; | 173 | 183 | ncrypto::EnginePointer private_key_engine_; | |
Collapse file Copy file name to clipboardExpand all lines: src/crypto/crypto_tls.cc +114-2Lines changed: 114 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 20 | 20 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | 21 | 21 |
| 22 | 22 | #include "crypto/crypto_tls.h" | | 23 | +#include <algorithm> | 23 | 24 | #include <cstdio> | | 25 | +#include <optional> | | 26 | +#include <span> | | 27 | +#include <string_view> | 24 | 28 | #include "async_wrap-inl.h" | 25 | 29 | #include "crypto/crypto_bio.h" | 26 | 30 | #include "crypto/crypto_clienthello-inl.h" | @@ -101,6 +105,93 @@ SSL_SESSION* GetSessionCallback( | 101 | 105 | return w->ReleaseSession(); | 102 | 106 | } | 103 | 107 |
| | 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 | + | 104 | 195 | void OnClientHello( | 105 | 196 | void* arg, | 106 | 197 | const ClientHelloParser::ClientHello& hello) { | @@ -430,6 +521,7 @@ TLSWrap::TLSWrap(Environment* env, | 430 | 521 | ssl_ = sc_->CreateSSL(); | 431 | 522 | CHECK(ssl_); | 432 | 523 |
| | 524 | + sc_->SetClientHelloCallback(EarlyClientHelloCallback); | 433 | 525 | sc_->SetGetSessionCallback(GetSessionCallback); | 434 | 526 | sc_->SetNewSessionCallback(NewSessionCallback); | 435 | 527 |
| @@ -1408,8 +1500,8 @@ int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) { | 1408 | 1500 | Local<Value> ctx = p->object()->Get(env->context(), env->sni_context_string()) | 1409 | 1501 | .FromMaybe(Local<Value>()); | 1410 | 1502 |
| 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; | 1413 | 1505 |
| 1414 | 1506 | if (!env->secure_context_constructor_template()->HasInstance(ctx)) { | 1415 | 1507 | // Failure: incorrect SNI context object | @@ -1429,6 +1521,26 @@ int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) { | 1429 | 1521 | return SSL_TLSEXT_ERR_OK; | 1430 | 1522 | } | 1431 | 1523 |
| | 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 | + | 1432 | 1544 | int TLSWrap::SetCACerts(SecureContext* sc) { | 1433 | 1545 | int err = SSL_set1_verify_cert_store(ssl_.get(), | 1434 | 1546 | SSL_CTX_get_cert_store(sc->ctx().get())); | |
Collapse file Copy file name to clipboardExpand all lines: src/crypto/crypto_tls.h +2Lines changed: 2 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 34 | 34 | #include <openssl/ssl.h> | 35 | 35 |
| 36 | 36 | #include <string> | | 37 | +#include <string_view> | 37 | 38 | #include <vector> | 38 | 39 |
| 39 | 40 | namespace node { | @@ -64,6 +65,7 @@ class TLSWrap : public AsyncWrap, | 64 | 65 | void set_cert_cb_running(bool on = true) { cert_cb_running_ = on; } | 65 | 66 | void set_awaiting_new_session(bool on = true) { awaiting_new_session_ = on; } | 66 | 67 | void enable_session_callbacks() { session_callbacks_ = true; } | | 68 | + bool BindSessionsToServerName(std::string_view servername); | 67 | 69 | bool is_server() const { return kind_ == Kind::kServer; } | 68 | 70 | bool is_client() const { return kind_ == Kind::kClient; } | 69 | 71 | bool is_awaiting_new_session() const { return awaiting_new_session_; } | |
Collapse file Copy file name to clipboard +104Lines changed: 104 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 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 | +})); |
|