Fix use-after-free in SSLClient destructor with mbedTLS (Fix #2492)

SSLClient::~SSLClient() freed the TLS context before shutting down
the SSL session. mbedTLS sessions hold a raw pointer into the
context's mbedtls_ssl_config, so a live keep-alive session's
close_notify would read freed memory. Shut down the session first,
then free the context.

Add a regression test that destructs an SSLClient while a keep-alive
mbedTLS session is still open.
This commit is contained in:
yhirose committed 2026-07-11 15:27:42 -04:00
1 parent b40937cea8
commit 873d701972
2 files changed
+41 -1

No files matched your search

+8 -1
View File
@@ -16107,11 +16107,18 @@ inline bool SSLServer::update_certs_pem(const char *cert_pem,
// SSL HTTP client implementation
inline SSLClient::~SSLClient() {
if (ctx_) { tls::free_context(ctx_); }
// Make sure to shut down SSL since shutdown_ssl will resolve to the
// base function rather than the derived function once we get to the
// base class destructor, and won't free the SSL (causing a leak).
// This must happen before the context is freed below: some backends
// (e.g. mbedTLS) have the SSL session borrow a raw pointer into the
// context, so freeing the context first leaves close_notify reading
// freed memory.
shutdown_ssl_impl(socket_, true);
if (ctx_) {
tls::free_context(ctx_);
ctx_ = nullptr;
}
}
inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }