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
18 changes: 9 additions & 9 deletions src/connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -260,13 +260,13 @@ void SendspinConnection::handle_noise_handshake_text(std::string_view text) {
HandshakeFrameResult result = this->noise_handshake_->on_text_frame(text, send_fn, outcome);

if (result == HandshakeFrameResult::ABORT) {
const std::string& server_error = this->noise_handshake_->server_error_reason();
if (server_error.empty()) {
const std::optional<ServerErrorReason> server_error =
this->noise_handshake_->server_error_reason();
if (!server_error.has_value()) {
SS_LOGW(TAG, "Noise handshake aborted; closing connection");
} else {
SS_LOGW(TAG,
"Noise handshake aborted by server/error (reason='%s'); closing connection",
server_error.c_str());
SS_LOGW(TAG, "Noise handshake aborted by server/error (reason=%s); closing connection",
to_cstr(*server_error));
}
// connection.md "Failure Handling": a handshake-phase failure closes the WebSocket
// without sending any application-level message.
Expand All @@ -288,8 +288,8 @@ void SendspinConnection::handle_noise_handshake_text(std::string_view text) {
this->noise_transport_.activate(std::move(outcome->session));
this->noise_handshake_.reset();
this->noise_handshake_complete_ = true;
SS_LOGI(TAG, "Noise transport active (server_id=%s, psk_category=%d)",
this->server_id_.c_str(), static_cast<int>(this->get_psk_category()));
SS_LOGI(TAG, "Noise transport active (server_id=%s, psk_category=%s)",
this->server_id_.c_str(), to_cstr(this->get_psk_category()));
}

// NEED_MORE, or COMPLETE handled above: nothing else to do until the next frame.
Expand Down Expand Up @@ -370,8 +370,8 @@ bool SendspinConnection::handle_noise_rehandshake(std::span<uint8_t> msg1_bytes)
// untouched; the server's first message under the new keys is server/activate, which
// first_activate_received_ (cleared above) now waits on.
SS_LOGI(TAG,
"Noise re-handshake complete: server_id=%s psk_category=%d; awaiting server/activate",
this->server_id_.c_str(), static_cast<int>(this->get_psk_category()));
"Noise re-handshake complete: server_id=%s psk_category=%s; awaiting server/activate",
this->server_id_.c_str(), to_cstr(this->get_psk_category()));
return true;
}

Expand Down
4 changes: 2 additions & 2 deletions src/connection_manager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -661,8 +661,8 @@ void ConnectionManager::on_server_activate(SendspinConnection* conn,
if (!activation_admissible) {
const SendspinGoodbyeReason reject_reason = inadmissible_reject_reason(
conn->get_psk_category(), msg.activities, has_roles, unpaired_access);
SS_LOGW(TAG, "server/activate inadmissible (psk_category=%d): closing with %s",
static_cast<int>(conn->get_psk_category()),
SS_LOGW(TAG, "server/activate inadmissible (psk_category=%s): closing with %s",
to_cstr(conn->get_psk_category()),
reject_reason == SendspinGoodbyeReason::PAIRING_REQUIRED ? "pairing_required"
: "unauthorized");
this->drop_connection(conn, reject_reason);
Expand Down
15 changes: 10 additions & 5 deletions src/crypto/constants.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,18 +72,23 @@ static constexpr size_t MAX_TRANSPORT_PLAINTEXT = 65535 - 16; // = 65519

/// @brief Largest Noise message 1 payload the client decrypts: the spec sets no bound, but the
/// payload it defines is small (psk_id JSON, ~60 bytes). 512 leaves room for future fields
/// without paying for a buffer sized like transport-mode traffic. noise-c bounds-checks against
/// this capacity and returns an error rather than overflowing it if a peer's payload does not fit
/// (verified against noise_handshakestate_read_message()'s payload->max_size check), so a longer
/// payload fails the handshake rather than corrupting memory. MAX_SERVER_INIT_BYTES bounds the
/// without paying for a buffer sized like transport-mode traffic. MAX_HANDSHAKE_MSG1_BYTES refuses
/// a message 1 that could carry a longer payload, and noise-c also bounds-checks against this
/// capacity (noise_handshakestate_read_message()'s payload->max_size check), so a longer payload
/// fails the handshake rather than corrupting memory. MAX_SERVER_INIT_BYTES bounds the
/// handshake's other peer input.
static constexpr size_t MAX_HANDSHAKE_MESSAGE_BYTES = 512;

/// @brief Largest Noise message 1 the client decodes: KKpsk2's "e, es, ss" sends the 32-byte
/// ephemeral key, then a payload of up to MAX_HANDSHAKE_MESSAGE_BYTES and its 16-byte AEAD tag.
/// A longer one could not be read, so it is refused before its buffer is allocated.
static constexpr size_t MAX_HANDSHAKE_MSG1_BYTES = 32 + MAX_HANDSHAKE_MESSAGE_BYTES + 16;

/// @brief Largest server/init the handshake keeps for its prologue: about five times the minimal
/// frame, a version and a PEER_ID_SIZE server_id in about 104 bytes (messaging.md "server/init").
/// It bounds the prologue buffer each handshake holds; the cost is that a later revision's
/// optional fields, which messaging.md "Forward compatibility" has the client ignore, must keep
/// the frame under it. MAX_HANDSHAKE_MESSAGE_BYTES bounds the handshake's other peer input.
/// the frame under it. MAX_HANDSHAKE_MSG1_BYTES bounds the handshake's other peer input.
static constexpr size_t MAX_SERVER_INIT_BYTES = 512;

/// @brief Per-connection reassembly buffer cap: 1 MiB.
Expand Down
2 changes: 1 addition & 1 deletion src/crypto/keys.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ std::optional<std::array<uint8_t, X25519_KEY_SIZE>> public_key_from_peer_id(
return std::nullopt;
}
std::array<uint8_t, X25519_KEY_SIZE> key{};
if (b64url_decode_into(peer_id, key.data(), key.size()) != X25519_KEY_SIZE) {
if (!b64url_decode_exact(peer_id, key)) {
return std::nullopt;
}
// The last character carries 2 unused bits; a nonzero pair decodes to the same key.
Expand Down
65 changes: 41 additions & 24 deletions src/noise_handshake.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#include "crypto/keys.h"
#include "noise_session.h"
#include "platform/base64.h"
#include "platform/crypto.h"
#include "platform/json_arena.h"
#include "platform/logging.h"
#include "platform/memory.h"
Expand All @@ -31,6 +32,14 @@ static const char* const TAG = "sendspin.noise_handshake";

namespace sendspin {

/// Most bytes of unauthenticated peer text (a frame's type, a server/error reason) one log line
/// prints. The longest such value messaging.md defines is 19 bytes.
static constexpr size_t PEER_TEXT_LOG_BYTES = 32;

static_assert(MAX_HANDSHAKE_MSG1_BYTES ==
X25519_KEY_SIZE + MAX_HANDSHAKE_MESSAGE_BYTES + AEAD_TAG_SIZE,
"message 1 is the ephemeral key, the payload and its tag");

// ============================================================================
// JSON serialization helpers
// ============================================================================
Expand Down Expand Up @@ -168,7 +177,7 @@ std::optional<Msg1CoreResult> run_msg1_core(HandshakeKind kind, const Identity&
}

// Parse psk_id from the decrypted msg1 payload: {"psk_id":"...","psk_category":"..."}. The
// payload is released as soon as its two fields are copied out, so the msg2 envelope the
// payload is released as soon as its two fields are read out, so the msg2 envelope the
// caller builds has the arena to itself.
ParsedJsonMessage payload(arena);
if (!payload.parse(reinterpret_cast<const char*>(msg1_payload.data()), payload_size.value())) {
Expand All @@ -179,12 +188,12 @@ std::optional<Msg1CoreResult> run_msg1_core(HandshakeKind kind, const Identity&
IdText psk_id;
bool psk_id_present = false;
bool psk_id_held = false;
std::string psk_category_code;
std::optional<PskCategory> psk_category;
payload.extract([&](JsonObjectConst root) {
const std::string_view text = root["psk_id"] | "";
const std::string_view text = root["psk_id"] | std::string_view("");
psk_id_present = !text.empty();
psk_id_held = psk_id.assign(text);
psk_category_code = root["psk_category"] | "";
psk_category = psk_category_from_string(root["psk_category"] | std::string_view(""));
});

if (!psk_id_present) {
Expand All @@ -195,16 +204,14 @@ std::optional<Msg1CoreResult> run_msg1_core(HandshakeKind kind, const Identity&
// messaging.md "noise/handshake": the payload declares which category the server is using the
// referenced PSK as. A missing or unknown code is a malformed payload, which connection.md
// "Failure Handling" makes a silent failure.
auto psk_category = psk_category_from_string(psk_category_code);
if (!psk_category.has_value()) {
SS_LOGE(TAG, "%s: msg1 payload psk_category missing or unknown ('%s')", log_prefix,
psk_category_code.c_str());
SS_LOGE(TAG, "%s: msg1 payload psk_category missing or not 'lt', 'pr' or 'sn'", log_prefix);
return std::nullopt;
}

const char* const psk_id_text = psk_id_held ? psk_id.c_str() : "(longer than a psk_id)";
SS_LOGD(TAG, "%s: psk_id='%s' psk_category='%s'", log_prefix, psk_id_text,
psk_category_code.c_str());
to_cstr(*psk_category));

std::optional<ResolvedPsk> resolved =
psk_id_held ? record_store.resolve_by_psk_id(psk_id.view(), psk_category.value())
Expand All @@ -228,7 +235,7 @@ std::optional<Msg1CoreResult> run_msg1_core(HandshakeKind kind, const Identity&
// "Pairing Records": an evicted record needs no wire signal of its own). Failing here
// instead would leave a client that lost its record reconnect-looping with no way back.
SS_LOGW(TAG, "%s: no '%s' PSK for psk_id='%s'; answering with the Sentinel PSK", log_prefix,
psk_category_code.c_str(), psk_id_text);
to_cstr(*psk_category), psk_id_text);
resolved = record_store.resolve_by_psk_id(SENTINEL_PSK_ID, PskCategory::SENTINEL);
if (!resolved.has_value()) {
SS_LOGE(TAG, "%s: the Sentinel PSK did not resolve", log_prefix);
Expand All @@ -237,7 +244,7 @@ std::optional<Msg1CoreResult> run_msg1_core(HandshakeKind kind, const Identity&
} else {
// connection.md "Sentinel Fallback" applies to the initial handshake alone.
SS_LOGW(TAG, "%s: no '%s' PSK for psk_id='%s', aborting", log_prefix,
psk_category_code.c_str(), psk_id_text);
to_cstr(*psk_category), psk_id_text);
return std::nullopt;
}

Expand Down Expand Up @@ -269,7 +276,7 @@ std::optional<Msg1CoreResult> run_msg1_core(HandshakeKind kind, const Identity&

std::optional<PlatformBuffer> read_noise_handshake_data(JsonObjectConst envelope,
const char* log_context) {
const std::string_view data_b64 = envelope["payload"]["data"] | "";
const std::string_view data_b64 = envelope["payload"]["data"] | std::string_view("");
if (data_b64.empty()) {
SS_LOGE(TAG, "%s: missing data field", log_context);
return std::nullopt;
Expand All @@ -280,6 +287,11 @@ std::optional<PlatformBuffer> read_noise_handshake_data(JsonObjectConst envelope
SS_LOGE(TAG, "%s: failed to base64url-decode noise msg1", log_context);
return std::nullopt;
}
if (size > MAX_HANDSHAKE_MSG1_BYTES) {
SS_LOGE(TAG, "%s: noise msg1 of %zu bytes is longer than %zu", log_context, size,
MAX_HANDSHAKE_MSG1_BYTES);
return std::nullopt;
}
PlatformBuffer bytes;
if (!bytes.allocate(size)) {
SS_LOGE(TAG, "%s: no memory to decode %zu bytes", log_context, size);
Expand Down Expand Up @@ -324,10 +336,13 @@ std::string_view NoiseHandshake::build_client_init() {

void NoiseHandshake::take_server_error(JsonObjectConst root, const char* log_context) {
// The handshake aborts either way; recognizing the message is what gives the abort the
// server's own account of the refusal.
this->server_error_reason_ = root["payload"]["reason"] | "";
SS_LOGE(TAG, "%s: server/error, reason='%s'; the server refused the connection", log_context,
this->server_error_reason_.c_str());
// server's own account of the refusal. The frame is unauthenticated, so its text is read in
// place and logged only up to PEER_TEXT_LOG_BYTES, never copied.
const std::string_view text = root["payload"]["reason"] | std::string_view("");
this->server_error_reason_ = server_error_reason_from_string(text);
const std::string_view logged = text.substr(0, PEER_TEXT_LOG_BYTES);
SS_LOGE(TAG, "%s: server/error, reason='%.*s'; the server refused the connection", log_context,
static_cast<int>(logged.size()), logged.data());
}

HandshakeFrameResult NoiseHandshake::on_text_frame(
Expand Down Expand Up @@ -357,23 +372,25 @@ HandshakeFrameResult NoiseHandshake::on_text_frame(
IdText server_id;
std::optional<PlatformBuffer> msg1_bytes;
const bool expected = frame.extract([&](JsonObjectConst root) {
const char* type = root["type"] | "";
const std::string_view type = root["type"] | std::string_view("");
// messaging.md "server/error": sent in place of server/init when the server cannot
// accept our client/init. Recognized in either wait so an abort names the server's
// reason.
if (std::strcmp(type, "server/error") == 0) {
if (type == "server/error") {
this->take_server_error(root, log_context);
return false;
}
if (std::strcmp(type, expected_type) != 0) {
SS_LOGE(TAG, "%s: unexpected type '%s'", log_context, type);
if (type != expected_type) {
const std::string_view logged = type.substr(0, PEER_TEXT_LOG_BYTES);
SS_LOGE(TAG, "%s: unexpected type '%.*s'", log_context, static_cast<int>(logged.size()),
logged.data());
return false;
}
if (awaiting_server_init) {
version = root["payload"]["version"] | 0;
// Refused when longer than a peer_id, leaving it empty for handle_server_init() to
// reject.
(void)server_id.assign(root["payload"]["server_id"] | "");
(void)server_id.assign(root["payload"]["server_id"] | std::string_view(""));
} else {
msg1_bytes = read_noise_handshake_data(root, to_cstr(HandshakeKind::INITIAL));
}
Expand Down Expand Up @@ -461,8 +478,8 @@ bool NoiseHandshake::handle_msg1(std::span<uint8_t> msg1_bytes,
return false;
}

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

// Built in the caller's optional, so no result temporary sits on this frame.
completed.emplace(std::move(core->session), this->server_id_, core->psk_id, core->psk_category);
Expand All @@ -488,8 +505,8 @@ std::optional<NoiseHandshakeResult> run_rehandshake_msg1(
return std::nullopt;
}

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

// The caller wraps msg2 in its noise/handshake envelope and sends it encrypted. Returned as a
// prvalue, which is built in the caller's optional; a named optional would be moved there,
Expand Down
50 changes: 44 additions & 6 deletions src/noise_handshake.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@
#include <functional>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <utility>

Expand All @@ -75,6 +74,44 @@ struct NoiseHandshakeResult {
NoiseMsg2 msg2_bytes{};
};

/// @brief Why a server refused our client/init: the reasons messaging.md "server/error" defines,
/// plus UNKNOWN for any other text or none
enum class ServerErrorReason : uint8_t {
UNSUPPORTED_VERSION, ///< "unsupported_version"
UNSUPPORTED_SUITE, ///< "unsupported_suite"
MALFORMED, ///< "malformed"
UNKNOWN, ///< Any other reason, or none
};

/// @brief Parses a server/error reason; UNKNOWN for text messaging.md does not define
inline ServerErrorReason server_error_reason_from_string(std::string_view text) {
if (text == "unsupported_version") {
return ServerErrorReason::UNSUPPORTED_VERSION;
}
if (text == "unsupported_suite") {
return ServerErrorReason::UNSUPPORTED_SUITE;
}
if (text == "malformed") {
return ServerErrorReason::MALFORMED;
}
return ServerErrorReason::UNKNOWN;
}

/// @brief Wire string for a ServerErrorReason; "unknown" for UNKNOWN.
inline const char* to_cstr(ServerErrorReason reason) {
switch (reason) {
case ServerErrorReason::UNSUPPORTED_VERSION:
return "unsupported_version";
case ServerErrorReason::UNSUPPORTED_SUITE:
return "unsupported_suite";
case ServerErrorReason::MALFORMED:
return "malformed";
case ServerErrorReason::UNKNOWN:
return "unknown";
}
return "unknown";
}

/// @brief Result of processing one incoming WS frame during the handshake.
enum class HandshakeFrameResult : uint8_t {
NEED_MORE, ///< Frame processed; waiting for the next frame.
Expand All @@ -98,8 +135,8 @@ bool build_noise_handshake_message(std::span<const uint8_t> noise_bytes, JsonDoc
/// re-handshake's, so the caller can release the parsed envelope before the handshake runs.
/// @param envelope Parsed noise/handshake envelope; its type is the caller's to check.
/// @param log_context Prefix for the failure log line.
/// @return The decoded bytes, or nullopt (logged) when data is missing, empty or not base64url,
/// or when their buffer cannot be allocated.
/// @return The decoded bytes, or nullopt (logged) when data is missing, empty, not base64url or
/// longer than MAX_HANDSHAKE_MSG1_BYTES, or when their buffer cannot be allocated.
std::optional<PlatformBuffer> read_noise_handshake_data(JsonObjectConst envelope,
const char* log_context);

Expand Down Expand Up @@ -185,12 +222,13 @@ class NoiseHandshake {
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.
/// @brief The reason carried by a server/error received during the handshake, or nullopt
/// when none arrived.
///
/// messaging.md "server/error": the server sends one in place of server/init when it cannot
/// accept our client/init. The message is unauthenticated, so connection.md "Failure Handling"
/// makes the reason a hint for logging and operator display.
const std::string& server_error_reason() const {
std::optional<ServerErrorReason> server_error_reason() const {
return this->server_error_reason_;
}

Expand Down Expand Up @@ -231,7 +269,7 @@ class NoiseHandshake {
PlatformBuffer prologue_;

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

/// server_id decoded from server/init (43-char base64url).
IdText server_id_;
Expand Down
9 changes: 9 additions & 0 deletions src/platform/base64.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

#pragma once

#include <array>
#include <cstddef>
#include <cstdint>
#include <optional>
Expand Down Expand Up @@ -305,6 +306,14 @@ inline std::optional<size_t> b64url_decode_into(std::string_view s, uint8_t* dst
return written;
}

/// @brief Decode base64url that must carry exactly N bytes straight into `out`, tolerating
/// missing `=` padding.
/// @return false on invalid input or any other length, with `out` unspecified.
template <size_t N>
inline bool b64url_decode_exact(std::string_view s, std::array<uint8_t, N>& out) {
return b64url_decode_into(s, out.data(), out.size()) == N;
}

/// @brief Decode base64url, tolerating missing `=` padding; nullopt on invalid input.
inline std::optional<std::vector<uint8_t>> b64url_decode(std::string_view s) {
const std::optional<size_t> size = b64url_decoded_size(s);
Expand Down
Loading
Loading