diff --git a/src/connection.cpp b/src/connection.cpp index dfe89fa7..256595ef 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -260,13 +260,13 @@ void SendspinConnection::handle_noise_handshake_text(std::string_view text) { HandshakeFrameResult result = this->noise_handshake_->on_text_frame(text, send_fn, outcome); if (result == HandshakeFrameResult::ABORT) { - const std::string& server_error = this->noise_handshake_->server_error_reason(); - if (server_error.empty()) { + const std::optional server_error = + this->noise_handshake_->server_error_reason(); + if (!server_error.has_value()) { SS_LOGW(TAG, "Noise handshake aborted; closing connection"); } else { - SS_LOGW(TAG, - "Noise handshake aborted by server/error (reason='%s'); closing connection", - server_error.c_str()); + SS_LOGW(TAG, "Noise handshake aborted by server/error (reason=%s); closing connection", + to_cstr(*server_error)); } // connection.md "Failure Handling": a handshake-phase failure closes the WebSocket // without sending any application-level message. @@ -288,8 +288,8 @@ void SendspinConnection::handle_noise_handshake_text(std::string_view text) { this->noise_transport_.activate(std::move(outcome->session)); this->noise_handshake_.reset(); this->noise_handshake_complete_ = true; - SS_LOGI(TAG, "Noise transport active (server_id=%s, psk_category=%d)", - this->server_id_.c_str(), static_cast(this->get_psk_category())); + SS_LOGI(TAG, "Noise transport active (server_id=%s, psk_category=%s)", + this->server_id_.c_str(), to_cstr(this->get_psk_category())); } // NEED_MORE, or COMPLETE handled above: nothing else to do until the next frame. @@ -370,8 +370,8 @@ bool SendspinConnection::handle_noise_rehandshake(std::span msg1_bytes) // untouched; the server's first message under the new keys is server/activate, which // first_activate_received_ (cleared above) now waits on. SS_LOGI(TAG, - "Noise re-handshake complete: server_id=%s psk_category=%d; awaiting server/activate", - this->server_id_.c_str(), static_cast(this->get_psk_category())); + "Noise re-handshake complete: server_id=%s psk_category=%s; awaiting server/activate", + this->server_id_.c_str(), to_cstr(this->get_psk_category())); return true; } diff --git a/src/connection_manager.cpp b/src/connection_manager.cpp index f844a897..b0588010 100644 --- a/src/connection_manager.cpp +++ b/src/connection_manager.cpp @@ -661,8 +661,8 @@ void ConnectionManager::on_server_activate(SendspinConnection* conn, if (!activation_admissible) { const SendspinGoodbyeReason reject_reason = inadmissible_reject_reason( conn->get_psk_category(), msg.activities, has_roles, unpaired_access); - SS_LOGW(TAG, "server/activate inadmissible (psk_category=%d): closing with %s", - static_cast(conn->get_psk_category()), + SS_LOGW(TAG, "server/activate inadmissible (psk_category=%s): closing with %s", + to_cstr(conn->get_psk_category()), reject_reason == SendspinGoodbyeReason::PAIRING_REQUIRED ? "pairing_required" : "unauthorized"); this->drop_connection(conn, reject_reason); diff --git a/src/crypto/constants.h b/src/crypto/constants.h index acd3a5c6..555c534d 100644 --- a/src/crypto/constants.h +++ b/src/crypto/constants.h @@ -72,18 +72,23 @@ static constexpr size_t MAX_TRANSPORT_PLAINTEXT = 65535 - 16; // = 65519 /// @brief Largest Noise message 1 payload the client decrypts: the spec sets no bound, but the /// payload it defines is small (psk_id JSON, ~60 bytes). 512 leaves room for future fields -/// without paying for a buffer sized like transport-mode traffic. noise-c bounds-checks against -/// this capacity and returns an error rather than overflowing it if a peer's payload does not fit -/// (verified against noise_handshakestate_read_message()'s payload->max_size check), so a longer -/// payload fails the handshake rather than corrupting memory. MAX_SERVER_INIT_BYTES bounds the +/// without paying for a buffer sized like transport-mode traffic. MAX_HANDSHAKE_MSG1_BYTES refuses +/// a message 1 that could carry a longer payload, and noise-c also bounds-checks against this +/// capacity (noise_handshakestate_read_message()'s payload->max_size check), so a longer payload +/// fails the handshake rather than corrupting memory. MAX_SERVER_INIT_BYTES bounds the /// handshake's other peer input. static constexpr size_t MAX_HANDSHAKE_MESSAGE_BYTES = 512; +/// @brief Largest Noise message 1 the client decodes: KKpsk2's "e, es, ss" sends the 32-byte +/// ephemeral key, then a payload of up to MAX_HANDSHAKE_MESSAGE_BYTES and its 16-byte AEAD tag. +/// A longer one could not be read, so it is refused before its buffer is allocated. +static constexpr size_t MAX_HANDSHAKE_MSG1_BYTES = 32 + MAX_HANDSHAKE_MESSAGE_BYTES + 16; + /// @brief Largest server/init the handshake keeps for its prologue: about five times the minimal /// frame, a version and a PEER_ID_SIZE server_id in about 104 bytes (messaging.md "server/init"). /// It bounds the prologue buffer each handshake holds; the cost is that a later revision's /// optional fields, which messaging.md "Forward compatibility" has the client ignore, must keep -/// the frame under it. MAX_HANDSHAKE_MESSAGE_BYTES bounds the handshake's other peer input. +/// the frame under it. MAX_HANDSHAKE_MSG1_BYTES bounds the handshake's other peer input. static constexpr size_t MAX_SERVER_INIT_BYTES = 512; /// @brief Per-connection reassembly buffer cap: 1 MiB. diff --git a/src/crypto/keys.cpp b/src/crypto/keys.cpp index c103180d..2906880a 100644 --- a/src/crypto/keys.cpp +++ b/src/crypto/keys.cpp @@ -79,7 +79,7 @@ std::optional> public_key_from_peer_id( return std::nullopt; } std::array key{}; - if (b64url_decode_into(peer_id, key.data(), key.size()) != X25519_KEY_SIZE) { + if (!b64url_decode_exact(peer_id, key)) { return std::nullopt; } // The last character carries 2 unused bits; a nonzero pair decodes to the same key. diff --git a/src/noise_handshake.cpp b/src/noise_handshake.cpp index 56cee621..9807343e 100644 --- a/src/noise_handshake.cpp +++ b/src/noise_handshake.cpp @@ -18,6 +18,7 @@ #include "crypto/keys.h" #include "noise_session.h" #include "platform/base64.h" +#include "platform/crypto.h" #include "platform/json_arena.h" #include "platform/logging.h" #include "platform/memory.h" @@ -31,6 +32,14 @@ static const char* const TAG = "sendspin.noise_handshake"; namespace sendspin { +/// Most bytes of unauthenticated peer text (a frame's type, a server/error reason) one log line +/// prints. The longest such value messaging.md defines is 19 bytes. +static constexpr size_t PEER_TEXT_LOG_BYTES = 32; + +static_assert(MAX_HANDSHAKE_MSG1_BYTES == + X25519_KEY_SIZE + MAX_HANDSHAKE_MESSAGE_BYTES + AEAD_TAG_SIZE, + "message 1 is the ephemeral key, the payload and its tag"); + // ============================================================================ // JSON serialization helpers // ============================================================================ @@ -168,7 +177,7 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& } // Parse psk_id from the decrypted msg1 payload: {"psk_id":"...","psk_category":"..."}. The - // payload is released as soon as its two fields are copied out, so the msg2 envelope the + // payload is released as soon as its two fields are read out, so the msg2 envelope the // caller builds has the arena to itself. ParsedJsonMessage payload(arena); if (!payload.parse(reinterpret_cast(msg1_payload.data()), payload_size.value())) { @@ -179,12 +188,12 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& IdText psk_id; bool psk_id_present = false; bool psk_id_held = false; - std::string psk_category_code; + std::optional psk_category; payload.extract([&](JsonObjectConst root) { - const std::string_view text = root["psk_id"] | ""; + const std::string_view text = root["psk_id"] | std::string_view(""); psk_id_present = !text.empty(); psk_id_held = psk_id.assign(text); - psk_category_code = root["psk_category"] | ""; + psk_category = psk_category_from_string(root["psk_category"] | std::string_view("")); }); if (!psk_id_present) { @@ -195,16 +204,14 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& // messaging.md "noise/handshake": the payload declares which category the server is using the // referenced PSK as. A missing or unknown code is a malformed payload, which connection.md // "Failure Handling" makes a silent failure. - auto psk_category = psk_category_from_string(psk_category_code); if (!psk_category.has_value()) { - SS_LOGE(TAG, "%s: msg1 payload psk_category missing or unknown ('%s')", log_prefix, - psk_category_code.c_str()); + SS_LOGE(TAG, "%s: msg1 payload psk_category missing or not 'lt', 'pr' or 'sn'", log_prefix); return std::nullopt; } const char* const psk_id_text = psk_id_held ? psk_id.c_str() : "(longer than a psk_id)"; SS_LOGD(TAG, "%s: psk_id='%s' psk_category='%s'", log_prefix, psk_id_text, - psk_category_code.c_str()); + to_cstr(*psk_category)); std::optional resolved = psk_id_held ? record_store.resolve_by_psk_id(psk_id.view(), psk_category.value()) @@ -228,7 +235,7 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& // "Pairing Records": an evicted record needs no wire signal of its own). Failing here // instead would leave a client that lost its record reconnect-looping with no way back. SS_LOGW(TAG, "%s: no '%s' PSK for psk_id='%s'; answering with the Sentinel PSK", log_prefix, - psk_category_code.c_str(), psk_id_text); + to_cstr(*psk_category), psk_id_text); resolved = record_store.resolve_by_psk_id(SENTINEL_PSK_ID, PskCategory::SENTINEL); if (!resolved.has_value()) { SS_LOGE(TAG, "%s: the Sentinel PSK did not resolve", log_prefix); @@ -237,7 +244,7 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& } else { // connection.md "Sentinel Fallback" applies to the initial handshake alone. SS_LOGW(TAG, "%s: no '%s' PSK for psk_id='%s', aborting", log_prefix, - psk_category_code.c_str(), psk_id_text); + to_cstr(*psk_category), psk_id_text); return std::nullopt; } @@ -269,7 +276,7 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& std::optional read_noise_handshake_data(JsonObjectConst envelope, const char* log_context) { - const std::string_view data_b64 = envelope["payload"]["data"] | ""; + const std::string_view data_b64 = envelope["payload"]["data"] | std::string_view(""); if (data_b64.empty()) { SS_LOGE(TAG, "%s: missing data field", log_context); return std::nullopt; @@ -280,6 +287,11 @@ std::optional read_noise_handshake_data(JsonObjectConst envelope SS_LOGE(TAG, "%s: failed to base64url-decode noise msg1", log_context); return std::nullopt; } + if (size > MAX_HANDSHAKE_MSG1_BYTES) { + SS_LOGE(TAG, "%s: noise msg1 of %zu bytes is longer than %zu", log_context, size, + MAX_HANDSHAKE_MSG1_BYTES); + return std::nullopt; + } PlatformBuffer bytes; if (!bytes.allocate(size)) { SS_LOGE(TAG, "%s: no memory to decode %zu bytes", log_context, size); @@ -324,10 +336,13 @@ std::string_view NoiseHandshake::build_client_init() { void NoiseHandshake::take_server_error(JsonObjectConst root, const char* log_context) { // The handshake aborts either way; recognizing the message is what gives the abort the - // server's own account of the refusal. - this->server_error_reason_ = root["payload"]["reason"] | ""; - SS_LOGE(TAG, "%s: server/error, reason='%s'; the server refused the connection", log_context, - this->server_error_reason_.c_str()); + // server's own account of the refusal. The frame is unauthenticated, so its text is read in + // place and logged only up to PEER_TEXT_LOG_BYTES, never copied. + const std::string_view text = root["payload"]["reason"] | std::string_view(""); + this->server_error_reason_ = server_error_reason_from_string(text); + const std::string_view logged = text.substr(0, PEER_TEXT_LOG_BYTES); + SS_LOGE(TAG, "%s: server/error, reason='%.*s'; the server refused the connection", log_context, + static_cast(logged.size()), logged.data()); } HandshakeFrameResult NoiseHandshake::on_text_frame( @@ -357,23 +372,25 @@ HandshakeFrameResult NoiseHandshake::on_text_frame( IdText server_id; std::optional msg1_bytes; const bool expected = frame.extract([&](JsonObjectConst root) { - const char* type = root["type"] | ""; + const std::string_view type = root["type"] | std::string_view(""); // messaging.md "server/error": sent in place of server/init when the server cannot // accept our client/init. Recognized in either wait so an abort names the server's // reason. - if (std::strcmp(type, "server/error") == 0) { + if (type == "server/error") { this->take_server_error(root, log_context); return false; } - if (std::strcmp(type, expected_type) != 0) { - SS_LOGE(TAG, "%s: unexpected type '%s'", log_context, type); + if (type != expected_type) { + const std::string_view logged = type.substr(0, PEER_TEXT_LOG_BYTES); + SS_LOGE(TAG, "%s: unexpected type '%.*s'", log_context, static_cast(logged.size()), + logged.data()); return false; } if (awaiting_server_init) { version = root["payload"]["version"] | 0; // Refused when longer than a peer_id, leaving it empty for handle_server_init() to // reject. - (void)server_id.assign(root["payload"]["server_id"] | ""); + (void)server_id.assign(root["payload"]["server_id"] | std::string_view("")); } else { msg1_bytes = read_noise_handshake_data(root, to_cstr(HandshakeKind::INITIAL)); } @@ -461,8 +478,8 @@ bool NoiseHandshake::handle_msg1(std::span msg1_bytes, return false; } - SS_LOGI(TAG, "Noise handshake complete: server_id=%s psk_category=%d", this->server_id_.c_str(), - static_cast(core->psk_category)); + SS_LOGI(TAG, "Noise handshake complete: server_id=%s psk_category=%s", this->server_id_.c_str(), + to_cstr(core->psk_category)); // Built in the caller's optional, so no result temporary sits on this frame. completed.emplace(std::move(core->session), this->server_id_, core->psk_id, core->psk_category); @@ -488,8 +505,8 @@ std::optional run_rehandshake_msg1( return std::nullopt; } - SS_LOGI(TAG, "Re-handshake complete: server_id=%s psk_category=%d", server_id.c_str(), - static_cast(core->psk_category)); + SS_LOGI(TAG, "Re-handshake complete: server_id=%s psk_category=%s", server_id.c_str(), + to_cstr(core->psk_category)); // The caller wraps msg2 in its noise/handshake envelope and sends it encrypted. Returned as a // prvalue, which is built in the caller's optional; a named optional would be moved there, diff --git a/src/noise_handshake.h b/src/noise_handshake.h index 093d6e75..fcbb18cc 100644 --- a/src/noise_handshake.h +++ b/src/noise_handshake.h @@ -50,7 +50,6 @@ #include #include #include -#include #include #include @@ -75,6 +74,44 @@ struct NoiseHandshakeResult { NoiseMsg2 msg2_bytes{}; }; +/// @brief Why a server refused our client/init: the reasons messaging.md "server/error" defines, +/// plus UNKNOWN for any other text or none +enum class ServerErrorReason : uint8_t { + UNSUPPORTED_VERSION, ///< "unsupported_version" + UNSUPPORTED_SUITE, ///< "unsupported_suite" + MALFORMED, ///< "malformed" + UNKNOWN, ///< Any other reason, or none +}; + +/// @brief Parses a server/error reason; UNKNOWN for text messaging.md does not define +inline ServerErrorReason server_error_reason_from_string(std::string_view text) { + if (text == "unsupported_version") { + return ServerErrorReason::UNSUPPORTED_VERSION; + } + if (text == "unsupported_suite") { + return ServerErrorReason::UNSUPPORTED_SUITE; + } + if (text == "malformed") { + return ServerErrorReason::MALFORMED; + } + return ServerErrorReason::UNKNOWN; +} + +/// @brief Wire string for a ServerErrorReason; "unknown" for UNKNOWN. +inline const char* to_cstr(ServerErrorReason reason) { + switch (reason) { + case ServerErrorReason::UNSUPPORTED_VERSION: + return "unsupported_version"; + case ServerErrorReason::UNSUPPORTED_SUITE: + return "unsupported_suite"; + case ServerErrorReason::MALFORMED: + return "malformed"; + case ServerErrorReason::UNKNOWN: + return "unknown"; + } + return "unknown"; +} + /// @brief Result of processing one incoming WS frame during the handshake. enum class HandshakeFrameResult : uint8_t { NEED_MORE, ///< Frame processed; waiting for the next frame. @@ -98,8 +135,8 @@ bool build_noise_handshake_message(std::span noise_bytes, JsonDoc /// re-handshake's, so the caller can release the parsed envelope before the handshake runs. /// @param envelope Parsed noise/handshake envelope; its type is the caller's to check. /// @param log_context Prefix for the failure log line. -/// @return The decoded bytes, or nullopt (logged) when data is missing, empty or not base64url, -/// or when their buffer cannot be allocated. +/// @return The decoded bytes, or nullopt (logged) when data is missing, empty, not base64url or +/// longer than MAX_HANDSHAKE_MSG1_BYTES, or when their buffer cannot be allocated. std::optional read_noise_handshake_data(JsonObjectConst envelope, const char* log_context); @@ -185,12 +222,13 @@ class NoiseHandshake { const std::function& send_fn, std::optional& completed); - /// @brief The reason carried by a server/error received during the handshake, or empty. + /// @brief The reason carried by a server/error received during the handshake, or nullopt + /// when none arrived. /// /// messaging.md "server/error": the server sends one in place of server/init when it cannot /// accept our client/init. The message is unauthenticated, so connection.md "Failure Handling" /// makes the reason a hint for logging and operator display. - const std::string& server_error_reason() const { + std::optional server_error_reason() const { return this->server_error_reason_; } @@ -231,7 +269,7 @@ class NoiseHandshake { PlatformBuffer prologue_; /// Reason from a received server/error. See server_error_reason(). - std::string server_error_reason_; + std::optional server_error_reason_; /// server_id decoded from server/init (43-char base64url). IdText server_id_; diff --git a/src/platform/base64.h b/src/platform/base64.h index d5c39b76..e2e54d10 100644 --- a/src/platform/base64.h +++ b/src/platform/base64.h @@ -20,6 +20,7 @@ #pragma once +#include #include #include #include @@ -305,6 +306,14 @@ inline std::optional b64url_decode_into(std::string_view s, uint8_t* dst return written; } +/// @brief Decode base64url that must carry exactly N bytes straight into `out`, tolerating +/// missing `=` padding. +/// @return false on invalid input or any other length, with `out` unspecified. +template +inline bool b64url_decode_exact(std::string_view s, std::array& out) { + return b64url_decode_into(s, out.data(), out.size()) == N; +} + /// @brief Decode base64url, tolerating missing `=` padding; nullopt on invalid input. inline std::optional> b64url_decode(std::string_view s) { const std::optional size = b64url_decoded_size(s); diff --git a/src/protocol.cpp b/src/protocol.cpp index 6b0603db..c0e1dadb 100644 --- a/src/protocol.cpp +++ b/src/protocol.cpp @@ -1268,17 +1268,14 @@ bool process_server_pair_init_message(JsonObject root, ServerPairInitPayload* pa SS_LOGE(TAG, "server/pair-init: nonce_A is not a string"); return false; } - auto decoded = b64url_decode(nonce_var.as()); - if (!decoded.has_value() || decoded->size() != 32) { + std::array nonce_a{}; + if (!b64url_decode_exact(nonce_var.as(), nonce_a)) { SS_LOGE(TAG, "server/pair-init: nonce_A is not 32 base64url-encoded bytes"); return false; } - if (payload == nullptr) { - return true; + if (payload != nullptr) { + payload->nonce_a = nonce_a; } - std::array nonce_a{}; - std::memcpy(nonce_a.data(), decoded->data(), nonce_a.size()); - payload->nonce_a = nonce_a; return true; } @@ -1288,17 +1285,14 @@ bool process_server_pair_auth_message(JsonObject root, ServerPairAuthPayload* pa return false; } - if (payload == nullptr) { - return true; - } - - const std::string msg1_b64 = root["payload"]["pake_msg_1"].as(); - auto msg1_bytes = b64url_decode(msg1_b64); - if (!msg1_bytes.has_value() || msg1_bytes->size() != 32) { + std::array pake_msg_1{}; + if (!b64url_decode_exact(root["payload"]["pake_msg_1"].as(), pake_msg_1)) { SS_LOGE(TAG, "server/pair-auth: pake_msg_1 is not 32 bytes"); return false; } - std::memcpy(payload->pake_msg_1.data(), msg1_bytes->data(), 32); + if (payload != nullptr) { + payload->pake_msg_1 = pake_msg_1; + } return true; } @@ -1308,17 +1302,14 @@ bool process_server_pair_confirm_message(JsonObject root, ServerPairConfirmPaylo return false; } - if (payload == nullptr) { - return true; - } - - const std::string kc_b64 = root["payload"]["server_kc"].as(); - auto kc_bytes = b64url_decode(kc_b64); - if (!kc_bytes.has_value() || kc_bytes->size() != 64) { + std::array server_kc{}; + if (!b64url_decode_exact(root["payload"]["server_kc"].as(), server_kc)) { SS_LOGE(TAG, "server/pair-confirm: server_kc is not 64 bytes"); return false; } - std::memcpy(payload->server_kc.data(), kc_bytes->data(), 64); + if (payload != nullptr) { + payload->server_kc = server_kc; + } return true; } diff --git a/src/record_store.h b/src/record_store.h index 0a6ffd95..2768c0fe 100644 --- a/src/record_store.h +++ b/src/record_store.h @@ -72,6 +72,19 @@ inline std::optional psk_category_from_string(std::string_view code return std::nullopt; } +/// @brief The wire code of `category`; see psk_category_from_string(). +inline const char* to_cstr(PskCategory category) { + switch (category) { + case PskCategory::LONG_TERM: + return "lt"; + case PskCategory::PAIRING: + return "pr"; + case PskCategory::SENTINEL: + return "sn"; + } + return "unknown"; +} + // ============================================================================ // Resolved PSK (handshake currency) // ============================================================================ diff --git a/tests/loopback_connection.h b/tests/loopback_connection.h index 7030d5e8..fff9313b 100644 --- a/tests/loopback_connection.h +++ b/tests/loopback_connection.h @@ -48,6 +48,7 @@ extern "C" { #include #include #include +#include #include #include @@ -167,7 +168,7 @@ class TestConnection : public SendspinConnection { /// Build and return `server/init` JSON for the given server_id and version. `type` is a /// parameter so a test can send the same payload under another envelope type. inline std::string make_server_init(const std::string& server_id, int version = 1, - const char* type = "server/init") { + std::string_view type = "server/init") { JsonDocument doc; doc["type"] = type; doc["payload"]["server_id"] = server_id; diff --git a/tests/test_dynamic_pairing_code.cpp b/tests/test_dynamic_pairing_code.cpp index a433caed..101ae8d8 100644 --- a/tests/test_dynamic_pairing_code.cpp +++ b/tests/test_dynamic_pairing_code.cpp @@ -110,10 +110,12 @@ TEST(DynamicPairingCode, ParseServerPairInitRejectsMalformedNonce) { std::array nonce_a{}; for (int i = 0; i < 32; ++i) nonce_a[i] = static_cast(i); std::array short_nonce{}; + std::array long_nonce{}; const ParseRow rows[] = { {"nonce_A-not-a-string", R"({"type":"server/pair-init","payload":{"nonce_A":5}})", false}, {"nonce_A-16-bytes", make_pair_init_json(b64url(short_nonce)), false}, + {"nonce_A-33-bytes", make_pair_init_json(b64url(long_nonce)), false}, {"nonce_A-not-base64", R"({"type":"server/pair-init","payload":{"nonce_A":"!!!not_base64!!!"}})", false}, // Control: a 32-byte base64url nonce_A. @@ -198,10 +200,12 @@ TEST(DynamicPairingCode, ParseServerPairAuthRejectsMalformedPakeMsg1) { std::array pake_msg_1{}; for (int i = 0; i < 32; ++i) pake_msg_1[i] = static_cast(i + 10); std::array short_share{}; + std::array long_share{}; const ParseRow rows[] = { {"pake_msg_1-missing", R"({"type":"server/pair-auth","payload":{}})", false}, {"pake_msg_1-16-bytes", make_pair_auth_json(b64url(short_share)), false}, + {"pake_msg_1-33-bytes", make_pair_auth_json(b64url(long_share)), false}, {"pake_msg_1-not-base64", R"({"type":"server/pair-auth","payload":{"pake_msg_1":"!!!not_valid!!!"}})", false}, // Control: a 32-byte base64url pake_msg_1. @@ -230,10 +234,12 @@ TEST(DynamicPairingCode, ParseServerPairConfirmRejectsMalformedServerKc) { std::array server_kc{}; for (int i = 0; i < 64; ++i) server_kc[i] = static_cast(i); std::array short_kc{}; + std::array long_kc{}; const ParseRow rows[] = { {"server_kc-missing", R"({"type":"server/pair-confirm","payload":{}})", false}, {"server_kc-32-bytes", make_pair_confirm_json(b64url(short_kc)), false}, + {"server_kc-65-bytes", make_pair_confirm_json(b64url(long_kc)), false}, {"server_kc-not-base64", R"({"type":"server/pair-confirm","payload":{"server_kc":"!!!not_valid!!!"}})", false}, // Control: a 64-byte base64url server_kc. diff --git a/tests/test_noise_transport.cpp b/tests/test_noise_transport.cpp index 2e6eede7..48e01e8c 100644 --- a/tests/test_noise_transport.cpp +++ b/tests/test_noise_transport.cpp @@ -413,6 +413,14 @@ TEST(NoiseHandshakeDriver, UnknownPskIdFallsBackToTheSentinelPsk) { EXPECT_EQ(over_long.result, HandshakeFrameResult::COMPLETE); EXPECT_EQ(over_long.category, PskCategory::SENTINEL); EXPECT_FALSE(over_long.peer_read_msg2); + + // So is the stored id with more after a NUL: the id is read at its full length. + Msg1Outcome nul_suffixed = run_msg1_with_payload([](const std::string& psk_id) { + return R"({"psk_id":")" + psk_id + R"(\u0000x","psk_category":"lt"})"; + }); + EXPECT_EQ(nul_suffixed.result, HandshakeFrameResult::COMPLETE); + EXPECT_EQ(nul_suffixed.category, PskCategory::SENTINEL); + EXPECT_FALSE(nul_suffixed.peer_read_msg2); } // messaging.md "noise/handshake": the payload declares which category the referenced PSK is used @@ -428,6 +436,8 @@ TEST(NoiseHandshakeDriver, Msg1PayloadPskCategoryIsValidated) { }; const Row rows[] = { {"code outside the defined set", R"(,"psk_category":"xx")", HandshakeFrameResult::ABORT}, + {"a defined code with more after a NUL", R"(,"psk_category":"lt\u0000x")", + HandshakeFrameResult::ABORT}, {"no psk_category at all", "", HandshakeFrameResult::ABORT}, // Control: the category the client actually holds the psk_id in resolves to the record, // and the peer that sent message 1 can read the message 2 that comes back. @@ -450,41 +460,72 @@ TEST(NoiseHandshakeDriver, Msg1PayloadPskCategoryIsValidated) { } // messaging.md "server/error": the server sends it in place of server/init when it cannot accept -// our client/init, then closes. The handshake aborts, and the reason it carries is logged rather -// than the frame being treated as an unparseable server/init. +// our client/init, then closes. The handshake aborts, and the reason it carries is kept as one of +// the reasons the spec defines, any other text (or none) as UNKNOWN, rather than the frame being +// treated as an unparseable server/init. TEST(NoiseHandshakeDriver, ServerErrorWhileAwaitingServerInitAborts) { - Identity client_id = Identity::generate().value(); - RecordStore rs(nullptr); + struct Row { + const char* frame; + std::optional expected; + }; + const Row rows[] = { + {R"({"type":"server/error","payload":{"reason":"unsupported_version"}})", + ServerErrorReason::UNSUPPORTED_VERSION}, + {R"({"type":"server/error","payload":{"reason":"unsupported_suite"}})", + ServerErrorReason::UNSUPPORTED_SUITE}, + {R"({"type":"server/error","payload":{"reason":"malformed"}})", + ServerErrorReason::MALFORMED}, + {R"({"type":"server/error","payload":{"reason":"Malformed"}})", ServerErrorReason::UNKNOWN}, + {R"({"type":"server/error","payload":{"reason":"malformed\u0000x"}})", + ServerErrorReason::UNKNOWN}, + {R"({"type":"server/error","payload":{"reason":7}})", ServerErrorReason::UNKNOWN}, + {R"({"type":"server/error","payload":{}})", ServerErrorReason::UNKNOWN}, + // Control: an abort on a frame that is not a server/error leaves no reason to report, so + // the connection does not attribute a generic failure to the server. + {R"({"type":"server/init","payload":{"version":99}})", std::nullopt}, + }; + for (const Row& row : rows) { + SCOPED_TRACE(row.frame); + Identity client_id = Identity::generate().value(); + RecordStore rs(nullptr); - TestArena arena; - NoiseHandshake nh(client_id, rs, NOISE_SUITE_CHACHAPOLY, arena); - std::optional completed; - nh.build_client_init(); + TestArena arena; + NoiseHandshake nh(client_id, rs, NOISE_SUITE_CHACHAPOLY, arena); + std::optional completed; + nh.build_client_init(); - auto r = nh.on_text_frame(R"({"type":"server/error","payload":{"reason":"unsupported_suite"}})", - [](const JsonDocument&) { return true; }, completed); - EXPECT_EQ(r, HandshakeFrameResult::ABORT); - EXPECT_EQ(nh.server_error_reason(), "unsupported_suite"); + auto r = nh.on_text_frame(row.frame, [](const JsonDocument&) { return true; }, completed); + EXPECT_EQ(r, HandshakeFrameResult::ABORT); + EXPECT_EQ(nh.server_error_reason(), row.expected); + } } -// Control: the same abort from a frame that is not a server/error leaves no reason to report, so -// the connection does not attribute a generic failure to the server. -TEST(NoiseHandshakeDriver, AbortWithoutServerErrorReportsNoReason) { - Identity client_id = Identity::generate().value(); - RecordStore rs(nullptr); - - TestArena arena; - NoiseHandshake nh(client_id, rs, NOISE_SUITE_CHACHAPOLY, arena); - std::optional completed; - nh.build_client_init(); - - auto r = nh.on_text_frame(R"({"type":"server/init","payload":{"version":99}})", - [](const JsonDocument&) { return true; }, completed); - EXPECT_EQ(r, HandshakeFrameResult::ABORT); - EXPECT_TRUE(nh.server_error_reason().empty()); +// A noise/handshake data field longer than any message 1 the client could read is refused before +// its buffer is allocated, so a pre-admission frame cannot make the client hold a peer-sized decode +// buffer. +TEST(NoiseHandshakeDriver, HandshakeDataLongerThanAMsg1IsRefused) { + struct Row { + const char* name; + size_t bytes; + bool accepted; + }; + const Row rows[] = { + {"Control: longest-msg1", MAX_HANDSHAKE_MSG1_BYTES, true}, + {"one-byte-over", MAX_HANDSHAKE_MSG1_BYTES + 1, false}, + }; + for (const Row& row : rows) { + SCOPED_TRACE(row.name); + const std::vector bytes(row.bytes, 0x5A); + const std::string frame = R"({"type":"noise/handshake","payload":{"data":")" + + b64url_encode(bytes.data(), bytes.size()) + R"("}})"; + JsonDocument doc; + ASSERT_EQ(deserializeJson(doc, frame), DeserializationError::Ok); + EXPECT_EQ(read_noise_handshake_data(doc.as(), "test").has_value(), + row.accepted); + } } -// The same frame after server/init, while the client is waiting for Noise message 1, is refused +// A server/error after server/init, while the client is waiting for Noise message 1, is refused // the same way instead of being read as a handshake message. TEST(NoiseHandshakeDriver, ServerErrorWhileAwaitingMsg1Aborts) { Identity client_id = Identity::generate().value(); @@ -502,17 +543,17 @@ TEST(NoiseHandshakeDriver, ServerErrorWhileAwaitingMsg1Aborts) { auto r = nh.on_text_frame(R"({"type":"server/error","payload":{"reason":"malformed"}})", [](const JsonDocument&) { return true; }, completed); EXPECT_EQ(r, HandshakeFrameResult::ABORT); - EXPECT_EQ(nh.server_error_reason(), "malformed"); + EXPECT_EQ(nh.server_error_reason(), ServerErrorReason::MALFORMED); } // A server/init is accepted only when its type, its server_id, its version and its length are all // usable: the server_id names the key and the frame goes into the prologue, so each is checked // before the handshake reads a Noise byte (connection.md "Handshake"). TEST(NoiseHandshakeDriver, ServerInitIsRefusedUnlessWellFormed) { - enum class ServerId : uint8_t { REAL, TOO_LONG, NON_CANONICAL }; + enum class ServerId : uint8_t { REAL, TOO_LONG, NON_CANONICAL, NUL_SUFFIXED }; struct Row { const char* name; - const char* type; + std::string_view type; ServerId server_id; int version; HandshakeFrameResult expected; @@ -527,6 +568,11 @@ TEST(NoiseHandshakeDriver, ServerInitIsRefusedUnlessWellFormed) { // The payload is the control's, so only the type field can produce the abort: a frame // whose payload would pass must still be refused for arriving under another type. {"another envelope type", "wrong/type", ServerId::REAL, 1, HandshakeFrameResult::ABORT}, + // A field is read at its full length, so a NUL cannot cut it back to an acceptable value. + {"the right type with more after a NUL", std::string_view("server/init\0x", 13), + ServerId::REAL, 1, HandshakeFrameResult::ABORT}, + {"the server_id with more after a NUL", "server/init", ServerId::NUL_SUFFIXED, 1, + HandshakeFrameResult::ABORT}, // A peer id is PEER_ID_SIZE characters of base64url; anything else cannot name a key. {"server_id of the wrong length", "server/init", ServerId::TOO_LONG, 1, HandshakeFrameResult::ABORT}, @@ -555,6 +601,8 @@ TEST(NoiseHandshakeDriver, ServerInitIsRefusedUnlessWellFormed) { peer_id = std::string(PEER_ID_SIZE + 2, 'A'); } else if (row.server_id == ServerId::NON_CANONICAL) { peer_id = non_canonical_spelling(peer_id); + } else if (row.server_id == ServerId::NUL_SUFFIXED) { + peer_id += std::string("\0x", 2); } std::string frame = make_server_init(peer_id, row.version, row.type); if (row.padded_to != 0) {