You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@trafficserver.apache.org by ez...@apache.org on 2026/10/19 22:03:30 UTC
(trafficserver) 26/30: [9.2.x] Fix mTLS for TLS resumption scenarios
This is an automated email from the ASF dual-hosted git repository.
ezelkow1 pushed a commit to branch 9.2.x
in repository https://gitbox.apache.org/repos/asf/trafficserver.git
commit a6d34195030167f04e43bd965ce58847eadc1f8b
Author: Brian Neradt <br...@gmail.com>
AuthorDate: Fri Sep 11 20:57:49 2026 -0500
[9.2.x] Fix mTLS for TLS resumption scenarios
mTLS on resumed sessions tried to rebuild the client certificate's chain,
which cannot be done: a resumed handshake never asks for a certificate
again, and a serialized session carries the leaf but not the
intermediates that verified it. Every client certificate issued by an
intermediate CA therefore failed on resumption while its fresh
handshakes kept succeeding.
Stop re-deriving trust and instead make a session ineligible to return
under any policy other than the one that verified it, by hashing the
verification scope (server name, verify mode and depth, and the trust
anchors in force) into the session id context both TLS libraries compare
before admitting a resumption. An out-of-scope session is a cache miss
and completes a full handshake under the policy in force now.
Backport of #629. Differences from master, all forced by this branch:
* TLSBasicSupport.h includes P_SSLUtils.h here, where master includes
SSLTypes.h, so the digest type is defined in P_SSLUtils.h instead.
SSLConfigParams reaches it without including TLSBasicSupport.h, which
would be a cycle.
* TLSSNISupport::get_sni_server_name() is added as a public accessor;
only the protected _get_sni_server_name() existed.
* swoc::file::load() and ts::transform_lower() do not exist here, so
ts::file::load() and ink_strlcpy() plus LowerCaseStr() are used.
* The OpenSSL ClientHello callback is gated on TS_USE_HELLO_CB and
returns SSL_CLIENT_HELLO_*, and BoringSSL has its own callback rather
than master's lambda.
* The tests use ssl_multicert.config, proxy.config.ssl.TLSv1_3 rather
than its v10 .enabled spelling, and traffic_manager plus
When.FileContains() for reloads, there being no Test.AddConfigReload().
tls_resume_cert_partition is deliberately not backported. It asserts
that a no-SNI session does not resume against a different
dest_ip-selected certificate, which does not hold on this branch: both
connections are served the first entry's certificate whatever the
destination address, so the test cannot distinguish the behavior it
targets. It tests an ambient property rather than this fix, which is why
its absence leaves the fix covered.
Two existing tests change with the behavior. Their cross-scope sessions
are now declined before the handshake completes, so the post-handshake
rejection they asserted is no longer reached and the client is refused
with a certificate_required alert instead of a reset. They now assert
that handshake evidence, and that the post-handshake guard is not
reached.
Co-Authored-By: Claude Opus 5 <no...@anthropic.com>
---
doc/admin-guide/files/sni.yaml.en.rst | 20 +-
.../monitoring/statistics/core/ssl.en.rst | 15 +-
doc/admin-guide/security/mtls.en.rst | 57 +++--
doc/release-notes/upgrading.en.rst | 16 ++
iocore/net/P_SSLConfig.h | 11 +
iocore/net/P_SSLUtils.h | 20 ++
iocore/net/SSLConfig.cc | 6 +
iocore/net/SSLNetVConnection.cc | 49 ++--
iocore/net/SSLUtils.cc | 235 +++++++++++++++++-
iocore/net/TLSBasicSupport.cc | 82 ++-----
iocore/net/TLSBasicSupport.h | 45 ++--
iocore/net/TLSSNISupport.cc | 6 +
iocore/net/TLSSNISupport.h | 8 +
.../tls/ssl/gen_intermediate_ca_certs.sh | 55 +++++
tests/gold_tests/tls/ssl/intca-root.key | 28 +++
tests/gold_tests/tls/ssl/intca-root.pem | 18 ++
tests/gold_tests/tls/ssl/intca-sub.key | 28 +++
tests/gold_tests/tls/ssl/intca-sub.pem | 19 ++
tests/gold_tests/tls/ssl/intclient.key | 28 +++
tests/gold_tests/tls/ssl/intclient.pem | 19 ++
.../tls/tls_resume_ca_bundle_reload.test.py | 251 +++++++++++++++++++
tests/gold_tests/tls/tls_resume_cross_sni.test.py | 189 +++++++++++++++
.../tls/tls_resume_intermediate_ca.test.py | 265 +++++++++++++++++++++
.../gold_tests/tls/tls_resume_verify_level.test.py | 198 +++++++++++++++
.../tls/tls_ticket_verify_client_ca_scope.test.py | 23 +-
.../tls/tls_ticket_verify_client_scope.test.py | 24 +-
26 files changed, 1553 insertions(+), 162 deletions(-)
diff --git a/doc/admin-guide/files/sni.yaml.en.rst b/doc/admin-guide/files/sni.yaml.en.rst
index 19d0ab9caa..429d22d24b 100644
--- a/doc/admin-guide/files/sni.yaml.en.rst
+++ b/doc/admin-guide/files/sni.yaml.en.rst
@@ -80,15 +80,17 @@ verify_client Inbound One of the values :code:`NONE`,
By default this is :ts:cv:`proxy.config.ssl.client.certification_level`.
- A resumed TLS session does not re-request a client certificate, so |TS|
- enforces ``MODERATE`` and ``STRICT`` against the certificate carried over
- from the session that was resumed, rejecting the handshake if it does not
- satisfy the current SNI's policy. That carried certificate is re-validated
- against the certificate authorities in force for the current SNI rather
- than trusting the result cached by the handshake that issued the session,
- so two SNIs sharing a listener at the same ``verify_client`` level do not
- accept each other's client certificates. Disabling session tickets via
- ``ssl_ticket_enabled`` is not required as a workaround for this.
+ A resumed TLS session does not re-request a client certificate, so |TS| only
+ resumes a session under the SNI and ``verify_client`` policy that issued it,
+ where the policy includes the trust anchors in force. A session offered under any
+ other SNI, after that SNI's policy changed, or after those trust anchors were
+ replaced, falls back to a full handshake in which the current policy is applied.
+ Replacing a bundle file named by ``verify_client_ca_certs`` takes effect on the
+ next connection, whereas replacing :ts:cv:`proxy.config.ssl.CA.cert.filename`
+ takes effect on the next :option:`traffic_ctl config reload`; a hashed directory
+ contributes only its path. Disabling session tickets via ``ssl_ticket_enabled``
+ is not required as a workaround for this. See :ref:`admin-mtls` for the cases
+ where the binding cannot be applied.
verify_client_ca_certs Both Specifies an alternate set of certificate authority certs to use to verify the
client cert. The value must be either a file path, or a nested set of key /
diff --git a/doc/admin-guide/monitoring/statistics/core/ssl.en.rst b/doc/admin-guide/monitoring/statistics/core/ssl.en.rst
index 055a842c6a..1cc9ce50ef 100644
--- a/doc/admin-guide/monitoring/statistics/core/ssl.en.rst
+++ b/doc/admin-guide/monitoring/statistics/core/ssl.en.rst
@@ -191,11 +191,16 @@ SSL/TLS
.. ts:stat:: global proxy.process.ssl.user_agent_resumed_cert_rejected integer
:type: counter
- Incoming client SSL connections rejected because the session they resumed did
- not satisfy the current SNI's :file:`sni.yaml` ``verify_client`` policy, either
- carrying no client certificate where one is required or carrying one that is
- not trusted by the certificate authorities configured for that SNI, since
- statistics collection began.
+ Incoming client SSL connections rejected because the session they resumed
+ carried no client certificate where the current SNI's :file:`sni.yaml`
+ ``verify_client`` policy requires one, since statistics collection began.
+ Sessions are normally bound to the SNI and ``verify_client`` policy that
+ issued them, and a session offered under a different policy is declined by
+ the TLS library and completes a full handshake instead, so this counter is
+ usually zero. It can still be reached where that binding cannot be applied
+ before the TLS library selects a session: on a build providing neither
+ ClientHello callback, and on |TS| built against OpenSSL when a plugin changes
+ client verification from a ``TS_EVENT_SSL_CERT`` hook.
.. ts:stat:: global proxy.process.ssl.user_agent_revoked_cert integer
:type: counter
diff --git a/doc/admin-guide/security/mtls.en.rst b/doc/admin-guide/security/mtls.en.rst
index dc4284c79a..3eb20c84fe 100644
--- a/doc/admin-guide/security/mtls.en.rst
+++ b/doc/admin-guide/security/mtls.en.rst
@@ -17,6 +17,8 @@
.. include:: ../../common.defs
+.. _admin-mtls:
+
Mututal TLS
***********
@@ -101,25 +103,42 @@ Then you would set :ts:cv:`proxy.config.ssl.CA.cert.filename` to client_CA_bundl
Session resumption across co-hosted SNIs
----------------------------------------
TLS session resumption never asks the client for its certificate again, so a resumed session
-carries forward whatever peer certificate the original handshake produced. |TS| therefore
-re-evaluates that certificate against the current SNI's policy as the handshake completes, and
-rejects the handshake when it does not satisfy it: either because the session carries no client
-certificate and the current SNI requires one, or because the certificate it does carry is not
-trusted by the certificate authorities configured for that SNI. Rejections increment
-:ts:stat:`proxy.process.ssl.user_agent_resumed_cert_rejected`.
-
-Note that the certificate is re-validated rather than trusted on the strength of the result
-cached when the session was created. That cached result was reached against whichever CA bundle
-applied to the SNI that issued the session, so relying on it would let two tenants sharing a
-listener at the same ``verify_client`` level accept each other's client certificates.
-
-Two caveats follow. First, a session restored from a ticket may not carry the intermediate
-certificates the client originally presented, so a client certificate issued by an intermediate
-CA needs that intermediate present in the applicable ``verify_client_ca_certs`` bundle (or in
-:ts:cv:`proxy.config.ssl.CA.cert.filename`) for its sessions to survive resumption. Second,
-|TS| cannot bind a ticket to the SNI it was issued under, so resumption between two SNIs that
-both use ``verify_client: NONE`` is still accepted. Where tenants have genuinely different
-security postures, prefer giving them separate listeners rather than co-hosting them on one.
+carries forward whatever peer certificate the original handshake produced. |TS| therefore binds
+every session it issues to the SNI it was issued under together with that SNI's ``verify_client``
+mode and depth, and the trust anchors the client certificate was verified against. A session
+offered under a different SNI, under the same SNI after its policy changed, or after those trust
+anchors were replaced, is not resumed. The TLS library declines it and proceeds with a full
+handshake, in which the current policy is applied as usual. This is what RFC 6066 section 3
+requires of session ID resumption; RFC 8446 imposes no equivalent requirement on TLS 1.3 tickets,
+and |TS| applies the binding to them because that is what makes ``verify_client`` enforceable
+across resumption.
+
+Two tenants sharing a listener therefore do not accept each other's sessions, whatever their
+``verify_client`` levels, except where the binding cannot be established before the TLS library
+selects a session. That is the case on a build providing neither ClientHello callback, and on
+|TS| built against OpenSSL when a plugin changes client verification from a ``TS_EVENT_SSL_CERT``
+hook, because OpenSSL creates and looks up the session before those hooks run.
+
+Which changes retire existing sessions depends on how the trust anchors are configured:
+
+- A bundle file, from ``verify_client_ca_certs``'s ``file`` or from
+ :ts:cv:`proxy.config.ssl.CA.cert.filename`, contributes the certificates it holds. Replacing
+ it in place retires the sessions it verified. For ``verify_client_ca_certs`` this takes effect
+ on the next connection; for :ts:cv:`proxy.config.ssl.CA.cert.filename` it takes effect on the
+ next :option:`traffic_ctl config reload`, because that bundle is read when certificate contexts
+ are built.
+- A hashed directory, from ``verify_client_ca_certs``'s ``dir`` or from
+ :ts:cv:`proxy.config.ssl.CA.cert.path`, contributes only its configured path. Its certificates
+ are read lazily during verification, and reading them on every handshake to discover which are
+ present would cost more than the guarantee is worth. Retiring a trust anchor from such a
+ directory does not retire the sessions it verified; where that matters, use a bundle file.
+
+Because a session can only be resumed under the policy that verified its client certificate, the
+certificate does not have to be re-validated on resumption. A client certificate issued by an
+intermediate CA therefore keeps working across resumption with only the root in the applicable CA
+bundle, exactly as it does on a full handshake. Should a resumed session nonetheless carry no
+client certificate where ``verify_client: STRICT`` requires one, |TS| rejects the handshake and
+increments :ts:stat:`proxy.process.ssl.user_agent_resumed_cert_rejected`.
Guidance for testing
--------------------
diff --git a/doc/release-notes/upgrading.en.rst b/doc/release-notes/upgrading.en.rst
index ded1bbe89e..156f27a808 100644
--- a/doc/release-notes/upgrading.en.rst
+++ b/doc/release-notes/upgrading.en.rst
@@ -72,6 +72,22 @@ a plugin will see outbound sessions pool per certificate, and so more outbound h
``ip,host`` explicitly to select what ``both`` selected before; that also turns the
client-certificate check on session reuse back off.
+Inbound TLS Session Resumption
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Inbound TLS sessions are now bound to the SNI they were issued under and to that
+SNI's ``verify_client`` policy from :file:`sni.yaml`, including the trust anchors
+the client certificate was verified against. A session ticket or session ID
+offered under a different SNI, after the policy for its SNI changed, or after
+those trust anchors were replaced, is no longer resumed and completes a full
+handshake instead. Replacing the bundle named by
+:ts:cv:`proxy.config.ssl.CA.cert.filename` takes effect on the next
+:option:`traffic_ctl config reload`, which is also when a replaced bundle begins
+to apply to fresh handshakes. Clients that key their session caches by hostname,
+which includes browsers and curl, are unaffected. Sessions issued by a previous
+release may not resume after the upgrade and complete a full handshake instead.
+See :ref:`admin-mtls` for details.
+
Connection Management
~~~~~~~~~~~~~~~~~~~~~
diff --git a/iocore/net/P_SSLConfig.h b/iocore/net/P_SSLConfig.h
index 3169729550..6b284ca556 100644
--- a/iocore/net/P_SSLConfig.h
+++ b/iocore/net/P_SSLConfig.h
@@ -31,6 +31,7 @@
#pragma once
#include <atomic>
+#include <optional>
#include <openssl/rand.h>
@@ -73,6 +74,16 @@ struct SSLConfigParams : public ConfigInfo {
char *serverCertChainFilename;
char *serverKeyPathOnly;
char *serverCACertFilename;
+
+ /** Digest of the trust anchors in proxy.config.ssl.CA.cert.filename, for the session id
+ context that scopes session resumption. Held here rather than process-wide so that the
+ handshake path reads it through the same scoped_config it already acquires, and so that it
+ is replaced with the configuration it describes. SSLConfig is always reconfigured before
+ SSLCertificateConfig, so it cannot go stale against the certificate contexts.
+ */
+ std::optional<VerifyScopeDigest> clientCADigest;
+ bool clientCADigestFailed = false;
+
char *serverCACertPath;
char *configFilePath;
char *dhparamsFile;
diff --git a/iocore/net/P_SSLUtils.h b/iocore/net/P_SSLUtils.h
index 0245219b58..7f734543d9 100644
--- a/iocore/net/P_SSLUtils.h
+++ b/iocore/net/P_SSLUtils.h
@@ -34,15 +34,27 @@
#include "records/I_RecCore.h"
#include "P_SSLCertLookup.h"
+#include <array>
#include <map>
#include <set>
#include <memory>
+#include <optional>
+#include <string_view>
struct SSLConfigParams;
class SSLNetVConnection;
typedef int ssl_error_t;
+/** Length of a verify-scope digest, which is a SHA-256 hash.
+
+ Defined here rather than in TLSBasicSupport, which is where master carries it, because this
+ branch's TLSBasicSupport.h includes this header and so cannot be included back from it.
+ */
+static constexpr size_t VERIFY_SCOPE_DIGEST_LENGTH = 32;
+
+using VerifyScopeDigest = std::array<unsigned char, VERIFY_SCOPE_DIGEST_LENGTH>;
+
#ifndef OPENSSL_IS_BORINGSSL
typedef int ssl_curve_id;
#else
@@ -155,6 +167,14 @@ SSLNetVConnection *SSLNetVCAccess(const SSL *ssl);
void setClientCertLevel(SSL *ssl, uint8_t certLevel);
void setClientCertCACerts(SSL *ssl, const char *file, const char *dir);
+
+/** Digest the client CA scope named by @a file and @a dir, for the session id context.
+
+ @return The digest, or no value when neither location is set. A set location that cannot be read
+ also yields no value, with @a failed set, so the caller refuses to resume rather than falling
+ back to a different scope.
+ */
+std::optional<VerifyScopeDigest> digestClientCAScope(std::string_view file, std::string_view dir, bool &failed);
void setTLSValidProtocols(SSL *ssl, unsigned long proto_mask, unsigned long max_mask);
// Helper functions to retrieve sni name or ip address from a SSL object
diff --git a/iocore/net/SSLConfig.cc b/iocore/net/SSLConfig.cc
index 16b2682026..9272f5e43c 100644
--- a/iocore/net/SSLConfig.cc
+++ b/iocore/net/SSLConfig.cc
@@ -391,6 +391,12 @@ SSLConfigParams::initialize()
ats_free(ssl_server_ca_cert_filename);
ats_free(CACertRelativePath);
+ // Digested here, once per configuration load, so that the handshake path never reads the bundle.
+ // Both locations are covered, matching what _set_verify_path() hands to
+ // SSL_CTX_load_verify_locations(), so that retargeting either one retires the sessions it verified.
+ clientCADigest = digestClientCAScope(serverCACertFilename != nullptr ? serverCACertFilename : "",
+ serverCACertPath != nullptr ? serverCACertPath : "", clientCADigestFailed);
+
// SSL session cache configurations
REC_ReadConfigInteger(ssl_origin_session_cache, "proxy.config.ssl.origin_session_cache");
REC_ReadConfigInteger(ssl_origin_session_cache_size, "proxy.config.ssl.origin_session_cache.size");
diff --git a/iocore/net/SSLNetVConnection.cc b/iocore/net/SSLNetVConnection.cc
index 5c8f50756a..1c86717068 100644
--- a/iocore/net/SSLNetVConnection.cc
+++ b/iocore/net/SSLNetVConnection.cc
@@ -1364,33 +1364,40 @@ SSLNetVConnection::sslServerHandShakeEvent(int &err)
switch (ssl_error) {
case SSL_ERROR_NONE:
// A resumed session carries forward the peer cert (or lack of one) from whichever connection
- // originally established it; verify_client for the current SNI was already (re-)applied for
- // this handshake, but a TLS library does not ask the peer for a certificate again on
- // resumption. The verify result it reports is likewise the one cached by the handshake that
- // created the session, evaluated against the CA store that applied to *that* connection's SNI,
- // so it says nothing about whether this SNI trusts the certificate. Re-check both the presence
- // and the trust of that certificate against the policy in force now.
- //
- // Gated on SSL_session_reused() only to keep the chain verification off the fresh-handshake
- // path, where the TLS library has just done the same work against the same store; that flag is
- // the library's own record of this handshake, so it cannot drift from the connection's state.
+ // originally established it, and a TLS library does not ask the peer for a certificate again on
+ // resumption. The session id context that bind_session_id_context_to_verify_scope() establishes
+ // from the ClientHello callback binds every session to the verify_client scope it was issued
+ // under, so the library only resumes sessions whose client certificate this SNI already
+ // verified. Sessions issued before that binding existed, or by a build without it, carry a
+ // different context and fall back to a full handshake. This check is the last line of defense
+ // should a session without a certificate be resumed under a policy that requires one, which a
+ // build with neither ClientHello callback can still admit because its earliest hook runs after
+ // the session lookup.
if (SSL_session_reused(ssl)) {
int verify_mode = SSL_get_verify_mode(ssl);
- if ((verify_mode & SSL_VERIFY_PEER) != 0) {
- bool satisfied = this->peer_provided_cert() ? this->is_peer_cert_trusted_by_current_ca() :
- (verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) == 0;
-
- if (!satisfied) {
- static LogMessage log_msg{IS_THROTTLED};
- SSL_INCREMENT_DYN_STAT(ssl_user_agent_resumed_cert_rejected_stat);
- log_msg.warning(MakeSourceLocation(), "rejecting a resumed TLS session that does not satisfy verify_client");
- SSLVCDebug(this, "rejecting a resumed TLS session that does not satisfy verify_client");
- return EVENT_ERROR;
- }
+ if ((verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) != 0 && !this->peer_provided_cert()) {
+ static LogMessage log_msg{IS_THROTTLED};
+ SSL_INCREMENT_DYN_STAT(ssl_user_agent_resumed_cert_rejected_stat);
+ log_msg.warning(MakeSourceLocation(), "rejecting a resumed TLS session that does not satisfy verify_client");
+ SSLVCDebug(this, "rejecting a resumed TLS session that does not satisfy verify_client");
+ return EVENT_ERROR;
}
}
+ // setClientCertCACerts() runs again from the certificate callback, after the session id context
+ // was established, so a store that loaded for the ClientHello callback and then failed there
+ // would leave this connection verifying against the SSL_CTX's store while the session it issues
+ // claims the scope of the store that did load. That window is checked here rather than only in
+ // bind_session_id_context_to_verify_scope(), which cannot see a failure that happens after it.
+ if (this->verify_scope_digest_failed()) {
+ static LogMessage scope_log_msg{IS_THROTTLED};
+
+ scope_log_msg.warning(MakeSourceLocation(), "rejecting a TLS session whose verify_client scope could not be established");
+ SSLVCDebug(this, "rejecting a TLS session whose verify_client scope could not be established");
+ return EVENT_ERROR;
+ }
+
if (is_debug_tag_set("ssl")) {
X509 *cert = SSL_get_peer_certificate(ssl);
diff --git a/iocore/net/SSLUtils.cc b/iocore/net/SSLUtils.cc
index b27f3b37b4..0cf423c3a3 100644
--- a/iocore/net/SSLUtils.cc
+++ b/iocore/net/SSLUtils.cc
@@ -24,6 +24,7 @@
#include "tscpp/util/TextView.h"
#include "tscore/ink_config.h"
#include "tscore/ink_platform.h"
+#include "tscore/MatcherUtils.h"
#include "tscore/SimpleTokenizer.h"
#include "tscore/I_Layout.h"
#include "tscore/ink_cap.h"
@@ -49,6 +50,8 @@
#include "TLSBasicSupport.h"
#include "tscore/LogMessage.h"
+#include <array>
+#include <optional>
#include <string>
#include <unistd.h>
#include <termios.h>
@@ -65,6 +68,7 @@
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
+#include <openssl/sha.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
@@ -100,6 +104,21 @@ SSLSessionCache *session_cache; // declared extern in P_SSLConfig.h
static int ssl_vc_index = -1;
+/**
+ Register the client CA bundle with the reload machinery.
+
+ The bundle is loaded into each SSL_CTX as it is built, so replacing it in place only takes effect
+ when the contexts are rebuilt. Tracking it alongside the certificate files lets a configuration
+ reload notice the change.
+ */
+static void
+track_client_ca_bundle(const char *file)
+{
+ if (SSLConfigParams::load_ssl_file_cb != nullptr && file != nullptr && file[0] != '\0') {
+ SSLConfigParams::load_ssl_file_cb(file);
+ }
+}
+
static ink_mutex *mutex_buf = nullptr;
static bool open_ssl_initialized = false;
@@ -397,6 +416,8 @@ ssl_verify_client_callback(int preverify_ok, X509_STORE_CTX *ctx)
return preverify_ok;
}
+static bool bind_session_id_context_to_verify_scope(SSL *ssl);
+
#if TS_USE_HELLO_CB
// Pausable callback
static int
@@ -428,6 +449,15 @@ ssl_client_hello_callback(SSL *s, int *al, void *arg)
if (!reenabled) {
return SSL_CLIENT_HELLO_RETRY;
}
+
+ // The last point before OpenSSL creates the session it will issue and looks up the one it was
+ // asked to resume. On BoringSSL this is instead done at the tail of the select_certificate_cb
+ // lambda, because the SSL_CTX switch that certificate selection performs there would discard a
+ // context set now.
+ if (!bind_session_id_context_to_verify_scope(s)) {
+ return SSL_CLIENT_HELLO_ERROR;
+ }
+
return SSL_CLIENT_HELLO_SUCCESS;
}
#elif defined(OPENSSL_IS_BORINGSSL)
@@ -527,6 +557,13 @@ ssl_servername_callback(SSL *ssl, int *al, void *arg)
if (ret != SSL_TLSEXT_ERR_OK) {
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
+
+ // Without a ClientHello callback this is the earliest hook available, which is later than the
+ // TLS library's session lookup. Sessions are still scoped from here on, but a cross-scope
+ // resumption can be admitted before this runs.
+ if (!bind_session_id_context_to_verify_scope(ssl)) {
+ return SSL_TLSEXT_ERR_ALERT_FATAL;
+ }
#endif
} else {
// This error suggests either of these:
@@ -1202,6 +1239,12 @@ SSLMultiCertConfigLoader::_set_handshake_callbacks(SSL_CTX *ctx)
ink_assert(!"unhandled cert result");
}
+ // After ssl_cert_callback(), so this survives the SSL_CTX switch certificate selection performs,
+ // and still ahead of BoringSSL's session lookup.
+ if (res == ssl_select_cert_success && !bind_session_id_context_to_verify_scope(client_hello->ssl)) {
+ res = ssl_select_cert_error;
+ }
+
return res;
});
#endif
@@ -1228,13 +1271,174 @@ setClientCertLevel(SSL *ssl, uint8_t certLevel)
SSL_set_verify_depth(ssl, params->verify_depth); // might want to make configurable at some point.
}
+/**
+ Bind the sessions this connection creates or resumes to its client verification scope.
+
+ A resumed handshake never asks the client for a certificate again, so a session may only be
+ resumed under the policy that already verified it. The session id context, which both TLS
+ libraries compare before admitting a resumption, therefore has to cover everything that decides
+ how a client certificate is verified: the server name, the verify mode and depth, and the trust
+ anchors in force. RFC 6066 section 3 requires this of session ID resumption; RFC 8446 does not
+ require it of tickets.
+
+ It must be set before the TLS library creates the session it will issue or looks up the one it
+ was asked to resume, which is why this runs from the ClientHello callback and unconditionally,
+ rather than from setClientCertCACerts().
+
+ On OpenSSL that is also before the TS_EVENT_SSL_CERT hooks, so a plugin changing verify settings
+ from those hooks leaves the session bound to a scope that is not the one enforced; the
+ TS_EVENT_SSL_CLIENT_HELLO hooks run first and are captured. BoringSSL binds after the
+ certificate hooks and does capture them.
+
+ @return false if the context could not be established, in which case the caller must fail the
+ handshake rather than proceed with one that would permit resumption across scopes.
+ */
+static bool
+bind_session_id_context_to_verify_scope(SSL *ssl)
+{
+ auto *tbs = TLSBasicSupport::getInstance(ssl);
+
+ if (tbs == nullptr) {
+ // Not an inbound connection this applies to, so there is nothing to scope.
+ return true;
+ }
+
+ const char *servername = "";
+
+ if (auto *snis = TLSSNISupport::getInstance(ssl); snis != nullptr) {
+ servername = snis->get_sni_server_name();
+ }
+
+ const int verify_mode = SSL_get_verify_mode(ssl);
+ const int verify_depth = SSL_get_verify_depth(ssl);
+ unsigned char hash_buf[SHA256_DIGEST_LENGTH];
+ SHA256_CTX ctx;
+ auto update = [&ctx](const void *data, size_t len) { SHA256_Update(&ctx, data, len); };
+ auto update_sv = [&update](std::string_view sv) {
+ const uint32_t len = static_cast<uint32_t>(sv.size());
+
+ update(&len, sizeof(len));
+ update(sv.data(), sv.size());
+ };
+ auto update_trust_store = [&]() -> bool {
+ // Sessions that never verified a certificate do not need to be retired when the CA store changes.
+ if ((verify_mode & SSL_VERIFY_PEER) == 0) {
+ return true;
+ }
+ // A store that was selected but could not be digested must not resolve to some other scope.
+ if (tbs->verify_scope_digest_failed()) {
+ return false;
+ }
+ // verify_client_ca_certs installed a store, digested where it was loaded.
+ if (auto const &scope_digest = tbs->get_verify_scope_digest(); scope_digest.has_value()) {
+ update(scope_digest->data(), scope_digest->size());
+ return true;
+ }
+ // Otherwise proxy.config.ssl.CA.cert.filename applies, digested when that configuration loaded.
+ SSLConfig::scoped_config params;
+
+ if (params->clientCADigestFailed) {
+ return false;
+ }
+ if (params->clientCADigest.has_value()) {
+ update(params->clientCADigest->data(), params->clientCADigest->size());
+ return true;
+ }
+ // No global bundle is configured, so there is no trust-anchor term to add.
+ return true;
+ };
+
+ static_assert(SHA256_DIGEST_LENGTH <= SSL_MAX_SID_CTX_LENGTH);
+
+ // Folded because SNIConfigParams::get() lowercases the name before matching, so two spellings
+ // select one policy and have to land in one scope.
+ char folded[TS_MAX_HOST_NAME_LEN + 1];
+
+ ink_strlcpy(folded, servername, sizeof(folded));
+ LowerCaseStr(folded);
+
+ SHA256_Init(&ctx);
+ update_sv(folded);
+ update(&verify_mode, sizeof(verify_mode));
+ update(&verify_depth, sizeof(verify_depth));
+
+ if (!update_trust_store()) {
+ return false;
+ }
+
+ SHA256_Final(hash_buf, &ctx);
+
+ if (SSL_set_session_id_context(ssl, hash_buf, sizeof(hash_buf)) != 1) {
+ SSLError("SSL_set_session_id_context failed for the client verification scope");
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ Digest the client CA scope named by @a file and @a dir, for the session id context.
+
+ A bundle file is covered by its contents, so replacing one in place retires the sessions it
+ verified. This has to be recomputed per connection rather than cached at configuration load,
+ because setClientCertCACerts() reloads the store from disk on every connection: a cached digest
+ would let a resumed session outlive trust anchors that fresh handshakes have already stopped
+ accepting. The cost is one file read, on a path that already reads and parses the same file.
+
+ A hashed directory is covered only by its path. Its certificates are read lazily during
+ verification, so enumerating them here would not see what a later handshake loads.
+
+ @return The digest, or no value when neither location is set. A set location that cannot be read
+ also yields no value, with @a failed set, so the caller refuses to resume rather than falling
+ back to a different scope.
+ */
+std::optional<VerifyScopeDigest>
+digestClientCAScope(std::string_view file, std::string_view dir, bool &failed)
+{
+ failed = false;
+
+ if (file.empty() && dir.empty()) {
+ return std::nullopt;
+ }
+
+ VerifyScopeDigest scope_digest;
+ SHA256_CTX ctx;
+ auto update_sv = [&ctx](std::string_view sv) {
+ const uint32_t len = static_cast<uint32_t>(sv.size());
+
+ SHA256_Update(&ctx, &len, sizeof(len));
+ SHA256_Update(&ctx, sv.data(), sv.size());
+ };
+
+ static_assert(VERIFY_SCOPE_DIGEST_LENGTH == SHA256_DIGEST_LENGTH);
+
+ SHA256_Init(&ctx);
+ update_sv(file);
+ update_sv(dir);
+
+ if (!file.empty()) {
+ std::error_code ec;
+ std::string contents = ts::file::load(ts::file::path{std::string{file}}, ec);
+
+ if (ec) {
+ // Deliberately not naming verify_client_ca_certs: this also digests the bundle from
+ // proxy.config.ssl.CA.cert.filename.
+ SSLError("failed to read client CA file '%.*s' for the session id context", static_cast<int>(file.size()), file.data());
+ failed = true;
+ return std::nullopt;
+ }
+ update_sv(contents);
+ }
+
+ SHA256_Final(scope_digest.data(), &ctx);
+
+ return scope_digest;
+}
+
void
setClientCertCACerts(SSL *ssl, const char *file, const char *dir)
{
- // Remembered on the connection because a resumed session's peer certificate has to be re-verified
- // against whichever store the current SNI selected, and the TLS libraries do not uniformly expose
- // a way to read that store back off the SSL object.
- X509_STORE *verify_store = nullptr;
+ bool store_failed = false;
if ((file != nullptr && file[0] != '\0') || (dir != nullptr && dir[0] != '\0')) {
#if TS_HAS_VERIFY_CERT_STORE
@@ -1243,14 +1447,12 @@ setClientCertCACerts(SSL *ssl, const char *file, const char *dir)
if (ctx != nullptr &&
X509_STORE_load_locations(ctx, file && file[0] != '\0' ? file : nullptr, dir && dir[0] != '\0' ? dir : nullptr)) {
SSL_set0_verify_cert_store(ssl, ctx);
- verify_store = ctx;
} else {
- // Leaving verify_store null here would silently fall back to the global CA
- // store on the resumption recheck, so an unusable path must be visible.
- static LogMessage log_msg{IS_THROTTLED};
- log_msg.warning(MakeSourceLocation(), "failed to load verify_client_ca_certs (file '%s', dir '%s')",
- file != nullptr ? file : "", dir != nullptr ? dir : "");
+ // Leaving this unset would silently verify the client against whichever store the SSL_CTX
+ // carries, which is not the one sni.yaml asked for. The connection is failed instead.
+ SSLError("failed to load verify_client_ca_certs file '%s' dir '%s'", file != nullptr ? file : "", dir != nullptr ? dir : "");
X509_STORE_free(ctx);
+ store_failed = true;
}
// SSL_set_client_CA_list takes ownership of the STACK_OF(X509) structure
@@ -1263,8 +1465,17 @@ setClientCertCACerts(SSL *ssl, const char *file, const char *dir)
#endif
}
+ // Recorded rather than applied here: the session id context has to be in place before the TLS
+ // library creates or looks up a session, which on OpenSSL is before this function's callers run.
if (auto *tbs = TLSBasicSupport::getInstance(ssl); tbs != nullptr) {
- tbs->set_verify_cert_store(verify_store);
+ bool digest_failed = false;
+ auto scope_digest = digestClientCAScope(file != nullptr ? file : "", dir != nullptr ? dir : "", digest_failed);
+
+ if (store_failed || digest_failed) {
+ tbs->mark_verify_scope_digest_failed();
+ } else {
+ tbs->set_verify_scope_digest(scope_digest);
+ }
}
}
@@ -1517,6 +1728,7 @@ SSLMultiCertConfigLoader::_set_verify_path(SSL_CTX *ctx, const SSLMultiCertConfi
(!params->serverCACertPath || params->serverCACertPath[0] == '\0') ? "[empty path]" : params->serverCACertPath);
return false;
}
+ track_client_ca_bundle(params->serverCACertFilename);
}
return true;
}
@@ -1556,6 +1768,7 @@ SSLMultiCertConfigLoader::_setup_client_cert_verification(SSL_CTX *ctx)
(!params->serverCACertPath || params->serverCACertPath[0] == '\0') ? "[empty path]" : params->serverCACertPath);
return false;
}
+ track_client_ca_bundle(params->serverCACertFilename);
}
if (params->clientCertLevel == 2) {
diff --git a/iocore/net/TLSBasicSupport.cc b/iocore/net/TLSBasicSupport.cc
index cb2e566e3c..528b83cd09 100644
--- a/iocore/net/TLSBasicSupport.cc
+++ b/iocore/net/TLSBasicSupport.cc
@@ -25,11 +25,6 @@
#include "TLSBasicSupport.h"
#include "SSLStats.h"
-#include <openssl/x509.h>
-#include <openssl/x509_vfy.h>
-
-#include <memory>
-
int TLSBasicSupport::_ex_data_index = -1;
void
@@ -62,73 +57,36 @@ TLSBasicSupport::unbind(SSL *ssl)
void
TLSBasicSupport::clear()
{
- this->set_verify_cert_store(nullptr);
- this->_tls_handshake_begin_time = 0;
- this->_tls_handshake_end_time = 0;
+ this->_verify_scope_digest.reset();
+ this->_verify_scope_digest_failed = false;
+ this->_tls_handshake_begin_time = 0;
+ this->_tls_handshake_end_time = 0;
}
void
-TLSBasicSupport::set_verify_cert_store(X509_STORE *store)
+TLSBasicSupport::set_verify_scope_digest(std::optional<VerifyScopeDigest> const &digest)
{
- if (this->_verify_cert_store == store) {
- return;
- }
+ this->_verify_scope_digest = digest;
+ this->_verify_scope_digest_failed = false;
+}
- if (store != nullptr) {
- X509_STORE_up_ref(store);
- }
- if (this->_verify_cert_store != nullptr) {
- X509_STORE_free(this->_verify_cert_store);
- }
- this->_verify_cert_store = store;
+void
+TLSBasicSupport::mark_verify_scope_digest_failed()
+{
+ this->_verify_scope_digest.reset();
+ this->_verify_scope_digest_failed = true;
}
bool
-TLSBasicSupport::is_peer_cert_trusted_by_current_ca() const
+TLSBasicSupport::verify_scope_digest_failed() const
{
- SSL *ssl = this->_get_ssl_object();
-
- if (ssl == nullptr) {
- return false;
- }
-
- // Without a verify_client_ca_certs override for this SNI, the context's own store is what the
- // handshake would have used.
- X509_STORE *store = this->_verify_cert_store != nullptr ? this->_verify_cert_store : SSL_CTX_get_cert_store(SSL_get_SSL_CTX(ssl));
-
- if (store == nullptr) {
- return false;
- }
-
- // SSL_get_peer_certificate is what the rest of this branch uses (see
- // peer_provided_cert() and the handshake paths); it is available on every TLS
- // library 9.2.x supports, including BoringSSL, which has no
- // SSL_get1_peer_certificate.
- std::unique_ptr<X509, decltype(&X509_free)> peer_cert{SSL_get_peer_certificate(ssl), &X509_free};
-
- if (peer_cert == nullptr) {
- return false;
- }
-
- std::unique_ptr<X509_STORE_CTX, decltype(&X509_STORE_CTX_free)> store_ctx{X509_STORE_CTX_new(), &X509_STORE_CTX_free};
-
- if (store_ctx == nullptr) {
- return false;
- }
-
- STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl);
-
- if (X509_STORE_CTX_init(store_ctx.get(), store, peer_cert.get(), chain) != 1) {
- return false;
- }
-
- // Match what the TLS library itself applies to a client certificate during a full handshake.
- if (X509_STORE_CTX_set_default(store_ctx.get(), "ssl_client") != 1 ||
- X509_VERIFY_PARAM_set1(X509_STORE_CTX_get0_param(store_ctx.get()), SSL_get0_param(ssl)) != 1) {
- return false;
- }
+ return this->_verify_scope_digest_failed;
+}
- return X509_verify_cert(store_ctx.get()) == 1;
+std::optional<TLSBasicSupport::VerifyScopeDigest> const &
+TLSBasicSupport::get_verify_scope_digest() const
+{
+ return this->_verify_scope_digest;
}
const char *
diff --git a/iocore/net/TLSBasicSupport.h b/iocore/net/TLSBasicSupport.h
index e1f8231a31..fa1985c664 100644
--- a/iocore/net/TLSBasicSupport.h
+++ b/iocore/net/TLSBasicSupport.h
@@ -24,6 +24,8 @@
#pragma once
+#include <optional>
+
#include <openssl/ssl.h>
#include "tscore/ink_hrtime.h"
@@ -45,27 +47,41 @@ public:
ink_hrtime get_tls_handshake_begin_time() const;
ink_hrtime get_tls_handshake_end_time() const;
+ /// Length of a verify-scope digest, which is a SHA-256 hash. Defined in P_SSLUtils.h, which
+ /// SSLConfigParams can reach without including this header.
+ static constexpr size_t VERIFY_SCOPE_DIGEST_LENGTH = ::VERIFY_SCOPE_DIGEST_LENGTH;
+
+ using VerifyScopeDigest = ::VerifyScopeDigest;
+
/**
- * Records the CA store being used to verify this connection's client certificate.
+ * Records a digest of the CA store sni.yaml's verify_client_ca_certs selected for this connection.
*
- * sni.yaml's verify_client_ca_certs installs a store on the connection, and the TLS libraries do
- * not uniformly let that store be read back, so it is remembered here as it is applied.
+ * The digest is taken where the store is loaded, because the TLS libraries do not uniformly let a
+ * store be read back off the SSL object, and because it must be folded into the session id context
+ * before the TLS library creates or looks up a session.
*
- * @param store The store selected for the current SNI, or nullptr when the SSL_CTX's store applies.
+ * @param digest Digest of the selected store, or no value when the SSL_CTX's own store applies.
*/
- void set_verify_cert_store(X509_STORE *store);
+ void set_verify_scope_digest(std::optional<VerifyScopeDigest> const &digest);
/**
- * Re-verifies the peer certificate against the CA store in effect for this connection.
+ * Records that a store was selected for this connection but could not be digested.
*
- * A resumed session carries forward the verification result cached by whichever handshake created
- * it, evaluated against the CA store that applied to that connection's SNI. Re-running the chain
- * verification is the only portable way to tell whether the peer certificate is trusted by the
- * SNI in use now.
- *
- * @return true if the peer presented a certificate that chains to a CA this connection trusts.
+ * Distinct from having no store at all: a failure must not silently resolve to some other scope,
+ * so the handshake is failed rather than bound to a context that would permit resumption across
+ * scopes.
+ */
+ void mark_verify_scope_digest_failed();
+
+ /**
+ * @return true if a store was selected but could not be loaded or digested.
+ */
+ bool verify_scope_digest_failed() const;
+
+ /**
+ * @return The digest recorded by set_verify_scope_digest(), if any.
*/
- bool is_peer_cert_trusted_by_current_ca() const;
+ std::optional<VerifyScopeDigest> const &get_verify_scope_digest() const;
protected:
void clear();
@@ -79,7 +95,8 @@ protected:
private:
static int _ex_data_index;
- X509_STORE *_verify_cert_store = nullptr;
+ std::optional<VerifyScopeDigest> _verify_scope_digest;
+ bool _verify_scope_digest_failed = false;
ink_hrtime _tls_handshake_begin_time = 0;
ink_hrtime _tls_handshake_end_time = 0;
diff --git a/iocore/net/TLSSNISupport.cc b/iocore/net/TLSSNISupport.cc
index b39f8f9046..3889321e24 100644
--- a/iocore/net/TLSSNISupport.cc
+++ b/iocore/net/TLSSNISupport.cc
@@ -141,6 +141,12 @@ TLSSNISupport::_clear()
_sni_server_name.reset();
}
+const char *
+TLSSNISupport::get_sni_server_name() const
+{
+ return this->_get_sni_server_name();
+}
+
const char *
TLSSNISupport::_get_sni_server_name() const
{
diff --git a/iocore/net/TLSSNISupport.h b/iocore/net/TLSSNISupport.h
index e8614ffa9b..10ba721f7a 100644
--- a/iocore/net/TLSSNISupport.h
+++ b/iocore/net/TLSSNISupport.h
@@ -40,6 +40,14 @@ public:
static void unbind(SSL *ssl);
int perform_sni_action();
+
+ /**
+ * @return The SNI server name this connection sent, or the empty string when it sent none.
+ *
+ * Public because the session id context that scopes resumption is derived from it, and that has
+ * to happen from the ClientHello callback, before the TLS library populates SSL_get_servername().
+ */
+ const char *get_sni_server_name() const;
// Callback functions for OpenSSL libraries
#if TS_USE_HELLO_CB || defined(OPENSSL_IS_BORINGSSL)
#ifdef OPENSSL_IS_BORINGSSL
diff --git a/tests/gold_tests/tls/ssl/gen_intermediate_ca_certs.sh b/tests/gold_tests/tls/ssl/gen_intermediate_ca_certs.sh
new file mode 100755
index 0000000000..e171ff9e67
--- /dev/null
+++ b/tests/gold_tests/tls/ssl/gen_intermediate_ca_certs.sh
@@ -0,0 +1,55 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Generate a three-level client PKI for the tls_resume_intermediate_ca Au test:
+#
+# intca-root (self-signed root CA)
+# -> intca-sub (intermediate CA)
+# -> intclient (client leaf certificate)
+#
+# The test configures ATS to trust only intca-root and has the client present
+# intclient together with intca-sub, so the intermediate must be supplied by the
+# client during the handshake rather than by the server's trust store.
+
+set -euo pipefail
+
+cd "$(dirname "$0")"
+
+rm -f intca-root.key intca-root.pem intca-sub.key intca-sub.pem intclient.key intclient.pem
+
+openssl genrsa -out intca-root.key 2048
+openssl req -config ./openssl.cnf -x509 -new -nodes -subj /CN=intca-root \
+ -addext "basicConstraints=critical,CA:TRUE" \
+ -addext "keyUsage=critical,keyCertSign,cRLSign" \
+ -key intca-root.key -sha256 -days 36500 -batch -out intca-root.pem
+
+openssl genrsa -out intca-sub.key 2048
+openssl req -config ./openssl.cnf -new -subj /CN=intca-sub -key intca-sub.key -batch -out tmp.csr
+openssl x509 -req -in tmp.csr -CA intca-root.pem -CAkey intca-root.key -set_serial 0x10 \
+ -days 36500 -sha256 -out intca-sub.pem \
+ -extfile <(printf 'basicConstraints=critical,CA:TRUE,pathlen:0\nkeyUsage=critical,keyCertSign,cRLSign\n')
+
+openssl genrsa -out intclient.key 2048
+openssl req -config ./openssl.cnf -new -subj /CN=intclient -key intclient.key -batch -out tmp.csr
+openssl x509 -req -in tmp.csr -CA intca-sub.pem -CAkey intca-sub.key -set_serial 0x11 \
+ -days 36500 -sha256 -out intclient.pem \
+ -extfile <(printf 'basicConstraints=CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=clientAuth\n')
+
+rm -f tmp.csr
+
+openssl verify -CAfile intca-root.pem -untrusted intca-sub.pem intclient.pem
diff --git a/tests/gold_tests/tls/ssl/intca-root.key b/tests/gold_tests/tls/ssl/intca-root.key
new file mode 100644
index 0000000000..406c5096ad
--- /dev/null
+++ b/tests/gold_tests/tls/ssl/intca-root.key
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDFlYYslMAxjt9f
+X6kIv+fn710MB340Pe55hiemcZJvy5oNj3IZgQGN7VtEHWNnGh4NW0p8Dw73okpz
+dWupnSF6nTupZNMjPi0hv0Dznoc/nO5zk7uPkAPX6878nD5vESR97LPH01LCKPPs
+XAGnk5RmaManFvGTUNMgrP5KV2MU5DZYDJGunu1JOpo1OfIyLp82v+pv06RWI27i
+voL1/anPC1o0bOza7qZpUCjGZrMRsbfTjKoV+HUbkdixTl4/EHqO042Kc72ZndZb
+5bDC1ZAfxgtBwE10m2m+rQybSAl4ecJEJALq2az+uvTTqMeHyYG4CvZyLpiq8zq0
++5/rNkaZAgMBAAECggEAUTD81kP36EV4B7aE/OnzD21edGt90lTisoBMucowrQzi
+zJC2B8Hp1BsFpmtXJg5m7AEoDeuYMG05n9FQAP5nO/3xfs3GL1TE8fmn5JQvqpW/
+rLG34KoC0k79mvNPeo92SeKjC8mMV+nBNk6mhWiREjYa751vfqQ3ZdWAlybqubHG
+RFsVxzTEl4fj/6dGWzPtyMaLgI2+CDTGU6f+vu3MZHamO/i5bWpLC1t9rhyGdeeR
+gCWllYSaW+CF/pK+Z/nl9bHyCT/JyijeL/gB7khuMKvUTzEOc7bSxvOmiIEYmvEv
+YQyaL0CRhJt5tTlWzNq+KApEiwYwSnkVHWgCC5uFAwKBgQDyOORCzZBK37E3kpAM
+wTHipSFx4Z4JUNYtEp4zV3soili/au1RU9ljaIk+XTJPGiAfcsEFL3VSmOqsicn3
+y7p0nkyDGUAQxd5XDWNhJHGMKYoTp+V9llt731pqWBaTWDyohbmImFfrpjPJS62z
+3u9Z8/v6dr95muK3wOx2Ct9S1wKBgQDQ0qLOJsrZcujhvTJpPw8toqoxoXOtuCrm
++sMYulBz/G2kT5g0g94xs2XzKjsD9Sdo78Xo7Gd20tY6aFmqmLrDW+ciXegM1nXi
+eWv6TM/bIgET+KdzMSwZkFfhmplkyWYokOzlsYHFjiaw74/ZdSJ3jSXr3x5O6gcT
+d7mYokF0DwKBgQCPiU8alx4OgIhP2jYqmMGrARfUmFJCSvjgNMwyuIBvAaydoguH
+yhxkYCoUHr4VSfIHMMVZAUqQ67UFEZHxmXSgbr4AYhIo3lhnVbOyeRogaO09wJyp
+01PbD/xQUGrwXbV0V+oeG8jeB9tgScxhbpZ/w6lqPrwwn6wCH/z/5ml4eQKBgQCi
+0/u6v6jgkadhjgNm6ZLORM5s0LXAuaBKZzIFcBIXvrdHrgDCwihZnMdcKovF9Dz8
+qCosC1pJ3vDIrmFskpbeiiTaOVsd14QoSgGWNJrHBebNSdBYE/mNHW5JLiF540jT
+TN5L5HOKNeOZh9Mk/x8XFWqCV4HsirNlzK9dgveCpQKBgEkE9QCCHLIONKeILqpu
+uid5yYdP0Cyfa7Rk/IEcjUci8QI14y2r7PIWhn0h7AoxIacNGXH1qyX1ZH9ZJS84
+pvBY5C+auunEmopSHJNExtSPylxhDDfx+JGqYGHnkjyfKBCyjn3J24IBepYKgN7q
+GiR1bNkCYh0A1gGtIkMsr2b2
+-----END PRIVATE KEY-----
diff --git a/tests/gold_tests/tls/ssl/intca-root.pem b/tests/gold_tests/tls/ssl/intca-root.pem
new file mode 100644
index 0000000000..828b3abf2a
--- /dev/null
+++ b/tests/gold_tests/tls/ssl/intca-root.pem
@@ -0,0 +1,18 @@
+-----BEGIN CERTIFICATE-----
+MIIC/DCCAeSgAwIBAgIUEDWkZZ7JZ8VqkaCxlCPXQskC+DkwDQYJKoZIhvcNAQEL
+BQAwFTETMBEGA1UEAwwKaW50Y2Etcm9vdDAgFw0yNjA5MDQyMDA2MDNaGA8yMTI2
+MDgxMTIwMDYwM1owFTETMBEGA1UEAwwKaW50Y2Etcm9vdDCCASIwDQYJKoZIhvcN
+AQEBBQADggEPADCCAQoCggEBAMWVhiyUwDGO319fqQi/5+fvXQwHfjQ97nmGJ6Zx
+km/Lmg2PchmBAY3tW0QdY2caHg1bSnwPDveiSnN1a6mdIXqdO6lk0yM+LSG/QPOe
+hz+c7nOTu4+QA9frzvycPm8RJH3ss8fTUsIo8+xcAaeTlGZoxqcW8ZNQ0yCs/kpX
+YxTkNlgMka6e7Uk6mjU58jIunza/6m/TpFYjbuK+gvX9qc8LWjRs7NrupmlQKMZm
+sxGxt9OMqhX4dRuR2LFOXj8Qeo7TjYpzvZmd1lvlsMLVkB/GC0HATXSbab6tDJtI
+CXh5wkQkAurZrP669NOox4fJgbgK9nIumKrzOrT7n+s2RpkCAwEAAaNCMEAwDwYD
+VR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFKuVOo5q76MF
+6qVXTuV3Wps0ADTiMA0GCSqGSIb3DQEBCwUAA4IBAQCRYSfvU1mrqtVwVMmxmnN5
+z+RUwIBQW0qi7SQ4jOCAkHG6MmVhlD982vx1iEqwTSEhwF/MhZMOtD6LOF4GDIME
+9Gu7ohFRxYmav2cp2fi+H4YxUEJnOxjOaY6uVlosNidPoimJynGb6xDty6Jr3AtR
+xgEaT4VK6Ca0F9r7m3pwDlGkoJGyOOKfRiC+RUSOpbMV/C3MVM6uUv5JitiXrpzG
+GOfWr/2fYfEpxxb6i9QAHSwI9kVJcGdemiheN8dZGut2cm+Rxr9HXzFGFSbV7Y95
+pK+h9uih2AWsygwyJXqUwTps0GOJZRGkOCPZqBIhYiqSyNiTmJ9iqatXOhG/6LiD
+-----END CERTIFICATE-----
diff --git a/tests/gold_tests/tls/ssl/intca-sub.key b/tests/gold_tests/tls/ssl/intca-sub.key
new file mode 100644
index 0000000000..455620d8f4
--- /dev/null
+++ b/tests/gold_tests/tls/ssl/intca-sub.key
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCuqlFU016pwCXs
+FQJtF3zFgPQjUsfqtYRLTULrMAAXux/Q0jjZDo8La/A9tOzznVGPgn6sFt7F2tdl
+VIIp0p6GEMPoUKtRvMWyVZIIEDWgxDhSxLuKF/e6mdsFEvnj+ztdQhvIGY/kazE6
+WbMezOPui+tUgFyATDqrtHuqQ5JcjzuWaH6OzdLGB9Zo681Jjwg9e8qwr7Nx4rxE
+XyU55P7OSfk7fwEBER+QTeyicYYG+J+G6uwZ9MAsFrvsbskPIXn8KIlvIvmvirRM
+T84IT2ZgUd6zbRxYYl+IHV4CGtRB/3Q+m/5DJK7D7IRyAE0EhvJgZnGNLtB7G+VL
+ik26NT0ZAgMBAAECggEAAy6Uoo+Ni65LB+Y+aqeGd8r4h5/gMaaCurl1WjdVZRlH
+rtme51YPJTrfP/czaDZp5Yv6dp7zCivesoNL3MBaxXVO5a+kiK3ASeuqUvhyoFNl
+dZ03umq4h18lVji+hy33lU8ZQPe1lJ3JojcUnt9w2T1reS5edl2NJb15EZoUs5gb
+r7L/TN8rZkawF1+u3V1/naMRCOgZKAP/V9kxMSlz3zdcYbT0oaP+hJHAK4mZN9eO
+QKyiHsAuM5MERNadZQJkbAkaT4vWQb6VG7D4RNT7/0dVAr6kUD3SQgUHtcAF2kqq
+Tdb/vHH2H21HZaH+7dIxTj/RarL49Fw4Tr+Qstms5QKBgQDhBKQ2kl1N6FjL5TaZ
+D4dqO3gf8kiDV/ZxVtJcIYZCJHYrYsFzfiHBxo1Dz43eaJgEumG0pgFd049+WG8j
+Lk6G32IEkAgbo2etWkh/U6Rja95hKzOWo2MH0diw9raJk+SgSV0aOdrcIPZuh1Bs
+HDeyVLw1Veq1HOD3gOFz2iQZzQKBgQDGttuZed0wl7FJATpTZYhmCHGOaQkGqHGe
+9cwsfhBJoFxebELCpjK2xtqbSgykwS4I6HiJMJgRuQY2A+EmfGVcH1NIf4NnXb2H
+3E1AtCYt1g7UVokqvxBsxvL8dn+XJJF0DrJbkdmBblMFXyh6CvdK9S2Mx9hGLkmm
+8003M7M0fQKBgEzBO46N4JvZnKh4WGZfgK6A+JnVGF0NHThOCFV67gQT0ec8uYY+
+yR8DLl6qJtdt0CUUuo1XbvHlX3YWjlpuykSBYDr0Mn/S/mOIf2BHVLTBL8rvZJqG
+wxoAv6yli2BkfUEbpVFz2K7r44OSTqGCApGnC8gZtYTwA+EJKl5NU7ElAoGBAJvC
+NTuF5DT0kkgxKDC6g0HHGIuSFTscyYLaE+JEJiwwAHca0PGWKGZQVIYocuSpb5YX
+8nNGncw2hYHNZKwwEZs2CqfnG27ocWmO6xbunoaLJTCXbAkPnqZFA62UjMpCJakc
+4/0Ww7DKc1Tgk++lrNUafUu+Ue4g1iaAy2ObqLpZAoGAB+O+bQDBJnAd2LxBqegX
+JxRrUcgFvzrhJMPhSaOc1p8/7u2Q583FKJdlSnHcyBbDldPvEt6q7fOpNdAHF54R
+V0M/rWvGK9I1GRJMq5KsZRgJLiEdsG2FvyfVheo46ClGhf5OC8yE9YqwCjhJyV1a
+398aE6yBp1dHp7Qy5V++7EQ=
+-----END PRIVATE KEY-----
diff --git a/tests/gold_tests/tls/ssl/intca-sub.pem b/tests/gold_tests/tls/ssl/intca-sub.pem
new file mode 100644
index 0000000000..07d1c8e324
--- /dev/null
+++ b/tests/gold_tests/tls/ssl/intca-sub.pem
@@ -0,0 +1,19 @@
+-----BEGIN CERTIFICATE-----
+MIIDDDCCAfSgAwIBAgIBEDANBgkqhkiG9w0BAQsFADAVMRMwEQYDVQQDDAppbnRj
+YS1yb290MCAXDTI2MDkwNDIwMDYwM1oYDzIxMjYwODExMjAwNjAzWjAUMRIwEAYD
+VQQDDAlpbnRjYS1zdWIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCu
+qlFU016pwCXsFQJtF3zFgPQjUsfqtYRLTULrMAAXux/Q0jjZDo8La/A9tOzznVGP
+gn6sFt7F2tdlVIIp0p6GEMPoUKtRvMWyVZIIEDWgxDhSxLuKF/e6mdsFEvnj+ztd
+QhvIGY/kazE6WbMezOPui+tUgFyATDqrtHuqQ5JcjzuWaH6OzdLGB9Zo681Jjwg9
+e8qwr7Nx4rxEXyU55P7OSfk7fwEBER+QTeyicYYG+J+G6uwZ9MAsFrvsbskPIXn8
+KIlvIvmvirRMT84IT2ZgUd6zbRxYYl+IHV4CGtRB/3Q+m/5DJK7D7IRyAE0EhvJg
+ZnGNLtB7G+VLik26NT0ZAgMBAAGjZjBkMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYD
+VR0PAQH/BAQDAgEGMB0GA1UdDgQWBBQEVHjmwNEwjgiJiVUKRbyjQdBd+TAfBgNV
+HSMEGDAWgBSrlTqOau+jBeqlV07ld1qbNAA04jANBgkqhkiG9w0BAQsFAAOCAQEA
+oTM+lYq+jLCfLFPt9eNiO6CdGZELuPLhDpyj5S6I5tOJlFduR38jQTefaC3Veuvl
+Df3IdZ5Ilq/NV8/up6KJ9W8pO0umQjocIOVjrhpAt3v3LDq/Knt0xt1IoZxCpgEV
+gKePYeKan4mQPgxhES2EXBNm8JACI/iDUazJDsNhD26kSSUnnNvsUywXsj8PhjM/
+DeIEYt53GCh4/NHQcj7SOcJAOLHICJm8N8SBYASLt00B2tWTF0x9+poWeHL3OxQn
+PCWJJd+UqVFDD7qWuc9wT6mXBGMBNhYWdBpk9DocfWHSAPCvw2mB7lsQsQtiz6xu
+PwqsncgBS8Q2UXrkmlYaEQ==
+-----END CERTIFICATE-----
diff --git a/tests/gold_tests/tls/ssl/intclient.key b/tests/gold_tests/tls/ssl/intclient.key
new file mode 100644
index 0000000000..7373dcea9d
--- /dev/null
+++ b/tests/gold_tests/tls/ssl/intclient.key
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC+6jkIk45n/ho0
+VYaKm3gEbRGfzUH508BX/BCOzBBx7QFgCMpLQwCC5MuKXYx0utvcer24Y4KEEDMj
+clgqJD/ToBdMOV58+a1xwcSKWkFvKK9w9tT5x37hVVVBQDfUEmEiKUe+rPRwH2hQ
+lrEyrX6EphaXAwDe4deI6YEsW4UufYLrk80b4wJZHl9z7wCQVNoT2RO9nXYSHVwX
+64SKUuMhctgb8ieYec2SXUBFTtsqXwCh4cXi6ZgCMervWil0mbYEJvXxsxnkcRVM
+OX6F7K/SiNfZj7TswGNFNhkPrId6Ae9mLntHTsA+vFPt9bAK2YDTapWKsQXxjwMJ
+dXYtGf7JAgMBAAECggEAAqXjBqBtUDnxCRrKk++WGZGdtfa13I44U8AWRrTD4aCk
+7T0R+TtDrY0Y2aF0ikXxOLynFwCiVcyXuP0kBemczQWibRc6nUclRbenTzfzQmRx
+EoMJ7zD6LIvvc8k9PP7IRB4IdbeWaFu3Ka79ZDON1q8rDwsmnvDI+Ygrl37pePyU
+go+kSwofz9QqeENafAoFjSjHmB/ERYCRT3VKchyVV6ztXz8F3UkqZKpzIZNzj4kP
+5XWFQnhC0+2qeGZ4dH6gk26vYQXao2mf/JeogHXqZNi2u9ScNnga3yq9BT/gFtoS
+OwdNYygNlSg5Cx+y3vo60+IEldAHn8/fDLExJTdDAQKBgQD1rb2D1/CthBqfrZD4
+IrId4Ib/gtzgDCuhVVlnvF2ZHW92nM45xRcIbXyJ7Ji+tpWG1KXPVxgSkNE6J1l7
+rq6w40BmZVHZ84smxd/G06YiNXH/iZJX4BKs/gqJHu4A+JESmBArMv4GWt9dOzCL
+GWXEqhmun/y0Xb/R1YAd1OfpYQKBgQDG74BuP5rJcHrLM2g+G9Ip/Ac8P3A16YuN
+IQdMATTPJyQJTFYHFdd0XT9lgxK6cwxht250J7GdC9o927u4fBu4yl4GMjF36PA9
+Uck3PZBhdwoCHyvR5yHtrqMzkd1outkKrrUl/NDwv5aACQVbY3us6/buSXCa2GMW
+AgrLamMGaQKBgH3a7DvvUm9BPnZQbvR+qapejCm2uznXYj56v5tBxt0aVDB6Mbcs
+fRknJWZumu0QEdeJdguafU19fIGDCPcwTHN3Z1VNUDoL5lwNgA6V/ASIRob2zc5Q
+jqCqX3FRM/GxZHgXCClpLPLKeKSFHuATOawey5tGgClR4WM4MTKXD9rhAoGAKOvR
+RlxtEazChZQQiF4esCY4ssr14REmdKRrpNXGsCoD/qmmNJTomfYoeVAqBRJvZJZf
+8SLNJVnvzbOqfLuC1FNEXg/rHxhaerKdKnDOh03+UAtrbyUVVJgM2CnUGpv803a2
+qpbDwBIY+kNgx7jCEwMC62dN83w5fahz4f4DWqkCgYAeAbzAz3n/e7/7MSXFzlQd
+kb+uOz6QhiKJPY8vSF4TgmcvNhY4CI84FTqngD60KAVirmqEX47HTQUXSLZD/h7+
+xa+XXIWBf/YzBqOUVXSm6aBmZdqKhIPopJSSnSPEbfw6GrK19IRg7BVwMKGdN3sv
+2cFQCt2RmwWbhjQNX3VhwA==
+-----END PRIVATE KEY-----
diff --git a/tests/gold_tests/tls/ssl/intclient.pem b/tests/gold_tests/tls/ssl/intclient.pem
new file mode 100644
index 0000000000..96109eec79
--- /dev/null
+++ b/tests/gold_tests/tls/ssl/intclient.pem
@@ -0,0 +1,19 @@
+-----BEGIN CERTIFICATE-----
+MIIDFzCCAf+gAwIBAgIBETANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAlpbnRj
+YS1zdWIwIBcNMjYwOTA0MjAwNjAzWhgPMjEyNjA4MTEyMDA2MDNaMBQxEjAQBgNV
+BAMMCWludGNsaWVudDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL7q
+OQiTjmf+GjRVhoqbeARtEZ/NQfnTwFf8EI7MEHHtAWAIyktDAILky4pdjHS629x6
+vbhjgoQQMyNyWCokP9OgF0w5Xnz5rXHBxIpaQW8or3D21PnHfuFVVUFAN9QSYSIp
+R76s9HAfaFCWsTKtfoSmFpcDAN7h14jpgSxbhS59guuTzRvjAlkeX3PvAJBU2hPZ
+E72ddhIdXBfrhIpS4yFy2BvyJ5h5zZJdQEVO2ypfAKHhxeLpmAIx6u9aKXSZtgQm
+9fGzGeRxFUw5foXsr9KI19mPtOzAY0U2GQ+sh3oB72Yue0dOwD68U+31sArZgNNq
+lYqxBfGPAwl1di0Z/skCAwEAAaNyMHAwCQYDVR0TBAIwADAOBgNVHQ8BAf8EBAMC
+B4AwEwYDVR0lBAwwCgYIKwYBBQUHAwIwHQYDVR0OBBYEFIwwL0Bc+YAZnEziYhsq
+Y2zPhoNbMB8GA1UdIwQYMBaAFARUeObA0TCOCImJVQpFvKNB0F35MA0GCSqGSIb3
+DQEBCwUAA4IBAQBJoMgXlB1MvAo0eeR/Ym5zurQBogMZXnhDZlXSzuvsHKx+OrUe
+zKUM+pRorjH6X6g5lm3bhIsUT+ndQpVU2uXrjt/AEUI1kdeikynea+7OAdpu23vK
+6nb4Rcf6kKlugom4U5l4qfNz/17kH+1eCcXlP5VL/Ft/CIwDHxq5NDtC50EHbkPJ
+CAnmIMNTPDUJkC8oeHaEHkC7zbvKMnF/68MBht2WquAfQkbiGVuS0UmVsjqyXTrx
+P7KJ82TBzwZce3WMuEF0vFpwLucJq40g/ZSOKDGKlTcqCTkX9C/NzKWc6u6GjYuk
+DhH6sFiXlGBIcv/CrVDsGAqrKvRPmHt2YMv8
+-----END CERTIFICATE-----
diff --git a/tests/gold_tests/tls/tls_resume_ca_bundle_reload.test.py b/tests/gold_tests/tls/tls_resume_ca_bundle_reload.test.py
new file mode 100644
index 0000000000..7d60e1f597
--- /dev/null
+++ b/tests/gold_tests/tls/tls_resume_ca_bundle_reload.test.py
@@ -0,0 +1,251 @@
+'''
+Test that a resumed mTLS session is retired when the global client CA bundle is replaced and reloaded.
+'''
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import re
+
+Test.Summary = '''
+Test that a session verified against proxy.config.ssl.CA.cert.filename under a
+verify_client: STRICT SNI stops resuming once that bundle is replaced in place
+and the configuration is reloaded, while the same session resumes before the
+change.
+'''
+
+Test.SkipUnless(Condition.HasOpenSSLVersion('1.1.1'))
+
+
+class TlsResumeCaBundleReload:
+ '''Test that resumption is bound to the contents of the global client CA bundle.'''
+
+ _sni = 'strict.example.com'
+ _bundle_name = 'client-ca.pem'
+
+ def __init__(self) -> None:
+ '''Configure the origin server, ATS process, and test runs.'''
+ Test.Setup.Copy('file.ticket')
+ Test.Setup.Copy('ssl/aaa-signed.pem')
+ Test.Setup.Copy('ssl/aaa-signed.key')
+ Test.Setup.Copy('ssl/bbb-ca.pem')
+ self.ticket_file = os.path.join(Test.RunDirectory, 'file.ticket')
+ self.session_path = os.path.join(Test.RunDirectory, 'session')
+ self._configure_server()
+ self._configure_ts()
+ self._add_resume_run()
+ self._add_replace_bundle_run()
+ self._add_stale_session_run()
+ self._add_log_assertions()
+
+ def _configure_server(self) -> None:
+ '''Configure the origin server with a simple response for the SNI's hostname.'''
+ server = Test.MakeOriginServer('server')
+ request_header = {
+ 'headers': f'GET / HTTP/1.1\r\nHost: {self._sni}\r\nConnection: close\r\n\r\n',
+ 'timestamp': '1469733493.993',
+ 'body': ''
+ }
+ response_header = {
+ 'headers': 'HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n',
+ 'timestamp': '1469733493.993',
+ 'body': 'hello'
+ }
+ server.addResponse('sessionlog.json', request_header, response_header)
+ self.server = server
+
+ # A second, identical origin exists only so that the run after the reload has a process to
+ # start, which is what carries the When.FileContains() wait for the rebuild.
+ reload_server = Test.MakeOriginServer('reload_server')
+ reload_server.addResponse('sessionlog.json', request_header, response_header)
+ self.reload_server = reload_server
+
+ def _configure_ts(self) -> None:
+ '''Configure the ATS process: a STRICT SNI relying on the global client CA bundle.'''
+ # traffic_manager is required for traffic_ctl config reload on this branch,
+ # which v10 no longer needs.
+ ts = Test.MakeATSProcess('ts', command='traffic_manager', enable_tls=True)
+ ts.addSSLfile('ssl/server.pem')
+ ts.addSSLfile('ssl/server.key')
+ self.bundle_path = os.path.join(ts.Variables.SSLDir, self._bundle_name)
+ ts.Setup.CopyAs('ssl/aaa-ca.pem', ts.Variables.SSLDir, self._bundle_name)
+
+ ts.Disk.ssl_multicert_config.AddLine('dest_ip=* ssl_cert_name=server.pem ssl_key_name=server.key')
+
+ ts.Disk.remap_config.AddLine(f'map / http://127.0.0.1:{self.server.Variables.Port}')
+
+ ts.Disk.records_config.update(
+ {
+ 'proxy.config.url_remap.pristine_host_hdr': 1,
+ 'proxy.config.ssl.server.cert.path': f'{ts.Variables.SSLDir}',
+ 'proxy.config.ssl.server.private_key.path': f'{ts.Variables.SSLDir}',
+ 'proxy.config.ssl.CA.cert.filename': self.bundle_path,
+ 'proxy.config.exec_thread.autoconfig.scale': 1.0,
+ 'proxy.config.ssl.server.session_ticket.enable': 1,
+ 'proxy.config.ssl.server.ticket_key.filename': self.ticket_file,
+ 'proxy.config.log.max_secs_per_buffer': 1,
+ })
+
+ # No verify_client_ca_certs, so the client certificate is verified
+ # against the global bundle loaded into the SSL_CTX.
+ ts.Disk.sni_yaml.AddLines([
+ 'sni:',
+ f'- fqdn: {self._sni}',
+ ' verify_client: STRICT',
+ ])
+
+ ts.Disk.logging_yaml.AddLines(
+ '''
+logging:
+ formats:
+ - name: testformat
+ format: '%<pssc> %<{Host}cqh>'
+ logs:
+ - mode: ascii
+ format: testformat
+ filename: squid
+'''.split("\n"))
+ self.ts = ts
+
+ def _client_command(self, session_arg: str) -> str:
+ '''
+ Build a shell command that connects once over TLSv1.3, presenting the
+ aaa-ca signed client certificate, and sends one request.
+
+ :param session_arg: The s_client argument saving or offering a session.
+ :return: Shell command performing the connection.
+ '''
+ port = self.ts.Variables.ssl_port
+ request = f'printf "GET / HTTP/1.1\\r\\nHost: {self._sni}\\r\\nConnection: close\\r\\n\\r\\n"'
+ return (
+ f'{request} | openssl s_client -connect 127.0.0.1:{port} -servername {self._sni} '
+ f'-cert ./aaa-signed.pem -key ./aaa-signed.key {session_arg} -tls1_3 -ign_eof')
+
+ def _add_resume_run(self) -> None:
+ '''Obtain a session ticket and resume it while the issuing CA is still trusted.'''
+ tr = Test.AddTestRun('Resume a session verified against the current CA bundle')
+ tr.Processes.Default.StartBefore(self.server)
+ tr.Processes.Default.StartBefore(self.ts)
+ tr.StillRunningAfter += self.server
+ tr.StillRunningAfter += self.ts
+ tr.Command = (
+ f'{self._client_command(f"-sess_out {self.session_path}")} && '
+ f'{self._client_command(f"-sess_in {self.session_path}")}')
+ tr.ReturnCode = 0
+ tr.Processes.Default.Streams.All = Testers.ContainsExpression(
+ 'Reused, TLSv1.3', 'The second connection should resume the session')
+
+ def _add_reload_run(self, description: str) -> None:
+ '''
+ Request a configuration reload.
+
+ This branch has no Test.AddConfigReload(). Waiting for the reload to take effect is left to
+ the next run, which hangs a When.FileContains() readiness condition off a process start,
+ the idiom the other reload tests on this branch use.
+
+ :param description: Description for the reload test run.
+ '''
+ tr = Test.AddTestRun(description)
+ tr.StillRunningAfter += self.server
+ tr.StillRunningAfter += self.ts
+ tr.Processes.Default.Command = 'traffic_ctl config reload'
+ # traffic_ctl reads the environment to find the management socket.
+ tr.Processes.Default.Env = self.ts.Env
+ tr.Processes.Default.ReturnCode = 0
+
+ def _add_replace_bundle_run(self) -> None:
+ '''Replace the global CA bundle in place with an unrelated CA and reload.'''
+ tr = Test.AddTestRun('Replace the global client CA bundle in place')
+ tr.StillRunningAfter += self.server
+ tr.StillRunningAfter += self.ts
+ tr.Processes.Default.Command = f'cp ./bbb-ca.pem {self.bundle_path}'
+ tr.Processes.Default.ReturnCode = 0
+
+ # The SSL_CTX loads the bundle when it is built, so the replacement takes
+ # effect through a reload rather than on the next connection. The bundle
+ # is tracked like the certificate files, so the reload rebuilds the
+ # certificate contexts without any other file having changed.
+ self._add_reload_run('Reload to rebuild the SSL_CTX with the new bundle')
+
+ def _add_stale_session_run(self) -> None:
+ '''
+ Offer the session verified under the replaced bundle.
+
+ The session must not be resumed. The full handshake that follows presents
+ the aaa-ca signed certificate again, which the new bundle does not trust,
+ so no request is served.
+ '''
+ tr = Test.AddTestRun('A session verified by the replaced CA bundle does not resume')
+ # Starting this origin is how the run waits for the reload to rebuild the certificate
+ # contexts: two loads of ssl_multicert.config, the one at startup and the one just
+ # requested.
+ tr.Processes.Default.StartBefore(
+ self.reload_server, ready=When.FileContains(self.ts.Disk.diags_log.Name, 'ssl_multicert.config finished loading', 2))
+ tr.StillRunningAfter += self.server
+ tr.StillRunningAfter += self.ts
+ tr.Command = self._client_command(f'-sess_in {self.session_path}')
+ # The two Excludes below would also hold if the client never reached ATS, which matters
+ # because this runs right after a reload. These two prove it did: a negotiated full
+ # handshake, then ATS refusing the certificate for the expected reason.
+ tr.Processes.Default.Streams.All = Testers.ContainsExpression(
+ 'New, TLSv1.3', 'The client must reach ATS and negotiate a full handshake')
+ tr.Processes.Default.Streams.All += Testers.ContainsExpression(
+ 'tlsv1 alert unknown ca', 'ATS must refuse the certificate the replaced bundle no longer trusts')
+ tr.Processes.Default.Streams.All += Testers.ExcludesExpression(
+ 'Reused, TLSv1.3', 'A session verified by a CA that is no longer trusted must not resume')
+ tr.Processes.Default.Streams.All += Testers.ExcludesExpression(
+ 'HTTP/1.1 200', 'A client certificate the current bundle does not trust must not be served')
+
+ @staticmethod
+ def check_regex_count(output_path: str, pattern: str, expected_count: int, description: str) -> tuple[bool, str, str]:
+ '''
+ Count regex matches in a process output file.
+
+ :param output_path: Path to the output file to inspect.
+ :param pattern: Regex pattern to count.
+ :param expected_count: Expected number of matches.
+ :param description: Description reported by the tester.
+ :return: AuTest lambda result tuple.
+ '''
+ with open(output_path, 'r') as f:
+ content = f.read()
+
+ matches = re.findall(pattern, content, re.MULTILINE)
+ if len(matches) == expected_count:
+ return (True, description, f'Found {len(matches)} matches for {pattern}')
+ return (False, description, f'Expected {expected_count} matches for {pattern}, found {len(matches)}')
+
+ def _add_log_assertions(self) -> None:
+ '''
+ Assert that only the fresh and the legitimately resumed request reached the origin.
+
+ A stale session that wrongly resumed would add a third access log line.
+ '''
+ tr = Test.AddTestRun('Wait for the access log')
+ tr.StillRunningAfter += self.server
+ tr.StillRunningAfter += self.ts
+ tr.Processes.Default.Command = (
+ f"{os.path.join(Test.Variables.AtsTestToolsDir, 'condwait')} 60 3 -f "
+ f"{os.path.join(self.ts.Variables.LOGDIR, 'squid.log')}")
+ tr.Processes.Default.ReturnCode = 0
+
+ self.ts.Disk.squid_log.Content = Testers.Lambda(
+ lambda info, tester: TlsResumeCaBundleReload.check_regex_count(
+ self.ts.Disk.squid_log.AbsPath, rf'^200 {re.escape(self._sni)}$', 2,
+ 'Only the fresh request and the resumption before the CA change should be served'))
+
+
+TlsResumeCaBundleReload()
diff --git a/tests/gold_tests/tls/tls_resume_cross_sni.test.py b/tests/gold_tests/tls/tls_resume_cross_sni.test.py
new file mode 100644
index 0000000000..9b55ec8dd3
--- /dev/null
+++ b/tests/gold_tests/tls/tls_resume_cross_sni.test.py
@@ -0,0 +1,189 @@
+'''
+Test that a TLS session is not resumed under an SNI other than the one that issued it.
+'''
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+
+Test.Summary = '''
+Test that a session issued under one SNI is not resumed under a different SNI
+sharing the same listener and certificate, for SNIs that set no verify_client
+at all, while resumption under the issuing SNI still works.
+'''
+
+Test.SkipUnless(Condition.HasOpenSSLVersion('1.1.1'))
+
+
+class TlsResumeCrossSni:
+ '''
+ Test that session resumption is bound to the SNI that issued the session.
+
+ Neither hostname appears in sni.yaml, so neither has a verify_client
+ setting. That is the default configuration and the one in which nothing
+ else scopes a session to its SNI, so it is what proves the binding is
+ applied unconditionally rather than only when verify_client is present.
+ '''
+
+ _issuing_sni = 'alpha.example.com'
+ _other_sni = 'beta.example.com'
+ _tls_versions = ('1.2', '1.3')
+
+ def __init__(self) -> None:
+ '''Configure the origin server, ATS process, and test runs.'''
+ Test.Setup.Copy('file.ticket')
+ self.ticket_file = os.path.join(Test.RunDirectory, 'file.ticket')
+ self._configure_server()
+ self._configure_ts()
+ for version in self._tls_versions:
+ self._add_same_sni_run(version)
+ self._add_cross_sni_run(version)
+ self._add_case_fold_run()
+
+ def _configure_server(self) -> None:
+ '''Configure the origin server with a simple response for each hostname.'''
+ server = Test.MakeOriginServer('server')
+ for host in (self._issuing_sni, self._other_sni):
+ request_header = {
+ 'headers': f'GET / HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n',
+ 'timestamp': '1469733493.993',
+ 'body': ''
+ }
+ response_header = {
+ 'headers': 'HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n',
+ 'timestamp': '1469733493.993',
+ 'body': 'hello'
+ }
+ server.addResponse('sessionlog.json', request_header, response_header)
+ self.server = server
+
+ def _configure_ts(self) -> None:
+ '''Configure the ATS process: one wildcard cert serving both hostnames, no sni.yaml entries.'''
+ ts = Test.MakeATSProcess('ts', enable_tls=True)
+ ts.addSSLfile('ssl/server.pem')
+ ts.addSSLfile('ssl/server.key')
+
+ # A single wildcard entry, so the only thing separating the two names is
+ # the SNI itself rather than a distinct certificate context.
+ ts.Disk.ssl_multicert_config.AddLine('dest_ip=* ssl_cert_name=server.pem ssl_key_name=server.key')
+
+ ts.Disk.remap_config.AddLine(f'map / http://127.0.0.1:{self.server.Variables.Port}')
+
+ ts.Disk.records_config.update(
+ {
+ 'proxy.config.url_remap.pristine_host_hdr': 1,
+ 'proxy.config.ssl.server.cert.path': f'{ts.Variables.SSLDir}',
+ 'proxy.config.ssl.server.private_key.path': f'{ts.Variables.SSLDir}',
+ 'proxy.config.exec_thread.autoconfig.scale': 1.0,
+ 'proxy.config.ssl.server.session_ticket.enable': 1,
+ 'proxy.config.ssl.server.ticket_key.filename': self.ticket_file,
+ 'proxy.config.ssl.TLSv1_2': 1,
+ 'proxy.config.ssl.TLSv1_3': 1,
+ })
+
+ # Deliberately no sni.yaml entries for either hostname: verify_client is
+ # left unset, which is the case that has no VerifyClient SNI action.
+ self.ts = ts
+
+ def _session_path(self, tls_version: str, label: str) -> str:
+ '''
+ Return the path of the file holding a saved session.
+
+ :param tls_version: The TLS version the session was negotiated with.
+ :param label: Distinguishes the sessions saved by different runs.
+ :return: Path of the session file.
+ '''
+ return os.path.join(Test.RunDirectory, f'session-{label}-{tls_version}')
+
+ def _client_command(self, tls_version: str, sni: str, session_arg: str) -> str:
+ '''
+ Build a shell command that connects once with the given SNI and sends one request.
+
+ :param tls_version: The TLS version to pin the connection to, '1.2' or '1.3'.
+ :param sni: The SNI and Host header to use.
+ :param session_arg: The s_client argument saving or offering a session.
+ :return: Shell command performing the connection.
+ '''
+ port = self.ts.Variables.ssl_port
+ version_flag = f'-tls1_{tls_version.split(".")[1]}'
+ request = f'printf "GET / HTTP/1.1\\r\\nHost: {sni}\\r\\nConnection: close\\r\\n\\r\\n"'
+ return (
+ f'{request} | openssl s_client -connect 127.0.0.1:{port} -servername {sni} '
+ f'{session_arg} {version_flag} -ign_eof')
+
+ def _add_same_sni_run(self, tls_version: str) -> None:
+ '''
+ Add a control run proving tickets are issued and resumable under one SNI.
+
+ Without this, a cross-SNI run that fails to resume would prove nothing,
+ since it would also pass if resumption were broken outright.
+
+ :param tls_version: The TLS version to pin both connections to.
+ '''
+ path = self._session_path(tls_version, 'same')
+ tr = Test.AddTestRun(f'A TLSv{tls_version} session resumes under the SNI that issued it')
+ if tls_version == self._tls_versions[0]:
+ tr.Processes.Default.StartBefore(self.server)
+ tr.Processes.Default.StartBefore(self.ts)
+ tr.StillRunningAfter += self.server
+ tr.StillRunningAfter += self.ts
+ tr.Command = (
+ f'{self._client_command(tls_version, self._issuing_sni, f"-sess_out {path}")} && '
+ f'{self._client_command(tls_version, self._issuing_sni, f"-sess_in {path}")}')
+ tr.ReturnCode = 0
+ tr.Processes.Default.Streams.All = Testers.ContainsExpression(
+ f'Reused, TLSv{tls_version}', 'A session offered under its issuing SNI should resume')
+
+ def _add_case_fold_run(self) -> None:
+ '''
+ Add a run offering a session under the same SNI spelled with different case.
+
+ sni.yaml matching lowercases the server name, so both spellings select
+ one policy and must therefore land in one resumption scope.
+ '''
+ path = self._session_path('1.3', 'fold')
+ tr = Test.AddTestRun('A session resumes under the same SNI spelled with different case')
+ tr.StillRunningAfter += self.server
+ tr.StillRunningAfter += self.ts
+ tr.Command = (
+ f'{self._client_command("1.3", self._issuing_sni, f"-sess_out {path}")} && '
+ f'{self._client_command("1.3", self._issuing_sni.upper(), f"-sess_in {path}")}')
+ tr.ReturnCode = 0
+ tr.Processes.Default.Streams.All = Testers.ContainsExpression(
+ 'Reused, TLSv1.3', 'Case differences in the SNI must not split the resumption scope')
+
+ def _add_cross_sni_run(self, tls_version: str) -> None:
+ '''
+ Add a run offering a session under a different SNI than issued it.
+
+ :param tls_version: The TLS version to pin both connections to.
+ '''
+ path = self._session_path(tls_version, 'cross')
+ tr = Test.AddTestRun(f'A TLSv{tls_version} session does not resume under a different SNI')
+ tr.StillRunningAfter += self.server
+ tr.StillRunningAfter += self.ts
+ tr.Command = (
+ f'{self._client_command(tls_version, self._issuing_sni, f"-sess_out {path}")} && '
+ f'{self._client_command(tls_version, self._other_sni, f"-sess_in {path}")}')
+ tr.ReturnCode = 0
+ # The second connection falls back to a full handshake, which succeeds
+ # because neither SNI requires a client certificate. So the resumption
+ # is what is under test here, not whether the request is served.
+ tr.Processes.Default.Streams.All = Testers.ExcludesExpression(
+ 'Reused', 'A session must not resume under an SNI other than the one that issued it')
+
+
+TlsResumeCrossSni()
diff --git a/tests/gold_tests/tls/tls_resume_intermediate_ca.test.py b/tests/gold_tests/tls/tls_resume_intermediate_ca.test.py
new file mode 100644
index 0000000000..111a8f0d09
--- /dev/null
+++ b/tests/gold_tests/tls/tls_resume_intermediate_ca.test.py
@@ -0,0 +1,265 @@
+'''
+Test that a resumed mTLS session survives when the client cert is issued by an intermediate CA.
+'''
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import re
+
+Test.Summary = '''
+Test that a verify_client: STRICT SNI whose trust bundle holds only a root CA
+keeps accepting a client certificate issued by an intermediate CA when the
+client resumes its TLS session, on both TLS 1.2 and TLS 1.3 ticket resumption,
+and that replacing that trust bundle in place retires the sessions it verified.
+'''
+
+Test.SkipUnless(Condition.HasOpenSSLVersion('1.1.1'))
+
+
+class TlsResumeIntermediateCa:
+ '''Test that ticket resumption works for a client cert that chains through an intermediate CA.'''
+
+ _sni = 'int.example.com'
+ _tls_versions = ('1.2', '1.3')
+
+ def __init__(self) -> None:
+ '''Configure the origin server, ATS process, and test runs.'''
+ Test.Setup.Copy('file.ticket')
+ Test.Setup.Copy('ssl/intclient.pem')
+ Test.Setup.Copy('ssl/intclient.key')
+ Test.Setup.Copy('ssl/intca-sub.pem')
+ Test.Setup.Copy('ssl/aaa-ca.pem')
+ self.ticket_file = os.path.join(Test.RunDirectory, 'file.ticket')
+ self._configure_server()
+ self._configure_ts()
+ for version in self._tls_versions:
+ self._add_resume_run(version)
+ self._add_replace_ca_run()
+ for version in self._tls_versions:
+ self._add_stale_session_run(version)
+ self._add_log_assertions()
+
+ def _configure_server(self) -> None:
+ '''Configure the origin server with a simple response for the SNI's hostname.'''
+ server = Test.MakeOriginServer('server')
+ request_header = {
+ 'headers': f'GET / HTTP/1.1\r\nHost: {self._sni}\r\nConnection: close\r\n\r\n',
+ 'timestamp': '1469733493.993',
+ 'body': ''
+ }
+ response_header = {
+ 'headers': 'HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n',
+ 'timestamp': '1469733493.993',
+ 'body': 'hello'
+ }
+ server.addResponse('sessionlog.json', request_header, response_header)
+ self.server = server
+
+ def _configure_ts(self) -> None:
+ '''Configure the ATS process: a STRICT SNI that trusts only the root of a three-level client PKI.'''
+ ts = Test.MakeATSProcess('ts', enable_tls=True)
+ ts.addSSLfile('ssl/server.pem')
+ ts.addSSLfile('ssl/server.key')
+ ts.Setup.Copy('ssl/intca-root.pem', ts.Variables.SSLDir)
+
+ ts.Disk.ssl_multicert_config.AddLine('dest_ip=* ssl_cert_name=server.pem ssl_key_name=server.key')
+
+ ts.Disk.remap_config.AddLine(f'map / http://127.0.0.1:{self.server.Variables.Port}')
+
+ ts.Disk.records_config.update(
+ {
+ 'proxy.config.url_remap.pristine_host_hdr': 1,
+ 'proxy.config.ssl.server.cert.path': f'{ts.Variables.SSLDir}',
+ 'proxy.config.ssl.server.private_key.path': f'{ts.Variables.SSLDir}',
+ 'proxy.config.exec_thread.autoconfig.scale': 1.0,
+ 'proxy.config.ssl.server.session_ticket.enable': 1,
+ 'proxy.config.ssl.server.ticket_key.filename': self.ticket_file,
+ 'proxy.config.ssl.TLSv1_2': 1,
+ 'proxy.config.ssl.TLSv1_3': 1,
+ 'proxy.config.log.max_secs_per_buffer': 1,
+ })
+
+ # Only the root is trusted. The intermediate that issued the client
+ # certificate is expected to arrive from the client in the handshake.
+ ts.Disk.sni_yaml.AddLines(
+ [
+ 'sni:',
+ f'- fqdn: {self._sni}',
+ ' verify_client: STRICT',
+ ' verify_client_ca_certs:',
+ f' file: {ts.Variables.SSLDir}/intca-root.pem',
+ ])
+
+ ts.Disk.logging_yaml.AddLines(
+ '''
+logging:
+ formats:
+ - name: testformat
+ format: '%<pssc> %<{Host}cqh>'
+ logs:
+ - mode: ascii
+ format: testformat
+ filename: squid
+'''.split("\n"))
+
+ ts.Disk.diags_log.Content = Testers.ExcludesExpression(
+ 'rejecting a resumed TLS session', 'A resumed session with a valid intermediate-issued cert must not be rejected')
+ self.ts = ts
+
+ def _session_path(self, tls_version: str) -> str:
+ '''
+ Return the path of the file holding the saved session for a TLS version.
+
+ :param tls_version: The TLS version the session was negotiated with, '1.2' or '1.3'.
+ :return: Path of the session file.
+ '''
+ return os.path.join(Test.RunDirectory, f'session-{tls_version}')
+
+ def _client_command(self, tls_version: str, session_arg: str) -> str:
+ '''
+ Build a shell command that connects once, presenting the intermediate-issued
+ client certificate along with its intermediate, and sends one request.
+
+ :param tls_version: The TLS version to pin the connection to, '1.2' or '1.3'.
+ :param session_arg: The s_client argument saving or offering a session.
+ :return: Shell command performing the connection.
+ '''
+ port = self.ts.Variables.ssl_port
+ version_flag = f'-tls1_{tls_version.split(".")[1]}'
+ cert_args = '-cert ./intclient.pem -key ./intclient.key -cert_chain ./intca-sub.pem'
+ request = f'printf "GET / HTTP/1.1\\r\\nHost: {self._sni}\\r\\nConnection: close\\r\\n\\r\\n"'
+ return (
+ f'{request} | openssl s_client -connect 127.0.0.1:{port} -servername {self._sni} {cert_args} '
+ f'{session_arg} {version_flag} -ign_eof')
+
+ def _resume_command(self, tls_version: str) -> str:
+ '''
+ Build a shell command that obtains a session ticket and then reconnects
+ with that ticket to resume the session.
+
+ :param tls_version: The TLS version to pin both connections to, '1.2' or '1.3'.
+ :return: Shell command performing both connections.
+ '''
+ session_path = self._session_path(tls_version)
+ return (
+ f'{self._client_command(tls_version, f"-sess_out {session_path}")} && '
+ f'{self._client_command(tls_version, f"-sess_in {session_path}")}')
+
+ def _add_resume_run(self, tls_version: str) -> None:
+ '''
+ Add a test run that issues and then resumes a session over the given TLS version.
+
+ :param tls_version: The TLS version to pin both connections to, '1.2' or '1.3'.
+ '''
+ tr = Test.AddTestRun(f'Resume a TLSv{tls_version} session carrying an intermediate-issued client cert')
+ if tls_version == self._tls_versions[0]:
+ tr.Processes.Default.StartBefore(self.server)
+ tr.Processes.Default.StartBefore(self.ts)
+ tr.StillRunningAfter += self.server
+ tr.StillRunningAfter += self.ts
+ tr.Command = self._resume_command(tls_version)
+ tr.ReturnCode = 0
+ # Resumption is negotiated before ATS decides whether to keep the
+ # connection, so "Reused" alone only proves the ticket was accepted by
+ # the TLS library. The access log count below proves the resumed
+ # request was actually served.
+ tr.Processes.Default.Streams.All = Testers.ContainsExpression(
+ f'Reused, TLSv{tls_version}', 'The second connection should resume the session')
+
+ def _add_replace_ca_run(self) -> None:
+ '''
+ Replace the trusted root in place with an unrelated CA.
+
+ The bundle keeps its path, so only its contents distinguish the trust
+ anchors that verified the saved sessions from the ones now in force.
+ '''
+ tr = Test.AddTestRun('Replace the trusted root CA bundle in place')
+ tr.StillRunningAfter += self.server
+ tr.StillRunningAfter += self.ts
+ tr.Processes.Default.Command = f'cp ./aaa-ca.pem {self.ts.Variables.SSLDir}/intca-root.pem'
+ tr.Processes.Default.ReturnCode = 0
+
+ def _add_stale_session_run(self, tls_version: str) -> None:
+ '''
+ Add a test run that offers a session verified under the replaced CA bundle.
+
+ The session must not be resumed. The full handshake that follows presents
+ the client certificate again, which the new bundle does not trust, so no
+ request is served.
+
+ :param tls_version: The TLS version the saved session was negotiated with, '1.2' or '1.3'.
+ '''
+ tr = Test.AddTestRun(f'A TLSv{tls_version} session verified by the replaced CA does not resume')
+ tr.StillRunningAfter += self.server
+ tr.StillRunningAfter += self.ts
+ tr.Command = self._client_command(tls_version, f'-sess_in {self._session_path(tls_version)}')
+ # The two Excludes below would also hold if the client never reached ATS, which matters
+ # because this runs right after the bundle was replaced. These two prove it did: a
+ # negotiated full handshake, then ATS refusing the certificate for the expected reason.
+ tr.Processes.Default.Streams.All = Testers.ContainsExpression(
+ f'New, TLSv{tls_version}', 'The client must reach ATS and negotiate a full handshake')
+ tr.Processes.Default.Streams.All += Testers.ContainsExpression(
+ 'tlsv1 alert unknown ca', 'ATS must refuse the certificate the replaced bundle no longer trusts')
+ tr.Processes.Default.Streams.All += Testers.ExcludesExpression(
+ f'Reused, TLSv{tls_version}', 'A session verified by a CA that is no longer trusted must not resume')
+ tr.Processes.Default.Streams.All += Testers.ExcludesExpression(
+ 'HTTP/1.1 200', 'A client certificate the current bundle does not trust must not be served')
+
+ @staticmethod
+ def check_regex_count(output_path: str, pattern: str, expected_count: int, description: str) -> tuple[bool, str, str]:
+ '''
+ Count regex matches in a process output file.
+
+ :param output_path: Path to the output file to inspect.
+ :param pattern: Regex pattern to count.
+ :param expected_count: Expected number of matches.
+ :param description: Description reported by the tester.
+ :return: AuTest lambda result tuple.
+ '''
+ with open(output_path, 'r') as f:
+ content = f.read()
+
+ matches = re.findall(pattern, content, re.MULTILINE)
+ if len(matches) == expected_count:
+ return (True, description, f'Found {len(matches)} matches for {pattern}')
+ return (False, description, f'Expected {expected_count} matches for {pattern}, found {len(matches)}')
+
+ def _add_log_assertions(self) -> None:
+ '''
+ Assert that every request from the fresh and resumed connections reached
+ the origin, and that nothing else did.
+
+ A rejected resumption never reaches the HTTP layer, so it shows up as a
+ missing access log line rather than as an error status, while a stale
+ session that wrongly resumed would add a line.
+ '''
+ tr = Test.AddTestRun('Wait for the access log')
+ tr.StillRunningAfter += self.server
+ tr.StillRunningAfter += self.ts
+ tr.Processes.Default.Command = (
+ f"{os.path.join(Test.Variables.AtsTestToolsDir, 'condwait')} 60 3 -f "
+ f"{os.path.join(self.ts.Variables.LOGDIR, 'squid.log')}")
+ tr.Processes.Default.ReturnCode = 0
+
+ expected = 2 * len(self._tls_versions)
+ self.ts.Disk.squid_log.Content = Testers.Lambda(
+ lambda info, tester: TlsResumeIntermediateCa.check_regex_count(
+ self.ts.Disk.squid_log.AbsPath, rf'^200 {re.escape(self._sni)}$', expected,
+ 'Every fresh and resumed request, and only those, should be served'))
+
+
+TlsResumeIntermediateCa()
diff --git a/tests/gold_tests/tls/tls_resume_verify_level.test.py b/tests/gold_tests/tls/tls_resume_verify_level.test.py
new file mode 100644
index 0000000000..ca4396155c
--- /dev/null
+++ b/tests/gold_tests/tls/tls_resume_verify_level.test.py
@@ -0,0 +1,198 @@
+'''
+Test that a TLS session is not resumed after its SNI's verify_client level changes.
+'''
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+
+Test.Summary = '''
+Test that raising verify_client from MODERATE to STRICT for one SNI stops that
+SNI's existing sessions from resuming, holding the server name and the CA
+bundle constant so that the verify mode is the only thing that changed.
+'''
+
+Test.SkipUnless(Condition.HasOpenSSLVersion('1.1.1'))
+
+
+class TlsResumeVerifyLevel:
+ '''
+ Test that the verify mode is part of the session resumption scope.
+
+ The other scope tests vary verify_client across two different SNIs, where
+ the server name alone would carry them. This one keeps a single SNI and a
+ single CA bundle and changes only the level, so it fails if the verify mode
+ term is dropped from the session id context.
+ '''
+
+ _sni = 'level.example.com'
+
+ def __init__(self) -> None:
+ '''Configure the origin server, ATS process, and test runs.'''
+ Test.Setup.Copy('file.ticket')
+ Test.Setup.Copy('ssl/aaa-signed.pem')
+ Test.Setup.Copy('ssl/aaa-signed.key')
+ self.ticket_file = os.path.join(Test.RunDirectory, 'file.ticket')
+ self.session_path = os.path.join(Test.RunDirectory, 'session')
+ self._configure_server()
+ self._configure_ts()
+ self._add_resume_run()
+ self._add_raise_level_run()
+ self._add_stale_session_run()
+
+ def _configure_server(self) -> None:
+ '''Configure the origin server with a simple response for the SNI's hostname.'''
+ server = Test.MakeOriginServer('server')
+ request_header = {
+ 'headers': f'GET / HTTP/1.1\r\nHost: {self._sni}\r\nConnection: close\r\n\r\n',
+ 'timestamp': '1469733493.993',
+ 'body': ''
+ }
+ response_header = {
+ 'headers': 'HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n',
+ 'timestamp': '1469733493.993',
+ 'body': 'hello'
+ }
+ server.addResponse('sessionlog.json', request_header, response_header)
+ self.server = server
+
+ # A second, identical origin exists only so that the run after the reload has a process to
+ # start, which is what carries the When.FileContains() wait for the new sni.yaml.
+ reload_server = Test.MakeOriginServer('reload_server')
+ reload_server.addResponse('sessionlog.json', request_header, response_header)
+ self.reload_server = reload_server
+
+ def _configure_ts(self) -> None:
+ '''Configure the ATS process with one MODERATE SNI and a fixed CA bundle.'''
+ # traffic_manager is required for traffic_ctl config reload on this branch,
+ # which v10 no longer needs.
+ ts = Test.MakeATSProcess('ts', command='traffic_manager', enable_tls=True)
+ ts.addSSLfile('ssl/server.pem')
+ ts.addSSLfile('ssl/server.key')
+ ts.Setup.Copy('ssl/aaa-ca.pem', ts.Variables.SSLDir)
+ self.ca_path = os.path.join(ts.Variables.SSLDir, 'aaa-ca.pem')
+
+ ts.Disk.ssl_multicert_config.AddLine('dest_ip=* ssl_cert_name=server.pem ssl_key_name=server.key')
+
+ ts.Disk.remap_config.AddLine(f'map / http://127.0.0.1:{self.server.Variables.Port}')
+
+ ts.Disk.records_config.update(
+ {
+ 'proxy.config.url_remap.pristine_host_hdr': 1,
+ 'proxy.config.ssl.server.cert.path': f'{ts.Variables.SSLDir}',
+ 'proxy.config.ssl.server.private_key.path': f'{ts.Variables.SSLDir}',
+ 'proxy.config.exec_thread.autoconfig.scale': 1.0,
+ 'proxy.config.ssl.server.session_ticket.enable': 1,
+ 'proxy.config.ssl.server.ticket_key.filename': self.ticket_file,
+ })
+
+ self.sni_path = os.path.join(ts.Variables.CONFIGDIR, 'sni.yaml')
+ ts.Disk.sni_yaml.AddLines(
+ [
+ 'sni:',
+ f'- fqdn: {self._sni}',
+ ' verify_client: MODERATE',
+ ' verify_client_ca_certs:',
+ f' file: {self.ca_path}',
+ ])
+ self.ts = ts
+
+ def _client_command(self, session_arg: str) -> str:
+ '''
+ Build a shell command that connects once presenting the aaa-ca signed client cert.
+
+ :param session_arg: The s_client argument saving or offering a session.
+ :return: Shell command performing the connection.
+ '''
+ port = self.ts.Variables.ssl_port
+ request = f'printf "GET / HTTP/1.1\\r\\nHost: {self._sni}\\r\\nConnection: close\\r\\n\\r\\n"'
+ return (
+ f'{request} | openssl s_client -connect 127.0.0.1:{port} -servername {self._sni} '
+ f'-cert ./aaa-signed.pem -key ./aaa-signed.key {session_arg} -tls1_3 -ign_eof')
+
+ def _add_resume_run(self) -> None:
+ '''Obtain a session under MODERATE and resume it while the level is unchanged.'''
+ tr = Test.AddTestRun('A session resumes while verify_client is unchanged')
+ tr.Processes.Default.StartBefore(self.server)
+ tr.Processes.Default.StartBefore(self.ts)
+ tr.StillRunningAfter += self.server
+ tr.StillRunningAfter += self.ts
+ tr.Command = (
+ f'{self._client_command(f"-sess_out {self.session_path}")} && '
+ f'{self._client_command(f"-sess_in {self.session_path}")}')
+ tr.ReturnCode = 0
+ tr.Processes.Default.Streams.All = Testers.ContainsExpression(
+ 'Reused, TLSv1.3', 'A session should resume while its scope is unchanged')
+
+ def _add_reload_run(self, description: str) -> None:
+ '''
+ Request a configuration reload.
+
+ This branch has no Test.AddConfigReload(). Waiting for the reload to take effect is left to
+ the next run, which hangs a When.FileContains() readiness condition off a process start,
+ the idiom the other reload tests on this branch use.
+
+ :param description: Description for the reload test run.
+ '''
+ tr = Test.AddTestRun(description)
+ tr.StillRunningAfter += self.server
+ tr.StillRunningAfter += self.ts
+ tr.Processes.Default.Command = 'traffic_ctl config reload'
+ # traffic_ctl reads the environment to find the management socket.
+ tr.Processes.Default.Env = self.ts.Env
+ tr.Processes.Default.ReturnCode = 0
+
+ def _add_raise_level_run(self) -> None:
+ '''Raise verify_client to STRICT for the same SNI, keeping the CA bundle identical.'''
+ tr = Test.AddTestRun('Raise verify_client from MODERATE to STRICT')
+ tr.StillRunningAfter += self.server
+ tr.StillRunningAfter += self.ts
+ sni = '\n'.join(
+ [
+ 'sni:',
+ f'- fqdn: {self._sni}',
+ ' verify_client: STRICT',
+ ' verify_client_ca_certs:',
+ f' file: {self.ca_path}',
+ ])
+ tr.Processes.Default.Command = f"printf '%s\\n' '{sni}' > {self.sni_path}"
+ tr.Processes.Default.ReturnCode = 0
+
+ self._add_reload_run('Reload the new verify_client level')
+
+ def _add_stale_session_run(self) -> None:
+ '''
+ Offer the session issued under MODERATE now that the SNI is STRICT.
+
+ The client still presents a certificate the bundle trusts, so the full
+ handshake succeeds. Only the resumption must be refused.
+ '''
+ tr = Test.AddTestRun('A session issued under MODERATE does not resume under STRICT')
+ # Starting this origin is how the run waits for the reload to apply the new policy: two
+ # loads of sni.yaml, the one at startup and the one just requested.
+ tr.Processes.Default.StartBefore(
+ self.reload_server, ready=When.FileContains(self.ts.Disk.diags_log.Name, 'sni.yaml finished loading', 2))
+ tr.StillRunningAfter += self.server
+ tr.StillRunningAfter += self.ts
+ tr.Command = self._client_command(f'-sess_in {self.session_path}')
+ tr.ReturnCode = 0
+ tr.Processes.Default.Streams.All = Testers.ExcludesExpression(
+ 'Reused', 'A session must not resume after its SNI verify_client level changed')
+ tr.Processes.Default.Streams.All += Testers.ContainsExpression(
+ 'HTTP/1.1 200', 'The full handshake that follows should still be served')
+
+
+TlsResumeVerifyLevel()
diff --git a/tests/gold_tests/tls/tls_ticket_verify_client_ca_scope.test.py b/tests/gold_tests/tls/tls_ticket_verify_client_ca_scope.test.py
index aecf02a5e3..c2429c3c0e 100644
--- a/tests/gold_tests/tls/tls_ticket_verify_client_ca_scope.test.py
+++ b/tests/gold_tests/tls/tls_ticket_verify_client_ca_scope.test.py
@@ -144,10 +144,13 @@ logging:
tr.StillRunningAfter += self.server
tr.StillRunningAfter += self.ts
tr.Command = self._resume_command('aaa.example.com', 'bbb.example.com')
- # The resumption attempt is rejected at the TLS layer before any HTTP
- # request is processed, so no particular client-side return code is
- # guaranteed here. Correctness is verified via the access log assertions
- # in _add_log_assertions() instead.
+ # The session is now bound to the trust anchors that verified its client certificate, so
+ # the offer is a cache miss rather than a rejected resumption: the client completes a full
+ # handshake under bbb.example.com's policy, which refuses it because the second connection
+ # presents no client certificate. No particular client-side return code is guaranteed.
+ tr.Processes.Default.Streams.All = Testers.ExcludesExpression('Reused', 'A ticket verified by another CA must not resume')
+ tr.Processes.Default.Streams.All += Testers.ContainsExpression(
+ 'alert certificate required', "bbb.example.com's verify_client must be enforced on the full handshake")
def _add_same_sni_run(self) -> None:
'''A ticket issued under aaa.example.com still resumes under aaa.example.com.'''
@@ -192,13 +195,13 @@ logging:
f"{os.path.join(self.ts.Variables.LOGDIR, 'squid.log')}")
tr.Processes.Default.ReturnCode = 0
- # Counting absent access-log lines alone cannot distinguish the new guard
- # from an ordinary verify_client rejection on a full handshake. Assert the
- # guard's own diagnostic so a resumption that silently did not happen, or a
- # rejection from some other path, fails the test.
- self.ts.Disk.diags_log.Content += Testers.ContainsExpression(
+ # Counting absent access-log lines alone cannot distinguish a session that was declined
+ # from one that was never offered. The cross-CA run asserts the handshake evidence
+ # directly; here, assert that nothing fell back to the post-handshake guard, which the
+ # session id context binding should keep out of reach.
+ self.ts.Disk.diags_log.Content += Testers.ExcludesExpression(
'rejecting a resumed TLS session that does not satisfy verify_client',
- 'The resumption recheck must be what rejected the session')
+ 'The session must be declined before the handshake completes, not rejected after it')
self.ts.Disk.squid_log.Content = Testers.Lambda(
lambda info, tester: TlsTicketVerifyClientCaScope.check_regex_count(
diff --git a/tests/gold_tests/tls/tls_ticket_verify_client_scope.test.py b/tests/gold_tests/tls/tls_ticket_verify_client_scope.test.py
index 2083b93abc..366bbbef90 100644
--- a/tests/gold_tests/tls/tls_ticket_verify_client_scope.test.py
+++ b/tests/gold_tests/tls/tls_ticket_verify_client_scope.test.py
@@ -138,11 +138,13 @@ logging:
tr.StillRunningAfter += self.server
tr.StillRunningAfter += self.ts
tr.Command = self._resume_command('open.example.com', '', 'strict.example.com')
- # The resumption attempt is rejected at the TLS layer before any HTTP
- # request is processed, so no particular client-side return code is
- # guaranteed here (it depends on how the peer observes the aborted
- # connection). Correctness is verified via the access log assertions
- # in _add_log_assertions() instead.
+ # The session is now bound to the verify_client scope that issued it, so the offer is a
+ # cache miss rather than a rejected resumption: the client completes a full handshake under
+ # strict.example.com's policy, which refuses it with a TLS alert for want of a client
+ # certificate. No particular client-side return code is guaranteed.
+ tr.Processes.Default.Streams.All = Testers.ExcludesExpression('Reused', 'A ticket issued under another SNI must not resume')
+ tr.Processes.Default.Streams.All += Testers.ContainsExpression(
+ 'alert certificate required', "strict.example.com's verify_client must be enforced on the full handshake")
def _add_same_sni_run(self) -> None:
'''A ticket issued under strict.example.com with a valid client cert still resumes under the same SNI.'''
@@ -189,13 +191,13 @@ logging:
f"{os.path.join(self.ts.Variables.LOGDIR, 'squid.log')}")
tr.Processes.Default.ReturnCode = 0
- # Counting absent access-log lines alone cannot distinguish the new guard
- # from an ordinary verify_client rejection on a full handshake. Assert the
- # guard's own diagnostic so a resumption that silently did not happen, or a
- # rejection from some other path, fails the test.
- self.ts.Disk.diags_log.Content += Testers.ContainsExpression(
+ # Counting absent access-log lines alone cannot distinguish a session that was declined
+ # from one that was never offered. The cross-SNI run asserts the handshake evidence
+ # directly; here, assert that nothing fell back to the post-handshake guard, which the
+ # session id context binding should keep out of reach.
+ self.ts.Disk.diags_log.Content += Testers.ExcludesExpression(
'rejecting a resumed TLS session that does not satisfy verify_client',
- 'The resumption recheck must be what rejected the session')
+ 'The session must be declined before the handshake completes, not rejected after it')
self.ts.Disk.squid_log.Content = Testers.Lambda(
lambda info, tester: TlsTicketVerifyClientScope.check_regex_count(