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
22 changes: 9 additions & 13 deletions src/connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
#include "time_filter.h"

#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstring>
#include <memory>
Expand Down Expand Up @@ -225,8 +226,7 @@ std::optional<int64_t> SendspinConnection::claim_time_frame(int64_t client_trans
void SendspinConnection::init_noise_handshake(const Identity& identity,
const RecordStore& record_store,
const char* suite_name) {
this->noise_handshake_ =
std::make_unique<NoiseHandshake>(identity, record_store, suite_name, *this->json_arena_);
this->noise_handshake_.emplace(identity, record_store, suite_name, *this->json_arena_);
// Retain for re-handshake: these pointers outlive connections (owned by the
// SendspinClient that constructed the manager which called this).
this->noise_identity_ = &identity;
Expand Down Expand Up @@ -264,7 +264,8 @@ void SendspinConnection::handle_noise_handshake_text(std::string_view text) {
return this->send_json(msg) == SsErr::OK;
};

HandshakeFrameResult result = this->noise_handshake_->on_text_frame(text, send_fn);
std::optional<NoiseHandshakeResult> outcome;
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();
Expand All @@ -283,16 +284,11 @@ void SendspinConnection::handle_noise_handshake_text(std::string_view text) {
}

if (result == HandshakeFrameResult::COMPLETE) {
auto outcome = this->noise_handshake_->take_result();
if (!outcome.has_value()) {
SS_LOGE(TAG, "Noise handshake: COMPLETE but no result");
this->noise_handshake_.reset();
return;
}
assert(outcome.has_value() && "a completed handshake hands out its result");
// 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.view(), outcome->resolved_psk.category,
outcome->resolved_psk.psk_id.view());
this->set_noise_handshake_result(outcome->server_id.view(), outcome->psk_category,
outcome->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 Down Expand Up @@ -372,8 +368,8 @@ bool SendspinConnection::handle_noise_rehandshake(std::span<uint8_t> msg1_bytes)
}

// Update PSK metadata from the re-handshake result. server_id is unchanged (same server).
this->psk_category_ = result->resolved_psk.category;
this->psk_id_ = result->resolved_psk.psk_id;
this->psk_category_ = result->psk_category;
this->psk_id_ = result->psk_id;

// pairing.md "Pairing index": a re-handshake starts a fresh count for the pairing_index /
// CPace-sid counter, same as an initial handshake.
Expand Down
9 changes: 5 additions & 4 deletions src/connection.h
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio

/// @brief Return true if a Noise handshake driver has been installed on this connection.
bool has_noise_handshake() const {
return this->noise_handshake_ != nullptr;
return this->noise_handshake_.has_value();
}

/// @brief Return the full Noise suite name supplied at init_noise_handshake() (e.g.
Expand Down Expand Up @@ -1033,15 +1033,16 @@ class SendspinConnection : public std::enable_shared_from_this<SendspinConnectio
/// Sends this connection's client/time bursts and feeds its time filter. Protocol task only.
SendspinTimeBurst time_burst_{};

/// Noise handshake driver, from init_noise_handshake() until the handshake completes or
/// aborts. Protocol task only.
std::optional<NoiseHandshake> noise_handshake_;

// Pointer fields

/// Time synchronization filter (Kalman-based). Shared so role threads can hold it without
/// holding this connection (ConnectionManager::time_filter()).
std::shared_ptr<SendspinTimeFilter> time_filter_;

/// Noise handshake driver (active from connection open until handshake complete).
std::unique_ptr<NoiseHandshake> noise_handshake_;

/// Retained for re-handshake: pointer to the client identity supplied at
/// init_noise_handshake(). Lifetime is owned by SendspinClient (outlives connections).
const Identity* noise_identity_{nullptr};
Expand Down
54 changes: 25 additions & 29 deletions src/noise_handshake.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,11 @@ namespace {
struct Msg1CoreResult {
/// The session, split into transport cipher states, with the resolved PSK bound.
NoiseSession session;
/// The PSK record that admitted the connection.
ResolvedPsk resolved_psk;
/// psk_id of the PSK that admitted the connection. Its bytes stay in run_msg1_core()'s
/// ResolvedPsk, wiped when that returns.
IdText psk_id;
/// Category of that PSK.
PskCategory psk_category{PskCategory::SENTINEL};
/// Serialized noise/handshake msg2 bytes (not yet wrapped in a JSON envelope).
NoiseMsg2 msg2_bytes{};
};
Expand Down Expand Up @@ -253,21 +256,10 @@ std::optional<Msg1CoreResult> run_msg1_core(HandshakeKind kind, const Identity&
return std::nullopt;
}

return Msg1CoreResult{std::move(session.value()), std::move(resolved.value()), msg2_bytes};
}

/// @brief Build a NoiseHandshakeResult from a completed Msg1CoreResult. Shared by
/// NoiseHandshake::handle_msg1 (initial handshake) and run_rehandshake_msg1: both assemble the
/// result identically from the core's session and resolved_psk; only msg2 differs, so the
/// 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, const IdText& server_id) {
NoiseHandshakeResult result;
result.session = std::make_unique<NoiseSession>(std::move(core.session));
result.server_id = server_id;
result.resolved_psk = std::move(core.resolved_psk);
return result;
return Msg1CoreResult{.session = std::move(session.value()),
.psk_id = resolved->psk_id,
.psk_category = resolved->category,
.msg2_bytes = msg2_bytes};
}

} // namespace
Expand Down Expand Up @@ -340,7 +332,8 @@ void NoiseHandshake::take_server_error(JsonObjectConst root, const char* log_con
}

