diff --git a/docs/usage.md b/docs/usage.md index c70cad6a..e5db3047 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -798,6 +798,34 @@ For a server, specifying `caFile` implies that: By default, a destination's hostname is always validated against the certificate that it presents. To accept certificates with any hostname, set `ix::SocketTLSOptions::disable_hostname_validation` to `true`. +### TLS key logging (OpenSSL) + +With OpenSSL 1.1.1 or newer, set `keyLogFile` in your TLS options before connecting +or starting a TLS server: + +```cpp +ix::SocketTLSOptions options; +options.keyLogFile = "tls.keys"; +webSocket.setTLSOptions(options); +``` + +The file contains TLS session secrets in NSS key-log format, which tools such as +Wireshark can use to decrypt captured traffic. An empty `keyLogFile` disables this +logging. Connections append to the file, including across reconnections; multiple +connections may share a destination. A connection fails if the file cannot be +opened. Other TLS backends reject this option explicitly. + +The `ws` TLS commands accept `--keylog-file` and the `SSLKEYLOGFILE` environment +variable. An explicit command-line option takes precedence: + +```sh +ws connect wss://example.com/ws --keylog-file tls.keys +SSLKEYLOGFILE=tls.keys ws connect wss://example.com/ws +``` + +The library API uses `keyLogFile` explicitly; environment-variable handling is +provided by the CLI. + ### Network.framework backend on macOS Build with `USE_NETWORK_FRAMEWORK=ON` to use native TLS for `wss://` and `https://` diff --git a/ixwebsocket/IXSocketFactory.cpp b/ixwebsocket/IXSocketFactory.cpp index 443abd76..3ed90570 100644 --- a/ixwebsocket/IXSocketFactory.cpp +++ b/ixwebsocket/IXSocketFactory.cpp @@ -35,6 +35,14 @@ namespace ix { (void) tlsOptions; errorMsg.clear(); +#if !defined(IXWEBSOCKET_USE_OPEN_SSL) || OPENSSL_VERSION_NUMBER < 0x10101000L || \ + defined(LIBRESSL_VERSION_NUMBER) + if (tls && !tlsOptions.keyLogFile.empty()) + { + errorMsg = "TLS key logging requires OpenSSL 1.1.1 or newer"; + return nullptr; + } +#endif std::unique_ptr socket; if (!tls) diff --git a/ixwebsocket/IXSocketNetwork.cpp b/ixwebsocket/IXSocketNetwork.cpp index aad8cafd..27b9fd9b 100644 --- a/ixwebsocket/IXSocketNetwork.cpp +++ b/ixwebsocket/IXSocketNetwork.cpp @@ -183,6 +183,11 @@ namespace ix std::string host, std::string& error) { + if (!options.keyLogFile.empty()) + { + error = "TLS key logging requires OpenSSL 1.1.1 or newer"; + return nullptr; + } if (!options.isUsingDefaultCiphers()) { error = "Network.framework backend does not support cipher strings"; diff --git a/ixwebsocket/IXSocketOpenSSL.cpp b/ixwebsocket/IXSocketOpenSSL.cpp index f8bf481d..6f2cdf4a 100644 --- a/ixwebsocket/IXSocketOpenSSL.cpp +++ b/ixwebsocket/IXSocketOpenSSL.cpp @@ -14,6 +14,7 @@ #include "IXUniquePtr.h" #include #include +#include #include #ifdef _WIN32 #include @@ -230,10 +231,65 @@ namespace ix int options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_CIPHER_SERVER_PREFERENCE; SSL_CTX_set_options(ctx, options); + if (!configureKeyLogging(ctx, errMsg)) + { + SSL_CTX_free(ctx); + return nullptr; + } } return ctx; } + bool SocketOpenSSL::configureKeyLogging(SSL_CTX* context, std::string& errMsg) + { + if (_tlsOptions.keyLogFile.empty()) + { + return true; + } +#if OPENSSL_VERSION_NUMBER >= 0x10101000L && !defined(LIBRESSL_VERSION_NUMBER) + std::ofstream file(_tlsOptions.keyLogFile, std::ios::app | std::ios::binary); + if (!file) + { + errMsg = "Cannot open TLS key log file: " + _tlsOptions.keyLogFile; + return false; + } + if (SSL_CTX_set_app_data(context, this) != 1) + { + errMsg = "Cannot configure TLS key logging"; + return false; + } + SSL_CTX_set_keylog_callback(context, keyLogCallback); + return true; +#else + (void) context; + errMsg = "TLS key logging requires OpenSSL 1.1.1 or newer"; + return false; +#endif + } + + void SocketOpenSSL::keyLogCallback(const SSL* ssl, const char* line) + { + auto* socket = static_cast(SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl))); + if (!socket || !line) + { + return; + } + const int savedError = Socket::getErrno(); + try + { + // Different connections can append to the same file; keep each line intact. + static std::mutex mutex; + std::lock_guard lock(mutex); + std::ofstream file(socket->_tlsOptions.keyLogFile, std::ios::app | std::ios::binary); + file << line << '\n'; + } + catch (...) + { + // A debugging log must not throw through OpenSSL's C callback. + } + Socket::setErrno(savedError); + } + bool SocketOpenSSL::openSSLAddCARootsFromString(const std::string roots) { // Create certificate store @@ -652,6 +708,11 @@ namespace ix return false; } + if (!configureKeyLogging(_ssl_context, errMsg)) + { + return false; + } + ERR_clear_error(); if (_tlsOptions.hasCertAndKey()) { diff --git a/ixwebsocket/IXSocketOpenSSL.h b/ixwebsocket/IXSocketOpenSSL.h index 7d4f3f79..18664bc1 100644 --- a/ixwebsocket/IXSocketOpenSSL.h +++ b/ixwebsocket/IXSocketOpenSSL.h @@ -43,6 +43,8 @@ namespace ix void openSSLInitialize(); std::string getSSLError(int ret); SSL_CTX* openSSLCreateContext(std::string& errMsg); + bool configureKeyLogging(SSL_CTX* context, std::string& errMsg); + static void keyLogCallback(const SSL* ssl, const char* line); bool openSSLAddCARootsFromString(const std::string roots); bool openSSLClientHandshake(const std::string& hostname, std::string& errMsg, diff --git a/ixwebsocket/IXSocketTLSOptions.cpp b/ixwebsocket/IXSocketTLSOptions.cpp index 5800ccdc..401b2dea 100644 --- a/ixwebsocket/IXSocketTLSOptions.cpp +++ b/ixwebsocket/IXSocketTLSOptions.cpp @@ -85,6 +85,7 @@ namespace ix ss << "TLS Options:" << std::endl; ss << " certFile = " << certFile << std::endl; ss << " keyFile = " << keyFile << std::endl; + ss << " keyLogFile = " << keyLogFile << std::endl; ss << " caFile = " << caFile << std::endl; ss << " ciphers = " << ciphers << std::endl; ss << " tls = " << tls << std::endl; diff --git a/ixwebsocket/IXSocketTLSOptions.h b/ixwebsocket/IXSocketTLSOptions.h index 2b5793b5..cb70a6b4 100644 --- a/ixwebsocket/IXSocketTLSOptions.h +++ b/ixwebsocket/IXSocketTLSOptions.h @@ -22,6 +22,9 @@ namespace ix // the key used for signing/encryption std::string keyFile; + // Append TLS session secrets in NSS key-log format (OpenSSL 1.1.1+ only). + std::string keyLogFile; + // the ca certificate (or certificate bundle) file containing // certificates to be trusted by peers; use 'SYSTEM' to // leverage the system defaults, use 'NONE' to disable peer verification diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 1503047a..e711bb9e 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -127,6 +127,11 @@ foreach(TEST_TARGET_NAME ${TEST_TARGET_NAMES}) endforeach() +if (TARGET IXSocketOpenSSLWriteTest) + target_compile_definitions(IXSocketOpenSSLWriteTest PRIVATE + IX_OPENSSL_TEST_OUTPUT_DIR="${CMAKE_CURRENT_BINARY_DIR}") +endif() + if (USE_WS) find_package(Python3 QUIET COMPONENTS Interpreter) if (Python3_Interpreter_FOUND) diff --git a/test/IXSocketNetworkTest.cpp b/test/IXSocketNetworkTest.cpp index 3e818504..4827152b 100644 --- a/test/IXSocketNetworkTest.cpp +++ b/test/IXSocketNetworkTest.cpp @@ -180,6 +180,16 @@ TEST_CASE("Network.framework TLS", "[network_tls]") CHECK_FALSE(result.first); CHECK(result.second.find("cipher") != std::string::npos); } + SECTION("unsupported key logging fails explicitly") + { + auto options = serverOptions(); + options.keyLogFile = "unused-keylog.log"; + HttpServer server(0); + server.setTLSOptions(options); + auto result = server.listen(); + CHECK_FALSE(result.first); + CHECK(result.second == "TLS key logging requires OpenSSL 1.1.1 or newer"); + } SECTION("bad identity fails at listen") { auto options = serverOptions(); diff --git a/test/IXSocketOpenSSLWriteTest.cpp b/test/IXSocketOpenSSLWriteTest.cpp index 566b0357..6f18f92f 100644 --- a/test/IXSocketOpenSSLWriteTest.cpp +++ b/test/IXSocketOpenSSLWriteTest.cpp @@ -3,9 +3,17 @@ * Copyright (c) 2026 Machine Zone, Inc. All rights reserved. */ #include "IXWebSocketSendBufferTest.h" +#include +#include +#include #include #include +#include #include +#include +#include +#include +#include #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(OPENSSL_NO_PSK) && !defined(OPENSSL_NO_TLS1_2) @@ -13,6 +21,10 @@ namespace ix { struct SocketOpenSSLWriteTestAccess { + static bool configureKeyLogging(SocketOpenSSL& socket, SSL_CTX* context, std::string& error) + { + return socket.configureKeyLogging(context, error); + } static bool handshake(SocketOpenSSL& socket, std::string& error, const CancellationRequest& cancelled) @@ -169,14 +181,14 @@ namespace return 16; } - void configure(bool server) + void configure(bool server, int version = TLS1_2_VERSION) { static std::unique_ptr method(makeMethod(), BIO_meth_free); context = SSL_CTX_new(TLS_method()); REQUIRE(context != nullptr); - REQUIRE(SSL_CTX_set_min_proto_version(context, TLS1_2_VERSION) == 1); - REQUIRE(SSL_CTX_set_max_proto_version(context, TLS1_2_VERSION) == 1); + REQUIRE(SSL_CTX_set_min_proto_version(context, version) == 1); + REQUIRE(SSL_CTX_set_max_proto_version(context, version) == 1); if (SSL_CTX_set_cipher_list(context, "PSK-AES128-GCM-SHA256") != 1) { SKIP("TLS 1.2 PSK AES-GCM ciphersuite is not enabled"); @@ -209,13 +221,23 @@ namespace MemoryPeer server; ix::WebSocketTransport transport; - explicit MemoryConnection(ix::SocketOpenSSL& socket) + explicit MemoryConnection(ix::SocketOpenSSL& socket, + ix::SocketOpenSSL* serverSocket = nullptr, + int version = TLS1_2_VERSION) : socket(socket) { client.other = &server; server.other = &client; - client.configure(false); - server.configure(true); + client.configure(false, version); + server.configure(true, version); + std::string error; + REQUIRE(ix::SocketOpenSSLWriteTestAccess::configureKeyLogging( + socket, client.context, error)); + if (serverSocket) + { + REQUIRE(ix::SocketOpenSSLWriteTestAccess::configureKeyLogging( + *serverSocket, server.context, error)); + } bool clientReady = false; bool serverReady = false; for (int attempt = 0; attempt < 100 && !(clientReady && serverReady); ++attempt) @@ -364,6 +386,158 @@ TEST_CASE("OpenSSL client handshakes stop on readiness errors", "[socket_openssl CHECK(error == "Socket error during TLS handshake"); } +#if OPENSSL_VERSION_NUMBER >= 0x10101000L && !defined(LIBRESSL_VERSION_NUMBER) +namespace +{ + struct KeyLogFile + { + std::string name = + std::string(IX_OPENSSL_TEST_OUTPUT_DIR) + "/keylog-" + ix::uuid4() + ".log"; + KeyLogFile() + { + std::ofstream file(name, std::ios::binary); + REQUIRE(file.is_open()); + file << "# existing content\n"; + } + ~KeyLogFile() + { + std::remove(name.c_str()); + } + std::vector lines() const + { + std::ifstream file(name, std::ios::binary); + REQUIRE(file.is_open()); + std::string line; + REQUIRE(static_cast(std::getline(file, line))); + CHECK(line == "# existing content"); + std::vector result; + while (std::getline(file, line)) + { + result.push_back(line); + } + return result; + } + }; + + std::set keyLogRandoms(const std::vector& lines) + { + std::set randoms; + const auto hex = [](char c) + { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); }; + for (const auto& line : lines) + { + std::string label, random, secret, extra; + std::istringstream stream(line); + REQUIRE(static_cast(stream >> label >> random >> secret)); + CHECK_FALSE(static_cast(stream >> extra)); + CHECK(random.size() == 64); + CHECK(std::all_of(random.begin(), random.end(), hex)); + CHECK_FALSE(secret.empty()); + CHECK(std::all_of(secret.begin(), secret.end(), hex)); + randoms.insert(random); + } + return randoms; + } +} // namespace + +TEST_CASE("OpenSSL key logs append client and server secrets across connections", + "[socket_openssl][keylog]") +{ + const bool sharedFile = GENERATE(false, true); + int version = TLS1_2_VERSION; +#ifndef OPENSSL_NO_TLS1_3 + version = GENERATE(TLS1_2_VERSION, TLS1_3_VERSION); +#endif + KeyLogFile clientFile, serverFile; + ix::SocketTLSOptions clientOptions, serverOptions; + clientOptions.keyLogFile = clientFile.name; + serverOptions.keyLogFile = sharedFile ? clientFile.name : serverFile.name; + for (unsigned i = 0; i < 3; ++i) + { + ix::SocketOpenSSL client(clientOptions), server(serverOptions); + MemoryConnection connection(client, &server, version); + } + const auto clientLines = clientFile.lines(); + CHECK(keyLogRandoms(clientLines).size() == 3); + if (sharedFile) + { + std::multiset lines(clientLines.begin(), clientLines.end()); + for (const auto& line : clientLines) + { + CHECK(lines.count(line) == 2); + } + } + else + { + const auto serverLines = serverFile.lines(); + CHECK(keyLogRandoms(serverLines).size() == 3); + CHECK(std::multiset(clientLines.begin(), clientLines.end()) == + std::multiset(serverLines.begin(), serverLines.end())); + } +} + +TEST_CASE("Concurrent OpenSSL key logs preserve complete lines and socket errors", + "[socket_openssl][keylog]") +{ + KeyLogFile file; + ix::SocketTLSOptions options; + options.keyLogFile = file.name; + ix::SocketOpenSSL first(options), second(options); + MemoryPeer firstPeer, secondPeer; + firstPeer.configure(false); + secondPeer.configure(false); + std::string error; + REQUIRE(ix::SocketOpenSSLWriteTestAccess::configureKeyLogging(first, firstPeer.context, error)); + REQUIRE( + ix::SocketOpenSSLWriteTestAccess::configureKeyLogging(second, secondPeer.context, error)); + auto callback = SSL_CTX_get_keylog_callback(firstPeer.context); + REQUIRE(callback != nullptr); + const std::string line = "CLIENT_RANDOM " + std::string(64, '0') + " " + std::string(96, '1'); + std::atomic errorsPreserved(true); + const auto write = [&](const SSL* ssl) + { + for (unsigned i = 0; i < 32; ++i) + { + ix::Socket::setErrno(EWOULDBLOCK); + callback(ssl, line.c_str()); + if (ix::Socket::getErrno() != EWOULDBLOCK) + { + errorsPreserved = false; + } + } + }; + std::thread a(write, firstPeer.ssl), b(write, secondPeer.ssl); + a.join(); + b.join(); + CHECK(errorsPreserved.load()); + const auto lines = file.lines(); + CHECK(lines.size() == 64); + for (const auto& actual : lines) + { + CHECK(actual == line); + } +} + +TEST_CASE("OpenSSL key logging is opt-in and rejects an unwritable destination", + "[socket_openssl][keylog]") +{ + MemoryPeer peer; + peer.configure(false); + ix::SocketOpenSSL disabled(ix::SocketTLSOptions {}); + std::string error; + REQUIRE(ix::SocketOpenSSLWriteTestAccess::configureKeyLogging(disabled, peer.context, error)); + CHECK(SSL_CTX_get_keylog_callback(peer.context) == nullptr); + KeyLogFile file; + ix::SocketTLSOptions options; + options.keyLogFile = file.name + "/cannot-create.log"; + ix::SocketOpenSSL invalid(options); + CHECK_FALSE( + ix::SocketOpenSSLWriteTestAccess::configureKeyLogging(invalid, peer.context, error)); + CHECK(error == "Cannot open TLS key log file: " + options.keyLogFile); + CHECK(SSL_CTX_get_keylog_callback(peer.context) == nullptr); +} +#endif + #else TEST_CASE("OpenSSL memory write tests require TLS 1.2 PSK and OpenSSL 1.1 APIs", "[socket_openssl]") { diff --git a/test/IXSocketTest.cpp b/test/IXSocketTest.cpp index 906b1804..1ca33317 100644 --- a/test/IXSocketTest.cpp +++ b/test/IXSocketTest.cpp @@ -17,6 +17,18 @@ using namespace ix; +#if !defined(IXWEBSOCKET_USE_OPEN_SSL) +TEST_CASE("TLS key logging rejects unsupported backends", "[socket][keylog]") +{ + ix::SocketTLSOptions options; + options.keyLogFile = "unused-keylog.log"; + std::string error; + CHECK_FALSE(ix::createSocket(true, -1, error, options)); + CHECK(error == "TLS key logging requires OpenSSL 1.1.1 or newer"); + CHECK(ix::createSocket(false, -1, error, options) != nullptr); +} +#endif + namespace { // No native descriptor: completed reads and EOF must not poll for more data. diff --git a/ws/ws.cpp b/ws/ws.cpp index 3e6c620a..f1b077b0 100644 --- a/ws/ws.cpp +++ b/ws/ws.cpp @@ -2562,6 +2562,11 @@ int main(int argc, char** argv) subcommand ->add_option("--key-file", tlsOptions.keyFile, "Path to the (PEM format) TLS key file") ->check(CLI::ExistingPath); + subcommand + ->add_option("--keylog-file", + tlsOptions.keyLogFile, + "Append TLS session secrets to this file (OpenSSL 1.1.1+)") + ->envname("SSLKEYLOGFILE"); subcommand ->add_option("--ca-file", tlsOptions.caFile, "Path to the (PEM format) ca roots file") ->check(CLI::ExistingPath);