From cc361d2251217e102522c714a89668b1b360051c Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Mon, 2 Nov 2026 13:31:11 -0500 Subject: [PATCH 1/3] Hold handshake peer and PSK ids inline The handshake copied the server_id from server/init into the driver and its result, and the psk_id from message 1 into the resolved PSK, its counterparty id and the connection, each a std::string past the inline capacity, and server/hello copied the whole ServerInformationObject to set its name. IdText holds a peer_id or psk_id inline (both are 43 characters); a longer psk_id is a lookup miss, so the Sentinel fallback still answers it. server/hello now moves only the name in. Accept to admission: 24 -> 17 allocations under libc++, 27 -> 19 under libstdc++. --- src/client_dispatch.cpp | 8 ++-- src/connection.cpp | 18 ++++----- src/connection.h | 26 ++++++------- src/connection_manager.cpp | 10 ++--- src/connection_manager.h | 2 +- src/connection_manager_pairing.cpp | 6 +-- src/crypto/keys.h | 52 +++++++++++++++++++++++++- src/noise_handshake.cpp | 60 ++++++++++++++++++------------ src/noise_handshake.h | 10 ++--- src/record_store.cpp | 18 ++++----- src/record_store.h | 15 ++++---- tests/record_test_helpers.h | 6 +++ tests/test_allocations.cpp | 6 +-- tests/test_noise_transport.cpp | 8 ++++ 14 files changed, 160 insertions(+), 85 deletions(-) diff --git a/src/client_dispatch.cpp b/src/client_dispatch.cpp index 3285ecf0..3733a2a8 100644 --- a/src/client_dispatch.cpp +++ b/src/client_dispatch.cpp @@ -511,16 +511,14 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const if (parsed.extract(&hello_msg)) { // server_id comes from the Noise handshake result (already set on the // connection); server/hello supplies the display name. - ServerInformationObject info = conn->get_server_information(); - info.name = hello_msg.name; - conn->set_server_information(std::move(info)); + conn->set_server_name(std::move(hello_msg.name)); conn->set_server_source_codecs(hello_msg.source_codecs); // The nursery scan later in this tick sends client/hello in reply; nothing // needs to be scheduled here. conn->set_server_hello_received(true); - SS_LOGD(TAG, "Connected to server '%s' (server_id=%s)", hello_msg.name.c_str(), - conn->get_server_id().c_str()); + SS_LOGD(TAG, "Connected to server '%s' (server_id=%s)", + conn->get_server_information().name.c_str(), conn->get_server_id().c_str()); } break; } diff --git a/src/connection.cpp b/src/connection.cpp index 7b50ef38..c2ef3502 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -286,8 +286,8 @@ void SendspinConnection::handle_noise_handshake_text(std::string_view text) { } // Record the server's identity (public key) and the PSK category/psk_id that admitted // the connection, resolved by the handshake. - this->set_noise_handshake_result(outcome->server_id, outcome->resolved_psk.category, - outcome->resolved_psk.psk_id); + this->set_noise_handshake_result(outcome->server_id.view(), outcome->resolved_psk.category, + outcome->resolved_psk.psk_id.view()); // pairing.md "Pairing index": a fresh handshake starts a fresh count for the // pairing_index / CPace-sid counter. this->reset_pairing_index(); @@ -341,11 +341,9 @@ bool SendspinConnection::handle_noise_rehandshake(std::span msg1_ SS_LOGE(TAG, "handle_noise_rehandshake: no handshake hash available"); return false; } - const std::string current_server_id = this->server_information_.server_id; - - auto result = run_rehandshake_msg1(msg1_bytes, current_server_id, *this->noise_identity_, - *this->noise_record_store_, this->noise_suite_name_, - prior_h.value(), *this->json_arena_); + auto result = run_rehandshake_msg1( + msg1_bytes, this->server_information_.server_id, *this->noise_identity_, + *this->noise_record_store_, this->noise_suite_name_, prior_h.value(), *this->json_arena_); if (!result.has_value()) { SS_LOGW(TAG, "handle_noise_rehandshake: re-handshake failed; closing connection"); return false; @@ -379,9 +377,9 @@ bool SendspinConnection::handle_noise_rehandshake(std::span msg1_ // connection.md "Re-handshake": neither hello is re-sent, so the hello state carries over // 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", - current_server_id.c_str(), static_cast(this->get_psk_category())); + SS_LOGI( + TAG, "Noise re-handshake complete: server_id=%s psk_category=%d; awaiting server/activate", + this->server_information_.server_id.c_str(), static_cast(this->get_psk_category())); return true; } diff --git a/src/connection.h b/src/connection.h index dc308886..5d8647e3 100644 --- a/src/connection.h +++ b/src/connection.h @@ -390,9 +390,10 @@ class SendspinConnection : public std::enable_shared_from_thispsk_id_; } @@ -691,11 +692,11 @@ class SendspinConnection : public std::enable_shared_from_thisserver_information_.server_id = server_id; this->psk_category_ = psk_category; - this->psk_id_ = psk_id; + this->psk_id_.assign(psk_id); } /// @brief Returns whether server/hello has arrived on this connection. @@ -717,11 +718,10 @@ class SendspinConnection : public std::enable_shared_from_thisserver_source_codecs_ = codecs.value_or(0); } - /// @brief Sets the server information (from server/hello message) - /// @param info The ServerInformationObject received during the hello handshake. - /// @note Called by hub after receiving server/hello message. - void set_server_information(ServerInformationObject info) { - this->server_information_ = std::move(info); + /// @brief Sets the server's display name from server/hello; the server_id the handshake + /// recorded stays. + void set_server_name(std::string name) { + this->server_information_.name = std::move(name); } // ======================================== @@ -1098,10 +1098,10 @@ class SendspinConnection : public std::enable_shared_from_this ConnectionManager::open_connection_psk_ids() const { psk_ids.reserve(MAX_OPEN_CONNECTIONS); for (const auto& entry : this->admitted_) { if (entry.conn != nullptr && !entry.conn->get_psk_id().empty()) { - psk_ids.push_back(entry.conn->get_psk_id()); + psk_ids.emplace_back(entry.conn->get_psk_id().view()); } } for (const auto& entry : this->nursery_) { if (!entry.conn->get_psk_id().empty()) { - psk_ids.push_back(entry.conn->get_psk_id()); + psk_ids.emplace_back(entry.conn->get_psk_id().view()); } } return psk_ids; @@ -1579,7 +1579,7 @@ bool ConnectionManager::send_hello_message(SendspinConnection* conn) { // Connection lifecycle // ============================================================================ -void ConnectionManager::drop_connections_using_psk_id(const std::string& psk_id, +void ConnectionManager::drop_connections_using_psk_id(const IdText& psk_id, const SendspinConnection* except) { if (psk_id.empty()) { return; @@ -1695,8 +1695,8 @@ void ConnectionManager::note_playback_activity(const SendspinConnection* conn) { // least recent until a deferred move lands. RecordStore::mutex_ is a leaf (docs/conventions.md, // "Threading and cross-thread state"), and this holds no other lock. if (conn->get_psk_category() == PskCategory::LONG_TERM) { - const std::string& psk_id = conn->get_psk_id(); - if (!psk_id.empty() && this->client_->record_store_->note_record_played(psk_id)) { + const IdText& psk_id = conn->get_psk_id(); + if (!psk_id.empty() && this->client_->record_store_->note_record_played(psk_id.view())) { this->client_->request_persist(); } } diff --git a/src/connection_manager.h b/src/connection_manager.h index 32dce5cc..0bb6ad92 100644 --- a/src/connection_manager.h +++ b/src/connection_manager.h @@ -762,7 +762,7 @@ class ConnectionManager { /// /// @param psk_id psk_id whose sessions are no longer trusted. /// @param except Connection to leave alone (its caller is already dropping it), or nullptr. - void drop_connections_using_psk_id(const std::string& psk_id, const SendspinConnection* except); + void drop_connections_using_psk_id(const IdText& psk_id, const SendspinConnection* except); // ======================================== // Pairing handlers diff --git a/src/connection_manager_pairing.cpp b/src/connection_manager_pairing.cpp index ae9c8734..ba26ba42 100644 --- a/src/connection_manager_pairing.cpp +++ b/src/connection_manager_pairing.cpp @@ -931,8 +931,8 @@ void ConnectionManager::handle_server_unpair(SendspinConnection* conn) { return; } - // Copied: the drops below release the connection that owns the string. - const std::string psk_id = conn->get_psk_id(); + // Copied: the drops below release the connection that owns the id. + const IdText psk_id = conn->get_psk_id(); SS_LOGI(TAG, "server/unpair: dropping record and disconnecting (server_id=%s, psk_id=%s)", conn->get_server_id().c_str(), psk_id.c_str()); @@ -940,7 +940,7 @@ void ConnectionManager::handle_server_unpair(SendspinConnection* conn) { // because a re-handshake on the revoked psk_id resolves against the store and must miss it // from this instant: deferring it would leave the credential usable until the flush. The slot // write is left to SendspinClient::flush_pending_persistence() on the main loop. - if (this->client_->record_store_->note_record_removed(psk_id)) { + if (this->client_->record_store_->note_record_removed(psk_id.view())) { this->client_->request_persist(); } diff --git a/src/crypto/keys.h b/src/crypto/keys.h index 894068c5..424eaaf5 100644 --- a/src/crypto/keys.h +++ b/src/crypto/keys.h @@ -13,7 +13,8 @@ // limitations under the License. /// @file keys.h -/// @brief Sendspin key helpers: PSK-ID derivation and X25519 Identity. +/// @brief Sendspin key helpers: PSK-ID derivation, X25519 Identity, and IdText, a peer_id or psk_id +/// held inline. /// /// Both values are fixed by connection.md "Pre-Shared Key" and "Identities": /// - `psk_id_for(psk)` = base64url(SHA-256(PSK_ID_LABEL || psk)) @@ -62,6 +63,55 @@ static constexpr size_t PEER_ID_SIZE = 43; /// the padded encoding carries before it is stripped, and the NUL. using PeerIdText = std::array; +/// @brief A peer_id or psk_id held inline, NUL-terminated +/// +/// Both are PEER_ID_SIZE base64url characters (psk_id_for(), Identity::peer_id()), so either fits +/// without a heap allocation; longer text names no id this client holds and is refused. +static_assert(PEER_ID_SIZE <= UINT8_MAX, "IdText holds its size in a uint8_t"); + +class IdText { +public: + IdText() = default; + + /// @brief Holds `text`. + /// @return false, leaving the text empty, when `text` is longer than PEER_ID_SIZE. + bool assign(std::string_view text) { + if (text.size() > PEER_ID_SIZE) { + this->size_ = 0; + this->chars_[0] = '\0'; + return false; + } + text.copy(this->chars_.data(), text.size()); + this->chars_[text.size()] = '\0'; + this->size_ = static_cast(text.size()); + return true; + } + + std::string_view view() const { + return {this->chars_.data(), this->size_}; + } + + const char* c_str() const { + return this->chars_.data(); + } + + bool empty() const { + return this->size_ == 0; + } + + bool operator==(std::string_view other) const { + return this->view() == other; + } + + bool operator==(const IdText& other) const { + return this->view() == other.view(); + } + +private: + std::array chars_{}; + uint8_t size_{0}; +}; + /// @brief Decode a peer_id to the X25519 public key it names. /// /// Accepts only the exact string `Identity::peer_id()` would produce for that key: 43 base64url diff --git a/src/noise_handshake.cpp b/src/noise_handshake.cpp index 904a783f..cfb745de 100644 --- a/src/noise_handshake.cpp +++ b/src/noise_handshake.cpp @@ -128,12 +128,12 @@ const char* to_cstr(HandshakeKind kind) { /// @return Populated Msg1CoreResult on success, or nullopt on any failure (caller aborts). std::optional run_msg1_core(HandshakeKind kind, const Identity& identity, const RecordStore& record_store, const char* suite_name, - const std::string& server_id, const uint8_t* prologue, + const IdText& server_id, const uint8_t* prologue, size_t prologue_len, std::span msg1_bytes, SendspinArenaAllocator& arena) { const char* log_prefix = to_cstr(kind); - auto server_pub = public_key_from_peer_id(server_id); + auto server_pub = public_key_from_peer_id(server_id.view()); if (!server_pub.has_value()) { SS_LOGE(TAG, "%s: invalid server_id (cannot decode public key)", log_prefix); return std::nullopt; @@ -164,14 +164,19 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& SS_LOGE(TAG, "%s: failed to parse msg1 payload JSON", log_prefix); return std::nullopt; } - std::string psk_id; + // A psk_id longer than any this client holds is a lookup miss, not a malformed payload. + IdText psk_id; + bool psk_id_present = false; + bool psk_id_held = false; std::string psk_category_code; - payload.extract([&psk_id, &psk_category_code](JsonObjectConst root) { - psk_id = root["psk_id"] | ""; + payload.extract([&](JsonObjectConst root) { + const std::string_view text = root["psk_id"] | ""; + psk_id_present = !text.empty(); + psk_id_held = psk_id.assign(text); psk_category_code = root["psk_category"] | ""; }); - if (psk_id.empty()) { + if (!psk_id_present) { SS_LOGE(TAG, "%s: psk_id missing from msg1 payload", log_prefix); return std::nullopt; } @@ -186,10 +191,13 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& return std::nullopt; } - SS_LOGD(TAG, "%s: psk_id='%s' psk_category='%s'", log_prefix, psk_id.c_str(), + 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()); - auto resolved = record_store.resolve_by_psk_id(psk_id, psk_category.value()); + std::optional resolved = + psk_id_held ? record_store.resolve_by_psk_id(psk_id.view(), psk_category.value()) + : std::nullopt; if (resolved.has_value()) { // Post-match check (connection.md "Pre-Shared Key"): every long-term PSK is persisted // with the server_id it was minted for. The Pairing and Sentinel PSKs are bound to no @@ -198,7 +206,8 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& if (resolved->category == PskCategory::LONG_TERM && resolved->counterparty_id != server_id) { SS_LOGW(TAG, "%s: PSK bound to server_id='%s', but connected to '%s'", log_prefix, - resolved->counterparty_id.value_or("").c_str(), server_id.c_str()); + resolved->counterparty_id.has_value() ? resolved->counterparty_id->c_str() : "", + server_id.c_str()); return std::nullopt; } } else if (kind == HandshakeKind::INITIAL) { @@ -209,7 +218,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.c_str()); + psk_category_code.c_str(), 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); @@ -218,7 +227,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.c_str()); + psk_category_code.c_str(), psk_id_text); return std::nullopt; } @@ -246,10 +255,10 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& /// caller sets it afterward. /// @param core Completed core result (session and resolved_psk are moved out of it). /// @param server_id Server peer_id to record on the result. -NoiseHandshakeResult make_handshake_result(Msg1CoreResult&& core, std::string server_id) { +NoiseHandshakeResult make_handshake_result(Msg1CoreResult&& core, const IdText& server_id) { NoiseHandshakeResult result; result.session = std::make_unique(std::move(core.session)); - result.server_id = std::move(server_id); + result.server_id = server_id; result.resolved_psk = std::move(core.resolved_psk); return result; } @@ -341,7 +350,7 @@ HandshakeFrameResult NoiseHandshake::on_text_frame( const char* expected_type = awaiting_server_init ? "server/init" : "noise/handshake"; int version = 0; - std::string server_id; + IdText server_id; std::optional msg1_bytes; const bool expected = frame.extract([&](JsonObjectConst root) { const char* type = root["type"] | ""; @@ -358,7 +367,8 @@ HandshakeFrameResult NoiseHandshake::on_text_frame( } if (awaiting_server_init) { version = root["payload"]["version"] | 0; - server_id = root["payload"]["server_id"] | ""; + // Refused when longer than a peer_id, which handle_server_init() then rejects. + server_id.assign(root["payload"]["server_id"] | ""); } else { msg1_bytes = read_noise_handshake_data(root, to_cstr(HandshakeKind::INITIAL)); } @@ -370,7 +380,7 @@ HandshakeFrameResult NoiseHandshake::on_text_frame( } if (awaiting_server_init) { - if (!this->handle_server_init(version, std::move(server_id), text)) { + if (!this->handle_server_init(version, server_id, text)) { this->state_ = State::ABORTED; return HandshakeFrameResult::ABORT; } @@ -391,7 +401,8 @@ HandshakeFrameResult NoiseHandshake::on_text_frame( // Private: handle server/init // ============================================================================ -bool NoiseHandshake::handle_server_init(int version, std::string server_id, std::string_view text) { +bool NoiseHandshake::handle_server_init(int version, const IdText& server_id, + std::string_view text) { if (version != PROTOCOL_VERSION) { SS_LOGE(TAG, "handle_server_init: unsupported version %d (expected %d)", version, PROTOCOL_VERSION); @@ -400,12 +411,12 @@ bool NoiseHandshake::handle_server_init(int version, std::string server_id, std: // Checked here rather than left to the handshake: records and the last-playback server store // the key, not the text, so a non-canonical spelling would not match itself after a reboot. - if (!public_key_from_peer_id(server_id).has_value()) { + if (!public_key_from_peer_id(server_id.view()).has_value()) { SS_LOGE(TAG, "handle_server_init: server_id is not a canonical base64url public key"); return false; } - this->server_id_ = std::move(server_id); + this->server_id_ = server_id; this->server_init_text_ = text; // Retain exact bytes for prologue SS_LOGD(TAG, "server/init received: server_id=%s", this->server_id_.c_str()); @@ -450,23 +461,26 @@ bool NoiseHandshake::handle_msg1(std::span msg1_bytes, // ============================================================================ std::optional run_rehandshake_msg1( - std::span msg1_bytes, const std::string& server_id, const Identity& identity, + std::span msg1_bytes, std::string_view server_id, const Identity& identity, const RecordStore& record_store, const char* suite_name, const std::array& prior_h, SendspinArenaAllocator& arena) { + // The id the initial handshake recorded; run_msg1_core()'s decode check refuses an empty one. + IdText known_server_id; + known_server_id.assign(server_id); // Prologue for re-handshake = prior handshake hash h (32 bytes) const uint8_t* prologue = prior_h.data(); const size_t prologue_len = prior_h.size(); auto core = run_msg1_core(HandshakeKind::REHANDSHAKE, identity, record_store, suite_name, - server_id, prologue, prologue_len, msg1_bytes, arena); + known_server_id, prologue, prologue_len, msg1_bytes, arena); if (!core.has_value()) { return std::nullopt; } - SS_LOGI(TAG, "Re-handshake complete: server_id=%s psk_category=%d", server_id.c_str(), + SS_LOGI(TAG, "Re-handshake complete: server_id=%s psk_category=%d", known_server_id.c_str(), static_cast(core->resolved_psk.category)); - NoiseHandshakeResult result = make_handshake_result(std::move(core.value()), server_id); + NoiseHandshakeResult result = make_handshake_result(std::move(core.value()), known_server_id); // The caller wraps msg2 in its noise/handshake envelope and sends it encrypted. result.msg2_bytes = std::move(core->msg2_bytes); return result; diff --git a/src/noise_handshake.h b/src/noise_handshake.h index b79622be..0247d30b 100644 --- a/src/noise_handshake.h +++ b/src/noise_handshake.h @@ -65,7 +65,7 @@ struct NoiseHandshakeResult { /// The cipher session ready for transport-mode encrypt/decrypt. std::unique_ptr session; /// Server's public key peer_id (43-char base64url). - std::string server_id; + IdText server_id; /// The PSK record that admitted the connection. ResolvedPsk resolved_psk; /// The Noise msg2 bytes to send to the peer, in a noise/handshake envelope @@ -130,7 +130,7 @@ std::optional read_noise_handshake_data(JsonObjectConst envelope /// @return Populated NoiseHandshakeResult (session + msg2_bytes to send) on success, /// or nullopt on any failure (caller should close the WebSocket). std::optional run_rehandshake_msg1( - std::span msg1_bytes, const std::string& server_id, const Identity& identity, + std::span msg1_bytes, std::string_view server_id, const Identity& identity, const RecordStore& record_store, const char* suite_name, const std::array& prior_h, SendspinArenaAllocator& arena); @@ -210,9 +210,9 @@ class NoiseHandshake { /// @brief Validate the fields read from a server/init frame. /// @param version payload.version (0 when absent). - /// @param server_id payload.server_id (empty when absent). + /// @param server_id payload.server_id (empty when absent or longer than a peer_id). /// @param text Exact received bytes, retained for the handshake prologue. - bool handle_server_init(int version, std::string server_id, std::string_view text); + bool handle_server_init(int version, const IdText& server_id, std::string_view text); /// @brief Authenticate and respond to the noise/handshake msg1. /// @param msg1_bytes The msg1 Noise bytes, read from the frame (read_noise_handshake_data()). @@ -232,7 +232,7 @@ class NoiseHandshake { std::string server_error_reason_; /// server_id decoded from server/init (43-char base64url). - std::string server_id_; + IdText server_id_; /// Exact bytes of the server/init frame we received (retained for prologue). std::string server_init_text_; diff --git a/src/record_store.cpp b/src/record_store.cpp index 34a00a50..6ac09eb8 100644 --- a/src/record_store.cpp +++ b/src/record_store.cpp @@ -218,7 +218,7 @@ void RecordStore::provision_pairing_psk_if_needed() { // PSK resolution // ============================================================================ -std::optional RecordStore::resolve_by_psk_id(const std::string& psk_id, +std::optional RecordStore::resolve_by_psk_id(std::string_view psk_id, PskCategory category) const { // No lock: this runs on the protocol task, which makes every change to records_, and the main // loop's persist_records() only reads records_ (see the persistence locking note below). @@ -230,10 +230,10 @@ std::optional RecordStore::resolve_by_psk_id(const std::string& psk const SendspinPairingRecord* rec = this->record_by_psk_id(psk_id); if (rec != nullptr) { ResolvedPsk r; - r.psk_id = rec->psk_id; + r.psk_id.assign(rec->psk_id); r.psk = rec->psk; r.category = PskCategory::LONG_TERM; - r.counterparty_id = rec->server_id; + r.counterparty_id.emplace().assign(rec->server_id); return r; } break; @@ -241,7 +241,7 @@ std::optional RecordStore::resolve_by_psk_id(const std::string& psk case PskCategory::PAIRING: { if (this->pairing_psk_.has_value() && this->pairing_psk_->psk_id == psk_id) { ResolvedPsk r; - r.psk_id = this->pairing_psk_->psk_id; + r.psk_id.assign(this->pairing_psk_->psk_id); r.psk = this->pairing_psk_->psk; r.category = PskCategory::PAIRING; return r; @@ -251,7 +251,7 @@ std::optional RecordStore::resolve_by_psk_id(const std::string& psk case PskCategory::SENTINEL: { if (psk_id == SENTINEL_PSK_ID) { ResolvedPsk r; - r.psk_id = SENTINEL_PSK_ID; + r.psk_id.assign(SENTINEL_PSK_ID); r.psk = SENTINEL_PSK; r.category = PskCategory::SENTINEL; return r; @@ -267,7 +267,7 @@ std::optional RecordStore::resolve_by_psk_id(const std::string& psk // Long-term record management // ============================================================================ -size_t RecordStore::find_index(const std::string& psk_id) const { +size_t RecordStore::find_index(std::string_view psk_id) const { for (size_t i = 0; i < this->records_.size(); ++i) { if (this->records_[i].record.psk_id == psk_id) { return i; @@ -302,7 +302,7 @@ void RecordStore::mark_slot_dirty_locked(uint8_t slot) { } } -const SendspinPairingRecord* RecordStore::record_by_psk_id(const std::string& psk_id) const { +const SendspinPairingRecord* RecordStore::record_by_psk_id(std::string_view psk_id) const { size_t idx = this->find_index(psk_id); if (idx == NPOS) { return nullptr; @@ -462,7 +462,7 @@ bool RecordStore::has_pending_writes() const { return this->order_dirty_ || !this->dirty_slots_.empty(); } -bool RecordStore::note_record_removed(const std::string& psk_id) { +bool RecordStore::note_record_removed(std::string_view psk_id) { std::lock_guard lock(this->mutex_); const size_t idx = this->find_index(psk_id); if (idx == NPOS) { @@ -474,7 +474,7 @@ bool RecordStore::note_record_removed(const std::string& psk_id) { return true; } -bool RecordStore::note_record_played(const std::string& psk_id) { +bool RecordStore::note_record_played(std::string_view psk_id) { std::lock_guard lock(this->mutex_); const size_t idx = this->find_index(psk_id); // A record that is already the most recent moves nothing and writes nothing, which is every diff --git a/src/record_store.h b/src/record_store.h index e421608d..00dcf1f6 100644 --- a/src/record_store.h +++ b/src/record_store.h @@ -27,6 +27,7 @@ #pragma once #include "crypto/constants.h" +#include "crypto/keys.h" #include "sendspin/client.h" #include "sendspin/config.h" @@ -77,11 +78,11 @@ inline std::optional psk_category_from_string(std::string_view code /// @brief A PSK selected during a handshake, with its trust metadata. struct ResolvedPsk { - std::string psk_id; + IdText psk_id; std::array psk{}; PskCategory category{PskCategory::SENTINEL}; /// Peer server_id; set for every long-term record, empty for the Sentinel and Pairing PSKs. - std::optional counterparty_id; + std::optional counterparty_id; ResolvedPsk() = default; ResolvedPsk(const ResolvedPsk&) = default; @@ -153,7 +154,7 @@ class RecordStore { /// @param category The category the server declared it is using that PSK as. /// Protocol task only. /// @return The matching PSK, or nullopt if this client holds no such PSK in that category. - [[nodiscard]] std::optional resolve_by_psk_id(const std::string& psk_id, + [[nodiscard]] std::optional resolve_by_psk_id(std::string_view psk_id, PskCategory category) const; // ======================================== @@ -215,7 +216,7 @@ class RecordStore { /// later. /// @param psk_id The record to erase. /// @return true when a record was erased, and the store therefore needs persisting. - [[nodiscard]] bool note_record_removed(const std::string& psk_id); + [[nodiscard]] bool note_record_removed(std::string_view psk_id); /// @brief Make the record at psk_id the most recently used one in RAM, leaving the durable /// half to a later persist_records(). No-op if absent or already the most recent. @@ -232,7 +233,7 @@ class RecordStore { /// written later. /// @param psk_id The record to move. /// @return true when the order moved, and the store therefore needs persisting. - [[nodiscard]] bool note_record_played(const std::string& psk_id); + [[nodiscard]] bool note_record_played(std::string_view psk_id); // ======================================== // Pairing PSK (the one the client accepts to admit a new server) @@ -340,7 +341,7 @@ class RecordStore { /// @brief The long-term record for psk_id, or nullptr. Call with mutex_ held, or on the /// protocol task; the pointer does not survive a mutation of records_. - [[nodiscard]] const SendspinPairingRecord* record_by_psk_id(const std::string& psk_id) const; + [[nodiscard]] const SendspinPairingRecord* record_by_psk_id(std::string_view psk_id) const; /// @brief The record bound to server_id, or nullptr. Same rules. [[nodiscard]] const SendspinPairingRecord* record_by_server_id( @@ -350,7 +351,7 @@ class RecordStore { static constexpr size_t NPOS = static_cast(-1); /// @brief Find the index of a record by psk_id, or NPOS if absent. - [[nodiscard]] size_t find_index(const std::string& psk_id) const; + [[nodiscard]] size_t find_index(std::string_view psk_id) const; /// @brief Drop the least recently used record no open connection is resolving against, to /// make room for a net-new one. Call with mutex_ held. diff --git a/tests/record_test_helpers.h b/tests/record_test_helpers.h index 76517725..02207e5c 100644 --- a/tests/record_test_helpers.h +++ b/tests/record_test_helpers.h @@ -33,12 +33,18 @@ #include #include #include +#include #include #include #include namespace sendspin { +/// Prints an IdText as its text in a failed assertion. +inline void PrintTo(const IdText& id, std::ostream* os) { + *os << '"' << id.view() << '"'; +} + /// Generate a random PSK of NOISE_PSK_SIZE bytes. inline std::array make_random_psk() { std::array psk{}; diff --git a/tests/test_allocations.cpp b/tests/test_allocations.cpp index f4badd26..8f00f3f3 100644 --- a/tests/test_allocations.cpp +++ b/tests/test_allocations.cpp @@ -428,11 +428,11 @@ constexpr uint16_t ALLOCATION_TEST_PORT = 19300; constexpr int TIME_BURST_SIZE = 8; // libstdc++ (ESP-IDF's) keeps strings of up to 15 characters inline, libc++ up to 22: the fake -// server's name, copied three times, allocates only under libstdc++. +// server's name, parsed and then published, allocates only under libstdc++. #ifdef _LIBCPP_VERSION -constexpr size_t ADMISSION_ALLOCATIONS = 24; +constexpr size_t ADMISSION_ALLOCATIONS = 17; #else -constexpr size_t ADMISSION_ALLOCATIONS = 27; +constexpr size_t ADMISSION_ALLOCATIONS = 19; #endif constexpr size_t CLIENT_STATE_ALLOCATIONS = 3; constexpr size_t TIME_BURST_ALLOCATIONS = 0; diff --git a/tests/test_noise_transport.cpp b/tests/test_noise_transport.cpp index 1a28950b..1b232e55 100644 --- a/tests/test_noise_transport.cpp +++ b/tests/test_noise_transport.cpp @@ -389,6 +389,14 @@ TEST(NoiseHandshakeDriver, UnknownPskIdFallsBackToTheSentinelPsk) { EXPECT_EQ(outcome.category, PskCategory::SENTINEL) << "category " << category; EXPECT_FALSE(outcome.peer_read_msg2) << "category " << category; } + + // An id longer than any psk_id is the same miss, though the record it extends is stored. + Msg1Outcome over_long = run_msg1_with_payload([](const std::string& psk_id) { + return R"({"psk_id":")" + psk_id + R"(x","psk_category":"lt"})"; + }); + EXPECT_EQ(over_long.result, HandshakeFrameResult::COMPLETE); + EXPECT_EQ(over_long.category, PskCategory::SENTINEL); + EXPECT_FALSE(over_long.peer_read_msg2); } // messaging.md "noise/handshake": the payload declares which category the referenced PSK is used From 777dd51105f2bd09fd7ad5063946b08302e58905 Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Mon, 2 Nov 2026 13:41:52 -0500 Subject: [PATCH 2/3] Keep the handshake prologue in one platform buffer The Noise prologue was client/init's text, server/init's text and their concatenation, three std::strings and three operator new allocations per handshake. NoiseHandshake now serializes client/init into a PlatformBuffer sized for it and a server/init of up to MAX_SERVER_INIT_BYTES behind it, and copies server/init in when it arrives, so the prologue is the buffer itself. The buffer comes from platform_malloc: if it cannot be had, the connection closes instead of the program aborting. A server/init longer than the cap fails the handshake. Accept to admission: 17 -> 14 allocations under libc++, 19 -> 16 under libstdc++. --- src/connection.cpp | 13 +++++++--- src/connection.h | 10 ++++---- src/noise_handshake.cpp | 46 ++++++++++++++++++++++------------ src/noise_handshake.h | 23 ++++++++++++----- tests/test_allocations.cpp | 4 +-- tests/test_noise_transport.cpp | 26 ++++++++++++++----- 6 files changed, 83 insertions(+), 39 deletions(-) diff --git a/src/connection.cpp b/src/connection.cpp index c2ef3502..e9413b75 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -241,12 +241,17 @@ void SendspinConnection::send_noise_client_init() { // Sent from the text the handshake retains for its prologue, the one JSON message that // does not go through send_json(). const std::string_view client_init = this->noise_handshake_->build_client_init(); - if (!client_init.empty()) { + if (client_init.empty()) { + // No memory for the prologue: without client/init the peer never proceeds, so the + // connection would only hold its nursery slot until the establish deadline. + this->noise_handshake_.reset(); + this->close_silently(SendspinGoodbyeReason::UNAUTHORIZED); + return; + } #ifdef SENDSPIN_ENABLE_MESSAGE_TRACE - this->message_tracer_.trace_outbound_text(client_init); + this->message_tracer_.trace_outbound_text(client_init); #endif - this->send_text_message(client_init.data(), client_init.size()); - } + this->send_text_message(client_init.data(), client_init.size()); } void SendspinConnection::handle_noise_handshake_text(std::string_view text) { diff --git a/src/connection.h b/src/connection.h index 5d8647e3..c119efa0 100644 --- a/src/connection.h +++ b/src/connection.h @@ -328,11 +328,11 @@ class SendspinConnection : public std::enable_shared_from_thisdetach_inbound(); this->close_transport_now(); diff --git a/src/noise_handshake.cpp b/src/noise_handshake.cpp index cfb745de..57cc98b3 100644 --- a/src/noise_handshake.cpp +++ b/src/noise_handshake.cpp @@ -35,10 +35,12 @@ namespace sendspin { // JSON serialization helpers // ============================================================================ -/// @brief Serialize client/init to JSON. +/// @brief Serialize client/init to JSON into `out`, allocated for it and for a server/init of up +/// to MAX_SERVER_INIT_BYTES behind it, the rest of the prologue. /// Format: {"type":"client/init","payload":{"client_id":"...","version":1,"suite":"..."}} -static std::string serialize_client_init(std::string_view client_id, const char* suite_name, - SendspinArenaAllocator& arena) { +/// @return The bytes of client/init written, or 0 when `out` cannot be allocated. +static size_t serialize_client_init(std::string_view client_id, const char* suite_name, + SendspinArenaAllocator& arena, PlatformBuffer& out) { // suite_name is the full name (e.g. NOISE_SUITE_CHACHAPOLY = "Noise_KKpsk2_25519_..."); the // wire value is the suffix after "Noise_KKpsk2_" (connection.md "Cipher Suites"). Strip // that prefix to produce the wire suite string. @@ -55,12 +57,12 @@ static std::string serialize_client_init(std::string_view client_id, const char* doc["payload"]["version"] = PROTOCOL_VERSION; doc["payload"]["suite"] = wire_suite; - // Retained as the prologue, so serialized into a string of its own, reserved to the exact - // length so it is allocated once. - std::string out; - out.reserve(measureJson(doc)); - serializeJson(doc, out); - return out; + // The NUL serializeJson() writes behind client/init lands where server/init goes. + const size_t size = measureJson(doc); + if (!out.allocate(size + MAX_SERVER_INIT_BYTES)) { + return 0; + } + return serializeJson(doc, out.as(), size + 1); } bool build_noise_handshake_message(std::span noise_bytes, JsonDocument& doc) { @@ -313,10 +315,15 @@ std::string_view NoiseHandshake::build_client_init() { } PeerIdText client_id{}; - this->client_init_text_ = - serialize_client_init(this->identity_.peer_id(client_id), this->suite_name_, this->arena_); + this->client_init_size_ = serialize_client_init( + this->identity_.peer_id(client_id), this->suite_name_, this->arena_, this->prologue_); + if (this->client_init_size_ == 0) { + SS_LOGE(TAG, "build_client_init: no memory for the prologue"); + this->state_ = State::ABORTED; + return {}; + } this->state_ = State::WAIT_SERVER_INIT; - return this->client_init_text_; + return {this->prologue_.as(), this->client_init_size_}; } void NoiseHandshake::take_server_error(JsonObjectConst root, const char* log_context) { @@ -416,8 +423,16 @@ bool NoiseHandshake::handle_server_init(int version, const IdText& server_id, return false; } + if (text.size() > MAX_SERVER_INIT_BYTES) { + SS_LOGE(TAG, "handle_server_init: %zu bytes, over the %zu a prologue keeps", text.size(), + MAX_SERVER_INIT_BYTES); + return false; + } + this->server_id_ = server_id; - this->server_init_text_ = text; // Retain exact bytes for prologue + // Exact bytes, behind client/init: the prologue + std::memcpy(this->prologue_.data() + this->client_init_size_, text.data(), text.size()); + this->server_init_size_ = text.size(); SS_LOGD(TAG, "server/init received: server_id=%s", this->server_id_.c_str()); return true; @@ -430,9 +445,8 @@ bool NoiseHandshake::handle_server_init(int version, const IdText& server_id, bool NoiseHandshake::handle_msg1(std::span msg1_bytes, const std::function& send_fn) { // Prologue = exact bytes of client/init || server/init - std::string prologue_str = this->client_init_text_ + this->server_init_text_; - const uint8_t* prologue = reinterpret_cast(prologue_str.data()); - size_t prologue_len = prologue_str.size(); + const uint8_t* prologue = this->prologue_.data(); + const size_t prologue_len = this->client_init_size_ + this->server_init_size_; auto core = run_msg1_core(HandshakeKind::INITIAL, this->identity_, this->record_store_, this->suite_name_, this->server_id_, prologue, prologue_len, diff --git a/src/noise_handshake.h b/src/noise_handshake.h index 0247d30b..d2d0aeb3 100644 --- a/src/noise_handshake.h +++ b/src/noise_handshake.h @@ -134,6 +134,13 @@ std::optional run_rehandshake_msg1( const RecordStore& record_store, const char* suite_name, const std::array& prior_h, SendspinArenaAllocator& arena); +/// @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. +static constexpr size_t MAX_SERVER_INIT_BYTES = 512; + // ============================================================================ // NoiseHandshake class (initial handshake state machine) // ============================================================================ @@ -211,7 +218,8 @@ class NoiseHandshake { /// @brief Validate the fields read from a server/init frame. /// @param version payload.version (0 when absent). /// @param server_id payload.server_id (empty when absent or longer than a peer_id). - /// @param text Exact received bytes, retained for the handshake prologue. + /// @param text Exact received bytes, retained for the handshake prologue; refused when + /// longer than MAX_SERVER_INIT_BYTES. bool handle_server_init(int version, const IdText& server_id, std::string_view text); /// @brief Authenticate and respond to the noise/handshake msg1. @@ -222,8 +230,9 @@ class NoiseHandshake { const std::function& send_fn); // Struct fields - /// Exact bytes of the client/init frame we sent (retained for prologue). - std::string client_init_text_; + /// The prologue: the exact bytes of the client/init we sent, then of the server/init we + /// received, in one buffer sized for both when client/init is built. + PlatformBuffer prologue_; /// Result available after COMPLETE. std::optional result_; @@ -234,9 +243,6 @@ class NoiseHandshake { /// server_id decoded from server/init (43-char base64url). IdText server_id_; - /// Exact bytes of the server/init frame we received (retained for prologue). - std::string server_init_text_; - const char* suite_name_; // Pointer fields @@ -246,6 +252,11 @@ class NoiseHandshake { const Identity& identity_; const RecordStore& record_store_; + // size_t fields + /// Bytes of prologue_ holding client/init, then server/init. + size_t client_init_size_{0}; + size_t server_init_size_{0}; + // 32-bit fields State state_{State::INIT}; }; diff --git a/tests/test_allocations.cpp b/tests/test_allocations.cpp index 8f00f3f3..89f93adc 100644 --- a/tests/test_allocations.cpp +++ b/tests/test_allocations.cpp @@ -430,9 +430,9 @@ constexpr int TIME_BURST_SIZE = 8; // libstdc++ (ESP-IDF's) keeps strings of up to 15 characters inline, libc++ up to 22: the fake // server's name, parsed and then published, allocates only under libstdc++. #ifdef _LIBCPP_VERSION -constexpr size_t ADMISSION_ALLOCATIONS = 17; +constexpr size_t ADMISSION_ALLOCATIONS = 14; #else -constexpr size_t ADMISSION_ALLOCATIONS = 19; +constexpr size_t ADMISSION_ALLOCATIONS = 16; #endif constexpr size_t CLIENT_STATE_ALLOCATIONS = 3; constexpr size_t TIME_BURST_ALLOCATIONS = 0; diff --git a/tests/test_noise_transport.cpp b/tests/test_noise_transport.cpp index 1b232e55..57d3bdd2 100644 --- a/tests/test_noise_transport.cpp +++ b/tests/test_noise_transport.cpp @@ -486,9 +486,9 @@ TEST(NoiseHandshakeDriver, ServerErrorWhileAwaitingMsg1Aborts) { EXPECT_EQ(nh.server_error_reason(), "malformed"); } -// A server/init is accepted only when its type, its server_id and its version are all usable: -// the server_id names the key and goes into the prologue, so both are checked before the -// handshake reads a Noise byte (connection.md "Handshake"). +// 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 }; struct Row { @@ -497,8 +497,14 @@ TEST(NoiseHandshakeDriver, ServerInitIsRefusedUnlessWellFormed) { ServerId server_id; int version; HandshakeFrameResult expected; + size_t padded_to{0}; // the frame's length after an unknown top-level field, 0 for none }; const Row rows[] = { + // The prologue keeps at most MAX_SERVER_INIT_BYTES of server/init. + {"longer than the prologue keeps", "server/init", ServerId::REAL, 1, + HandshakeFrameResult::ABORT, MAX_SERVER_INIT_BYTES + 1}, + {"Control: exactly as long as the prologue keeps", "server/init", ServerId::REAL, 1, + HandshakeFrameResult::NEED_MORE, MAX_SERVER_INIT_BYTES}, // 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}, @@ -530,9 +536,17 @@ TEST(NoiseHandshakeDriver, ServerInitIsRefusedUnlessWellFormed) { } else if (row.server_id == ServerId::NON_CANONICAL) { peer_id = non_canonical_spelling(peer_id); } - EXPECT_EQ(nh.on_text_frame(make_server_init(peer_id, row.version, row.type), - [](const JsonDocument&) { return true; }), - row.expected); + std::string frame = make_server_init(peer_id, row.version, row.type); + if (row.padded_to != 0) { + // An unrecognized payload field, which messaging.md "Forward compatibility" has the + // client ignore, placed before the payload's closing brace. + const size_t field_overhead = std::string_view(R"(,"pad":"")").size(); + ASSERT_LT(frame.size() + field_overhead, row.padded_to); + const size_t xs = row.padded_to - frame.size() - field_overhead; + frame.insert(frame.size() - 2, R"(,"pad":")" + std::string(xs, 'x') + "\""); + ASSERT_EQ(frame.size(), row.padded_to); + } + EXPECT_EQ(nh.on_text_frame(frame, [](const JsonDocument&) { return true; }), row.expected); } } From 80a12d58b131876c25df074ad99d7e3c441a7c75 Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Mon, 2 Nov 2026 14:00:09 -0500 Subject: [PATCH 3/3] Hold Noise handshake scratch in caller buffers NoiseSession::read_msg1() decrypts message 1 in place into a payload buffer the caller sizes (a PlatformBuffer capped at MAX_HANDSHAKE_MESSAGE_BYTES), and write_msg2_and_split() writes message 2 into a fixed 50-byte array, so the handshake no longer copies msg1 or builds msg2 and its payload in vectors. A payload over the cap still aborts the handshake; the driver table now pins both sides of that boundary. Accept to admission: 14 -> 11 allocations under libc++, 16 -> 13 under libstdc++. --- src/client_dispatch.cpp | 7 +++---- src/connection.cpp | 2 +- src/connection.h | 5 +++-- src/crypto/constants.h | 13 ++++++------ src/noise_handshake.cpp | 36 +++++++++++++++++++------------- src/noise_handshake.h | 13 ++++++------ src/noise_session.cpp | 31 ++++++++------------------- src/noise_session.h | 20 ++++++++++++------ tests/test_allocations.cpp | 4 ++-- tests/test_noise_rehandshake.cpp | 17 +++++++-------- tests/test_noise_transport.cpp | 36 ++++++++++++++++++++++++-------- 11 files changed, 100 insertions(+), 84 deletions(-) diff --git a/src/client_dispatch.cpp b/src/client_dispatch.cpp index 3733a2a8..5f9f609c 100644 --- a/src/client_dispatch.cpp +++ b/src/client_dispatch.cpp @@ -542,10 +542,9 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const // is ordered with the decrypt of the next frame and with every send // (connection.md "Re-handshake"). SS_LOGI(TAG, "noise/handshake received in-band: starting re-handshake"); - const std::optional msg1_bytes = - parsed.extract([](JsonObjectConst root) { - return read_noise_handshake_data(root, "re-handshake"); - }); + std::optional msg1_bytes = parsed.extract([](JsonObjectConst root) { + return read_noise_handshake_data(root, "re-handshake"); + }); if (!msg1_bytes.has_value() || !conn->handle_noise_rehandshake({msg1_bytes->data(), msg1_bytes->size()})) { SS_LOGW(TAG, "noise/handshake re-handshake failed; closing connection"); diff --git a/src/connection.cpp b/src/connection.cpp index e9413b75..d2f66e81 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -308,7 +308,7 @@ void SendspinConnection::handle_noise_handshake_text(std::string_view text) { // NEED_MORE, or COMPLETE handled above: nothing else to do until the next frame. } -bool SendspinConnection::handle_noise_rehandshake(std::span msg1_bytes) { +bool SendspinConnection::handle_noise_rehandshake(std::span msg1_bytes) { // Runs on the protocol task (from SendspinClient::process_json_message() for a decrypted // "noise/handshake" message, itself only reachable post-COMPLETE, so this always runs on // the same thread as the decrypt path, sequential with it and never concurrent). diff --git a/src/connection.h b/src/connection.h index c119efa0..07797844 100644 --- a/src/connection.h +++ b/src/connection.h @@ -221,10 +221,11 @@ class SendspinConnection : public std::enable_shared_from_this msg1_bytes); + bool handle_noise_rehandshake(std::span msg1_bytes); /// @brief Sends a JSON message: serialized straight into the Noise transport's send buffer /// (NoiseTransport::stage_json()), then encrypted there once the transport is active, or sent diff --git a/src/crypto/constants.h b/src/crypto/constants.h index da3abf19..3c11c231 100644 --- a/src/crypto/constants.h +++ b/src/crypto/constants.h @@ -72,13 +72,12 @@ static constexpr int PROTOCOL_VERSION = 1; /// Plaintext includes the leading type byte, so usable payload is one byte less. static constexpr size_t MAX_TRANSPORT_PLAINTEXT = 65535 - 16; // = 65519 -/// @brief Buffer size for a single Noise handshake control message (msg1 decrypted payload, -/// msg2 ciphertext): 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 message does not fit (verified against -/// noise_handshakestate_read_message()'s payload->max_size check), so a legitimate handshake -/// message exceeding this size fails the handshake rather than corrupting memory. +/// @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. static constexpr size_t MAX_HANDSHAKE_MESSAGE_BYTES = 512; /// @brief Per-connection reassembly buffer cap: 1 MiB. diff --git a/src/noise_handshake.cpp b/src/noise_handshake.cpp index 57cc98b3..1a7bef33 100644 --- a/src/noise_handshake.cpp +++ b/src/noise_handshake.cpp @@ -23,9 +23,9 @@ #include "platform/memory.h" #include +#include #include #include -#include static const char* const TAG = "sendspin.noise_handshake"; @@ -93,7 +93,7 @@ struct Msg1CoreResult { /// The PSK record that admitted the connection. ResolvedPsk resolved_psk; /// Serialized noise/handshake msg2 bytes (not yet wrapped in a JSON envelope). - std::vector msg2_bytes; + NoiseMsg2 msg2_bytes{}; }; /// @brief Which handshake a msg1 belongs to. @@ -131,8 +131,7 @@ const char* to_cstr(HandshakeKind kind) { std::optional run_msg1_core(HandshakeKind kind, const Identity& identity, const RecordStore& record_store, const char* suite_name, const IdText& server_id, const uint8_t* prologue, - size_t prologue_len, - std::span msg1_bytes, + size_t prologue_len, std::span msg1_bytes, SendspinArenaAllocator& arena) { const char* log_prefix = to_cstr(kind); auto server_pub = public_key_from_peer_id(server_id.view()); @@ -152,9 +151,16 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& return std::nullopt; } - auto msg1_payload = session->read_msg1(msg1_bytes.data(), msg1_bytes.size()); - if (msg1_payload.empty()) { - SS_LOGE(TAG, "%s: read_msg1 failed (auth error in msg1 static DH)", log_prefix); + // The payload is shorter than the message, and MAX_HANDSHAKE_MESSAGE_BYTES bounds it. + PlatformBuffer msg1_payload; + if (!msg1_payload.allocate(std::min(msg1_bytes.size(), MAX_HANDSHAKE_MESSAGE_BYTES))) { + SS_LOGE(TAG, "%s: no memory for the msg1 payload", log_prefix); + return std::nullopt; + } + const std::optional payload_size = + session->read_msg1(msg1_bytes, {msg1_payload.data(), msg1_payload.size()}); + if (!payload_size.has_value()) { + SS_LOGE(TAG, "%s: read_msg1 failed", log_prefix); return std::nullopt; } @@ -162,7 +168,7 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& // payload is released as soon as its two fields are copied out, so the msg2 envelope the // caller builds has the arena to itself. ParsedJsonMessage payload(arena); - if (!payload.parse(reinterpret_cast(msg1_payload.data()), msg1_payload.size())) { + if (!payload.parse(reinterpret_cast(msg1_payload.data()), payload_size.value())) { SS_LOGE(TAG, "%s: failed to parse msg1 payload JSON", log_prefix); return std::nullopt; } @@ -241,14 +247,13 @@ std::optional run_msg1_core(HandshakeKind kind, const Identity& } // Write msg2 (payload: `{}`) and split to transport mode - std::vector msg2_bytes; + NoiseMsg2 msg2_bytes{}; if (!session->write_msg2_and_split(msg2_bytes)) { SS_LOGE(TAG, "%s: write_msg2_and_split failed", log_prefix); return std::nullopt; } - return Msg1CoreResult{std::move(session.value()), std::move(resolved.value()), - std::move(msg2_bytes)}; + return Msg1CoreResult{std::move(session.value()), std::move(resolved.value()), msg2_bytes}; } /// @brief Build a NoiseHandshakeResult from a completed Msg1CoreResult. Shared by @@ -442,7 +447,7 @@ bool NoiseHandshake::handle_server_init(int version, const IdText& server_id, // Private: handle noise/handshake msg1 // ============================================================================ -bool NoiseHandshake::handle_msg1(std::span msg1_bytes, +bool NoiseHandshake::handle_msg1(std::span msg1_bytes, const std::function& send_fn) { // Prologue = exact bytes of client/init || server/init const uint8_t* prologue = this->prologue_.data(); @@ -475,7 +480,7 @@ bool NoiseHandshake::handle_msg1(std::span msg1_bytes, // ============================================================================ std::optional run_rehandshake_msg1( - std::span msg1_bytes, std::string_view server_id, const Identity& identity, + std::span msg1_bytes, std::string_view server_id, const Identity& identity, const RecordStore& record_store, const char* suite_name, const std::array& prior_h, SendspinArenaAllocator& arena) { // The id the initial handshake recorded; run_msg1_core()'s decode check refuses an empty one. @@ -494,9 +499,10 @@ std::optional run_rehandshake_msg1( SS_LOGI(TAG, "Re-handshake complete: server_id=%s psk_category=%d", known_server_id.c_str(), static_cast(core->resolved_psk.category)); - NoiseHandshakeResult result = make_handshake_result(std::move(core.value()), known_server_id); // The caller wraps msg2 in its noise/handshake envelope and sends it encrypted. - result.msg2_bytes = std::move(core->msg2_bytes); + const NoiseMsg2 msg2_bytes = core->msg2_bytes; + NoiseHandshakeResult result = make_handshake_result(std::move(core.value()), known_server_id); + result.msg2_bytes = msg2_bytes; return result; } diff --git a/src/noise_handshake.h b/src/noise_handshake.h index d2d0aeb3..000ad309 100644 --- a/src/noise_handshake.h +++ b/src/noise_handshake.h @@ -54,7 +54,6 @@ #include #include #include -#include namespace sendspin { @@ -71,7 +70,7 @@ struct NoiseHandshakeResult { /// The Noise msg2 bytes to send to the peer, in a noise/handshake envelope /// (build_noise_handshake_message()). Set only for re-handshake results (initial handshake /// sends msg2 inline). - std::vector msg2_bytes; + NoiseMsg2 msg2_bytes{}; }; /// @brief Result of processing one incoming WS frame during the handshake. @@ -120,7 +119,8 @@ std::optional read_noise_handshake_data(JsonObjectConst envelope /// 4. Bind the resolved PSK onto the same session (NoiseSession::set_psk). /// 5. Write msg2 and split -> new session. /// -/// @param msg1_bytes The re-handshake msg1 (Noise bytes, decoded from the envelope). +/// @param msg1_bytes The re-handshake msg1 (Noise bytes, decoded from the envelope); cleared +/// on return. /// @param server_id Known server peer_id (43-char base64url) from the prior handshake. /// @param identity Our static X25519 identity. /// @param record_store Record store for psk_id resolution (read-only on protocol task). @@ -130,7 +130,7 @@ std::optional read_noise_handshake_data(JsonObjectConst envelope /// @return Populated NoiseHandshakeResult (session + msg2_bytes to send) on success, /// or nullopt on any failure (caller should close the WebSocket). std::optional run_rehandshake_msg1( - std::span msg1_bytes, std::string_view server_id, const Identity& identity, + std::span msg1_bytes, std::string_view server_id, const Identity& identity, const RecordStore& record_store, const char* suite_name, const std::array& prior_h, SendspinArenaAllocator& arena); @@ -223,10 +223,11 @@ class NoiseHandshake { bool handle_server_init(int version, const IdText& server_id, std::string_view text); /// @brief Authenticate and respond to the noise/handshake msg1. - /// @param msg1_bytes The msg1 Noise bytes, read from the frame (read_noise_handshake_data()). + /// @param msg1_bytes The msg1 Noise bytes, read from the frame (read_noise_handshake_data()); + /// cleared on return. /// @param send_fn Sends the msg2 frame back to the peer. /// @return true when msg1 authenticated and msg2 was sent. - bool handle_msg1(std::span msg1_bytes, + bool handle_msg1(std::span msg1_bytes, const std::function& send_fn); // Struct fields diff --git a/src/noise_session.cpp b/src/noise_session.cpp index a3f3964e..917b0024 100644 --- a/src/noise_session.cpp +++ b/src/noise_session.cpp @@ -172,37 +172,28 @@ std::optional NoiseSession::as_responder(const char* suite_name, // Handshake // ============================================================================ -std::vector NoiseSession::read_msg1(const uint8_t* msg1_bytes, size_t msg1_len) { +std::optional NoiseSession::read_msg1(std::span msg1, std::span payload) { if (!this->hs_) { SS_LOGE(TAG, "read_msg1: handshake state is null"); - return {}; + return std::nullopt; } if (noise_handshakestate_get_action(this->hs_) != NOISE_ACTION_READ_MESSAGE) { SS_LOGE(TAG, "read_msg1: unexpected handshake action (not READ_MESSAGE)"); - return {}; + return std::nullopt; } - // Payload buffer large enough for any handshake payload; see - // MAX_HANDSHAKE_MESSAGE_BYTES in crypto/constants.h. - std::vector payload_buf(MAX_HANDSHAKE_MESSAGE_BYTES); - - // Input buffer: noise-c needs a mutable copy - std::vector in_buf(msg1_bytes, msg1_bytes + msg1_len); - NoiseBuffer msg_in; NoiseBuffer payload_out; - noise_buffer_set_input(msg_in, in_buf.data(), in_buf.size()); - noise_buffer_set_output(payload_out, payload_buf.data(), payload_buf.size()); + noise_buffer_set_input(msg_in, msg1.data(), msg1.size()); + noise_buffer_set_output(payload_out, payload.data(), payload.size()); int err = noise_handshakestate_read_message(this->hs_, &msg_in, &payload_out); if (err != NOISE_ERROR_NONE) { SS_LOGW(TAG, "read_msg1: noise_handshakestate_read_message failed (err=%d)", err); - return {}; + return std::nullopt; } - - payload_buf.resize(payload_out.size); - return payload_buf; + return payload_out.size; } bool NoiseSession::set_psk(const uint8_t* psk) { @@ -220,7 +211,7 @@ bool NoiseSession::set_psk(const uint8_t* psk) { return true; } -bool NoiseSession::write_msg2_and_split(std::vector& msg2_out) { +bool NoiseSession::write_msg2_and_split(NoiseMsg2& msg2_out) { if (!this->hs_) { SS_LOGE(TAG, "write_msg2_and_split: handshake state is null"); return false; @@ -233,13 +224,10 @@ bool NoiseSession::write_msg2_and_split(std::vector& msg2_out) { // msg2 plaintext payload: `{}` (2 bytes UTF-8) const uint8_t msg2_payload[] = {'{', '}'}; + static_assert(NOISE_MSG2_BYTES == X25519_KEY_SIZE + sizeof(msg2_payload) + AEAD_TAG_SIZE); NoiseBuffer payload_in; noise_buffer_set_input(payload_in, const_cast(msg2_payload), sizeof(msg2_payload)); - // Output buffer: handshake message 2 is small; see MAX_HANDSHAKE_MESSAGE_BYTES in - // crypto/constants.h. - msg2_out.resize(MAX_HANDSHAKE_MESSAGE_BYTES); - NoiseBuffer msg_out; noise_buffer_set_output(msg_out, msg2_out.data(), msg2_out.size()); @@ -249,7 +237,6 @@ bool NoiseSession::write_msg2_and_split(std::vector& msg2_out) { err); return false; } - msg2_out.resize(msg_out.size); if (noise_handshakestate_get_action(this->hs_) != NOISE_ACTION_SPLIT) { SS_LOGE(TAG, "write_msg2_and_split: expected SPLIT action after write, got %d", diff --git a/src/noise_session.h b/src/noise_session.h index 58a98a70..ac8b39ad 100644 --- a/src/noise_session.h +++ b/src/noise_session.h @@ -36,8 +36,7 @@ #include #include #include -#include -#include +#include // noise-c forward declarations: the implementation includes the actual headers. struct NoiseHandshakeState_s; @@ -47,6 +46,13 @@ typedef struct NoiseCipherState_s NoiseCipherState; namespace sendspin { +/// @brief Bytes of Noise message 2: the responder's ephemeral key, then the `{}` payload +/// write_msg2_and_split() sends and its authentication tag. +static constexpr size_t NOISE_MSG2_BYTES = 32 + 2 + 16; + +/// @brief Noise message 2, which is always NOISE_MSG2_BYTES long. +using NoiseMsg2 = std::array; + /// @brief Noise KKpsk2 session: handshake and transport state. /// /// Construct via the factory `NoiseSession::as_responder()`. @@ -91,9 +97,11 @@ class NoiseSession { // Handshake // ======================================== - /// @brief Decrypt Noise message 1 and return its plaintext payload. - /// @return Decrypted payload, or empty vector on auth failure. - std::vector read_msg1(const uint8_t* msg1_bytes, size_t msg1_len); + /// @brief Decrypt Noise message 1 into `payload`. + /// @param msg1 The message; noise-c decrypts its parts in place and clears it. + /// @param payload Output for the plaintext payload; must not overlap `msg1`. + /// @return The payload's size, or nullopt on auth failure or a payload larger than `payload`. + std::optional read_msg1(std::span msg1, std::span payload); /// @brief Bind (or rebind) the pre-shared key on this handshake state. /// @@ -109,7 +117,7 @@ class NoiseSession { /// @brief Encrypt Noise message 2 (payload = `{}` UTF-8) and split into /// transport cipher states. /// @return true on success; transport mode is now active. - bool write_msg2_and_split(std::vector& msg2_out); + bool write_msg2_and_split(NoiseMsg2& msg2_out); /// @brief The 32-byte Noise handshake hash `h` (available after split). const std::array& handshake_hash() const { diff --git a/tests/test_allocations.cpp b/tests/test_allocations.cpp index 89f93adc..c29e268d 100644 --- a/tests/test_allocations.cpp +++ b/tests/test_allocations.cpp @@ -430,9 +430,9 @@ constexpr int TIME_BURST_SIZE = 8; // libstdc++ (ESP-IDF's) keeps strings of up to 15 characters inline, libc++ up to 22: the fake // server's name, parsed and then published, allocates only under libstdc++. #ifdef _LIBCPP_VERSION -constexpr size_t ADMISSION_ALLOCATIONS = 14; +constexpr size_t ADMISSION_ALLOCATIONS = 11; #else -constexpr size_t ADMISSION_ALLOCATIONS = 16; +constexpr size_t ADMISSION_ALLOCATIONS = 13; #endif constexpr size_t CLIENT_STATE_ALLOCATIONS = 3; constexpr size_t TIME_BURST_ALLOCATIONS = 0; diff --git a/tests/test_noise_rehandshake.cpp b/tests/test_noise_rehandshake.cpp index 5b577ba9..c5f0a058 100644 --- a/tests/test_noise_rehandshake.cpp +++ b/tests/test_noise_rehandshake.cpp @@ -234,20 +234,16 @@ static std::optional run_rehandshake( return std::nullopt; } - auto result = - run_rehandshake_msg1(msg1_bytes_of(msg1_json), init.server_id.peer_id(), init.client_id, rs, - suite_name.c_str(), prior_h, TestArena()); + std::vector msg1_bytes = msg1_bytes_of(msg1_json); + auto result = run_rehandshake_msg1(msg1_bytes, init.server_id.peer_id(), init.client_id, rs, + suite_name.c_str(), prior_h, TestArena()); if (!result.has_value()) { ADD_FAILURE() << "run_rehandshake_msg1 returned nullopt"; return std::nullopt; } // The result carries msg2's Noise bytes; the initiator reads them directly. - std::vector& msg2_bytes = result->msg2_bytes; - if (msg2_bytes.empty()) { - ADD_FAILURE() << "the re-handshake produced no msg2"; - return std::nullopt; - } + NoiseMsg2& msg2_bytes = result->msg2_bytes; std::vector msg2_payload_buf(4096); NoiseBuffer msg2_in; @@ -389,8 +385,9 @@ TEST(NoiseRehandshake, UnknownPskIdAborts) { ASSERT_FALSE(msg1_json.empty()); // run_rehandshake_msg1 must return nullopt (unknown psk_id). - auto result = run_rehandshake_msg1(msg1_bytes_of(msg1_json), init.server_id.peer_id(), - init.client_id, empty_rs, suite.c_str(), prior_h, TestArena()); + std::vector msg1_bytes = msg1_bytes_of(msg1_json); + auto result = run_rehandshake_msg1(msg1_bytes, init.server_id.peer_id(), init.client_id, + empty_rs, suite.c_str(), prior_h, TestArena()); EXPECT_FALSE(result.has_value()) << "run_rehandshake_msg1 should fail with an unknown psk_id"; } diff --git a/tests/test_noise_transport.cpp b/tests/test_noise_transport.cpp index 57d3bdd2..96782aef 100644 --- a/tests/test_noise_transport.cpp +++ b/tests/test_noise_transport.cpp @@ -102,6 +102,17 @@ struct RefusingAllocator : ArduinoJson::Allocator { void* reallocate(void* /*ptr*/, size_t /*new_size*/) override { return nullptr; } }; +/// Pads `json` to exactly `size` bytes with an unrecognized field, which messaging.md "Forward +/// compatibility" has the client ignore, inserted before the closing brace that sits +/// `brace_from_end` bytes from the end. +void pad_with_unknown_field(std::string& json, size_t size, size_t brace_from_end) { + const size_t field_overhead = std::string_view(R"(,"pad":"")").size(); + ASSERT_LT(json.size() + field_overhead, size); + const size_t xs = size - json.size() - field_overhead; + json.insert(json.size() - brace_from_end, R"(,"pad":")" + std::string(xs, 'x') + "\""); + ASSERT_EQ(json.size(), size); +} + } // namespace // ============================================================================ @@ -538,13 +549,9 @@ TEST(NoiseHandshakeDriver, ServerInitIsRefusedUnlessWellFormed) { } std::string frame = make_server_init(peer_id, row.version, row.type); if (row.padded_to != 0) { - // An unrecognized payload field, which messaging.md "Forward compatibility" has the - // client ignore, placed before the payload's closing brace. - const size_t field_overhead = std::string_view(R"(,"pad":"")").size(); - ASSERT_LT(frame.size() + field_overhead, row.padded_to); - const size_t xs = row.padded_to - frame.size() - field_overhead; - frame.insert(frame.size() - 2, R"(,"pad":")" + std::string(xs, 'x') + "\""); - ASSERT_EQ(frame.size(), row.padded_to); + // Inside the payload, whose closing brace precedes the envelope's. + pad_with_unknown_field(frame, row.padded_to, 2); + ASSERT_FALSE(HasFatalFailure()); } EXPECT_EQ(nh.on_text_frame(frame, [](const JsonDocument&) { return true; }), row.expected); } @@ -1292,15 +1299,21 @@ TEST(NoiseTransport, EncryptInPlaceRefusesMissingTagRoomAndMarksAFailedEncrypt) // ============================================================================ // Noise message 1 that cannot be read as one aborts the handshake rather than being retried or -// ignored (connection.md "Failure Handling"). +// ignored (connection.md "Failure Handling"), and so does one whose payload is longer than the +// MAX_HANDSHAKE_MESSAGE_BYTES the client decrypts. TEST(NoiseHandshakeDriver, MalformedMsg1Aborts) { struct Row { const char* name; bool well_formed; // build message 1 with a real initiator std::vector noise_bytes; // the frame's noise bytes when it is not well formed HandshakeFrameResult expected; + size_t payload_size{0}; // a well-formed payload padded to this length, 0 for unpadded }; const Row rows[] = { + {"a payload longer than the client decrypts", true, {}, HandshakeFrameResult::ABORT, + MAX_HANDSHAKE_MESSAGE_BYTES + 1}, + {"Control: a payload exactly as long as the client decrypts", true, {}, + HandshakeFrameResult::COMPLETE, MAX_HANDSHAKE_MESSAGE_BYTES}, {"empty noise bytes", false, {}, HandshakeFrameResult::ABORT}, // Well-formed base64url, but fails Noise authentication as message 1. {"garbage of a plausible length", false, std::vector(64, 0xAB), @@ -1341,7 +1354,12 @@ TEST(NoiseHandshakeDriver, MalformedMsg1Aborts) { ASSERT_NE(init_hs_raw, nullptr); HsGuard guard(init_hs_raw); - const std::string msg1_text = build_msg1_envelope(init_hs_raw, psk_id_for(psk)); + std::string payload = R"({"psk_id":")" + psk_id_for(psk) + R"(","psk_category":"lt"})"; + if (row.payload_size != 0) { + pad_with_unknown_field(payload, row.payload_size, 1); + ASSERT_FALSE(HasFatalFailure()); + } + const std::string msg1_text = build_msg1_envelope_with_payload(init_hs_raw, payload); ASSERT_FALSE(msg1_text.empty()); EXPECT_EQ(nh.on_text_frame(msg1_text, send_fn), row.expected); }