HandshakeFrameResult NoiseHandshake::on_text_frame(
std::string_view text, const std::function<bool(const JsonDocument&)>& send_fn) {
std::string_view text, const std::function<bool(const JsonDocument&)>& send_fn,
std::optional<NoiseHandshakeResult>& completed) {
if (this->state_ != State::WAIT_SERVER_INIT && this->state_ != State::WAIT_MSG1) {
SS_LOGE(TAG, "on_text_frame: no frame expected in this state");
this->state_ = State::ABORTED;
Expand Down Expand Up @@ -401,7 +394,7 @@ HandshakeFrameResult NoiseHandshake::on_text_frame(
}

if (!msg1_bytes.has_value() ||
!this->handle_msg1({msg1_bytes->data(), msg1_bytes->size()}, send_fn)) {
!this->handle_msg1({msg1_bytes->data(), msg1_bytes->size()}, send_fn, completed)) {
this->state_ = State::ABORTED;
return HandshakeFrameResult::ABORT;
}
Expand Down Expand Up @@ -448,7 +441,8 @@ bool NoiseHandshake::handle_server_init(int version, const IdText& server_id,
// ============================================================================

bool NoiseHandshake::handle_msg1(std::span<uint8_t> msg1_bytes,
const std::function<bool(const JsonDocument&)>& send_fn) {
const std::function<bool(const JsonDocument&)>& send_fn,
std::optional<NoiseHandshakeResult>& completed) {
// Prologue = exact bytes of client/init || server/init
const uint8_t* prologue = this->prologue_.data();
const size_t prologue_len = this->client_init_size_ + this->server_init_size_;
Expand All @@ -468,9 +462,10 @@ bool NoiseHandshake::handle_msg1(std::span<uint8_t> msg1_bytes,
}

SS_LOGI(TAG, "Noise handshake complete: server_id=%s psk_category=%d", this->server_id_.c_str(),
static_cast<int>(core->resolved_psk.category));
static_cast<int>(core->psk_category));

this->result_ = make_handshake_result(std::move(core.value()), this->server_id_);
// 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);

return true;
}
Expand All @@ -497,13 +492,14 @@ std::optional<NoiseHandshakeResult> run_rehandshake_msg1(
}

SS_LOGI(TAG, "Re-handshake complete: server_id=%s psk_category=%d", known_server_id.c_str(),
static_cast<int>(core->resolved_psk.category));

// The caller wraps msg2 in its noise/handshake envelope and sends it encrypted.
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;
static_cast<int>(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,
// since this function also returns nullopt.
return std::optional<NoiseHandshakeResult>(std::in_place, std::move(core->session),
known_server_id, core->psk_id, core->psk_category,
core->msg2_bytes);
}

} // namespace sendspin
35 changes: 17 additions & 18 deletions src/noise_handshake.h
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
#include <array>
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <span>
#include <string>
Expand All @@ -62,11 +61,14 @@ class SendspinArenaAllocator;
/// @brief Outcome of a successful Noise handshake (initial or re-handshake).
struct NoiseHandshakeResult {
/// The cipher session ready for transport-mode encrypt/decrypt.
std::unique_ptr<NoiseSession> session;
NoiseSession session;
/// Server's public key peer_id (43-char base64url).
IdText server_id;
/// The PSK record that admitted the connection.
ResolvedPsk resolved_psk;
/// psk_id of the PSK that admitted the connection. The handshake has already mixed the PSK
/// into session's keys, so the result carries none of its bytes.
IdText psk_id;
/// Category of that PSK.
PskCategory psk_category{PskCategory::SENTINEL};
/// 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).
Expand Down Expand Up @@ -147,8 +149,8 @@ static constexpr size_t MAX_SERVER_INIT_BYTES = 512;

/// @brief Noise handshake state machine for the Sendspin client (Noise responder).
///
/// build_client_init() produces the first cleartext frame, on_text_frame() takes each incoming
/// text frame, and take_result() yields the session once that returns COMPLETE.
/// build_client_init() produces the first cleartext frame, and on_text_frame() takes each
/// incoming text frame, handing out the session with the frame that completes the handshake.
///
/// Threading: runs entirely on the protocol task, which is where RecordStore::resolve_by_psk_id()
/// runs (see record_store.h).
Expand Down Expand Up @@ -182,10 +184,13 @@ class NoiseHandshake {

/// @brief Process one incoming WS text frame.
/// Must be called in sequence: server/init, then noise/handshake msg1.
/// @param send_fn Callable that sends a JSON message to the peer as a TEXT frame.
/// Signature: `bool send_fn(const JsonDocument& msg)`.
/// @param send_fn Callable that sends a JSON message to the peer as a TEXT frame.
/// Signature: `bool send_fn(const JsonDocument& msg)`.
/// @param completed Set to the handshake's result when this returns COMPLETE, untouched
/// otherwise.
HandshakeFrameResult on_text_frame(std::string_view text,
const std::function<bool(const JsonDocument&)>& send_fn);
const std::function<bool(const JsonDocument&)>& send_fn,
std::optional<NoiseHandshakeResult>& completed);

/// @brief The reason carried by a server/error received during the handshake, or empty.
///
Expand All @@ -196,11 +201,6 @@ class NoiseHandshake {
return this->server_error_reason_;
}

/// @brief Take ownership of the handshake result (only valid after COMPLETE).
std::optional<NoiseHandshakeResult> take_result() {
return std::move(this->result_);
}

private:
enum class State : uint8_t {
INIT, ///< client/init not yet sent
Expand All @@ -226,18 +226,17 @@ class NoiseHandshake {
/// @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.
/// @param completed Set to the handshake's result on success.
/// @return true when msg1 authenticated and msg2 was sent.
bool handle_msg1(std::span<uint8_t> msg1_bytes,
const std::function<bool(const JsonDocument&)>& send_fn);
const std::function<bool(const JsonDocument&)>& send_fn,
std::optional<NoiseHandshakeResult>& completed);

// Struct fields
/// 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<NoiseHandshakeResult> result_;

/// Reason from a received server/error. See server_error_reason().
std::string server_error_reason_;

Expand Down
6 changes: 3 additions & 3 deletions src/noise_transport.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,8 @@ static const char* const TAG = "sendspin.noise_transport";
// Session lifecycle
// ============================================================================

void NoiseTransport::activate(std::unique_ptr<NoiseSession> session) {
void NoiseTransport::activate(NoiseSession session) {
this->session_ = std::move(session);
this->active_ = true;
}

std::optional<std::array<uint8_t, 32>> NoiseTransport::handshake_hash() const {
Expand All @@ -58,6 +57,7 @@ size_t NoiseTransport::encrypt_in_place(uint8_t* buf, size_t buf_capacity, size_
#endif

// noise-c advances the send nonce past a failed encrypt too.
// NOLINTNEXTLINE(bugprone-unchecked-optional-access): callers check the session first
const size_t ct_len = this->session_->encrypt(buf, plaintext_len, buf_capacity);
if (ct_len == 0) {
SS_LOGE(TAG, "Noise encrypt failed");
Expand Down Expand Up @@ -147,7 +147,7 @@ SsErr NoiseTransport::send_binary_lent(OutboundRing& ring, void* item, size_t me
return err;
}

SsErr NoiseTransport::send_msg2_and_swap(size_t len, std::unique_ptr<NoiseSession> next_session) {
SsErr NoiseTransport::send_msg2_and_swap(size_t len, NoiseSession next_session) {
// msg2 goes out under the OLD session, then the session swaps. Every send runs on the
// protocol task, as this does, so no encrypt can fall between the two.
SsErr err = this->send_staged_json(len);
Expand Down
14 changes: 5 additions & 9 deletions src/noise_transport.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <utility>

Expand Down Expand Up @@ -95,7 +94,7 @@ class NoiseTransport {

/// @brief Installs the cipher session produced by the initial Noise handshake and marks
/// the transport active. Called on the protocol task at handshake COMPLETE.
void activate(std::unique_ptr<NoiseSession> session);
void activate(NoiseSession session);

/// @brief Returns the current session's 32-byte Noise handshake hash, or nullopt if no
/// session is active. Protocol task only.
Expand All @@ -105,7 +104,7 @@ class NoiseTransport {
/// swaps). This is the check send paths use to decide encrypted-vs-cleartext. Protocol task
/// only.
bool is_active() const {
return this->active_;
return this->session_.has_value();
}

/// @brief Whether a send failed once its first frame was encrypted. Each encrypt spends a send
Expand Down Expand Up @@ -159,7 +158,7 @@ class NoiseTransport {
/// text) under the OLD session, then swap to the new session. Protocol task only, like every
/// other send, so no encrypt falls between the msg2 send and the swap.
/// @return SsErr::OK on success (session swapped); on error the old session is kept.
SsErr send_msg2_and_swap(size_t len, std::unique_ptr<NoiseSession> next_session);
SsErr send_msg2_and_swap(size_t len, NoiseSession next_session);

// ========================================
// Inbound (decrypt + reassemble); protocol task only
Expand Down Expand Up @@ -260,12 +259,12 @@ class NoiseTransport {
/// reasm_buf_.
PlatformBuffer send_buf_;

// Pointer fields
/// Noise cipher session (set at handshake COMPLETE, replaced on re-handshake swap).
/// Protocol task only.
std::unique_ptr<NoiseSession> session_;
std::optional<NoiseSession> session_;

#ifdef SENDSPIN_ENABLE_MESSAGE_TRACE
// Pointer fields
/// From set_message_tracer(); nullptr for none. Written once at setup, then protocol task
/// only.
const MessageTracer* message_tracer_{nullptr};
Expand All @@ -280,9 +279,6 @@ class NoiseTransport {
/// Memory placement for reasm_buf_ and send_buf_.
MemoryLocation buffer_location_{MemoryLocation::PREFER_EXTERNAL};

/// True once a transport session exists. See is_active(). Protocol task only.
bool active_{false};

/// See is_send_desynced(). Protocol task only.
bool send_desynced_{false};

Expand Down
Loading
Loading