Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 6 additions & 9 deletions src/client_dispatch.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -511,16 +511,14 @@ void SendspinClient::process_json_message(SendspinConnection& connection, const
if (parsed.extract<process_server_hello_message>(&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;
}
Expand All @@ -544,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<PlatformBuffer> msg1_bytes =
parsed.extract([](JsonObjectConst root) {
return read_noise_handshake_data(root, "re-handshake");
});
std::optional<PlatformBuffer> 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");
Expand Down
33 changes: 18 additions & 15 deletions src/connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -286,8 +291,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();
Expand All @@ -303,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<const uint8_t> msg1_bytes) {
bool SendspinConnection::handle_noise_rehandshake(std::span<uint8_t> 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).
Expand Down Expand Up @@ -341,11 +346,9 @@ bool SendspinConnection::handle_noise_rehandshake(std::span<const uint8_t> 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;
Expand Down Expand Up @@ -379,9 +382,9 @@ bool SendspinConnection::handle_noise_rehandshake(std::span<const uint8_t> 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<int>(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<int>(this->get_psk_category()));
return true;
}

Expand Down
41 changes: 21 additions & 20 deletions src/connection.h
Original file line number Diff line number Diff line change
Expand Up @@ -221,10 +221,11 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
/// the new keys; neither hello is re-sent, and the manager's nursery is not involved (the
/// connection stays current/established throughout, with no drop/reconnect).
///
/// @param msg1_bytes The re-handshake msg1 Noise bytes (read_noise_handshake_data()).
/// @param msg1_bytes The re-handshake msg1 Noise bytes (read_noise_handshake_data()); cleared
/// on return.
/// @return true on success (session swapped; a post-swap server/activate is expected next).
/// false on any failure (caller should close the WebSocket).
bool handle_noise_rehandshake(std::span<const uint8_t> msg1_bytes);
bool handle_noise_rehandshake(std::span<uint8_t> 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
Expand Down Expand Up @@ -328,11 +329,11 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
/// connection.md "Failure Handling": handshake-phase failures, an AEAD failure once in
/// transport mode, and malformed fragment sequences all close the WebSocket without sending a
/// client/goodbye (or any other application-level message). Called on the protocol task, from
/// the receive path and settle_noise_send(), so this routes to close_transport_now()
/// (non-blocking on every platform) instead of disconnect() (which can block on a transport
/// join; see close_transport_now()).
/// The inbound gate is detached first, so nothing the peer sent after the failure is processed,
/// and the protocol task reports the loss.
/// the receive path, settle_noise_send() and send_noise_client_init(), so this routes to
/// close_transport_now() (non-blocking on every platform) instead of disconnect() (which can
/// block on a transport join; see close_transport_now()). The inbound gate is detached first,
/// so nothing the peer sent after the failure is processed, and the protocol task reports the
/// loss.
void close_silently(SendspinGoodbyeReason /*reason*/) {
this->detach_inbound();
this->close_transport_now();
Expand Down Expand Up @@ -390,9 +391,10 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
}

/// @brief Returns the psk_id of the matched PSK (set at COMPLETE and rewritten at every
/// in-band re-handshake; empty for Sentinel or when no Noise handshake has completed).
/// in-band re-handshake; SENTINEL_PSK_ID for the Sentinel PSK, empty until a Noise handshake
/// completes).
/// Protocol task only, the thread that writes it.
const std::string& get_psk_id() const {
const IdText& get_psk_id() const {
return this->psk_id_;
}

Expand Down Expand Up @@ -691,11 +693,11 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio

/// @brief Sets the server_id and PSK metadata from the Noise handshake result.
/// Called at COMPLETE in connection.cpp.
void set_noise_handshake_result(const std::string& server_id, PskCategory psk_category,
const std::string& psk_id) {
void set_noise_handshake_result(std::string_view server_id, PskCategory psk_category,
std::string_view psk_id) {
this->server_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.
Expand All @@ -717,11 +719,10 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
this->server_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);
}

// ========================================
Expand Down Expand Up @@ -1098,10 +1099,10 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
/// Retained for re-handshake: Noise suite name supplied at init_noise_handshake().
const char* noise_suite_name_ = nullptr;

/// psk_id of the PSK matched by the Noise handshake (empty for Sentinel, or when no
/// Noise handshake has completed). Written at handshake COMPLETE and at every in-band
/// psk_id of the PSK matched by the Noise handshake (SENTINEL_PSK_ID for the Sentinel PSK,
/// empty until a Noise handshake completes). Written at handshake COMPLETE and at every in-band
/// re-handshake. Protocol task only.
std::string psk_id_{};
IdText psk_id_{};

// Struct fields

Expand Down
10 changes: 5 additions & 5 deletions src/connection_manager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -916,12 +916,12 @@ std::vector<std::string> 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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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();
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/connection_manager.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions src/connection_manager_pairing.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -931,16 +931,16 @@ 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());

// Drop the matched pairing record (messaging.md "server/unpair"). The RAM erase runs here,
// 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();
}

Expand Down
13 changes: 6 additions & 7 deletions src/crypto/constants.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
52 changes: 51 additions & 1 deletion src/crypto/keys.h
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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<char, PEER_ID_SIZE + 2>;

/// @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<uint8_t>(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<char, PEER_ID_SIZE + 1> 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
Expand Down
Loading
Loading