diff --git a/httplib.h b/httplib.h index 2bac990c..14088ed0 100644 --- a/httplib.h +++ b/httplib.h @@ -20150,6 +20150,21 @@ inline bool SSLServer::is_valid() const { return ctx_ != nullptr && Server::is_valid(); } +namespace detail { + +// Before these, SSL_free_buffers() could free a buffer that a record whose +// body has not arrived yet still uses (CVE-2024-4741). `version` is +// OpenSSL_version_num(). +inline bool ssl_free_buffers_is_safe(unsigned long version) { + if (version >= 0x30400000UL) { return true; } + if (version >= 0x30300000UL) { return version >= 0x30300010UL; } // 3.3.1 + if (version >= 0x30200000UL) { return version >= 0x30200020UL; } // 3.2.2 + if (version >= 0x30100000UL) { return version >= 0x30100060UL; } // 3.1.6 + return version >= 0x300000e0UL; // 3.0.14 +} + +} // namespace detail + // A connection that keep-alive parking keeps for SSLServer. The worker that // first resumes it runs the handshake, so one that has not sent its // ClientHello yet waits in the event loop like an idle connection. @@ -20180,9 +20195,11 @@ struct SSLServer::TlsConnection final : Server::KeepAliveConnection { void release_buffers() override { #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \ !defined(LIBRESSL_VERSION_NUMBER) - // The record buffers are most of an idle session's memory. It keeps them - // when a record is still pending, and makes new ones on the next read. - SSL_free_buffers(static_cast(session)); + // The record buffers are most of an idle session's memory, and the next + // read makes new ones. The library that runs decides whether that is safe. + static const auto safe = + detail::ssl_free_buffers_is_safe(OpenSSL_version_num()); + if (safe) { SSL_free_buffers(static_cast(session)); } #endif } diff --git a/test/test.cc b/test/test.cc index 6165e1ad..1a975b18 100644 --- a/test/test.cc +++ b/test/test.cc @@ -95,6 +95,9 @@ macos_ssl_trust_settings_result(CFArrayRef trust_settings); } // namespace impl #endif } // namespace tls +namespace detail { +bool ssl_free_buffers_is_safe(unsigned long version); +} // namespace detail } // namespace httplib #endif @@ -34445,6 +34448,22 @@ bool tls_get_ok(Client &cli) { } // namespace parking_test +TEST(KeepAliveParkingTest, SslFreeBuffersOnlyWhereTheCveIsFixed) { + struct { + unsigned long version; + bool safe; + } cases[] = { + {0x30000020UL, false}, {0x300000d0UL, false}, {0x300000e0UL, true}, + {0x300000f0UL, true}, {0x30100050UL, false}, {0x30100060UL, true}, + {0x30200010UL, false}, {0x30200020UL, true}, {0x30300000UL, false}, + {0x30300010UL, true}, {0x30400000UL, true}, {0x40000000UL, true}, + }; + for (const auto &c : cases) { + EXPECT_EQ(c.safe, detail::ssl_free_buffers_is_safe(c.version)) + << std::hex << c.version; + } +} + TEST(KeepAliveParkingTest, IdleTlsConnectionsDoNotHoldTheWorkers) { using namespace parking_test; SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);