From d48f597526f904812a5c182f88a83f3ec926d302 Mon Sep 17 00:00:00 2001 From: Finn <117590961+Peaks2000@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:32:57 +0000 Subject: [PATCH 1/3] fix(security): enforce setup, revocation and stream authentication boundaries --- docs/configuration.md | 5 + docs/getting_started.md | 11 +- src/confighttp.cpp | 28 +++- src/confighttp.h | 13 ++ src/control_protocol.h | 81 +++++++++++ src/crypto.cpp | 34 ++--- src/crypto.h | 10 +- src/nvhttp.cpp | 123 +++++++++++++++- src/nvhttp.h | 15 +- src/rtsp.cpp | 50 +++++-- src/rtsp.h | 11 ++ src/stream.cpp | 62 +++++--- tests/unit/test_confighttp.cpp | 41 ++++++ tests/unit/test_control_protocol.cpp | 141 ++++++++++++++++++ tests/unit/test_crypto.cpp | 50 +++++++ tests/unit/test_nvhttp_client_auth.cpp | 90 ++++++++++++ tests/unit/test_nvhttp_https.cpp | 190 ++++++++++++++++++++++++- tests/unit/test_rtsp.cpp | 40 ++++++ 18 files changed, 926 insertions(+), 69 deletions(-) create mode 100644 src/control_protocol.h create mode 100644 tests/unit/test_control_protocol.cpp diff --git a/docs/configuration.md b/docs/configuration.md index 6024df7cdb6..bfab9fabaf0 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1784,6 +1784,9 @@ consent prompt for directory ACLs, so the Web UI shows setup steps for correctin ### lan_encryption_mode +@note{Authenticated encrypted RTSP setup is always required. This setting controls audio/video encryption and +cannot enable legacy plaintext RTSP setup.} + @@ -1821,6 +1824,8 @@ consent prompt for directory ACLs, so the Web UI shows setup steps for correctin ### wan_encryption_mode +@note{Authenticated encrypted RTSP setup is always required, independently of this audio/video encryption policy.} +
Description
diff --git a/docs/getting_started.md b/docs/getting_started.md index 4f1bb107ae7..337cf375590 100644 --- a/docs/getting_started.md +++ b/docs/getting_started.md @@ -697,6 +697,7 @@ by default. You may replace *localhost* with your internal ip address. > [!CAUTION] > If running for the first time, make sure to note the username and password that you created. +> The `origin_web_ui_allowed` network restriction also applies to initial credential creation. 1. Change the web-ui to your desired theme, using the dropdown menu in the navbar. ![Theme Selection](images/split-themes.png) @@ -706,7 +707,9 @@ by default. You may replace *localhost* with your internal ip address. ![Configuration](images/configuration-search.png) 4. Find Moonlight clients and other tools for Sunshine in the `Featured Apps` tab. ![Featured Apps](images/featured-apps.png) -5. In Moonlight, you may need to add the PC manually. +5. Use a Moonlight client that supports authenticated encrypted RTSP setup. Clients without this support cannot + start or resume a stream and receive an error asking them to update. This requirement applies even when + audio/video encryption is disabled. In Moonlight, you may need to add the PC manually. 6. When Moonlight requests for you insert the pin: - Login to the web-ui @@ -822,3 +825,9 @@ Tutorials and Guides are community generated. Want to contribute? Reach out to u [latest-release]: https://github.com/SunshineStream/Sunshine/releases/latest + +### Revoking client access + +Unpairing or disabling a client revokes its active streams and pending launches. Other paired clients remain +permitted to connect. Re-enabling or pairing a client again requires a new launch; it does not restore an +old connection's authorization. diff --git a/src/confighttp.cpp b/src/confighttp.cpp index 7a5f0c69a69..34488a5e437 100644 --- a/src/confighttp.cpp +++ b/src/confighttp.cpp @@ -640,12 +640,12 @@ namespace confighttp { } /** - * @brief Authenticate the user. + * @brief Enforce the Web UI remote-address policy, including initial setup. * @param response The HTTP response object. * @param request The HTTP request object. - * @return True if the user is authenticated, false otherwise. + * @return True when the source address is allowed, false otherwise. */ - bool authenticate(const resp_https_t &response, const req_https_t &request) { + bool check_access(const resp_https_t &response, const req_https_t &request) { auto address = net::addr_to_normalized_string(request->remote_endpoint().address()); if (const auto ip_type = net::from_address(address); ip_type > http::origin_web_ui_allowed) { @@ -654,6 +654,20 @@ namespace confighttp { return false; } + return true; + } + + /** + * @brief Authenticate credentials after enforcing the Web UI network policy. + * @param response The HTTP response object. + * @param request The HTTP request object. + * @return True when the source address and credentials are authorized. + */ + bool authenticate(const resp_https_t &response, const req_https_t &request) { + if (!check_access(response, request)) { + return false; + } + // If credentials are shown, redirect the user to a /welcome page if (config::sunshine.username.empty()) { send_redirect(response, request, "/welcome"); @@ -1519,9 +1533,14 @@ namespace confighttp { nlohmann::json output_tree; const nlohmann::json input_tree = nlohmann::json::parse(ss); const std::string uuid = input_tree.value("uuid", ""); + const auto cert = nvhttp::get_cert_by_uuid(uuid); const bool removed = nvhttp::unpair_client(uuid); output_tree["status"] = removed; + if (removed && !cert.empty()) { + rtsp_stream::terminate_sessions_by_cert(cert); + } + if (removed && nvhttp::get_all_clients().empty()) { proc::proc.terminate(); } @@ -1829,6 +1848,9 @@ namespace confighttp { * @api_examples{/api/password|:| POST|:| {"currentUsername":"admin","currentPassword":"admin","newUsername":"admin","newPassword":"admin","confirmNewPassword":"admin"}} */ void savePassword(const resp_https_t &response, const req_https_t &request) { + if (!check_access(response, request)) { + return; + } if (!check_content_type(response, request, "application/json")) { return; } diff --git a/src/confighttp.h b/src/confighttp.h index fb379312436..950c5622114 100644 --- a/src/confighttp.h +++ b/src/confighttp.h @@ -40,6 +40,19 @@ namespace confighttp { void send_response(const resp_https_t &response, const nlohmann::json &output_tree); void send_unauthorized(const resp_https_t &response, const req_https_t &request); void send_redirect(const resp_https_t &response, const req_https_t &request, const char *path); + /** + * @brief Enforce the Web UI remote-address policy independently of credentials. + * @param response HTTP response used to report a forbidden address. + * @param request Request whose remote address is checked. + * @return True when the source address is allowed. + */ + bool check_access(const resp_https_t &response, const req_https_t &request); + /** + * @brief Create initial credentials or change existing credentials after access checks. + * @param response HTTP response object to populate. + * @param request JSON credential update request. + */ + void savePassword(const resp_https_t &response, const req_https_t &request); bool authenticate(const resp_https_t &response, const req_https_t &request); void not_found(const resp_https_t &response, const std::string &error_message = "Not Found"); void bad_request(const resp_https_t &response, const std::string &error_message = "Bad Request"); diff --git a/src/control_protocol.h b/src/control_protocol.h new file mode 100644 index 00000000000..8a765694b3b --- /dev/null +++ b/src/control_protocol.h @@ -0,0 +1,81 @@ +/** + * @file src/control_protocol.h + * @brief Bounded parsing of GameStream control envelopes before decryption. + */ +#pragma once + +// standard includes +#include +#include +#include +#include +#include + +// lib includes +#include + +namespace stream::control { + constexpr std::size_t TAG_SIZE = 16; ///< AES-GCM tag size on the control wire protocol. + + /** + * @brief Validated encrypted envelope excluding the outer message type. + */ + struct encrypted_message_t { + std::uint32_t sequence; ///< Sequence used to construct the message IV. + std::string_view tagged_cipher; ///< Bounded view of the authentication tag and ciphertext. + }; + + /** + * @brief Validate an encrypted envelope before reading its sequence or ciphertext. + * @param payload Wire bytes after the two-byte outer message type. + * @return Parsed envelope, or no value for an incomplete or inconsistent length. + */ + inline std::optional parse_encrypted(std::string_view payload) { + constexpr std::size_t header_size = sizeof(std::uint16_t) + sizeof(std::uint32_t); + constexpr std::size_t minimum_length = sizeof(std::uint32_t) + TAG_SIZE + 4; + if (payload.size() < header_size) { + return std::nullopt; + } + const auto *bytes = reinterpret_cast(payload.data()); + const auto length = boost::endian::endian_load(bytes); + if (length < minimum_length || length != payload.size() - sizeof(length)) { + return std::nullopt; + } + const auto sequence = boost::endian::endian_load(bytes + sizeof(length)); + return encrypted_message_t {sequence, payload.substr(header_size)}; + } + + /** + * @brief Validate the big-endian length prefix of legacy encrypted input. + * @param payload Wire bytes after the outer message type. + * @return Bounded tag and ciphertext, or no value for an invalid length. + */ + inline std::optional parse_legacy_input(std::string_view payload) { + constexpr auto header_size = sizeof(std::uint32_t); + if (payload.size() < header_size) { + return std::nullopt; + } + const auto length = boost::endian::endian_load(reinterpret_cast(payload.data())); + if (length < TAG_SIZE || length != payload.size() - header_size) { + return std::nullopt; + } + return payload.substr(header_size); + } + + /** + * @brief Read a complete decrypted secondary control header. + * @param plaintext Complete authenticated plaintext including its secondary header. + * @return Message type and actual authenticated payload, or no value for a short header. + */ + inline std::optional> parse_plaintext(std::string_view plaintext) { + constexpr std::size_t header_size = 4; + if (plaintext.size() < header_size) { + return std::nullopt; + } + const auto *bytes = reinterpret_cast(plaintext.data()); + const auto type = boost::endian::endian_load(bytes); + // Preserve legacy header semantics: dispatch is bounded by authenticated bytes, + // not by the advisory secondary payloadLength field. + return std::pair {type, plaintext.substr(header_size)}; + } +} // namespace stream::control diff --git a/src/crypto.cpp b/src/crypto.cpp index 4837fa82103..7b9078c05a9 100644 --- a/src/crypto.cpp +++ b/src/crypto.cpp @@ -2,6 +2,10 @@ * @file src/crypto.cpp * @brief Definitions for cryptography functions. */ +// standard includes +#include +#include + // lib includes #include #include @@ -142,33 +146,29 @@ namespace crypto { } int gcm_t::decrypt(const std::string_view &tagged_cipher, std::vector &plaintext, aes_t *iv) { + plaintext.clear(); + if (tagged_cipher.size() < tag_size || tagged_cipher.size() - tag_size > static_cast(std::numeric_limits::max() - 16) || key.size() != 16 || iv == nullptr || iv->empty() || iv->size() > static_cast(std::numeric_limits::max())) { + return -1; + } if (!decrypt_ctx && init_decrypt_gcm(decrypt_ctx, &key, iv, padding)) { + decrypt_ctx.reset(); return -1; } - // Calling with cipher == nullptr results in a parameter change - // without requiring a reallocation of the internal cipher ctx. + // Reset message state while retaining the cipher context and negotiated key. if (EVP_DecryptInit_ex(decrypt_ctx.get(), nullptr, nullptr, nullptr, iv->data()) != 1) { - return false; + return -1; } - auto cipher = tagged_cipher.substr(tag_size); - auto tag = tagged_cipher.substr(0, tag_size); - - plaintext.resize(round_to_pkcs7_padded(cipher.size())); + const auto cipher = tagged_cipher.substr(tag_size); + const auto tag = tagged_cipher.substr(0, tag_size); + // Reserve a writable output byte even for an authenticated empty message. + plaintext.resize(std::max(16, round_to_pkcs7_padded(cipher.size()))); int final_outlen; int update_outlen; - - if (EVP_DecryptUpdate(decrypt_ctx.get(), plaintext.data(), &update_outlen, (const std::uint8_t *) cipher.data(), (int) cipher.size()) != 1) { - return -1; - } - - if (EVP_CIPHER_CTX_ctrl(decrypt_ctx.get(), EVP_CTRL_GCM_SET_TAG, (int) tag.size(), const_cast(tag.data())) != 1) { - return -1; - } - - if (EVP_DecryptFinal_ex(decrypt_ctx.get(), plaintext.data() + update_outlen, &final_outlen) != 1) { + if (EVP_DecryptUpdate(decrypt_ctx.get(), plaintext.data(), &update_outlen, (const std::uint8_t *) cipher.data(), (int) cipher.size()) != 1 || EVP_CIPHER_CTX_ctrl(decrypt_ctx.get(), EVP_CTRL_GCM_SET_TAG, (int) tag.size(), const_cast(tag.data())) != 1 || EVP_DecryptFinal_ex(decrypt_ctx.get(), plaintext.data() + update_outlen, &final_outlen) != 1) { + plaintext.clear(); return -1; } diff --git a/src/crypto.h b/src/crypto.h index 98be726c14e..c075662c0e2 100644 --- a/src/crypto.h +++ b/src/crypto.h @@ -320,12 +320,12 @@ namespace crypto { int encrypt(const std::string_view &plaintext, std::uint8_t *tagged_cipher, aes_t *iv); /** - * @brief Decrypt ciphertext into the supplied plaintext buffer. + * @brief Authenticate and decrypt a complete tag-prefixed AES-GCM message. * - * @param cipher Ciphertext bytes to decrypt or output buffer for encryption. - * @param plaintext Plaintext bytes to encrypt. - * @param iv Initialization vector for the cipher operation. - * @return Number of bytes written, signature bytes, or an error status depending on the overload. + * @param cipher Complete authentication tag followed by ciphertext. + * @param plaintext Receives authenticated plaintext; empty on failure. + * @param iv Nonempty initialization vector for the cipher operation. + * @return Zero on success, or -1 for invalid input or authentication failure. */ int decrypt(const std::string_view &cipher, std::vector &plaintext, aes_t *iv); }; diff --git a/src/nvhttp.cpp b/src/nvhttp.cpp index 7601cb89690..2e0f2ae081d 100644 --- a/src/nvhttp.cpp +++ b/src/nvhttp.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -87,6 +88,36 @@ namespace nvhttp { protected: boost::asio::ssl::context context {boost::asio::ssl::context::tls_server}; ///< TLS server context configured with Sunshine's certificate and protocol policy. + using connection_key_t = std::pair; ///< Local and remote endpoints uniquely identifying an active TCP connection. + std::map> client_connections; ///< Live TLS connections indexed by both endpoints. + std::mutex client_connections_mutex; ///< Protects connection lookup across HTTPS workers. + + /** + * @brief Recheck the certificate on the request's own TLS connection before dispatch. + * @param handler Original HTTP route handler. + * @return Handler that rejects revoked identities and refreshes request-local identity. + */ + std::function, std::shared_ptr)> authorize_request(std::function, std::shared_ptr)> handler) { + return [this, handler = std::move(handler)](auto response, auto request) { + std::shared_ptr connection; + { + std::lock_guard lock {client_connections_mutex}; + if (const auto it = client_connections.find({request->local_endpoint(), request->remote_endpoint()}); it != client_connections.end()) { + connection = it->second.lock(); + } + } + if (!connection || !verify(connection->socket->native_handle())) { + response->close_connection_after_response = true; + if (on_verify_failed) { + on_verify_failed(response, request); + } else { + response->write(SimpleWeb::StatusCode::client_error_unauthorized); + } + return; + } + handler(response, request); + }; + } /** * @brief Enable client-certificate verification after the listening socket is bound. @@ -94,6 +125,14 @@ namespace nvhttp { */ void after_bind() override { if (verify) { + for (auto &[pattern, methods] : resource) { + for (auto &[method, handler] : methods) { + handler = authorize_request(std::move(handler)); + } + } + for (auto &[method, handler] : default_resource) { + handler = authorize_request(std::move(handler)); + } context.set_verify_mode(boost::asio::ssl::verify_peer | boost::asio::ssl::verify_fail_if_no_peer_cert | boost::asio::ssl::verify_client_once); context.set_verify_callback([](int, boost::asio::ssl::verify_context &) { // To respond with an error message, a connection must be established @@ -114,6 +153,14 @@ namespace nvhttp { if (verify && !verify(session->connection->socket->native_handle())) { this->write(session, on_verify_failed); } else { + if (verify) { + std::lock_guard lock {client_connections_mutex}; + std::erase_if(client_connections, [](const auto &entry) { + return entry.second.expired(); + }); + const auto &socket = session->connection->socket->lowest_layer(); + client_connections[{socket.local_endpoint(), socket.remote_endpoint()}] = session->connection; + } this->read(session); } } else if (this->on_error) { @@ -184,6 +231,7 @@ namespace nvhttp { std::string uuid; ///< Persistent Moonlight client UUID associated with the certificate. std::string cert; ///< Certificate PEM string or path. bool enabled = true; ///< Whether this persisted client entry may connect. + std::shared_ptr revoked = std::make_shared(false); ///< Revocation state retained by pending and active launches. }; /** @@ -209,9 +257,9 @@ namespace nvhttp { client_t client_root; ///< In-memory representation of the paired-client database. std::atomic session_id_counter; ///< Monotonic counter used to allocate GameStream session IDs. - // Set by TLS verify callback, read by launch/resume handler (single-threaded HTTPS server) - std::string last_verified_client_cert; ///< Last client certificate accepted by the TLS verify callback. // NOSONAR(cpp:S5421): intentionally mutable global - std::string last_verified_client_name; ///< Friendly name of last client certificate accepted by the TLS verify callback. // NOSONAR(cpp:S5421): intentionally mutable global + // Revalidated immediately before each request; isolated across HTTPS worker threads. + thread_local std::string last_verified_client_cert; ///< Last client certificate accepted by the TLS verify callback. // NOSONAR(cpp:S5421): intentionally mutable global + thread_local std::string last_verified_client_name; ///< Friendly name of last client certificate accepted by the TLS verify callback. // NOSONAR(cpp:S5421): intentionally mutable global /** * @brief Case-insensitive map used for HTTP headers and query parameters. @@ -322,6 +370,7 @@ namespace nvhttp { cert_chain.clear(); for (const auto &named_cert : client_root.named_devices) { if (!named_cert.enabled) { + named_cert.revoked->store(true, std::memory_order_release); continue; } @@ -438,6 +487,9 @@ namespace nvhttp { } std::lock_guard lock {client_auth_mutex()}; + for (const auto &previous : client_root.named_devices) { + previous.revoked->store(true, std::memory_order_release); + } client_root = std::move(client); rebuild_client_cert_chain(); } @@ -466,7 +518,11 @@ namespace nvhttp { std::lock_guard lock {client_auth_mutex()}; std::erase_if(client_root.named_devices, [&certificate](const named_cert_t &existing_client) { auto existing_certificate = crypto::x509(existing_client.cert); - return existing_certificate && X509_cmp(existing_certificate.get(), certificate.get()) == 0; + const bool replaced = existing_certificate && X509_cmp(existing_certificate.get(), certificate.get()) == 0; + if (replaced) { + existing_client.revoked->store(true, std::memory_order_release); + } + return replaced; }); client_root.named_devices.emplace_back(std::move(named_cert)); rebuild_client_cert_chain(); @@ -477,6 +533,21 @@ namespace nvhttp { return uuid; } + /** + * @brief Look up the revocation state for an enabled canonical client identity. + * @param cert Canonical PEM certificate accepted for this request. + * @return Shared revocation state, or a revoked state for an unknown client. + */ + std::shared_ptr client_revocation_state(std::string_view cert) { + std::lock_guard lock {client_auth_mutex()}; + for (const auto &client : client_root.named_devices) { + if (client.cert == cert && client.enabled) { + return client.revoked; + } + } + return std::make_shared(true); + } + /** * @brief Create launch session. * @@ -533,6 +604,7 @@ namespace nvhttp { } launch_session->rtsp_url_scheme = launch_session->rtsp_cipher ? "rtspenc://"s : "rtsp://"s; launch_session->client_cert = last_verified_client_cert; + launch_session->revoked = client_revocation_state(launch_session->client_cert); launch_session->client_name = last_verified_client_name; // Generate the unique identifiers for this connection that we will send later during RTSP handshake @@ -1415,8 +1487,19 @@ namespace nvhttp { return; } + if (util::from_view(get_arg(args, "corever", "0")) < 1) { + tree.put("root..status_code", 403); + tree.put("root..status_message", "Authenticated RTSP is required. Update your Moonlight client."); + return; + } + host_audio = util::from_view(get_arg(args, "localAudioPlayMode")); auto launch_session = make_launch_session(host_audio, args); + if (!rtsp_stream::accepts_rtsp(*launch_session)) { + tree.put("root..status_code", 403); + tree.put("root..status_message", "Client authorization was revoked"); + return; + } if (rtsp_stream::session_count() == 0) { // The display should be restored in case something fails as there are no other sessions. @@ -1524,6 +1607,12 @@ namespace nvhttp { return; } + if (util::from_view(get_arg(args, "corever", "0")) < 1) { + tree.put("root..status_code", 403); + tree.put("root..status_message", "Authenticated RTSP is required. Update your Moonlight client."); + return; + } + // Newer Moonlight clients send localAudioPlayMode on /resume too, // so we should use it if it's present in the args and there are // no active sessions we could be interfering with. @@ -1532,6 +1621,11 @@ namespace nvhttp { host_audio = util::from_view(get_arg(args, "localAudioPlayMode")); } const auto launch_session = make_launch_session(host_audio, args); + if (!rtsp_stream::accepts_rtsp(*launch_session)) { + tree.put("root..status_code", 403); + tree.put("root..status_message", "Client authorization was revoked"); + return; + } if (no_active_sessions) { // We want to prepare display only if there are no active sessions at @@ -1789,6 +1883,9 @@ namespace nvhttp { void erase_all_clients() { std::lock_guard lock {client_auth_mutex()}; + for (const auto &client : client_root.named_devices) { + client.revoked->store(true, std::memory_order_release); + } client_root = {}; cert_chain.clear(); save_state(); @@ -1799,6 +1896,7 @@ namespace nvhttp { bool removed = false; for (auto it = client_root.named_devices.begin(); it != client_root.named_devices.end();) { if ((*it).uuid == uuid) { + it->revoked->store(true, std::memory_order_release); it = client_root.named_devices.erase(it); removed = true; } else { @@ -1815,6 +1913,12 @@ namespace nvhttp { std::lock_guard lock {client_auth_mutex()}; for (auto &named_cert : client_root.named_devices) { if (named_cert.uuid == uuid) { + if (named_cert.enabled != enabled) { + named_cert.revoked->store(true, std::memory_order_release); + if (enabled) { + named_cert.revoked = std::make_shared(false); + } + } named_cert.enabled = enabled; rebuild_client_cert_chain(); save_state(); @@ -1855,7 +1959,8 @@ namespace nvhttp { std::unique_ptr> make_https_server( const std::string &certificate_file, const std::string &private_key_file, - std::shared_ptr &handler_scope + std::shared_ptr &handler_scope, + std::function verifier ) { /** * @brief Expose the production HTTPS handler scope to lifetime regression tests. @@ -1868,6 +1973,14 @@ namespace nvhttp { auto server = std::make_unique(certificate_file, private_key_file); handler_scope = server->handler_runner; + server->verify = std::move(verifier); + server->default_resource["GET"] = [](auto response, auto) { + response->write("authorized"); + }; + server->on_verify_failed = [](auto response, auto) { + response->close_connection_after_response = true; + response->write(SimpleWeb::StatusCode::client_error_unauthorized); + }; return server; } diff --git a/src/nvhttp.h b/src/nvhttp.h index a7c0fc9ad1a..4039d1c7a85 100644 --- a/src/nvhttp.h +++ b/src/nvhttp.h @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -102,10 +103,16 @@ namespace nvhttp { SimpleWeb::HTTPS(io_context, ctx) { } + /** + * @brief Send a best-effort TLS close notification without waiting for the peer. + */ virtual ~SunshineHTTPS() { - // Gracefully shutdown the TLS connection + // A peer withholding close_notify must not block the HTTPS IO worker. SimpleWeb::error_code ec; - shutdown(ec); + lowest_layer().non_blocking(true, ec); + if (!ec) { + shutdown(ec); + } } }; @@ -398,12 +405,14 @@ namespace nvhttp { * @param certificate_file Path to the server certificate PEM file. * @param private_key_file Path to the matching private key PEM file. * @param handler_scope Receives the scope runner that prevents destruction during callbacks. + * @param verifier Optional production-path client verifier used for revocation tests. * @return HTTPS server ready for test endpoint configuration. */ std::unique_ptr> make_https_server( const std::string &certificate_file, const std::string &private_key_file, - std::shared_ptr &handler_scope + std::shared_ptr &handler_scope, + std::function verifier = {} ); /** diff --git a/src/rtsp.cpp b/src/rtsp.cpp index cd2dd9e86de..0450c907c4b 100644 --- a/src/rtsp.cpp +++ b/src/rtsp.cpp @@ -401,6 +401,10 @@ namespace rtsp_stream { * @param req Parsed RTSP request being handled. */ void handle_data(msg_t &&req) { + if (!accepts_rtsp(*session)) { + respond(sock, *session, nullptr, 403, "Forbidden", req->sequenceNumber, {}); + return; + } handle_data_fn(sock, *session, std::move(req)); } @@ -505,7 +509,7 @@ namespace rtsp_stream { auto socket = std::move(next_socket); auto launch_session {launch_event.view(0s)}; - if (launch_session) { + if (launch_session && accepts_rtsp(*launch_session)) { // Associate the current RTSP session with this socket and start reading socket->session = launch_session; socket->read(); @@ -545,7 +549,7 @@ namespace rtsp_stream { */ void session_raise(std::shared_ptr launch_session) { // If a launch event is still pending, don't overwrite it. - if (launch_event.view(0s)) { + if (const auto pending = launch_event.view(0s); pending && !pending->revoked->load(std::memory_order_acquire)) { return; } @@ -636,22 +640,28 @@ namespace rtsp_stream { } /** - * @brief Removes the provided session from the set of sessions. - * @param session The session to remove. + * @brief Start and register a stream atomically with respect to revocation. + * @param stream_session Allocated stream whose workers have not started. + * @param launch Launch authorization shared with RTSP sockets. + * @param address Remote address to use for the stream. + * @return Zero on success, or -1 when revoked or startup fails. */ - void remove(const std::shared_ptr &session) { + int start_session(const std::shared_ptr &stream_session, const launch_session_t &launch, const std::string &address) { auto lg = _session_slots.lock(); - _session_slots->erase(session); + if (!accepts_rtsp(launch) || stream::session::start(*stream_session, address)) { + return -1; + } + _session_slots->emplace(stream_session); + return 0; } /** - * @brief Inserts the provided session into the set of sessions. - * @param session The session to insert. + * @brief Removes the provided session from the set of sessions. + * @param session The session to remove. */ - void insert(const std::shared_ptr &session) { + void remove(const std::shared_ptr &session) { auto lg = _session_slots.lock(); - _session_slots->emplace(session); - BOOST_LOG(info) << "New streaming session started [active sessions: "sv << _session_slots->size() << ']'; + _session_slots->erase(session); } /** @@ -688,6 +698,20 @@ namespace rtsp_stream { std::shared_ptr next_socket; }; +#ifdef SUNSHINE_TESTS + namespace test_support { + /** + * @brief Exercise denied stream admission before any stream object is accessed. + * @param launch Plaintext or revoked launch to reject. + * @return Stream startup result from the production admission boundary. + */ + int reject_stream_for_testing(const launch_session_t &launch) { + rtsp_server_t isolated_server; + return isolated_server.start_session({}, launch, "127.0.0.1"); + } + } // namespace test_support +#endif + rtsp_server_t server {}; ///< Singleton RTSP server used by GameStream launch sessions. /** @@ -1254,9 +1278,7 @@ namespace rtsp_stream { } auto stream_session = stream::session::alloc(config, session); - rtsp_server->insert(stream_session); - - if (stream::session::start(*stream_session, sock.remote_endpoint().address().to_string())) { + if (rtsp_server->start_session(stream_session, session, sock.remote_endpoint().address().to_string())) { BOOST_LOG(error) << "Failed to start a streaming session"sv; rtsp_server->remove(stream_session); diff --git a/src/rtsp.h b/src/rtsp.h index 108c881e200..4ca55233e98 100644 --- a/src/rtsp.h +++ b/src/rtsp.h @@ -9,6 +9,7 @@ #include #include #include +#include // local includes #include "crypto.h" @@ -74,6 +75,7 @@ namespace rtsp_stream { */ struct launch_session_t { uint32_t id; ///< RTSP launch-session identifier assigned before stream startup. + std::shared_ptr revoked = std::make_shared(false); ///< Revocation shared with accepted sockets and active streams. crypto::aes_t gcm_key; ///< AES-GCM key negotiated for encrypted RTSP messages. crypto::aes_t iv; ///< Initial RTSP AES-GCM IV supplied by the client. @@ -101,6 +103,15 @@ namespace rtsp_stream { std::string client_cert; ///< PEM certificate for the paired Moonlight client. }; + /** + * @brief Require authenticated RTSP setup and reject a revoked launch. + * @param session Pending launch to check. + * @return True when this launch may accept authenticated RTSP messages. + */ + inline bool accepts_rtsp(const launch_session_t &session) { + return session.rtsp_cipher.has_value() && !session.revoked->load(std::memory_order_acquire); + } + /** * @brief Queue a launch session until the RTSP client connects. * diff --git a/src/stream.cpp b/src/stream.cpp index a222b4045e2..cd4a24d997f 100644 --- a/src/stream.cpp +++ b/src/stream.cpp @@ -22,6 +22,7 @@ // local includes #include "config.h" +#include "control_protocol.h" #include "display_device.h" #include "globals.h" #include "input.h" @@ -81,6 +82,7 @@ using asio::ip::udp; using namespace std::literals; namespace stream { + static_assert(control::TAG_SIZE == crypto::cipher::tag_size); /** * @brief Enumerates supported socket options. @@ -562,6 +564,7 @@ namespace stream { std::uint32_t launch_session_id; ///< RTSP launch-session ID associated with this stream. std::string client_cert; ///< PEM certificate for the paired client owning the stream. + std::shared_ptr revoked; ///< Launch revocation shared with accepted RTSP sockets. std::string input_session_id; ///< Stable client identity used to retain input devices across resume. safe::mail_raw_t::event_t shutdown_event; ///< Event raised when the stream should shut down. @@ -762,6 +765,7 @@ namespace stream { auto res = enet_host_service(_host.get(), &event, (enet_uint32) timeout.count()); if (res > 0) { + net::packet_t packet {event.type == ENET_EVENT_TYPE_RECEIVE ? event.packet : nullptr}; auto session = get_session(event.peer, event.data); if (!session) { BOOST_LOG(warning) << "Rejected connection from ["sv << platf::from_sockaddr((sockaddr *) &event.peer->address.address) << "]: it's not properly set up"sv; @@ -770,12 +774,16 @@ namespace stream { return; } + if (session->revoked->load(std::memory_order_acquire)) { + session::stop(*session); + enet_peer_disconnect_now(event.peer, 0); + return; + } session->pingTimeout = std::chrono::steady_clock::now() + config::stream.ping_timeout; switch (event.type) { case ENET_EVENT_TYPE_RECEIVE: { - net::packet_t packet {event.packet}; auto message = parse_control_packet(*packet); if (message) { call(message->first, session, message->second, false); @@ -1203,7 +1211,11 @@ namespace stream { }); server->map(packetTypes[IDX_LOSS_STATS], [&](session_t *session, const std::string_view &payload) { - auto stats = (int32_t *) payload.data(); + if (payload.size() < 4 * sizeof(std::int32_t)) { + return; + } + std::array stats; + std::memcpy(stats.data(), payload.data(), sizeof(stats)); auto count = stats[0]; std::chrono::milliseconds t {stats[1]}; @@ -1225,7 +1237,11 @@ namespace stream { }); server->map(packetTypes[IDX_INVALIDATE_REF_FRAMES], [&](session_t *session, const std::string_view &payload) { - auto frames = (std::int64_t *) payload.data(); + if (payload.size() < 2 * sizeof(std::int64_t)) { + return; + } + std::array frames; + std::memcpy(frames.data(), payload.data(), sizeof(frames)); auto firstFrame = frames[0]; auto lastFrame = frames[1]; @@ -1240,8 +1256,12 @@ namespace stream { server->map(packetTypes[IDX_INPUT_DATA], [&](session_t *session, const std::string_view &payload) { BOOST_LOG(debug) << "type [IDX_INPUT_DATA]"sv; - auto tagged_cipher_length = util::endian::big(*(int32_t *) payload.data()); - std::string_view tagged_cipher {payload.data() + sizeof(tagged_cipher_length), (size_t) tagged_cipher_length}; + const auto message = control::parse_legacy_input(payload); + if (!message) { + BOOST_LOG(warning) << "Dropping malformed legacy input envelope"sv; + return; + } + const auto tagged_cipher = *message; std::vector plaintext; @@ -1256,8 +1276,8 @@ namespace stream { return; } - if (tagged_cipher_length >= 16 + iv.size()) { - std::copy(payload.end() - 16, payload.end(), std::begin(iv)); + if (tagged_cipher.size() >= crypto::cipher::tag_size + iv.size()) { + std::copy(tagged_cipher.end() - iv.size(), tagged_cipher.end(), std::begin(iv)); } input::passthrough(session->input, std::move(plaintext)); @@ -1266,18 +1286,13 @@ namespace stream { server->map(packetTypes[IDX_ENCRYPTED], [server](session_t *session, const std::string_view &payload) { BOOST_LOG(verbose) << "type [IDX_ENCRYPTED]"sv; - auto header = (control_encrypted_p) (payload.data() - 2); - - auto length = util::endian::little(header->length); - auto seq = util::endian::little(header->seq); - - if (length < (16 + 4 + 4)) { - BOOST_LOG(warning) << "Control: Runt packet"sv; + const auto message = control::parse_encrypted(payload); + if (!message) { + BOOST_LOG(warning) << "Dropping malformed encrypted control envelope"sv; return; } - - auto tagged_cipher_length = length - 4; - std::string_view tagged_cipher {(char *) header->payload(), (size_t) tagged_cipher_length}; + auto seq = message->sequence; + const auto tagged_cipher = message->tagged_cipher; auto &cipher = session->control.cipher; auto &iv = session->control.incoming_iv; @@ -1311,8 +1326,13 @@ namespace stream { return; } - auto type = *(std::uint16_t *) plaintext.data(); - std::string_view next_payload {(char *) plaintext.data() + 4, plaintext.size() - 4}; + const auto inner_message = control::parse_plaintext({reinterpret_cast(plaintext.data()), plaintext.size()}); + if (!inner_message) { + BOOST_LOG(warning) << "Dropping malformed decrypted control header"sv; + session::stop(*session); + return; + } + const auto [type, next_payload] = *inner_message; if (type == packetTypes[IDX_ENCRYPTED]) { BOOST_LOG(error) << "Bad packet type [IDX_ENCRYPTED] found"sv; @@ -1354,6 +1374,9 @@ namespace stream { auto session = *pos; + if (session->revoked->load(std::memory_order_acquire)) { + session::stop(*session); + } if (now > session->pingTimeout) { auto address = session->control.peer ? platf::from_sockaddr((sockaddr *) &session->control.peer->address.address) : session->control.expected_peer_address; BOOST_LOG(info) << address << ": Ping Timeout"sv; @@ -2395,6 +2418,7 @@ namespace stream { session->shutdown_event = mail->event(mail::shutdown); session->launch_session_id = launch_session.id; session->client_cert = launch_session.client_cert; + session->revoked = launch_session.revoked; session->input_session_id = launch_session.client_cert.empty() ? launch_session.unique_id : launch_session.client_cert; session->config = config; diff --git a/tests/unit/test_confighttp.cpp b/tests/unit/test_confighttp.cpp index 9fe7fb78f2e..459637b60d2 100644 --- a/tests/unit/test_confighttp.cpp +++ b/tests/unit/test_confighttp.cpp @@ -108,6 +108,8 @@ class ConfigHttpTest: public BaseTest { // NOSONAR(cpp:S3656): protected member std::string saved_username; std::string saved_password; std::string saved_salt; + std::string saved_credentials_file; ///< Original credentials path restored after each test. + net::net_e saved_origin_policy; ///< Original remote-address policy. std::string saved_locale; std::vector saved_csrf_allowed_origins; std::filesystem::path test_web_dir; @@ -135,6 +137,9 @@ class ConfigHttpTest: public BaseTest { // NOSONAR(cpp:S3656): protected member saved_username = config::sunshine.username; saved_password = config::sunshine.password; saved_salt = config::sunshine.salt; + saved_credentials_file = config::sunshine.credentials_file; + saved_origin_policy = http::origin_web_ui_allowed; + http::origin_web_ui_allowed = net::LAN; saved_locale = config::sunshine.locale; saved_csrf_allowed_origins = config::sunshine.csrf_allowed_origins; @@ -157,6 +162,8 @@ class ConfigHttpTest: public BaseTest { // NOSONAR(cpp:S3656): protected member // Create test web directory in temp test_web_dir = std::filesystem::temp_directory_path() / "sunshine_test_confighttp"; // NOSONAR(cpp:S5443): safe for tests std::filesystem::create_directories(test_web_dir / "web"); + config::sunshine.credentials_file = (test_web_dir / "credentials.json").string(); + std::filesystem::remove(config::sunshine.credentials_file); confighttp::set_portal_token_path_provider_for_testing([this]() { return test_web_dir / "portal_token"; }); @@ -345,6 +352,7 @@ class ConfigHttpTest: public BaseTest { // NOSONAR(cpp:S3656): protected member server->resource["^/pairing-test$"]["POST"] = confighttp::savePin; server->resource["^/portal-token-reset-test$"]["POST"] = confighttp::resetPortalToken; server->resource["^/api/apps$"]["POST"] = confighttp::saveApp; + server->resource["^/api/password$"]["POST"] = confighttp::savePassword; server->default_resource["GET"] = confighttp::getFallbackPage; // Start server @@ -385,6 +393,8 @@ class ConfigHttpTest: public BaseTest { // NOSONAR(cpp:S3656): protected member config::sunshine.username = saved_username; config::sunshine.password = saved_password; config::sunshine.salt = saved_salt; + config::sunshine.credentials_file = saved_credentials_file; + http::origin_web_ui_allowed = saved_origin_policy; config::sunshine.locale = saved_locale; config::sunshine.csrf_allowed_origins = saved_csrf_allowed_origins; nvhttp::expire_pair_sessions(std::chrono::steady_clock::time_point::max()); @@ -2248,3 +2258,34 @@ TEST_F(ConfigHttpTest, SaveAppOmitsNullOptionalFieldsAndPreservesConfiguredValue EXPECT_FALSE(app.at("prep-cmd").at(0).contains("elevated")); } } + +/** + * @brief Initial credential creation must enforce the address policy without browser headers. + */ +TEST_F(ConfigHttpTest, InitialCredentialsRejectDisallowedSourceBeforeWritingState) { + config::sunshine.username.clear(); + // A deny-all policy reaches the forbidden branch using a portable loopback fixture. + // net_e has a fixed int underlying type, so this sentinel is representable. + http::origin_web_ui_allowed = static_cast(-1); + SimpleWeb::CaseInsensitiveMultimap headers {{"Content-Type", "application/json"}}; + const auto response = client->request("POST", "/api/password", R"({"newUsername":"attacker","newPassword":"password","confirmNewPassword":"password"})", headers); + EXPECT_EQ(response->status_code, "403 Forbidden"); + EXPECT_TRUE(config::sunshine.username.empty()); + EXPECT_FALSE(std::filesystem::exists(config::sunshine.credentials_file)); +} + +/** + * @brief Allowed initial enrollment works, and subsequent changes still require authentication. + */ +TEST_F(ConfigHttpTest, AllowedInitialCredentialsDoNotEnableUnauthenticatedPasswordChanges) { + config::sunshine.username.clear(); + http::origin_web_ui_allowed = net::PC; + SimpleWeb::CaseInsensitiveMultimap headers {{"Content-Type", "application/json"}}; + const auto response = client->request("POST", "/api/password", R"({"newUsername":"new-admin","newPassword":"new-password","confirmNewPassword":"new-password"})", headers); + EXPECT_EQ(response->status_code, "200 OK"); + EXPECT_EQ(config::sunshine.username, "new-admin"); + EXPECT_TRUE(std::filesystem::exists(config::sunshine.credentials_file)); + const auto denied = client->request("POST", "/api/password", R"({"newUsername":"attacker","newPassword":"password","confirmNewPassword":"password"})", headers); + EXPECT_EQ(denied->status_code, "401 Unauthorized"); + EXPECT_EQ(config::sunshine.username, "new-admin"); +} diff --git a/tests/unit/test_control_protocol.cpp b/tests/unit/test_control_protocol.cpp new file mode 100644 index 00000000000..5243f4486ed --- /dev/null +++ b/tests/unit/test_control_protocol.cpp @@ -0,0 +1,141 @@ +/** + * @file tests/unit/test_control_protocol.cpp + * @brief Regression tests for bounds checked control-channel envelopes. + */ + +// test includes +#include "../tests_common.h" + +// standard includes +#include +#include +#include +#include + +// local includes +#include + +/** + * @brief Short encrypted envelopes and inconsistent advertised lengths are rejected. + */ +TEST(ControlEnvelopeTest, RejectsTruncatedEncryptedHeadersAndCiphertext) { + std::string message(26, '\0'); + message[0] = 24; + for (std::size_t size = 0; size < message.size(); ++size) { + SCOPED_TRACE(size); + EXPECT_FALSE(stream::control::parse_encrypted(std::string_view(message).substr(0, size))); + } + message.push_back('\0'); + EXPECT_FALSE(stream::control::parse_encrypted(message)); + message[0] = static_cast(0xff); + message[1] = static_cast(0xff); + EXPECT_FALSE(stream::control::parse_encrypted(message)); + message.resize(26); + message[0] = 23; + message[1] = 0; + EXPECT_FALSE(stream::control::parse_encrypted(message)); +} + +/** + * @brief Valid encrypted envelopes preserve their sequence and exact ciphertext bounds. + */ +TEST(ControlEnvelopeTest, AcceptsEncryptedEnvelopeWithUnalignedStorage) { + std::string storage(27, '\0'); + storage[1] = 24; + storage[3] = 0x12; + storage[4] = 0x34; + storage[5] = 0x56; + storage[6] = 0x78; + const auto message = stream::control::parse_encrypted(std::string_view(storage).substr(1)); + ASSERT_TRUE(message); + EXPECT_EQ(message->sequence, 0x78563412U); + EXPECT_EQ(message->tagged_cipher.data(), storage.data() + 7); + EXPECT_EQ(message->tagged_cipher.size(), 20); +} + +/** + * @brief The largest wire-representable encrypted message remains valid. + */ +TEST(ControlEnvelopeTest, AcceptsMaximumEncryptedWireLength) { + std::string message(65537, '\0'); + message[0] = static_cast(0xff); + message[1] = static_cast(0xff); + const auto parsed = stream::control::parse_encrypted(message); + ASSERT_TRUE(parsed); + EXPECT_EQ(parsed->tagged_cipher.size(), 65531); +} + +/** + * @brief Legacy prefixes must describe the complete available tag and ciphertext. + */ +TEST(ControlEnvelopeTest, RejectsInvalidLegacyLengths) { + std::string message(20, '\0'); + message[3] = 16; + for (std::size_t size = 0; size < message.size(); ++size) { + SCOPED_TRACE(size); + EXPECT_FALSE(stream::control::parse_legacy_input(std::string_view(message).substr(0, size))); + } + for (const auto length : {0U, 15U, 17U, 0x7fffffffU, 0x80000000U, 0xffffffffU}) { + SCOPED_TRACE(length); + for (unsigned index = 0; index < 4; ++index) { + message[index] = static_cast(length >> (24 - 8 * index)); + } + EXPECT_FALSE(stream::control::parse_legacy_input(message)); + } +} + +/** + * @brief A bounded legacy message may contain only a tag or nonempty ciphertext. + */ +TEST(ControlEnvelopeTest, PreservesValidLegacyCiphertext) { + for (const auto size : {16U, 32U, 256U}) { + std::string message(size + 4, '\0'); + message[2] = static_cast(size >> 8); + message[3] = static_cast(size); + const auto parsed = stream::control::parse_legacy_input(message); + ASSERT_TRUE(parsed); + EXPECT_EQ(parsed->size(), size); + EXPECT_EQ(parsed->data(), message.data() + 4); + } +} + +/** + * @brief Truncated decrypted secondary headers are rejected before reading their type. + */ +TEST(ControlEnvelopeTest, RejectsMalformedSecondaryHeaders) { + const std::string message {"\x06\x02\x01\0x", 5}; + for (std::size_t size = 0; size < 4; ++size) { + EXPECT_FALSE(stream::control::parse_plaintext(std::string_view(message).substr(0, size))); + } +} + +/** + * @brief Valid empty and nonempty inner messages retain their type and payload. + */ +TEST(ControlEnvelopeTest, AcceptsValidSecondaryHeaders) { + const std::string empty {"\x02\x03\0\0", 4}; + const auto parsed_empty = stream::control::parse_plaintext(empty); + ASSERT_TRUE(parsed_empty); + EXPECT_EQ(parsed_empty->first, 0x0302); + EXPECT_TRUE(parsed_empty->second.empty()); + const std::string nonempty {"\x06\x02\x01\0x", 5}; + const auto parsed = stream::control::parse_plaintext(nonempty); + ASSERT_TRUE(parsed); + EXPECT_EQ(parsed->first, 0x0206); + EXPECT_EQ(parsed->second, "x"); +} + +/** + * @brief Advisory secondary lengths cannot extend or truncate the authenticated payload. + */ +TEST(ControlEnvelopeTest, BoundsSecondaryPayloadByAuthenticatedBytes) { + std::string message {"\x06\x02\0\0x", 5}; + for (const auto length : {0U, 1U, 2U, 65535U}) { + message[2] = static_cast(length); + message[3] = static_cast(length >> 8); + const auto parsed = stream::control::parse_plaintext(message); + ASSERT_TRUE(parsed); + EXPECT_EQ(parsed->first, 0x0206); + EXPECT_EQ(parsed->second, "x"); + } +} diff --git a/tests/unit/test_crypto.cpp b/tests/unit/test_crypto.cpp index b4398edc98c..21af40b3d79 100644 --- a/tests/unit/test_crypto.cpp +++ b/tests/unit/test_crypto.cpp @@ -7,6 +7,8 @@ #include "../tests_common.h" // standard includes +#include +#include #include #include @@ -101,3 +103,51 @@ TEST(CryptoTest, CertificateChainRequiresExactPairedIdentity) { EXPECT_EQ(certificate_chain.verify(paired_certificate.get()), nullptr); EXPECT_NE(certificate_chain.verify(derived_certificate.get()), nullptr); } + +/** + * @brief GCM rejects incomplete tags and invalid key or IV inputs without plaintext. + */ +TEST(CryptoTest, GcmRejectsMalformedInputsBeforeReadingCiphertext) { + crypto::cipher::gcm_t cipher {crypto::aes_t(16, 0), false}; + crypto::aes_t iv(12, 0); + std::vector plaintext {1, 2, 3}; + for (std::size_t size = 0; size < crypto::cipher::tag_size; ++size) { + const std::string truncated(size, '\0'); + EXPECT_EQ(cipher.decrypt(truncated, plaintext, &iv), -1); + EXPECT_TRUE(plaintext.empty()); + } + const std::string tag(crypto::cipher::tag_size, '\0'); + EXPECT_EQ(cipher.decrypt(tag, plaintext, nullptr), -1); + crypto::aes_t empty_iv; + EXPECT_EQ(cipher.decrypt(tag, plaintext, &empty_iv), -1); + for (const auto size : {0U, 15U, 17U}) { + crypto::cipher::gcm_t invalid_key {crypto::aes_t(size, 0), false}; + EXPECT_EQ(invalid_key.decrypt(tag, plaintext, &iv), -1); + EXPECT_TRUE(plaintext.empty()); + } +} + +/** + * @brief Authentication failure clears output and does not poison later valid messages. + */ +TEST(CryptoTest, GcmAuthenticatesEmptyAndNonemptyMessagesAndRecoversAfterFailure) { + crypto::aes_t key(16, 0x42); + crypto::aes_t iv(12, 0x24); + crypto::cipher::gcm_t sender {key, false}; + crypto::cipher::gcm_t receiver {key, false}; + for (const std::string &message : {std::string {}, std::string {"control message"}}) { + std::vector ciphertext(crypto::cipher::tag_size + message.size() + 16); + ASSERT_EQ(sender.encrypt(message, ciphertext.data(), &iv), message.size()); + ciphertext.resize(crypto::cipher::tag_size + message.size()); + const std::string valid(ciphertext.begin(), ciphertext.end()); + std::vector plaintext; + ASSERT_EQ(receiver.decrypt(valid, plaintext, &iv), 0); + EXPECT_EQ(std::string(plaintext.begin(), plaintext.end()), message); + auto forged = valid; + forged[0] ^= 1; + EXPECT_EQ(receiver.decrypt(forged, plaintext, &iv), -1); + EXPECT_TRUE(plaintext.empty()); + ASSERT_EQ(receiver.decrypt(valid, plaintext, &iv), 0); + EXPECT_EQ(std::string(plaintext.begin(), plaintext.end()), message); + } +} diff --git a/tests/unit/test_nvhttp_client_auth.cpp b/tests/unit/test_nvhttp_client_auth.cpp index 297390793cd..9af0f7effea 100644 --- a/tests/unit/test_nvhttp_client_auth.cpp +++ b/tests/unit/test_nvhttp_client_auth.cpp @@ -17,6 +17,16 @@ // local includes #include #include +#include + +namespace nvhttp { + /** + * @brief Read the production authorization lifetime shared by streams and RTSP. + * @param cert Canonical PEM client identity. + * @return Revocation state for that identity, revoked when it is not authorized. + */ + std::shared_ptr client_revocation_state(std::string_view cert); +} // namespace nvhttp namespace fs = std::filesystem; @@ -200,3 +210,83 @@ TEST_F(ClientAuthorizationTest, ConcurrentStateChangesRemainConsistent) { ASSERT_TRUE(nvhttp::set_client_enabled(uuid, false)); EXPECT_FALSE(nvhttp::test_support::authorize_client_certificate(credentials.x509)); } + +/** + * @brief Removing one client revokes retained sessions while preserving other identities. + */ +TEST_F(ClientAuthorizationTest, UnpairRevokesExistingLaunchStateWithoutRevokingOtherClients) { + const auto first = crypto::gen_creds("revoked client", 2048); + const auto second = crypto::gen_creds("retained client", 2048); + const auto first_id = nvhttp::test_support::add_client("first", first.x509, true); + ASSERT_FALSE(first_id.empty()); + ASSERT_FALSE(nvhttp::test_support::add_client("second", second.x509, true).empty()); + const auto pending_or_active = nvhttp::client_revocation_state(first.x509); + const auto other = nvhttp::client_revocation_state(second.x509); + EXPECT_FALSE(pending_or_active->load()); + ASSERT_TRUE(nvhttp::unpair_client(first_id)); + EXPECT_TRUE(pending_or_active->load()); + EXPECT_TRUE(nvhttp::client_revocation_state(first.x509)->load()); + EXPECT_FALSE(other->load()); + EXPECT_TRUE(nvhttp::test_support::authorize_client_certificate(second.x509)); +} + +/** + * @brief Re-enabling a client creates a new lifetime instead of resurrecting revoked sessions. + */ +TEST_F(ClientAuthorizationTest, ReenableDoesNotRestoreOldLaunchAuthorization) { + const auto credentials = crypto::gen_creds("reenabled client", 2048); + const auto uuid = nvhttp::test_support::add_client("client", credentials.x509, true); + ASSERT_FALSE(uuid.empty()); + const auto old = nvhttp::client_revocation_state(credentials.x509); + ASSERT_TRUE(nvhttp::set_client_enabled(uuid, false)); + EXPECT_TRUE(old->load()); + EXPECT_TRUE(nvhttp::client_revocation_state(credentials.x509)->load()); + ASSERT_TRUE(nvhttp::set_client_enabled(uuid, true)); + EXPECT_TRUE(old->load()); + EXPECT_FALSE(nvhttp::client_revocation_state(credentials.x509)->load()); + EXPECT_TRUE(nvhttp::client_revocation_state("unknown certificate")->load()); +} + +/** + * @brief Re-pairing and removing all clients invalidate previously retained launch state. + */ +TEST_F(ClientAuthorizationTest, RePairAndUnpairAllInvalidateRetainedLaunches) { + const auto credentials = crypto::gen_creds("repaired client", 2048); + ASSERT_FALSE(nvhttp::test_support::add_client("original", credentials.x509, true).empty()); + const auto old = nvhttp::client_revocation_state(credentials.x509); + ASSERT_FALSE(nvhttp::test_support::add_client("replacement", credentials.x509, true).empty()); + EXPECT_TRUE(old->load()); + const auto replacement = nvhttp::client_revocation_state(credentials.x509); + EXPECT_FALSE(replacement->load()); + nvhttp::erase_all_clients(); + EXPECT_TRUE(replacement->load()); +} + +/** + * @brief Teardown from an earlier disable cannot invalidate a subsequent authorized launch. + */ +TEST_F(ClientAuthorizationTest, DelayedTeardownPreservesReenabledPendingLaunch) { + const auto credentials = crypto::gen_creds("reenabled pending client", 2048); + const auto uuid = nvhttp::test_support::add_client("client", credentials.x509, true); + ASSERT_FALSE(uuid.empty()); + const auto old = nvhttp::client_revocation_state(credentials.x509); + ASSERT_TRUE(nvhttp::set_client_enabled(uuid, false)); + ASSERT_TRUE(nvhttp::set_client_enabled(uuid, true)); + + auto pending = std::make_shared(); + pending->id = 42; + pending->client_cert = credentials.x509; + pending->revoked = nvhttp::client_revocation_state(credentials.x509); + pending->rtsp_cipher.emplace(crypto::aes_t(16, 0), false); + rtsp_stream::launch_session_raise(pending); + const auto cleanup = util::fail_guard([&]() { + rtsp_stream::launch_session_clear(pending->id); + }); + + // The disable's teardown is delayed until after the new enabled lifetime is in use. + rtsp_stream::terminate_sessions_by_cert(credentials.x509); + EXPECT_TRUE(old->load()); + EXPECT_FALSE(pending->revoked->load()); + EXPECT_TRUE(rtsp_stream::accepts_rtsp(*pending)); + EXPECT_EQ(nvhttp::client_revocation_state(credentials.x509), pending->revoked); +} diff --git a/tests/unit/test_nvhttp_https.cpp b/tests/unit/test_nvhttp_https.cpp index 3bb94e54ad6..9281d31dcad 100644 --- a/tests/unit/test_nvhttp_https.cpp +++ b/tests/unit/test_nvhttp_https.cpp @@ -7,12 +7,20 @@ #include "../tests_common.h" // standard includes +#include #include #include #include +#include #include +#include +#include +#include #include +// lib includes +#include + // local includes #include #include @@ -31,14 +39,15 @@ namespace { void SetUp() override { BaseTest::SetUp(); const auto credentials = crypto::gen_creds("Sunshine HTTPS lifetime test", 2048); + certificate_pem = credentials.x509; certificate_file = std::filesystem::path {SUNSHINE_TEST_BIN_DIR} / "https_lifetime_cert.pem"; private_key_file = std::filesystem::path {SUNSHINE_TEST_BIN_DIR} / "https_lifetime_key.pem"; std::ofstream {certificate_file} << credentials.x509; std::ofstream {private_key_file} << credentials.pkey; - server = nvhttp::test_support::make_https_server(certificate_file.string(), private_key_file.string(), handler_scope); + server = nvhttp::test_support::make_https_server(certificate_file.string(), private_key_file.string(), handler_scope, verifier()); server->io_service = std::make_shared(); - server->config.address = "127.0.0.1"; + server->config.address = listen_address(); server->config.port = 0; server->start([this](unsigned short assigned_port) { port = assigned_port; @@ -47,6 +56,22 @@ namespace { ASSERT_NE(port, 0); } + /** + * @brief Select the listener address used by a network fixture. + * @return IPv4 loopback address for lifetime tests. + */ + virtual std::string listen_address() { + return "127.0.0.1"; + } + + /** + * @brief Supply optional client authorization for a production HTTPS fixture. + * @return Empty verifier for lifetime tests. + */ + virtual std::function verifier() { + return {}; + } + /** * @brief Drain canceled callbacks and remove the generated credentials. */ @@ -93,10 +118,171 @@ namespace { std::future stopped_future; ///< Signals that all callback guards have been released. unsigned short port = 0; ///< Assigned loopback port. int error_callbacks = 0; ///< Number of errors delivered while testing a handler. + std::string certificate_pem; ///< Canonical certificate presented by the first test client. std::filesystem::path certificate_file; ///< Generated server certificate. std::filesystem::path private_key_file; ///< Generated server private key. }; + /** + * @brief Exercise request authorization on an already-open TLS connection. + */ + struct HttpsRevocationTest: HttpsHandlerLifetimeTest { + /** + * @brief Return the current authorization decision for the presented certificate. + * @return Verifier shared with the fixture's authorization state. + */ + std::function verifier() override { + return [this](SSL *ssl) { + ++verification_count; +#if OPENSSL_VERSION_MAJOR >= 3 + crypto::x509_t certificate {SSL_get1_peer_certificate(ssl)}; +#else + crypto::x509_t certificate {SSL_get_peer_certificate(ssl)}; +#endif + std::lock_guard lock {identity_mutex}; + last_certificate = certificate ? crypto::pem(certificate) : std::string {}; + return authorized.load() && !last_certificate.empty() && last_certificate != rejected_certificate ? 1 : 0; + }; + } + + /** + * @brief Accept connections addressed to different local loopback interfaces. + * @return IPv4 wildcard listener address. + */ + std::string listen_address() override { + return "0.0.0.0"; + } + + /** + * @brief Send one keep-alive request and consume its complete response. + * @param client Connected TLS client. + * @return HTTP response status line. + */ + static std::string request(boost::asio::ssl::stream &client) { + const std::string wire = "GET /authorization-test HTTP/1.1\r\nHost: localhost\r\n\r\n"; + boost::asio::write(client, boost::asio::buffer(wire)); + boost::asio::streambuf buffer; + boost::asio::read_until(client, buffer, "\r\n\r\n"); + std::istream headers {&buffer}; + std::string status; + std::getline(headers, status); + std::string line; + std::size_t content_length = 0; + while (std::getline(headers, line) && line != "\r") { + if (line.starts_with("Content-Length: ")) { + content_length = std::stoul(line.substr(16)); + } + } + if (buffer.size() < content_length) { + boost::asio::read(client, buffer, boost::asio::transfer_exactly(content_length - buffer.size())); + } + return status; + } + + /** + * @brief Run the production HTTPS listener with a protected test route. + */ + void SetUp() override { + HttpsHandlerLifetimeTest::SetUp(); + // after_bind wraps handlers, so use the wrapped default route configured by the factory. + io_thread = std::jthread([this]() { + server->io_service->run(); + }); + } + + /** + * @brief Stop the IO thread before draining callbacks in the parent fixture. + */ + void TearDown() override { + server->stop(); + if (io_thread.joinable()) { + io_thread.join(); + } + HttpsHandlerLifetimeTest::TearDown(); + } + + std::mutex identity_mutex; ///< Protects certificate observations across fixture and IO threads. + std::string last_certificate; ///< Identity checked by the most recent production callback. + std::string rejected_certificate; ///< Identity revoked while a connection remains open. + std::atomic_bool authorized {true}; ///< Simulated paired-client authorization. + std::atomic_int verification_count {0}; ///< Verifications across handshake and requests. + std::jthread io_thread; ///< Thread dispatching the real HTTPS callbacks. + }; + + /** + * @brief Revocation applies to keep-alive requests even after a successful handshake. + */ + TEST_F(HttpsRevocationTest, RechecksAuthorizationBeforeEveryKeepAliveRequest) { + boost::asio::io_context client_io; + boost::asio::ssl::context tls {boost::asio::ssl::context::tls_client}; + tls.set_verify_mode(boost::asio::ssl::verify_none); + tls.use_certificate_chain_file(certificate_file.string()); + tls.use_private_key_file(private_key_file.string(), boost::asio::ssl::context::pem); + boost::asio::ssl::stream client {client_io, tls}; + client.lowest_layer().connect({boost::asio::ip::address_v4::loopback(), port}); + client.handshake(boost::asio::ssl::stream_base::client); + + EXPECT_NE(request(client).find("200 OK"), std::string::npos); + authorized = false; + EXPECT_NE(request(client).find("401 Unauthorized"), std::string::npos); + EXPECT_GE(verification_count.load(), 3); + } + + /** + * @brief Connections sharing a remote endpoint retain distinct local-interface identities. + */ + TEST_F(HttpsRevocationTest, UsesBothEndpointsWhenReauthorizingKeepAliveClients) { + boost::asio::io_context io; + boost::asio::ssl::context first_tls {boost::asio::ssl::context::tls_client}; + first_tls.set_verify_mode(boost::asio::ssl::verify_none); + first_tls.use_certificate_chain_file(certificate_file.string()); + first_tls.use_private_key_file(private_key_file.string(), boost::asio::ssl::context::pem); + boost::asio::ssl::stream first {io, first_tls}; + first.lowest_layer().open(tcp::v4()); + first.lowest_layer().set_option(tcp::socket::reuse_address(true)); + first.lowest_layer().bind({boost::asio::ip::address_v4::loopback(), 0}); + first.lowest_layer().connect({boost::asio::ip::make_address_v4("127.0.0.1"), port}); + first.handshake(boost::asio::ssl::stream_base::client); + + const auto second_credentials = crypto::gen_creds("Sunshine second client", 2048); + const auto second_cert = certificate_file.string() + ".second"; + const auto second_key = private_key_file.string() + ".second"; + const auto cleanup = util::fail_guard([&]() { + std::error_code ec; + std::filesystem::remove(second_cert, ec); + std::filesystem::remove(second_key, ec); + }); + std::ofstream {second_cert} << second_credentials.x509; + std::ofstream {second_key} << second_credentials.pkey; + boost::asio::ssl::context second_tls {boost::asio::ssl::context::tls_client}; + second_tls.set_verify_mode(boost::asio::ssl::verify_none); + second_tls.use_certificate_chain_file(second_cert); + second_tls.use_private_key_file(second_key, boost::asio::ssl::context::pem); + boost::asio::ssl::stream second {io, second_tls}; + second.lowest_layer().open(tcp::v4()); + second.lowest_layer().set_option(tcp::socket::reuse_address(true)); + boost::system::error_code bind_error; + second.lowest_layer().bind(first.lowest_layer().local_endpoint(), bind_error); + if (bind_error) { + GTEST_SKIP() << "Platform cannot reuse a source endpoint across destinations: " << bind_error.message(); + } + second.lowest_layer().connect({boost::asio::ip::make_address_v4("127.0.0.2"), port}); + second.handshake(boost::asio::ssl::stream_base::client); + + EXPECT_NE(request(first).find("200 OK"), std::string::npos); + { + std::lock_guard lock {identity_mutex}; + EXPECT_EQ(last_certificate, certificate_pem); + rejected_certificate = certificate_pem; + } + EXPECT_NE(request(first).find("401 Unauthorized"), std::string::npos); + EXPECT_NE(request(second).find("200 OK"), std::string::npos); + { + std::lock_guard lock {identity_mutex}; + EXPECT_EQ(last_certificate, second_credentials.x509); + } + } + /** * @brief Canceling a pending accept holds the server guard through its error callback. */ diff --git a/tests/unit/test_rtsp.cpp b/tests/unit/test_rtsp.cpp index fa610b4a4c1..7a767983f9b 100644 --- a/tests/unit/test_rtsp.cpp +++ b/tests/unit/test_rtsp.cpp @@ -61,6 +61,15 @@ TEST(RtspHeaderTest, ConstAccessorsPreserveTheSerializedHeader) { namespace rtsp_stream { class rtsp_server_t; + namespace test_support { + /** + * @brief Attempt production stream admission with an unauthorized launch. + * @param launch Plaintext or revoked launch to reject before starting workers. + * @return Production stream startup result. + */ + int reject_stream_for_testing(const launch_session_t &launch); + } // namespace test_support + /** * @brief Release a parsed RTSP message and its allocation. * @param message Message to release. @@ -185,3 +194,34 @@ TEST(RtspDescribeTest, SurroundParamsCompensateClientRotationForEveryStreamConfi EXPECT_EQ(advertised[x], expected[x].second) << "stream config " << expected[x].first; } } + +/** + * @brief Only encrypted, unrevoked launches can accept RTSP messages. + */ +TEST(RtspAuthorizationTest, RejectsPlaintextAndRevokedLaunches) { + rtsp_stream::launch_session_t session {}; + EXPECT_FALSE(rtsp_stream::accepts_rtsp(session)); + session.rtsp_cipher.emplace(crypto::aes_t(16, 0), false); + EXPECT_TRUE(rtsp_stream::accepts_rtsp(session)); + const auto retained_authorization = session.revoked; + retained_authorization->store(true, std::memory_order_release); + EXPECT_FALSE(rtsp_stream::accepts_rtsp(session)); +} + +/** + * @brief Plaintext launch state cannot reach stream startup. + */ +TEST(RtspAuthorizationTest, RejectsPlaintextAtStreamAdmission) { + rtsp_stream::launch_session_t launch {}; + EXPECT_EQ(rtsp_stream::test_support::reject_stream_for_testing(launch), -1); +} + +/** + * @brief An accepted socket cannot restart a stream after its client is revoked. + */ +TEST(RtspAuthorizationTest, RejectsRevokedLaunchAtStreamAdmission) { + rtsp_stream::launch_session_t launch {}; + launch.rtsp_cipher.emplace(crypto::aes_t(16, 0), false); + launch.revoked->store(true, std::memory_order_release); + EXPECT_EQ(rtsp_stream::test_support::reject_stream_for_testing(launch), -1); +} From 73c18713a3e8624b13e45ec7e389f65ee5a4be13 Mon Sep 17 00:00:00 2001 From: Finn <117590961+Peaks2000@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:04:48 +0000 Subject: [PATCH 2/3] fix: resolve security PR quality gate findings --- src/control_protocol.h | 3 +-- src/crypto.cpp | 6 ++++-- src/nvhttp.cpp | 21 +++++++++++---------- src/stream.cpp | 7 +++---- tests/unit/test_control_protocol.cpp | 8 ++++---- tests/unit/test_crypto.cpp | 2 +- tests/unit/test_nvhttp_client_auth.cpp | 14 +++++++++++--- tests/unit/test_nvhttp_https.cpp | 10 ++++++++-- 8 files changed, 43 insertions(+), 28 deletions(-) diff --git a/src/control_protocol.h b/src/control_protocol.h index 8a765694b3b..4e3fe5f398d 100644 --- a/src/control_protocol.h +++ b/src/control_protocol.h @@ -55,8 +55,7 @@ namespace stream::control { if (payload.size() < header_size) { return std::nullopt; } - const auto length = boost::endian::endian_load(reinterpret_cast(payload.data())); - if (length < TAG_SIZE || length != payload.size() - header_size) { + if (const auto length = boost::endian::endian_load(reinterpret_cast(payload.data())); length < TAG_SIZE || length != payload.size() - header_size) { return std::nullopt; } return payload.substr(header_size); diff --git a/src/crypto.cpp b/src/crypto.cpp index 7b9078c05a9..9bd386f57b1 100644 --- a/src/crypto.cpp +++ b/src/crypto.cpp @@ -161,13 +161,15 @@ namespace crypto { } const auto cipher = tagged_cipher.substr(tag_size); - const auto tag = tagged_cipher.substr(0, tag_size); + // OpenSSL accepts a mutable tag buffer, so retain a writable copy. + std::array tag; + std::copy_n(tagged_cipher.begin(), tag.size(), tag.begin()); // Reserve a writable output byte even for an authenticated empty message. plaintext.resize(std::max(16, round_to_pkcs7_padded(cipher.size()))); int final_outlen; int update_outlen; - if (EVP_DecryptUpdate(decrypt_ctx.get(), plaintext.data(), &update_outlen, (const std::uint8_t *) cipher.data(), (int) cipher.size()) != 1 || EVP_CIPHER_CTX_ctrl(decrypt_ctx.get(), EVP_CTRL_GCM_SET_TAG, (int) tag.size(), const_cast(tag.data())) != 1 || EVP_DecryptFinal_ex(decrypt_ctx.get(), plaintext.data() + update_outlen, &final_outlen) != 1) { + if (EVP_DecryptUpdate(decrypt_ctx.get(), plaintext.data(), &update_outlen, (const std::uint8_t *) cipher.data(), (int) cipher.size()) != 1 || EVP_CIPHER_CTX_ctrl(decrypt_ctx.get(), EVP_CTRL_GCM_SET_TAG, (int) tag.size(), tag.data()) != 1 || EVP_DecryptFinal_ex(decrypt_ctx.get(), plaintext.data() + update_outlen, &final_outlen) != 1) { plaintext.clear(); return -1; } diff --git a/src/nvhttp.cpp b/src/nvhttp.cpp index 2e0f2ae081d..36e4f6842f9 100644 --- a/src/nvhttp.cpp +++ b/src/nvhttp.cpp @@ -1912,18 +1912,19 @@ namespace nvhttp { bool set_client_enabled(const std::string_view uuid, bool enabled) { std::lock_guard lock {client_auth_mutex()}; for (auto &named_cert : client_root.named_devices) { - if (named_cert.uuid == uuid) { - if (named_cert.enabled != enabled) { - named_cert.revoked->store(true, std::memory_order_release); - if (enabled) { - named_cert.revoked = std::make_shared(false); - } + if (named_cert.uuid != uuid) { + continue; + } + if (named_cert.enabled != enabled) { + named_cert.revoked->store(true, std::memory_order_release); + if (enabled) { + named_cert.revoked = std::make_shared(false); } - named_cert.enabled = enabled; - rebuild_client_cert_chain(); - save_state(); - return true; } + named_cert.enabled = enabled; + rebuild_client_cert_chain(); + save_state(); + return true; } return false; } diff --git a/src/stream.cpp b/src/stream.cpp index cd4a24d997f..c360a1d011e 100644 --- a/src/stream.cpp +++ b/src/stream.cpp @@ -1253,7 +1253,7 @@ namespace stream { session->video.invalidate_ref_frames_events->raise(std::make_pair(firstFrame, lastFrame)); }); - server->map(packetTypes[IDX_INPUT_DATA], [&](session_t *session, const std::string_view &payload) { + server->map(packetTypes[IDX_INPUT_DATA], [](session_t *session, const std::string_view &payload) { BOOST_LOG(debug) << "type [IDX_INPUT_DATA]"sv; const auto message = control::parse_legacy_input(payload); @@ -1265,9 +1265,8 @@ namespace stream { std::vector plaintext; - auto &cipher = session->control.cipher; auto &iv = session->control.legacy_input_enc_iv; - if (cipher.decrypt(tagged_cipher, plaintext, &iv)) { + if (session->control.cipher.decrypt(tagged_cipher, plaintext, &iv)) { // something went wrong :( BOOST_LOG(error) << "Failed to verify tag"sv; @@ -1332,7 +1331,7 @@ namespace stream { session::stop(*session); return; } - const auto [type, next_payload] = *inner_message; + const auto &[type, next_payload] = *inner_message; if (type == packetTypes[IDX_ENCRYPTED]) { BOOST_LOG(error) << "Bad packet type [IDX_ENCRYPTED] found"sv; diff --git a/tests/unit/test_control_protocol.cpp b/tests/unit/test_control_protocol.cpp index 5243f4486ed..0d9b8f37955 100644 --- a/tests/unit/test_control_protocol.cpp +++ b/tests/unit/test_control_protocol.cpp @@ -103,7 +103,7 @@ TEST(ControlEnvelopeTest, PreservesValidLegacyCiphertext) { * @brief Truncated decrypted secondary headers are rejected before reading their type. */ TEST(ControlEnvelopeTest, RejectsMalformedSecondaryHeaders) { - const std::string message {"\x06\x02\x01\0x", 5}; + const std::string message {"\x{06}\x{02}\x{01}\0x", 5}; for (std::size_t size = 0; size < 4; ++size) { EXPECT_FALSE(stream::control::parse_plaintext(std::string_view(message).substr(0, size))); } @@ -113,12 +113,12 @@ TEST(ControlEnvelopeTest, RejectsMalformedSecondaryHeaders) { * @brief Valid empty and nonempty inner messages retain their type and payload. */ TEST(ControlEnvelopeTest, AcceptsValidSecondaryHeaders) { - const std::string empty {"\x02\x03\0\0", 4}; + const std::string empty {"\x{02}\x{03}\0\0", 4}; const auto parsed_empty = stream::control::parse_plaintext(empty); ASSERT_TRUE(parsed_empty); EXPECT_EQ(parsed_empty->first, 0x0302); EXPECT_TRUE(parsed_empty->second.empty()); - const std::string nonempty {"\x06\x02\x01\0x", 5}; + const std::string nonempty {"\x{06}\x{02}\x{01}\0x", 5}; const auto parsed = stream::control::parse_plaintext(nonempty); ASSERT_TRUE(parsed); EXPECT_EQ(parsed->first, 0x0206); @@ -129,7 +129,7 @@ TEST(ControlEnvelopeTest, AcceptsValidSecondaryHeaders) { * @brief Advisory secondary lengths cannot extend or truncate the authenticated payload. */ TEST(ControlEnvelopeTest, BoundsSecondaryPayloadByAuthenticatedBytes) { - std::string message {"\x06\x02\0\0x", 5}; + std::string message {"\x{06}\x{02}\0\0x", 5}; for (const auto length : {0U, 1U, 2U, 65535U}) { message[2] = static_cast(length); message[3] = static_cast(length >> 8); diff --git a/tests/unit/test_crypto.cpp b/tests/unit/test_crypto.cpp index 21af40b3d79..d002f609fcf 100644 --- a/tests/unit/test_crypto.cpp +++ b/tests/unit/test_crypto.cpp @@ -144,7 +144,7 @@ TEST(CryptoTest, GcmAuthenticatesEmptyAndNonemptyMessagesAndRecoversAfterFailure ASSERT_EQ(receiver.decrypt(valid, plaintext, &iv), 0); EXPECT_EQ(std::string(plaintext.begin(), plaintext.end()), message); auto forged = valid; - forged[0] ^= 1; + forged[0] = valid[0] == 'x' ? 'y' : 'x'; EXPECT_EQ(receiver.decrypt(forged, plaintext, &iv), -1); EXPECT_TRUE(plaintext.empty()); ASSERT_EQ(receiver.decrypt(valid, plaintext, &iv), 0); diff --git a/tests/unit/test_nvhttp_client_auth.cpp b/tests/unit/test_nvhttp_client_auth.cpp index 9af0f7effea..759a7e13a45 100644 --- a/tests/unit/test_nvhttp_client_auth.cpp +++ b/tests/unit/test_nvhttp_client_auth.cpp @@ -231,19 +231,27 @@ TEST_F(ClientAuthorizationTest, UnpairRevokesExistingLaunchStateWithoutRevokingO } /** - * @brief Re-enabling a client creates a new lifetime instead of resurrecting revoked sessions. + * @brief Re-enable creates a new authorization lifetime, while repeated updates preserve it. */ TEST_F(ClientAuthorizationTest, ReenableDoesNotRestoreOldLaunchAuthorization) { const auto credentials = crypto::gen_creds("reenabled client", 2048); const auto uuid = nvhttp::test_support::add_client("client", credentials.x509, true); ASSERT_FALSE(uuid.empty()); const auto old = nvhttp::client_revocation_state(credentials.x509); + EXPECT_FALSE(nvhttp::set_client_enabled("unknown client", false)); + ASSERT_TRUE(nvhttp::set_client_enabled(uuid, true)); + EXPECT_EQ(nvhttp::client_revocation_state(credentials.x509), old); + EXPECT_FALSE(old->load()); ASSERT_TRUE(nvhttp::set_client_enabled(uuid, false)); EXPECT_TRUE(old->load()); EXPECT_TRUE(nvhttp::client_revocation_state(credentials.x509)->load()); ASSERT_TRUE(nvhttp::set_client_enabled(uuid, true)); EXPECT_TRUE(old->load()); - EXPECT_FALSE(nvhttp::client_revocation_state(credentials.x509)->load()); + const auto current = nvhttp::client_revocation_state(credentials.x509); + EXPECT_FALSE(current->load()); + ASSERT_TRUE(nvhttp::set_client_enabled(uuid, true)); + EXPECT_EQ(nvhttp::client_revocation_state(credentials.x509), current); + EXPECT_FALSE(current->load()); EXPECT_TRUE(nvhttp::client_revocation_state("unknown certificate")->load()); } @@ -279,7 +287,7 @@ TEST_F(ClientAuthorizationTest, DelayedTeardownPreservesReenabledPendingLaunch) pending->revoked = nvhttp::client_revocation_state(credentials.x509); pending->rtsp_cipher.emplace(crypto::aes_t(16, 0), false); rtsp_stream::launch_session_raise(pending); - const auto cleanup = util::fail_guard([&]() { + const auto cleanup = util::fail_guard([pending]() { rtsp_stream::launch_session_clear(pending->id); }); diff --git a/tests/unit/test_nvhttp_https.cpp b/tests/unit/test_nvhttp_https.cpp index 9281d31dcad..85dcb733cc2 100644 --- a/tests/unit/test_nvhttp_https.cpp +++ b/tests/unit/test_nvhttp_https.cpp @@ -132,7 +132,7 @@ namespace { * @return Verifier shared with the fixture's authorization state. */ std::function verifier() override { - return [this](SSL *ssl) { + return [this](const SSL *ssl) { ++verification_count; #if OPENSSL_VERSION_MAJOR >= 3 crypto::x509_t certificate {SSL_get1_peer_certificate(ssl)}; @@ -247,7 +247,7 @@ namespace { const auto second_credentials = crypto::gen_creds("Sunshine second client", 2048); const auto second_cert = certificate_file.string() + ".second"; const auto second_key = private_key_file.string() + ".second"; - const auto cleanup = util::fail_guard([&]() { + const auto cleanup = util::fail_guard([&second_cert, &second_key]() { std::error_code ec; std::filesystem::remove(second_cert, ec); std::filesystem::remove(second_key, ec); @@ -269,6 +269,12 @@ namespace { second.lowest_layer().connect({boost::asio::ip::make_address_v4("127.0.0.2"), port}); second.handshake(boost::asio::ssl::stream_base::client); + // Finish the server-side handshake callback before observing request-local identity. + EXPECT_NE(request(second).find("200 OK"), std::string::npos); + { + std::lock_guard lock {identity_mutex}; + EXPECT_EQ(last_certificate, second_credentials.x509); + } EXPECT_NE(request(first).find("200 OK"), std::string::npos); { std::lock_guard lock {identity_mutex}; From 679b2c4051b5df843537b0c42b382426eba44bf6 Mon Sep 17 00:00:00 2001 From: Finn <117590961+Peaks2000@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:13:22 +0000 Subject: [PATCH 3/3] docs: avoid duplicate API parameter documentation --- src/confighttp.h | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/confighttp.h b/src/confighttp.h index 950c5622114..c1bfcf8beab 100644 --- a/src/confighttp.h +++ b/src/confighttp.h @@ -40,18 +40,7 @@ namespace confighttp { void send_response(const resp_https_t &response, const nlohmann::json &output_tree); void send_unauthorized(const resp_https_t &response, const req_https_t &request); void send_redirect(const resp_https_t &response, const req_https_t &request, const char *path); - /** - * @brief Enforce the Web UI remote-address policy independently of credentials. - * @param response HTTP response used to report a forbidden address. - * @param request Request whose remote address is checked. - * @return True when the source address is allowed. - */ bool check_access(const resp_https_t &response, const req_https_t &request); - /** - * @brief Create initial credentials or change existing credentials after access checks. - * @param response HTTP response object to populate. - * @param request JSON credential update request. - */ void savePassword(const resp_https_t &response, const req_https_t &request); bool authenticate(const resp_https_t &response, const req_https_t &request); void not_found(const resp_https_t &response, const std::string &error_message = "Not Found");
Description