Files
aevolution/tests/network_tls.cpp
T
dingoandClaude Opus 5.5 8fbe093cc8 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>
2026-10-01 18:53:55 -04:00

254 lines
10 KiB
C++

#include "evo/network/protocol.hpp"
#include "evo/network/tls_channel.hpp"
#include "network_test.hpp"
#include <array>
#include <deque>
#include <mbedtls/x509_crt.h>
#include <psa/crypto.h>
#include <string>
#include <vector>
namespace evo::network_test {
namespace {
using namespace evo::network;
constexpr const char* server_name = "dev-region.evolution.test";
// Throwaway test credentials; production/dev deployment keys are never generated here.
struct Key {
Key() {
mbedtls_pk_init(&pk);
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1));
psa_set_key_bits(&attributes, 256);
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH | PSA_KEY_USAGE_EXPORT);
psa_set_key_algorithm(&attributes, PSA_ALG_ECDSA(PSA_ALG_SHA_256));
mbedtls_svc_key_id_t id = PSA_KEY_ID_NULL;
CHECK(psa_crypto_init() == PSA_SUCCESS &&
psa_generate_key(&attributes, &id) == PSA_SUCCESS);
CHECK(mbedtls_pk_copy_from_psa(id, &pk) == 0);
(void)psa_destroy_key(id);
}
~Key() {
mbedtls_pk_free(&pk);
}
Key(const Key&) = delete;
Key& operator=(const Key&) = delete;
[[nodiscard]] std::string pem() {
std::array<unsigned char, 4096> buffer{};
CHECK(mbedtls_pk_write_key_pem(&pk, buffer.data(), buffer.size()) == 0);
return reinterpret_cast<const char*>(buffer.data());
}
mbedtls_pk_context pk;
};
std::string certificate(Key& subject, Key& issuer, const char* subject_name,
const char* issuer_name, bool authority, unsigned char serial) {
mbedtls_x509write_cert crt;
mbedtls_x509write_crt_init(&crt);
mbedtls_x509write_crt_set_version(&crt, MBEDTLS_X509_CRT_VERSION_3);
mbedtls_x509write_crt_set_md_alg(&crt, MBEDTLS_MD_SHA256);
mbedtls_x509write_crt_set_subject_key(&crt, &subject.pk);
mbedtls_x509write_crt_set_issuer_key(&crt, &issuer.pk);
CHECK(mbedtls_x509write_crt_set_serial_raw(&crt, &serial, 1) == 0 &&
mbedtls_x509write_crt_set_validity(&crt, "20250101000000", "20991231235959") == 0 &&
mbedtls_x509write_crt_set_subject_name(&crt, subject_name) == 0 &&
mbedtls_x509write_crt_set_issuer_name(&crt, issuer_name) == 0 &&
mbedtls_x509write_crt_set_basic_constraints(&crt, authority ? 1 : 0, -1) == 0 &&
mbedtls_x509write_crt_set_key_usage(&crt, authority
? MBEDTLS_X509_KU_KEY_CERT_SIGN
: MBEDTLS_X509_KU_DIGITAL_SIGNATURE) == 0);
std::array<unsigned char, 4096> buffer{};
const int result = mbedtls_x509write_crt_pem(&crt, buffer.data(), buffer.size());
mbedtls_x509write_crt_free(&crt);
CHECK(result == 0);
return reinterpret_cast<const char*>(buffer.data());
}
struct Pki {
Pki(const char* name = server_name) {
authority =
certificate(ca_key, ca_key, "CN=AEvolution dev CA", "CN=AEvolution dev CA", true, 1);
const std::string subject = std::string{"CN="} + name;
server.certificate_chain_pem =
certificate(server_key, ca_key, subject.c_str(), "CN=AEvolution dev CA", false, 2);
server.private_key_pem = server_key.pem();
}
Key ca_key, server_key;
std::string authority;
ServerCredentials server;
};
// Two in-memory byte queues with optional faults.
struct Wire {
std::deque<std::uint8_t> to_server, to_client;
bool fail{};
};
class Endpoint final : public ByteTransport {
public:
Endpoint(Wire& wire, bool is_server) : wire_{wire}, server_{is_server} {}
std::expected<std::size_t, TransportError> write(std::span<const std::uint8_t> bytes) override {
if (wire_.fail)
return std::unexpected(TransportError::failed);
auto& out = server_ ? wire_.to_client : wire_.to_server;
const auto count = std::min<std::size_t>(bytes.size(), 700); // Force partial writes.
out.insert(out.end(), bytes.begin(), bytes.begin() + static_cast<std::ptrdiff_t>(count));
return count;
}
std::expected<std::size_t, TransportError> read(std::span<std::uint8_t> bytes) override {
if (wire_.fail)
return std::unexpected(TransportError::failed);
auto& in = server_ ? wire_.to_server : wire_.to_client;
const auto count = std::min(bytes.size(), in.size());
for (std::size_t i = 0; i < count; ++i) {
bytes[i] = in.front();
in.pop_front();
}
return count;
}
private:
Wire& wire_;
bool server_;
};
struct Pair {
explicit Pair(const ServerCredentials& credentials, const ClientTrust& trust)
: server_end{wire, true}, client_end{wire, false} {
auto s = TlsChannel::server(credentials, server_end);
auto c = TlsChannel::client(trust, client_end);
CHECK(s && c);
server = std::move(*s);
client = std::move(*c);
}
// Pumps both handshakes; returns the first error, if any.
std::expected<void, std::pair<bool, TlsError>> handshake() {
bool server_done = false, client_done = false;
for (int i = 0; i < 200 && !(server_done && client_done); ++i) {
if (!client_done) {
const auto p = client->handshake();
if (!p)
return std::unexpected(std::pair{false, p.error()});
client_done = *p == TlsProgress::done;
}
if (!server_done) {
const auto p = server->handshake();
if (!p)
return std::unexpected(std::pair{true, p.error()});
server_done = *p == TlsProgress::done;
}
}
CHECK(server_done && client_done);
return {};
}
std::vector<std::uint8_t> transfer(TlsChannel& from, TlsChannel& to,
std::span<const std::uint8_t> bytes) {
std::size_t sent = 0;
std::vector<std::uint8_t> received;
std::array<std::uint8_t, 4096> buffer{};
for (int i = 0; i < 1000 && received.size() < bytes.size(); ++i) {
if (sent < bytes.size()) {
const auto n = from.send(bytes.subspan(sent));
CHECK(n);
sent += *n;
}
const auto n = to.receive(buffer);
CHECK(n);
received.insert(received.end(), buffer.begin(),
buffer.begin() + static_cast<std::ptrdiff_t>(*n));
}
return received;
}
Wire wire;
Endpoint server_end, client_end;
std::unique_ptr<TlsChannel> server, client;
};
void handshake_and_frames() {
Pki pki;
Pair pair{pki.server, {pki.authority, server_name}};
CHECK(pair.handshake());
CHECK(pair.client->version() == "TLSv1.3" && pair.server->version() == "TLSv1.3");
const auto suite = pair.client->suite();
CHECK(suite == "TLS1-3-AES-128-GCM-SHA256" || suite == "TLS1-3-CHACHA20-POLY1305-SHA256");
// A protocol frame crosses the channel and is reassembled by a FrameReader.
const auto hello = encode(Hello{0, std::vector<std::uint8_t>(108, 0x42)});
CHECK(hello);
const auto at_server = pair.transfer(*pair.client, *pair.server, *hello);
CHECK(at_server == *hello);
FrameReader reader;
CHECK(reader.feed(at_server));
const auto frame = reader.take();
CHECK(frame && frame->type == MessageType::hello);
const auto large = std::vector<std::uint8_t>(100'000, 0x17); // Multiple TLS records.
CHECK(pair.transfer(*pair.server, *pair.client, large) == large);
// Orderly close: the peer observes close_notify as `closed`.
CHECK(pair.client->close());
std::array<std::uint8_t, 16> buffer{};
std::expected<std::size_t, TlsError> r = 0;
for (int i = 0; i < 10 && r && *r == 0; ++i)
r = pair.server->receive(buffer);
CHECK(refused(r, TlsError::closed));
CHECK(refused(pair.server->send(buffer), TlsError::closed)); // Latched.
}
void rejections() {
Pki pki;
Pki other;
// Untrusted authority and wrong host name fail peer verification on the client.
{
Pair pair{pki.server, {other.authority, server_name}};
const auto r = pair.handshake();
CHECK(!r && !r.error().first && r.error().second == TlsError::peer_verification);
}
{
Pair pair{pki.server, {pki.authority, "other.evolution.test"}};
const auto r = pair.handshake();
CHECK(!r && !r.error().first && r.error().second == TlsError::peer_verification);
}
// Configuration and credential errors.
Wire wire;
Endpoint end{wire, false};
CHECK(refused(TlsChannel::client({pki.authority, ""}, end), TlsError::configuration));
CHECK(refused(TlsChannel::client({"not a certificate", server_name}, end),
TlsError::credentials));
CHECK(refused(TlsChannel::server({pki.server.certificate_chain_pem, "garbage"}, end),
TlsError::credentials));
CHECK(refused(
TlsChannel::server({pki.server.certificate_chain_pem, other.server.private_key_pem}, end),
TlsError::credentials)); // Key does not match the certificate.
// A modified application record is rejected (AEAD integrity).
{
Pair pair{pki.server, {pki.authority, server_name}};
CHECK(pair.handshake());
const std::array<std::uint8_t, 64> data{};
const auto sent = pair.client->send(data);
CHECK(sent && *sent == data.size());
CHECK(pair.wire.to_server.size() > 20);
pair.wire.to_server[pair.wire.to_server.size() - 5] ^= 0x01;
std::array<std::uint8_t, 256> buffer{};
auto r = pair.server->receive(buffer);
while (r && *r > 0)
r = pair.server->receive(buffer);
CHECK(refused(r, TlsError::record));
}
// Transport failure surfaces as `transport` and latches.
{
Pair pair{pki.server, {pki.authority, server_name}};
pair.wire.fail = true;
CHECK(refused(pair.client->handshake(), TlsError::transport));
CHECK(refused(pair.client->handshake(), TlsError::transport));
}
// Plaintext protocol bytes are not TLS: the server rejects them.
{
Pair pair{pki.server, {pki.authority, server_name}};
const auto plain = encode(IntentMessage{1, 1, 1, 1, 0, 0});
pair.wire.to_server.insert(pair.wire.to_server.end(), plain.begin(), plain.end());
const auto r = pair.server->handshake();
CHECK(!r && r.error() == TlsError::handshake);
}
}
} // namespace
void tls_tests() {
handshake_and_frames();
rejections();
}
} // namespace evo::network_test