Implement M9.6 narrow secure dev-session protocol

Add protocol v1: versioned, bounded frames (Hello, Welcome, Intent,
IntentResult, environment/organism views, Close) carrying session, epoch
and commit watermark, with an explicit little-endian canonical codec, a
header-first FrameReader, seeded mutation tests and a libFuzzer target.
SessionAdmission enforces world/region scope, grant lifetime and skew,
single-use grants, one session per subject, epoch, replay, tick window
and per-session rate.

Dev identity is a 108-byte HMAC-SHA256 grant (PSA) that cannot be
created or verified outside the dev environment. Transport security is
TLS 1.3 only via pinned Mbed TLS 4.1.1 LTS with TLS 1.2, DTLS, tickets
and PSK compiled out, AEAD suites, ECDHE groups and a pinned dev CA.
Opt-in EVO_BUILD_NETWORK, new network CI suite. Sockets and region
integration follow in M9.7. ADR-0082 records the decision.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-10-01 18:53:55 -04:00
co-authored by Claude Opus 5.5
parent 9bb147de82
commit 8fbe093cc8
39 changed files with 3200 additions and 27 deletions
+118
View File
@@ -0,0 +1,118 @@
#include "evo/network/admission.hpp"
#include <algorithm>
namespace evo::network {
namespace {
constexpr std::int32_t max_component = 1000;
bool valid_vector(std::int16_t x, std::int16_t y) {
const std::int32_t ix = x, iy = y;
return ix >= -max_component && ix <= max_component && iy >= -max_component &&
iy <= max_component && ix * ix + iy * iy <= max_component * max_component;
}
} // namespace
std::expected<SessionAdmission, AdmissionError> SessionAdmission::create(AdmissionConfig config) {
if (config.world.world == 0 || config.world.frame == 0 || config.region == 0 ||
config.epoch == 0 || config.max_sessions == 0 || config.max_sessions > 256 ||
config.max_remembered_grants < config.max_sessions ||
config.max_remembered_grants > 65536 || config.intent_window == 0 ||
config.window_ticks == 0 || config.max_intents_per_window == 0 ||
config.max_grant_lifetime == 0 || config.max_grant_lifetime > 86400 ||
config.clock_skew > 300)
return std::unexpected(AdmissionError::invalid_config);
SessionAdmission admission{config};
admission.sessions_.reserve(config.max_sessions);
admission.grants_.reserve(config.max_remembered_grants);
return admission;
}
std::expected<Welcome, AdmissionError> SessionAdmission::open(const VerifiedGrant& grant,
std::uint64_t now_seconds,
std::uint64_t server_tick,
std::uint64_t commit_watermark) {
const auto& c = grant.claims();
if (c.world != config_.world)
return std::unexpected(AdmissionError::wrong_world);
if (c.region != config_.region)
return std::unexpected(AdmissionError::wrong_region);
if (c.expires_at <= c.issued_at || c.expires_at - c.issued_at > config_.max_grant_lifetime)
return std::unexpected(AdmissionError::invalid_lifetime);
if (c.issued_at > now_seconds && c.issued_at - now_seconds > config_.clock_skew)
return std::unexpected(AdmissionError::not_yet_valid);
if (now_seconds >= c.expires_at)
return std::unexpected(AdmissionError::expired);
// Forget only grants that can no longer verify as unexpired.
std::erase_if(grants_, [&](const Remembered& r) { return r.expires_at <= now_seconds; });
if (std::ranges::any_of(grants_, [&](const Remembered& r) { return r.grant_id == c.grant_id; }))
return std::unexpected(AdmissionError::grant_reused);
if (std::ranges::any_of(sessions_, [&](const Session& s) { return s.subject == c.subject; }))
return std::unexpected(AdmissionError::duplicate_subject);
if (sessions_.size() >= config_.max_sessions)
return std::unexpected(AdmissionError::sessions_full);
if (grants_.size() >= config_.max_remembered_grants)
return std::unexpected(AdmissionError::grants_full); // Fail closed, never forget early.
grants_.push_back({c.grant_id, c.expires_at});
const auto id = next_session_++;
sessions_.push_back({id, c.subject, config_.epoch, c.expires_at, 0, server_tick, 0});
Welcome welcome;
welcome.session = id;
welcome.world = config_.world.world;
welcome.frame = config_.world.frame;
welcome.region = config_.region;
welcome.epoch = config_.epoch;
welcome.server_tick = server_tick;
welcome.commit_watermark = commit_watermark;
welcome.grant_expires_at = c.expires_at;
welcome.intent_window = config_.intent_window;
welcome.window_ticks = config_.window_ticks;
welcome.max_intents_per_window = config_.max_intents_per_window;
return welcome;
}
IntentResult SessionAdmission::admit(const IntentMessage& intent, std::uint64_t server_tick,
std::uint64_t now_seconds) {
IntentResult result{intent.sequence, IntentStatus::admitted, server_tick};
const auto found =
std::ranges::find_if(sessions_, [&](const Session& s) { return s.id == intent.session; });
if (found == sessions_.end()) {
result.status = IntentStatus::unknown_session;
return result;
}
auto& s = *found;
// Every attempt by a known session counts toward its rate, admitted or not.
if (server_tick < s.window_start || server_tick - s.window_start >= config_.window_ticks) {
s.window_start = server_tick;
s.attempts = 0;
}
if (s.attempts >= config_.max_intents_per_window)
result.status = IntentStatus::rate_limited;
else if (intent.epoch != config_.epoch || s.epoch != config_.epoch)
result.status = IntentStatus::stale_epoch;
else if (now_seconds >= s.expires_at)
result.status = IntentStatus::expired;
else if (!valid_vector(intent.move_x, intent.move_y))
result.status = IntentStatus::invalid_vector;
else if (intent.sequence <= s.last_sequence)
result.status = IntentStatus::replayed;
else if (intent.tick < server_tick || intent.tick - server_tick > config_.intent_window)
result.status = IntentStatus::outside_window;
if (s.attempts < config_.max_intents_per_window)
++s.attempts;
if (result.status == IntentStatus::admitted)
s.last_sequence = intent.sequence;
return result;
}
std::expected<void, AdmissionError> SessionAdmission::close(std::uint64_t session) {
if (std::erase_if(sessions_, [&](const Session& s) { return s.id == session; }) == 0)
return std::unexpected(AdmissionError::unknown_session);
return {};
}
std::expected<void, AdmissionError> SessionAdmission::advance_epoch(std::uint64_t epoch) {
if (epoch <= config_.epoch)
return std::unexpected(AdmissionError::invalid_config);
config_.epoch = epoch;
return {};
}
} // namespace evo::network
+528
View File
@@ -0,0 +1,528 @@
#include "evo/network/protocol.hpp"
#include <algorithm>
#include <bit>
#include <utility>
namespace evo::network {
namespace {
constexpr std::uint8_t last_type = static_cast<std::uint8_t>(MessageType::close);
constexpr std::uint8_t last_status = static_cast<std::uint8_t>(IntentStatus::rate_limited);
constexpr std::uint8_t last_reason = static_cast<std::uint8_t>(CloseReason::server_shutdown);
constexpr std::uint8_t last_presence = static_cast<std::uint8_t>(client::FieldPresence::present);
constexpr std::uint8_t last_moisture = static_cast<std::uint8_t>(world::MoistureStatus::available);
constexpr std::uint8_t last_state = static_cast<std::uint8_t>(client::OrganismState::dead);
class Writer {
public:
void u8(std::uint8_t v) {
bytes_.push_back(v);
}
void u16(std::uint16_t v) {
put(v, 2);
}
void u32(std::uint32_t v) {
put(v, 4);
}
void u64(std::uint64_t v) {
put(v, 8);
}
void i16(std::int16_t v) {
u16(std::bit_cast<std::uint16_t>(v));
}
void i64(std::int64_t v) {
u64(std::bit_cast<std::uint64_t>(v));
}
void raw(std::span<const std::uint8_t> v) {
bytes_.insert(bytes_.end(), v.begin(), v.end());
}
[[nodiscard]] std::vector<std::uint8_t> take() {
return std::move(bytes_);
}
private:
void put(std::uint64_t v, int count) {
for (int i = 0; i < count; ++i)
bytes_.push_back(static_cast<std::uint8_t>(v >> (8 * i)));
}
std::vector<std::uint8_t> bytes_;
};
// Bounds-checked little-endian reader; the first failure is sticky.
class Reader {
public:
explicit Reader(std::span<const std::uint8_t> bytes) : bytes_{bytes} {}
std::uint8_t u8() {
return static_cast<std::uint8_t>(get(1));
}
std::uint16_t u16() {
return static_cast<std::uint16_t>(get(2));
}
std::uint32_t u32() {
return static_cast<std::uint32_t>(get(4));
}
std::uint64_t u64() {
return get(8);
}
std::int16_t i16() {
return std::bit_cast<std::int16_t>(u16());
}
std::int64_t i64() {
return std::bit_cast<std::int64_t>(u64());
}
std::span<const std::uint8_t> raw(std::size_t count) {
if (!ok_ || bytes_.size() - at_ < count) {
ok_ = false;
return {};
}
const auto out = bytes_.subspan(at_, count);
at_ += count;
return out;
}
// Rejects a value outside [0, last] without consuming further input.
std::uint8_t bounded(std::uint8_t last) {
const auto v = u8();
if (v > last)
invalid_ = true;
return v;
}
void invalid() {
invalid_ = true;
}
[[nodiscard]] std::expected<void, ProtocolError> finish() const {
if (!ok_)
return std::unexpected(ProtocolError::truncated);
if (invalid_)
return std::unexpected(ProtocolError::invalid_value);
if (at_ != bytes_.size())
return std::unexpected(ProtocolError::trailing_bytes);
return {};
}
[[nodiscard]] bool ok() const noexcept {
return ok_ && !invalid_;
}
private:
std::uint64_t get(std::size_t count) {
if (!ok_ || bytes_.size() - at_ < count) {
ok_ = false;
return 0;
}
std::uint64_t v = 0;
for (std::size_t i = 0; i < count; ++i)
v |= static_cast<std::uint64_t>(bytes_[at_ + i]) << (8 * i);
at_ += count;
return v;
}
std::span<const std::uint8_t> bytes_;
std::size_t at_{};
bool ok_{true}, invalid_{};
};
// Casts only on the validated path; an out-of-range byte flags the reader invalid
// and yields the enum's zero value, which the decoder then discards.
template <typename E> E enumerator(Reader& r, std::uint8_t last) {
const auto v = r.bounded(last);
return v <= last ? static_cast<E>(v) : E{};
}
struct Header {
MessageType type;
std::uint32_t length;
};
std::expected<Header, ProtocolError> parse_header(std::span<const std::uint8_t> bytes) {
Reader r{bytes.first(frame_header_bytes)};
const auto magic = r.u32();
const auto version = r.u16();
const auto type = r.u8();
const auto flags = r.u8();
const auto length = r.u32();
if (magic != frame_magic)
return std::unexpected(ProtocolError::bad_magic);
if (version != protocol_version)
return std::unexpected(ProtocolError::unsupported_version);
if (type == 0 || type > last_type)
return std::unexpected(ProtocolError::unknown_type);
if (flags != 0)
return std::unexpected(ProtocolError::reserved_flags);
if (length > max_frame_payload)
return std::unexpected(ProtocolError::oversized);
return Header{static_cast<MessageType>(type), length};
}
std::vector<std::uint8_t> framed(MessageType type, Writer& payload) {
const auto bytes = payload.take();
return encode_frame(type, bytes);
}
std::expected<Reader, ProtocolError> open(FrameView frame, MessageType type) {
if (frame.type != type)
return std::unexpected(ProtocolError::wrong_type);
return Reader{frame.payload};
}
void write(Writer& w, const ViewHeader& h) {
w.u64(h.session);
w.u64(h.epoch);
w.u64(h.server_tick);
w.u64(h.commit_watermark);
w.u64(h.baseline);
}
ViewHeader read_view_header(Reader& r) {
ViewHeader h;
h.session = r.u64();
h.epoch = r.u64();
h.server_tick = r.u64();
h.commit_watermark = r.u64();
h.baseline = r.u64();
return h;
}
} // namespace
std::vector<std::uint8_t> encode_frame(MessageType type, std::span<const std::uint8_t> payload) {
Writer w;
w.u32(frame_magic);
w.u16(protocol_version);
w.u8(static_cast<std::uint8_t>(type));
w.u8(0);
w.u32(static_cast<std::uint32_t>(payload.size()));
w.raw(payload);
return w.take();
}
std::expected<FrameView, ProtocolError> decode_frame(std::span<const std::uint8_t> bytes) {
if (bytes.size() < frame_header_bytes)
return std::unexpected(ProtocolError::truncated);
const auto header = parse_header(bytes);
if (!header)
return std::unexpected(header.error());
const auto total = frame_header_bytes + header->length;
if (bytes.size() < total)
return std::unexpected(ProtocolError::truncated);
if (bytes.size() > total)
return std::unexpected(ProtocolError::trailing_bytes);
return FrameView{header->type, bytes.subspan(frame_header_bytes)};
}
std::expected<std::size_t, ProtocolError> FrameReader::feed(std::span<const std::uint8_t> bytes) {
if (error_)
return std::unexpected(*error_);
std::size_t taken = 0;
while (taken < bytes.size() && buffer_.size() < expected_) {
const auto count = std::min(expected_ - buffer_.size(), bytes.size() - taken);
buffer_.insert(buffer_.end(), bytes.begin() + static_cast<std::ptrdiff_t>(taken),
bytes.begin() + static_cast<std::ptrdiff_t>(taken + count));
taken += count;
if (buffer_.size() == frame_header_bytes && expected_ == frame_header_bytes) {
const auto header = parse_header(buffer_);
if (!header) {
error_ = header.error();
buffer_.clear();
return std::unexpected(*error_);
}
expected_ = frame_header_bytes + header->length;
if (header->length == 0)
break;
}
}
return taken;
}
std::optional<OwnedFrame> FrameReader::take() {
if (error_ || buffer_.size() < frame_header_bytes || buffer_.size() != expected_)
return std::nullopt;
OwnedFrame frame{static_cast<MessageType>(buffer_[6]),
{buffer_.begin() + frame_header_bytes, buffer_.end()}};
buffer_.clear();
expected_ = frame_header_bytes;
return frame;
}
std::expected<std::vector<std::uint8_t>, ProtocolError> encode(const Hello& m) {
if (m.grant.empty() || m.grant.size() > max_grant_bytes)
return std::unexpected(ProtocolError::invalid_value);
Writer w;
w.u32(m.required_features);
w.u16(static_cast<std::uint16_t>(m.grant.size()));
w.raw(m.grant);
return framed(MessageType::hello, w);
}
std::vector<std::uint8_t> encode(const Welcome& m) {
Writer w;
for (const auto v : {m.session, m.world, m.frame, m.region, m.epoch, m.server_tick,
m.commit_watermark, m.grant_expires_at})
w.u64(v);
w.u32(m.intent_window);
w.u32(m.window_ticks);
w.u32(m.max_intents_per_window);
return framed(MessageType::welcome, w);
}
std::vector<std::uint8_t> encode(const IntentMessage& m) {
Writer w;
w.u64(m.session);
w.u64(m.epoch);
w.u64(m.sequence);
w.u64(m.tick);
w.i16(m.move_x);
w.i16(m.move_y);
return framed(MessageType::intent, w);
}
std::vector<std::uint8_t> encode(const IntentResult& m) {
Writer w;
w.u64(m.sequence);
w.u8(static_cast<std::uint8_t>(m.status));
w.u64(m.server_tick);
return framed(MessageType::intent_result, w);
}
std::vector<std::uint8_t> encode(CloseReason reason) {
Writer w;
w.u8(static_cast<std::uint8_t>(reason));
return framed(MessageType::close, w);
}
std::vector<std::uint8_t> encode(const ViewHeader& header,
const client::EnvironmentPresentation& view) {
Writer w;
write(w, header);
const auto revision = view.revision();
w.u64(revision.identity.world);
w.u64(revision.identity.frame);
w.u64(revision.tick);
w.u64(revision.field_revision);
w.u32(view.requested_mask());
w.i64(view.slice_z());
w.u16(static_cast<std::uint16_t>(view.cells().size()));
for (const auto& c : view.cells()) {
w.i64(c.voxel.x);
w.i64(c.voxel.y);
w.u64(c.chunk_revision);
for (const auto v : {c.habitat.x, c.habitat.y, c.habitat.z, c.habitat.width,
c.habitat.height, c.habitat.depth})
w.u32(static_cast<std::uint32_t>(v.value)); // Validated <= 1e6 um.
w.u64(c.volume.value);
w.u16(c.substrate.value);
w.u16(c.terrain_material.value);
w.u16(c.terrain_fill);
for (std::size_t k = 0; k < world::field_count; ++k) {
w.u8(static_cast<std::uint8_t>(c.presence.at(k)));
if (c.presence.at(k) == client::FieldPresence::present)
w.u64(c.quantity.at(k));
}
w.u8(static_cast<std::uint8_t>(c.moisture_status));
if (c.moisture_status == world::MoistureStatus::available) {
w.u64(c.moisture.numerator);
w.u64(c.moisture.denominator);
}
}
return framed(MessageType::environment_view, w);
}
std::vector<std::uint8_t> encode(const ViewHeader& header,
const client::OrganismPresentation& view) {
Writer w;
write(w, header);
const auto revision = view.revision();
w.u64(revision.identity.world);
w.u64(revision.identity.frame);
w.u64(revision.tick);
w.u64(revision.revision);
w.i64(view.slice_z());
w.u16(static_cast<std::uint16_t>(view.cells().size()));
for (const auto& c : view.cells()) {
const auto& p = c.phenotype;
w.u64(c.id);
w.i64(c.voxel.x);
w.i64(c.voxel.y);
w.u32(static_cast<std::uint32_t>(c.x.value)); // Validated < 1e6 um.
w.u32(static_cast<std::uint32_t>(c.y.value));
w.u64(p.structural_mass);
w.u64(p.membrane_mass);
w.u64(p.total_mass);
w.u32(p.extent);
w.u64(p.surface);
w.u64(p.maintenance);
w.u32(p.movement_speed);
w.u64(p.ingestion_rate);
w.u32(p.conversion_per_thousand);
w.u32(p.thermal_shortfall);
w.u32(c.growth.realized_per_thousand);
w.u32(c.growth.damage_per_thousand);
w.u8(static_cast<std::uint8_t>(c.state));
}
return framed(MessageType::organism_view, w);
}
std::expected<Hello, ProtocolError> decode_hello(FrameView frame) {
auto r = open(frame, MessageType::hello);
if (!r)
return std::unexpected(r.error());
Hello m;
m.required_features = r->u32();
const auto length = r->u16();
if (length == 0 || length > max_grant_bytes)
r->invalid();
const auto grant = r->raw(r->ok() ? length : 0);
if (auto done = r->finish(); !done)
return std::unexpected(done.error());
if (m.required_features != 0)
return std::unexpected(ProtocolError::unsupported_feature);
m.grant.assign(grant.begin(), grant.end());
return m;
}
std::expected<Welcome, ProtocolError> decode_welcome(FrameView frame) {
auto r = open(frame, MessageType::welcome);
if (!r)
return std::unexpected(r.error());
Welcome m;
m.session = r->u64();
m.world = r->u64();
m.frame = r->u64();
m.region = r->u64();
m.epoch = r->u64();
m.server_tick = r->u64();
m.commit_watermark = r->u64();
m.grant_expires_at = r->u64();
m.intent_window = r->u32();
m.window_ticks = r->u32();
m.max_intents_per_window = r->u32();
if (auto done = r->finish(); !done)
return std::unexpected(done.error());
if (m.session == 0 || m.window_ticks == 0 || m.max_intents_per_window == 0)
return std::unexpected(ProtocolError::invalid_value);
return m;
}
std::expected<IntentMessage, ProtocolError> decode_intent(FrameView frame) {
auto r = open(frame, MessageType::intent);
if (!r)
return std::unexpected(r.error());
IntentMessage m;
m.session = r->u64();
m.epoch = r->u64();
m.sequence = r->u64();
m.tick = r->u64();
m.move_x = r->i16();
m.move_y = r->i16();
if (auto done = r->finish(); !done)
return std::unexpected(done.error());
return m; // Range/semantics belong to admission, which reports a status.
}
std::expected<IntentResult, ProtocolError> decode_intent_result(FrameView frame) {
auto r = open(frame, MessageType::intent_result);
if (!r)
return std::unexpected(r.error());
IntentResult m;
m.sequence = r->u64();
m.status = enumerator<IntentStatus>(*r, last_status);
m.server_tick = r->u64();
if (auto done = r->finish(); !done)
return std::unexpected(done.error());
return m;
}
std::expected<CloseReason, ProtocolError> decode_close(FrameView frame) {
auto r = open(frame, MessageType::close);
if (!r)
return std::unexpected(r.error());
const auto reason = enumerator<CloseReason>(*r, last_reason);
if (auto done = r->finish(); !done)
return std::unexpected(done.error());
return reason;
}
std::expected<std::pair<ViewHeader, client::EnvironmentPresentation>, ProtocolError>
decode_environment_view(FrameView frame) {
auto r = open(frame, MessageType::environment_view);
if (!r)
return std::unexpected(r.error());
const auto header = read_view_header(*r);
client::EnvironmentRevision revision;
revision.identity.world = r->u64();
revision.identity.frame = r->u64();
revision.tick = r->u64();
revision.field_revision = r->u64();
const auto mask = r->u32();
const auto slice = r->i64();
const auto count = r->u16();
if (count > client::max_environment_cells)
r->invalid();
std::vector<client::EnvironmentCell> cells;
for (std::uint16_t i = 0; r->ok() && i < count; ++i) {
client::EnvironmentCell c;
c.voxel = {r->i64(), r->i64(), slice};
c.chunk_revision = r->u64();
c.habitat = {{r->u32()}, {r->u32()}, {r->u32()}, {r->u32()}, {r->u32()}, {r->u32()}};
c.volume = {r->u64()};
c.substrate = {r->u16()};
c.terrain_material = {r->u16()};
c.terrain_fill = r->u16();
for (std::size_t k = 0; k < world::field_count; ++k) {
c.presence.at(k) = enumerator<client::FieldPresence>(*r, last_presence);
if (c.presence.at(k) == client::FieldPresence::present)
c.quantity.at(k) = r->u64();
}
c.moisture_status = enumerator<world::MoistureStatus>(*r, last_moisture);
if (c.moisture_status == world::MoistureStatus::available)
c.moisture = {r->u64(), r->u64()};
cells.push_back(c);
}
if (auto done = r->finish(); !done)
return std::unexpected(done.error());
auto view = client::EnvironmentPresentation::create(revision, mask, slice, cells);
if (!view)
return std::unexpected(ProtocolError::invalid_value);
return std::pair{header, std::move(*view)};
}
std::expected<std::pair<ViewHeader, client::OrganismPresentation>, ProtocolError>
decode_organism_view(FrameView frame) {
auto r = open(frame, MessageType::organism_view);
if (!r)
return std::unexpected(r.error());
const auto header = read_view_header(*r);
client::OrganismRevision revision;
revision.identity.world = r->u64();
revision.identity.frame = r->u64();
revision.tick = r->u64();
revision.revision = r->u64();
const auto slice = r->i64();
const auto count = r->u16();
if (count > client::max_organism_cells)
r->invalid();
std::vector<client::OrganismCell> cells;
for (std::uint16_t i = 0; r->ok() && i < count; ++i) {
client::OrganismCell c;
c.id = r->u64();
c.voxel = {r->i64(), r->i64(), slice};
c.x = {r->u32()};
c.y = {r->u32()};
auto& p = c.phenotype;
p.structural_mass = r->u64();
p.membrane_mass = r->u64();
p.total_mass = r->u64();
p.extent = r->u32();
p.surface = r->u64();
p.maintenance = r->u64();
p.movement_speed = r->u32();
p.ingestion_rate = r->u64();
p.conversion_per_thousand = r->u32();
p.thermal_shortfall = r->u32();
c.growth.realized_per_thousand = r->u32();
c.growth.damage_per_thousand = r->u32();
c.state = enumerator<client::OrganismState>(*r, last_state);
cells.push_back(c);
}
if (auto done = r->finish(); !done)
return std::unexpected(done.error());
auto view = client::OrganismPresentation::create(revision, slice, cells);
if (!view)
return std::unexpected(ProtocolError::invalid_value);
return std::pair{header, std::move(*view)};
}
IntentMessage make_intent(std::uint64_t session, std::uint64_t epoch,
const client::Intention& intention) noexcept {
return {session, epoch, intention.sequence, intention.tick, intention.move_x, intention.move_y};
}
} // namespace evo::network
+204
View File
@@ -0,0 +1,204 @@
#include "evo/network/tls_channel.hpp"
#include <algorithm>
#include <climits>
#include <mbedtls/ssl.h>
#include <mbedtls/x509_crt.h>
#include <optional>
#include <psa/crypto.h>
// The owned user config (third_party/mbedtls/evo_mbedtls_config.h) must be in effect.
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) || defined(MBEDTLS_SSL_PROTO_DTLS) || \
defined(MBEDTLS_SSL_SESSION_TICKETS) || defined(MBEDTLS_SSL_RENEGOTIATION) || \
defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED) || \
defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED) || \
!defined(MBEDTLS_SSL_PROTO_TLS1_3)
#error "ADR-0082 requires the TLS 1.3-only Mbed TLS configuration"
#endif
namespace evo::network {
namespace {
// ADR-0082 profile: TLS 1.3 only, AEAD suites, ECDHE groups, ephemeral key exchange.
constexpr int suites[]{MBEDTLS_TLS1_3_AES_128_GCM_SHA256, MBEDTLS_TLS1_3_CHACHA20_POLY1305_SHA256,
0};
constexpr std::uint16_t groups[]{MBEDTLS_SSL_IANA_TLS_GROUP_X25519,
MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1, 0};
const unsigned char* bytes_of(const std::string& text) {
return reinterpret_cast<const unsigned char*>(text.c_str());
}
} // namespace
struct TlsChannel::Impl {
explicit Impl(ByteTransport& t) : transport{t} {
mbedtls_ssl_config_init(&config);
mbedtls_ssl_init(&ssl);
mbedtls_x509_crt_init(&chain);
mbedtls_x509_crt_init(&authority);
mbedtls_pk_init(&key);
}
~Impl() {
mbedtls_ssl_free(&ssl);
mbedtls_ssl_config_free(&config);
mbedtls_x509_crt_free(&chain);
mbedtls_x509_crt_free(&authority);
mbedtls_pk_free(&key); // Zeroizes key material.
}
Impl(const Impl&) = delete;
Impl& operator=(const Impl&) = delete;
static int send(void* context, const unsigned char* buffer, std::size_t length) {
auto& self = *static_cast<Impl*>(context);
const auto result = self.transport.write(
{buffer, std::min<std::size_t>(length, static_cast<std::size_t>(INT_MAX))});
if (!result) {
self.transport_failed = true;
return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
}
return *result == 0 ? MBEDTLS_ERR_SSL_WANT_WRITE : static_cast<int>(*result);
}
static int receive(void* context, unsigned char* buffer, std::size_t length) {
auto& self = *static_cast<Impl*>(context);
const auto result = self.transport.read(
{buffer, std::min<std::size_t>(length, static_cast<std::size_t>(INT_MAX))});
if (!result) {
if (result.error() == TransportError::closed)
return 0; // End of stream.
self.transport_failed = true;
return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
}
return *result == 0 ? MBEDTLS_ERR_SSL_WANT_READ : static_cast<int>(*result);
}
bool common(int endpoint) {
if (psa_crypto_init() != PSA_SUCCESS ||
mbedtls_ssl_config_defaults(&config, endpoint, MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT) != 0)
return false;
mbedtls_ssl_conf_min_tls_version(&config, MBEDTLS_SSL_VERSION_TLS1_3);
mbedtls_ssl_conf_max_tls_version(&config, MBEDTLS_SSL_VERSION_TLS1_3);
mbedtls_ssl_conf_ciphersuites(&config, suites);
mbedtls_ssl_conf_groups(&config, groups);
mbedtls_ssl_conf_tls13_key_exchange_modes(&config,
MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL);
return true;
}
bool attach() {
if (mbedtls_ssl_setup(&ssl, &config) != 0)
return false;
mbedtls_ssl_set_bio(&ssl, this, send, receive, nullptr);
return true;
}
std::unexpected<TlsError> fail(TlsError e) {
error = e;
return std::unexpected(e);
}
std::unexpected<TlsError> fail_from(int code, TlsError otherwise) {
if (transport_failed)
return fail(TlsError::transport);
// Primary chain/name rejection or secondary certificate checks (ssl_tls.c).
if (code == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED || code == MBEDTLS_ERR_SSL_BAD_CERTIFICATE)
return fail(TlsError::peer_verification);
return fail(otherwise);
}
ByteTransport& transport;
mbedtls_ssl_config config;
mbedtls_ssl_context ssl;
mbedtls_x509_crt chain, authority;
mbedtls_pk_context key;
bool transport_failed{};
std::optional<TlsError> error;
};
TlsChannel::TlsChannel(std::unique_ptr<Impl> impl) : impl_{std::move(impl)} {}
TlsChannel::~TlsChannel() = default;
std::expected<std::unique_ptr<TlsChannel>, TlsError>
TlsChannel::server(const ServerCredentials& credentials, ByteTransport& transport) {
auto impl = std::make_unique<Impl>(transport);
if (!impl->common(MBEDTLS_SSL_IS_SERVER))
return std::unexpected(TlsError::configuration);
// PEM parsing requires the terminating NUL in the length.
if (mbedtls_x509_crt_parse(&impl->chain, bytes_of(credentials.certificate_chain_pem),
credentials.certificate_chain_pem.size() + 1) != 0 ||
mbedtls_pk_parse_key(&impl->key, bytes_of(credentials.private_key_pem),
credentials.private_key_pem.size() + 1, nullptr, 0) != 0 ||
mbedtls_pk_check_pair(&impl->chain.pk, &impl->key) != 0 ||
mbedtls_ssl_conf_own_cert(&impl->config, &impl->chain, &impl->key) != 0)
return std::unexpected(TlsError::credentials);
// Client identity is the in-channel grant, not a client certificate.
mbedtls_ssl_conf_authmode(&impl->config, MBEDTLS_SSL_VERIFY_NONE);
if (!impl->attach())
return std::unexpected(TlsError::configuration);
return std::unique_ptr<TlsChannel>(new TlsChannel(std::move(impl)));
}
std::expected<std::unique_ptr<TlsChannel>, TlsError> TlsChannel::client(const ClientTrust& trust,
ByteTransport& transport) {
if (trust.server_name.empty())
return std::unexpected(TlsError::configuration);
auto impl = std::make_unique<Impl>(transport);
if (!impl->common(MBEDTLS_SSL_IS_CLIENT))
return std::unexpected(TlsError::configuration);
if (mbedtls_x509_crt_parse(&impl->authority, bytes_of(trust.authority_pem),
trust.authority_pem.size() + 1) != 0)
return std::unexpected(TlsError::credentials);
mbedtls_ssl_conf_ca_chain(&impl->config, &impl->authority, nullptr);
mbedtls_ssl_conf_authmode(&impl->config, MBEDTLS_SSL_VERIFY_REQUIRED);
if (!impl->attach() || mbedtls_ssl_set_hostname(&impl->ssl, trust.server_name.c_str()) != 0)
return std::unexpected(TlsError::configuration);
return std::unique_ptr<TlsChannel>(new TlsChannel(std::move(impl)));
}
std::expected<TlsProgress, TlsError> TlsChannel::handshake() {
if (const auto latched = impl_->error)
return std::unexpected(*latched);
const int result = mbedtls_ssl_handshake(&impl_->ssl);
if (result == 0)
return TlsProgress::done;
if (result == MBEDTLS_ERR_SSL_WANT_READ || result == MBEDTLS_ERR_SSL_WANT_WRITE)
return TlsProgress::want_io;
return impl_->fail_from(result, TlsError::handshake);
}
std::expected<std::size_t, TlsError> TlsChannel::send(std::span<const std::uint8_t> bytes) {
if (const auto latched = impl_->error)
return std::unexpected(*latched);
const int result = mbedtls_ssl_write(&impl_->ssl, bytes.data(), bytes.size());
if (result >= 0)
return static_cast<std::size_t>(result);
if (result == MBEDTLS_ERR_SSL_WANT_READ || result == MBEDTLS_ERR_SSL_WANT_WRITE)
return 0;
return impl_->fail_from(result, TlsError::record);
}
std::expected<std::size_t, TlsError> TlsChannel::receive(std::span<std::uint8_t> bytes) {
if (const auto latched = impl_->error)
return std::unexpected(*latched);
const int result = mbedtls_ssl_read(&impl_->ssl, bytes.data(), bytes.size());
if (result > 0)
return static_cast<std::size_t>(result);
if (result == MBEDTLS_ERR_SSL_WANT_READ || result == MBEDTLS_ERR_SSL_WANT_WRITE)
return 0;
if (result == 0 || result == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
return impl_->fail(TlsError::closed);
return impl_->fail_from(result, TlsError::record);
}
std::expected<TlsProgress, TlsError> TlsChannel::close() {
if (const auto latched = impl_->error)
return std::unexpected(*latched);
const int result = mbedtls_ssl_close_notify(&impl_->ssl);
if (result == 0)
return TlsProgress::done;
if (result == MBEDTLS_ERR_SSL_WANT_READ || result == MBEDTLS_ERR_SSL_WANT_WRITE)
return TlsProgress::want_io;
return impl_->fail_from(result, TlsError::record);
}
std::string_view TlsChannel::version() const noexcept {
const char* name = mbedtls_ssl_get_version(&impl_->ssl);
return name == nullptr ? std::string_view{} : std::string_view{name};
}
std::string_view TlsChannel::suite() const noexcept {
const char* name = mbedtls_ssl_get_ciphersuite(&impl_->ssl);
return name == nullptr ? std::string_view{} : std::string_view{name};
}
} // namespace evo::network
+129
View File
@@ -0,0 +1,129 @@
#include "evo/network/dev_grant.hpp"
#include <algorithm>
#include <psa/crypto.h>
#include <type_traits>
namespace evo::network {
namespace {
static_assert(std::is_same_v<mbedtls_svc_key_id_t, std::uint32_t>,
"key ids are stored as plain PSA identifiers");
constexpr std::array<std::uint8_t, 16> marker{'E', 'V', 'O', '-', 'D', 'E', 'V', '-',
'O', 'N', 'L', 'Y', 0, 0, 0, 0};
constexpr std::uint16_t grant_version = 1;
constexpr std::uint8_t dev_environment_byte = 1;
constexpr std::size_t claims_end = 76; // Tag covers bytes [0, 76).
constexpr psa_algorithm_t algorithm = PSA_ALG_HMAC(PSA_ALG_SHA_256);
void put(DevGrant& out, std::size_t at, std::uint64_t v, std::size_t count) {
for (std::size_t i = 0; i < count; ++i)
out.at(at + i) = static_cast<std::uint8_t>(v >> (8 * i));
}
std::uint64_t get(std::span<const std::uint8_t> in, std::size_t at, std::size_t count) {
std::uint64_t v = 0;
for (std::size_t i = 0; i < count; ++i)
v |= static_cast<std::uint64_t>(in[at + i]) << (8 * i);
return v;
}
bool structurally_valid(const DevGrantClaims& c) {
return c.grant_id != 0 && c.subject != 0 && c.world.world != 0 && c.world.frame != 0 &&
c.region != 0 && c.expires_at > c.issued_at;
}
} // namespace
std::expected<DevGrantKey, GrantError> DevGrantKey::import(DeploymentEnvironment environment,
std::span<const std::uint8_t> secret) {
// The dev identity must not exist anywhere but the dev environment.
if (environment != DeploymentEnvironment::dev)
return std::unexpected(GrantError::not_dev_environment);
if (secret.size() != dev_key_bytes ||
std::ranges::all_of(secret, [](std::uint8_t b) { return b == 0; }))
return std::unexpected(GrantError::invalid_key);
if (psa_crypto_init() != PSA_SUCCESS)
return std::unexpected(GrantError::crypto);
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_set_key_type(&attributes, PSA_KEY_TYPE_HMAC);
psa_set_key_bits(&attributes, dev_key_bytes * 8);
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE | PSA_KEY_USAGE_VERIFY_MESSAGE);
psa_set_key_algorithm(&attributes, algorithm);
mbedtls_svc_key_id_t key = PSA_KEY_ID_NULL;
const auto status = psa_import_key(&attributes, secret.data(), secret.size(), &key);
psa_reset_key_attributes(&attributes);
if (status != PSA_SUCCESS)
return std::unexpected(GrantError::crypto);
return DevGrantKey{key};
}
DevGrantKey::DevGrantKey(DevGrantKey&& other) noexcept : key_{other.key_} {
other.key_ = PSA_KEY_ID_NULL;
}
DevGrantKey& DevGrantKey::operator=(DevGrantKey&& other) noexcept {
if (this != &other) {
if (key_ != PSA_KEY_ID_NULL)
(void)psa_destroy_key(key_);
key_ = other.key_;
other.key_ = PSA_KEY_ID_NULL;
}
return *this;
}
DevGrantKey::~DevGrantKey() {
if (key_ != PSA_KEY_ID_NULL)
(void)psa_destroy_key(key_);
}
std::expected<DevGrant, GrantError> DevGrantKey::issue(const DevGrantClaims& claims) const {
if (key_ == PSA_KEY_ID_NULL)
return std::unexpected(GrantError::invalid_key);
if (!structurally_valid(claims))
return std::unexpected(GrantError::invalid_claims);
DevGrant out{};
std::ranges::copy(marker, out.begin());
put(out, 16, grant_version, 2);
out.at(18) = dev_environment_byte;
out.at(19) = 0;
put(out, 20, claims.grant_id, 8);
put(out, 28, claims.subject, 8);
put(out, 36, claims.world.world, 8);
put(out, 44, claims.world.frame, 8);
put(out, 52, claims.region, 8);
put(out, 60, claims.issued_at, 8);
put(out, 68, claims.expires_at, 8);
std::size_t length = 0;
if (psa_mac_compute(key_, algorithm, out.data(), claims_end, out.data() + claims_end,
dev_grant_bytes - claims_end, &length) != PSA_SUCCESS ||
length != dev_grant_bytes - claims_end)
return std::unexpected(GrantError::crypto);
return out;
}
std::expected<VerifiedGrant, GrantError>
DevGrantKey::verify(std::span<const std::uint8_t> grant) const {
if (key_ == PSA_KEY_ID_NULL)
return std::unexpected(GrantError::invalid_key);
if (grant.size() != dev_grant_bytes)
return std::unexpected(GrantError::malformed);
// Authenticate first: no claim byte influences behaviour until the tag matches.
const auto status = psa_mac_verify(key_, algorithm, grant.data(), claims_end,
grant.data() + claims_end, dev_grant_bytes - claims_end);
if (status == PSA_ERROR_INVALID_SIGNATURE)
return std::unexpected(GrantError::bad_tag);
if (status != PSA_SUCCESS)
return std::unexpected(GrantError::crypto);
if (!std::equal(marker.begin(), marker.end(), grant.begin()))
return std::unexpected(GrantError::wrong_marker);
if (get(grant, 16, 2) != grant_version || grant[19] != 0)
return std::unexpected(GrantError::unsupported_version);
if (grant[18] != dev_environment_byte)
return std::unexpected(GrantError::wrong_environment);
DevGrantClaims claims;
claims.grant_id = get(grant, 20, 8);
claims.subject = get(grant, 28, 8);
claims.world = {get(grant, 36, 8), get(grant, 44, 8)};
claims.region = get(grant, 52, 8);
claims.issued_at = get(grant, 60, 8);
claims.expires_at = get(grant, 68, 8);
if (!structurally_valid(claims))
return std::unexpected(GrantError::invalid_claims);
return VerifiedGrant{claims};
}
} // namespace evo::network