From 5f587f80e1f03074ce0ef14e2e55ffe00d50c1af Mon Sep 17 00:00:00 2001 From: dingo Date: Wed, 7 Oct 2026 22:57:45 -0400 Subject: [PATCH] Add M10.9c-1 session fuzzing and in-process abuse tests ADR-0097. A libFuzzer target for session protocol v4, grants, tickets and snapshot assembly (canonical re-encoding, verifiers always refuse, a completed snapshot is applied), with the code under test compiled in, and a seeded smoke CTest of the same target on every platform. Four quic-sessions abuse tests measure an honest session tick by tick under a Hello flood (garbage, untrusted grants, silence), a datagram flood, a slow peer and a connect/disconnect storm; it keeps every snapshot and receipt while connections and retained state stay bounded. evo-session-probe run --grants FILE [--grant N] logs in from an existing bundle (a dev renewal's) without an issuer key. client_lifecycle uses SDL_getenv (MSVC rejected std::getenv). Co-Authored-By: Claude Opus 5.5 --- CMakePresets.json | 8 +- apps/evo-session-probe/main.cpp | 72 +++-- cmake/Network.cmake | 16 ++ docs/ROADMAP.md | 6 +- docs/STATUS.md | 10 +- .../0097-m10-load-and-abuse-qualification.md | 40 +++ docs/engineering/VALIDATION.md | 41 +++ tests/client_lifecycle.cpp | 2 +- tests/fuzz/session_fuzz.cpp | 78 ++++++ tests/fuzz/session_fuzz_smoke.cpp | 68 +++++ tests/quic_sessions.cpp | 261 ++++++++++++++++++ tests/region_m10_session_tests.cpp | 21 ++ 12 files changed, 597 insertions(+), 26 deletions(-) create mode 100644 tests/fuzz/session_fuzz.cpp create mode 100644 tests/fuzz/session_fuzz_smoke.cpp diff --git a/CMakePresets.json b/CMakePresets.json index 1f3aac4..d7f18f5 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -23,10 +23,10 @@ {"name": "tsan", "configurePreset": "tsan"}, {"name": "client", "configurePreset": "client", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-client-ui-model-tests", "evo-client-panel-tests", "evo-client-bindings-tests"]}, {"name": "client-probe", "configurePreset": "client-probe", "targets": ["evo-client-probe"]}, - {"name": "network", "configurePreset": "network", "targets": ["evo-client-state-tests", "evo-network-tests", "evo-dev-session"]}, - {"name": "quic", "configurePreset": "quic", "targets": ["evo-quic-smoke-tests", "evo-quic-transport-tests", "evo-quic-session-tests", "evo-quic-hol-measure", "evo-session-probe", "evo-load", "evo-network-tests"]}, - {"name": "client-network", "configurePreset": "client-network", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-client-ui-model-tests", "evo-client-panel-tests", "evo-client-bindings-tests", "evo-network-tests", "evo-dev-session", "evo-quic-session-tests", "evo-client-remote-tests", "evo-motion-trace", "evo-session-probe"]}, - {"name": "client-package", "configurePreset": "client-package", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-client-ui-model-tests", "evo-client-panel-tests", "evo-client-bindings-tests", "evo-network-tests", "evo-dev-session", "evo-quic-session-tests", "evo-client-remote-tests", "evo-motion-trace"]} + {"name": "network", "configurePreset": "network", "targets": ["evo-client-state-tests", "evo-network-tests", "evo-session-fuzz-smoke", "evo-dev-session"]}, + {"name": "quic", "configurePreset": "quic", "targets": ["evo-quic-smoke-tests", "evo-quic-transport-tests", "evo-quic-session-tests", "evo-quic-hol-measure", "evo-session-probe", "evo-load", "evo-network-tests", "evo-session-fuzz-smoke"]}, + {"name": "client-network", "configurePreset": "client-network", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-client-ui-model-tests", "evo-client-panel-tests", "evo-client-bindings-tests", "evo-network-tests", "evo-session-fuzz-smoke", "evo-dev-session", "evo-quic-session-tests", "evo-client-remote-tests", "evo-motion-trace", "evo-session-probe"]}, + {"name": "client-package", "configurePreset": "client-package", "targets": ["evo-client-state-tests", "evo-client", "evo-client-lifecycle-tests", "evo-client-environment-tests", "evo-client-organism-tests", "evo-client-ui-model-tests", "evo-client-panel-tests", "evo-client-bindings-tests", "evo-network-tests", "evo-session-fuzz-smoke", "evo-dev-session", "evo-quic-session-tests", "evo-client-remote-tests", "evo-motion-trace"]} ], "testPresets": [ {"name": "debug", "configurePreset": "debug", "output": {"outputOnFailure": true}}, diff --git a/apps/evo-session-probe/main.cpp b/apps/evo-session-probe/main.cpp index d1eeb47..4f8fd7e 100644 --- a/apps/evo-session-probe/main.cpp +++ b/apps/evo-session-probe/main.cpp @@ -34,6 +34,12 @@ // answered but failed the pinned CA/name check; idle means nothing answered) // Statuses, results and reasons are the session-v1 wire values. Exits 0 once every // action is final and every query answered, 1 on timeout, 3 when the server closes. +// evo-session-probe run --connect HOST:PORT --server-name NAME --ca FILE --grants FILE +// [--grant N] [options as above] +// M10.9 (ADR-0097): logs in with grant N (from 0) of an existing bundle instead of +// signing one, e.g. the bundle a dev renewal produced; no issuer key is needed here. +// Serials rise through a bundle and a used serial is refused (stale_grant), so each +// login takes the next N. Prints "grant N of COUNT" first. // The issuer key is a development credential: the probe refuses any environment but dev. #include "evo/client/region_session.hpp" #include "evo/network/session_grant.hpp" @@ -161,7 +167,8 @@ int keys(const std::filesystem::path& out) { } struct RunOptions { - std::string host, server_name, ca, issuer_key; + std::string host, server_name, ca, issuer_key, grants_file; + std::uint64_t grant_index{}; std::uint16_t port{}; std::uint64_t world{}, frame{}, region{}, serial{}, lifetime{60}, intents{}, actions{}, action_base{1}, timeout_ms{20000}; @@ -242,22 +249,44 @@ int grants(const RunOptions& o, const std::string& out, std::uint64_t count) { return 0; } +// Grant `index` of a bundle file (concatenated 160-byte grants). +std::optional bundled(const std::string& path, std::uint64_t index) { + const auto bytes = read(path); + const auto count = bytes.size() / session_grant_bytes; + if (bytes.empty() || bytes.size() % session_grant_bytes != 0 || index >= count) + return std::nullopt; + SessionGrant g{}; + std::copy_n(bytes.begin() + static_cast(index * session_grant_bytes), + session_grant_bytes, reinterpret_cast(g.data())); + std::printf("grant %llu of %zu\n", static_cast(index), count); + return g; +} + int run(const RunOptions& o) { - const auto key = issuer(o.issuer_key); - if (!key) { - std::puts("error issuer-key"); - return 2; + std::optional grant; + if (!o.grants_file.empty()) { + grant = bundled(o.grants_file, o.grant_index); + if (!grant) { + std::puts("error grants"); + return 2; + } + } else { + const auto key = issuer(o.issuer_key); + if (!key) { + std::puts("error issuer-key"); + return 2; + } + if (!o.account) + return 2; // Required at parse time. + GrantClaims claims; + claims.account = *o.account; + claims.serial = o.serial; + claims.world = {o.world, o.frame}; + claims.region = o.region; + claims.issued_at = now_seconds(); + claims.expires_at = claims.issued_at + o.lifetime; + grant = sign(*key, claims); } - if (!o.account) - return 2; // Required at parse time. - GrantClaims claims; - claims.account = *o.account; - claims.serial = o.serial; - claims.world = {o.world, o.frame}; - claims.region = o.region; - claims.issued_at = now_seconds(); - claims.expires_at = claims.issued_at + o.lifetime; - const auto grant = sign(*key, claims); if (!grant) { std::puts("error grant"); return 2; @@ -424,6 +453,10 @@ int main(int argc, char** argv) { o.ca = value; else if (flag == "--issuer-key") o.issuer_key = value; + else if (flag == "--grants" && !bundle) + o.grants_file = value; + else if (n && flag == "--grant" && !bundle) + o.grant_index = *n; else if (flag == "--account") ok = (o.account = account_of(value)).has_value(); else if (flag == "--query" && n) @@ -462,16 +495,19 @@ int main(int argc, char** argv) { if (bundle && ok && !o.issuer_key.empty() && o.account && o.world != 0 && o.frame != 0 && o.region != 0 && !out.empty() && o.lifetime >= 60 && o.host.empty()) return grants(o, out, count); + const bool signs = o.grants_file.empty(); if (bundle || !ok || o.host.empty() || o.server_name.empty() || o.ca.empty() || - o.issuer_key.empty() || !o.account || o.world == 0 || o.frame == 0 || o.region == 0 || - o.serial == 0) { + (signs && (o.issuer_key.empty() || !o.account || o.world == 0 || o.frame == 0 || + o.region == 0 || o.serial == 0)) || + (!signs && !o.issuer_key.empty())) { std::fputs("usage: evo-session-probe keys --out DIR | grants --issuer-key FILE " "--world N --frame N --region N --account HEX32 --out FILE [--serial N] " "[--count 1..64] [--lifetime 60..14400] | run --connect HOST:PORT " "--server-name NAME --ca FILE --issuer-key FILE --world N --frame N " "--region N --account HEX32 --serial N [--lifetime S] [--intents N] " "[--actions N --action-base ID] [--query ID]... [--timeout-ms N] " - "[--interest X,Y,Z,R] [--snapshots N]\n", + "[--interest X,Y,Z,R] [--snapshots N] | run --connect HOST:PORT " + "--server-name NAME --ca FILE --grants FILE [--grant N] [run options]\n", stderr); return 2; } diff --git a/cmake/Network.cmake b/cmake/Network.cmake index bf47ae5..791b19a 100644 --- a/cmake/Network.cmake +++ b/cmake/Network.cmake @@ -74,6 +74,12 @@ if(BUILD_TESTING) evo_owned_target(evo-network-tests) add_test(NAME network COMMAND evo-network-tests) set_tests_properties(network PROPERTIES TIMEOUT 120 LABELS "network") + # M10.9c (ADR-0097): the session protocol fuzz target, run as a seeded smoke test. + add_executable(evo-session-fuzz-smoke tests/fuzz/session_fuzz.cpp tests/fuzz/session_fuzz_smoke.cpp) + target_link_libraries(evo-session-fuzz-smoke PRIVATE evo_network_tls) + evo_owned_target(evo-session-fuzz-smoke) + add_test(NAME session-fuzz-smoke COMMAND evo-session-fuzz-smoke) + set_tests_properties(session-fuzz-smoke PROPERTIES TIMEOUT 300 LABELS "network") endif() if(EVO_BUILD_FUZZER) # Coverage-guided codec fuzzing (Linux Clang; see the EVO_BUILD_FUZZER guard). @@ -83,4 +89,14 @@ if(EVO_BUILD_FUZZER) evo_owned_target(evo-dev-session-fuzz) target_compile_options(evo-dev-session-fuzz PRIVATE -fsanitize=fuzzer,address,undefined -fno-omit-frame-pointer) target_link_options(evo-dev-session-fuzz PRIVATE -fsanitize=fuzzer,address,undefined) + # M10.9c: session protocol v4, grants, tickets and snapshot assembly (ADR-0097). + # The code under test is compiled into the target so coverage instruments it. + add_executable(evo-session-fuzz tests/fuzz/session_fuzz.cpp + src/network/protocol/session_protocol.cpp src/network/protocol/replication.cpp + src/network/protocol/probe_motion.cpp src/network/protocol/session_control.cpp src/network/tls/session_grant.cpp + src/network/tls/handoff_ticket.cpp) + target_link_libraries(evo-session-fuzz PRIVATE evo_client_views evo_client_controls mbedtls) + evo_owned_target(evo-session-fuzz) + target_compile_options(evo-session-fuzz PRIVATE -fsanitize=fuzzer,address,undefined -fno-omit-frame-pointer) + target_link_options(evo-session-fuzz PRIVATE -fsanitize=fuzzer,address,undefined) endif() diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index e72648f..2ac8205 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -545,8 +545,10 @@ sweep, replay guard). M10.8 complete. 10.9 split (ADR-0097; only evolution-dev r runs qualify): 10.9a per-tick work measurement, load governor (refuse logins, then shed replication with hysteresis) and its metrics done; 10.9b evo-load multi-client tool (per-client distributions, starvation check, step verdicts, server gauges) and its process -smoke done; 10.9c abuse suite (fuzz, floods, slow peers, storms, lease loss) and 10.9d -dev-cluster harness and reference results follow. +smoke done; 10.9c-1 session fuzz target and smoke, in-process Hello and datagram floods, +slow peer and connect/disconnect storm with honest-service checks done; 10.9c-2 lease loss +with 20+ bots and a live raw-UDP abuse sender, and 10.9d dev-cluster drill harness and +reference results follow. **Entry:** M9 client/session evidence and M7/M8 dev/stage durability. Read NETWORK_ARCHITECTURE, PERSISTENCE_ARCHITECTURE and ADR-0017. The M9 transport is diff --git a/docs/STATUS.md b/docs/STATUS.md index f4e715d..33e5370 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -113,7 +113,15 @@ per step pooled and per-client distributions, a starvation check, a budget verdi region's gauges, ending with the sustainable bot count. In a local development reference (not evidence), one region stayed within budget up to 24 bots and the governor began refusing at 32 (work p95 about 14 ms), with responses about 103 ms and outcomes about -665 ms throughout. Next: 10.9c, the abuse suite. +665 ms throughout. M10.9c-1 adds the abuse suite's first half: +- a libFuzzer target for session protocol v4, grants, tickets and snapshot assembly (23 + million inputs, no findings), also run as a seeded smoke test on every platform; +- in-process floods (Hello, datagram), a slow peer and a connect/disconnect storm, during + which an honest session kept every snapshot and receipt. + +`evo-session-probe` can now log in from a renewal's grant bundle. A dev login was welcomed +and its intention admitted (the dev region does not simulate outside drills). Next: +10.9c-2, lease loss with 20+ bots and a live raw-UDP sender. ## Previous gate - 2026-10-02 diff --git a/docs/adr/0097-m10-load-and-abuse-qualification.md b/docs/adr/0097-m10-load-and-abuse-qualification.md index f7edf41..f6e9de2 100644 --- a/docs/adr/0097-m10-load-and-abuse-qualification.md +++ b/docs/adr/0097-m10-load-and-abuse-qualification.md @@ -155,3 +155,43 @@ snapshots. limit, and the 32 established sessions are unaffected. Prediction errors were 0 (no loss on loopback), and no client starved at any step. The host step dominates the work; the session layer stays near 0.25 ms per session (budget 0.5). + +## 10.9c-1 abuse suite: fuzzing and in-process abuse (2026-10-07) +- **Fuzzing** (`tests/fuzz/session_fuzz.cpp`). For any input: + - `decode_session` never crashes, and an accepted message has a stable canonical form + (decode, encode, decode, encode gives the same bytes); + - an accepted snapshot chunk reaches the client's assembler without crashing; + - `GrantVerifier` and `HandoffVerifier` refuse the bytes, as they do the grant slot of a + decoded Hello. Each holds a real key, so an acceptance would mean a claim byte was + trusted before the signature. + + Two builds: + - `evo-session-fuzz`: libFuzzer with ASan and UBSan behind `EVO_BUILD_FUZZER`, with the + session codec, replication, motion, control and verifier sources compiled in so + coverage instruments them; + - `session-fuzz-smoke`: CTest, label `network`, on every platform. It feeds 68,000 + seeded inputs: random bytes, and bit flips, truncations, extensions and edge-byte + overwrites of an encoding of every v4 message type. +- **In-process abuse** (`quic-sessions`). Each test measures an honest session tick by tick + while the abuse runs. It must keep at least 90 % of its snapshots and admitted receipts, + and the server's connections and retained state must stay bounded: + - **Hello flood:** 160 raw connections over 40 ticks, sending garbage (closed with + `protocol`), well-formed Hellos signed by an untrusted key (`unauthenticated`), or + nothing (`timeout`). Connections stay within the transport bound of 32, and the region + returns to the honest connection alone. + - **Datagram flood:** an authenticated peer sends hundreds of intentions per tick for any + tick. They are throttled per session (one per tick, refused receipts), and garbage + then closes the peer (`protocol`). + - **Slow peer:** an established client that never reads or acknowledges anything. The + server retains at most its baselines for it (392 entities against a bound of 490). + - **Storm:** 120 logins across 12 accounts, half closed politely and half vanishing. The + region returns to one session and one connection. +- **Probe:** `evo-session-probe run --grants FILE [--grant N]` logs in with grant N of an + existing bundle, such as one from the dev renewal, without an issuer key. It is covered + by the M10 process test and was used against evolution-dev, where the login was welcomed + and its intention admitted. That region runs without synthetic inputs, as the Git + policy requires, so nothing is simulated there outside a drill. +- **Not yet (10.9c-2):** lease loss and SIGKILL with 20 or more `evo-load` bots attached, + and a live raw-UDP sender of mutated datagrams. Our client endpoint caps its own send + rate, so it cannot load the server's per-connection datagram cap (64, newest wins, with + an O(queue) eviction scan); the raw sender measures that. diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index 3bc6143..1396990 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -5022,3 +5022,44 @@ Evidence: in the 2026-10-07 Gitea client run, all 13 CTest tests and the X11 pro smokes passed; only the extra 32-cycle X11 invocation failed at `Application::open()`. The same 32-cycle lifecycle test passed under SDL's dummy driver. The X11 failure did not report its typed error, so the failing X11 backend stage was not established. + +## 2026-10-07 — M10.9c-1 fuzzing and in-process abuse (ADR-0097) + +Implemented: +- `tests/fuzz/session_fuzz.cpp` as a libFuzzer target (`evo-session-fuzz`, with the code + under test compiled in) and the seeded `session-fuzz-smoke` CTest (label `network`). +- Four `quic-sessions` abuse tests, each measuring an honest session tick by tick: + Hello flood, datagram flood, slow peer, and a connect/disconnect storm. +- `evo-session-probe run --grants FILE [--grant N]`, covered by the M10 process test. +- `tests/client_lifecycle.cpp` uses `SDL_getenv`: MSVC rejected `std::getenv` + (deprecation warning as error) from `1204750`, which CI cannot see (no Windows runner). + +Results: +- **libFuzzer** (Clang 19, ASan and UBSan): 35.6 million inputs, then 23.3 million after + the snapshot-application assertion was added, 5 minutes each. Coverage 1541, then 1650; + no crash or sanitizer report. +- **Smoke:** 68,000 inputs per run. +- **Hello flood:** 160 peers. Every connected one was refused with the right reason + (52 `protocol`, 51 `unauthenticated`, 50 `timeout`), connections peaked at 29 of 32, + and the honest session kept 60 of 60 snapshots and receipts. +- **Datagram flood:** 1920 intentions accepted by the sender, of which 1914 were refused + by the throttle. Garbage closed the peer with `protocol`, and the honest session kept + 40 of 40. +- **Slow peer:** retained entities peaked at 392 against a bound of 490, and the honest + session kept 80 of 80. +- **Storm:** 120 logins (69 seen established). The region returned to one session and one + connection, and the honest session kept 60 of 60. +- **evolution-dev, with the renewal's bundle:** grant 0 was welcomed (epoch 51), and its + first intention and an action were admitted. Nothing is simulated there outside a drill + (`REGION_INPUTS` is empty by policy), so there were no outcomes or snapshots. + +Executed: +- **Linux GCC 14:** + - presets `quic` and `network` 5/5; + - `postgres-check.sh` with QUIC, all 18 suites, with the probe's bundle login. +- **Linux Clang 19:** clang-tidy 19 on the fuzz target and smoke, `quic_sessions.cpp`, the + probe and the M10 process tests (8 findings fixed); clang-format 19. +- **Windows MSVC 19.44:** presets `quic` 5/5 and `client-network` 15/15. + +Not done (10.9c-2): lease loss with 20 or more bots, and a live raw-UDP sender of mutated +datagrams that loads the server's per-connection datagram cap. diff --git a/tests/client_lifecycle.cpp b/tests/client_lifecycle.cpp index 4f8b6e3..dd312b8 100644 --- a/tests/client_lifecycle.cpp +++ b/tests/client_lifecycle.cpp @@ -90,7 +90,7 @@ void lifecycle() { CHECK(refused(Application::open({0, 64, false, "software"}), Error::invalid_config)); CHECK(refused(Application::open({64, 64, false, "evo-invalid"}), Error::renderer)); CHECK(SDL_WasInit(0) == 0); // Failed partial initialization released SDL. - const char* video_driver = std::getenv("SDL_VIDEO_DRIVER"); + const char* video_driver = SDL_getenv("SDL_VIDEO_DRIVER"); // Portable; MSVC deprecates getenv. const int rounds = video_driver != nullptr && std::string_view{video_driver} == "x11" ? 1 : 32; for (int round = 0; round < rounds; ++round) { auto result = Application::open({160, 120, false, "software"}); diff --git a/tests/fuzz/session_fuzz.cpp b/tests/fuzz/session_fuzz.cpp new file mode 100644 index 0000000..09c0f4a --- /dev/null +++ b/tests/fuzz/session_fuzz.cpp @@ -0,0 +1,78 @@ +// M10.9c (ADR-0097) session protocol v4 fuzz target. Any input: +// - decoding never crashes, and an accepted message has a stable canonical form +// (decode, encode, decode, encode gives the same bytes: no field is silently dropped); +// - an accepted snapshot chunk reaches the client's assembler without crashing; +// - grant and ticket verification refuse it (no claim byte is trusted before the +// signature: a fuzzer cannot forge ECDSA), also for the grant slot of a decoded Hello. +// Built as a libFuzzer target with EVO_BUILD_FUZZER (Linux Clang) and as a seeded smoke +// test everywhere (tests/fuzz/session_fuzz_smoke.cpp). +#include "evo/network/handoff_ticket.hpp" +#include "evo/network/replication.hpp" +#include "evo/network/session_grant.hpp" +#include "evo/network/session_protocol.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using namespace evo::network; +constexpr evo::world::WorldIdentity world{9, 2}; +constexpr std::uint64_t region = 21; +constexpr std::uint64_t now = 1'000'000; + +// Verifiers holding one fixed, valid key each (the fuzzer never has its private half). +struct Verifiers { + std::optional grants; + std::optional tickets; + Verifiers() { + std::array scalar{}; + scalar.back() = 0x2A; + const auto issuer = GrantSigningKey::import(DeploymentEnvironment::dev, 1, scalar); + auto g = GrantVerifier::create(DeploymentEnvironment::dev); + if (!issuer || !g || !g->add_key(1, *issuer->public_key())) + std::abort(); + grants.emplace(std::move(*g)); + const auto source = HandoffSigningKey::import(DeploymentEnvironment::dev, 4, scalar); + auto t = HandoffVerifier::create(DeploymentEnvironment::dev, world, region); + if (!source || !t || !t->add_key(4, 4, *source->public_key())) + std::abort(); + tickets.emplace(std::move(*t)); + } +}; +const Verifiers& verifiers() { + static const Verifiers v; + return v; +} +void refused(std::span bytes) { + const auto& v = verifiers(); + if (!v.grants || !v.tickets || v.grants->verify(bytes) || v.tickets->verify(bytes, now)) + std::abort(); + (void)looks_like_handoff_ticket(bytes); +} +} // namespace + +extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t* data, std::size_t size) { + const std::span bytes{data, size}; + refused(bytes); + const auto decoded = decode_session(bytes); + if (!decoded) + return 0; + const auto canonical = encode_session(*decoded); + const auto again = decode_session(canonical); + if (!again || encode_session(*again) != canonical) + std::abort(); + if (const auto* hello = std::get_if(&*decoded)) + refused(hello->grant); + if (const auto* chunk = std::get_if(&*decoded)) { + SnapshotAssembler client{world, chunk->epoch}; + if (const auto accepted = client.accept(*chunk); + accepted && *accepted && client.latest() == nullptr) + std::abort(); // A completed snapshot must be applied. + } + return 0; +} diff --git a/tests/fuzz/session_fuzz_smoke.cpp b/tests/fuzz/session_fuzz_smoke.cpp new file mode 100644 index 0000000..9b07cc6 --- /dev/null +++ b/tests/fuzz/session_fuzz_smoke.cpp @@ -0,0 +1,68 @@ +// Seeded smoke run of the session fuzz target (tests/fuzz/session_fuzz.cpp) on every +// platform: random inputs, and mutations (bit flips, truncation, extension, byte +// overwrites) of a valid encoding of every v4 message type. +#include "evo/core/random.hpp" +#include "evo/network/session_protocol.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t*, std::size_t); + +namespace { +using namespace evo::network; +template +std::vector> seeds(std::index_sequence) { + return {encode_session(SessionMessage{std::in_place_index})...}; +} +} // namespace + +int main() { + auto corpus = seeds(std::make_index_sequence>{}); + std::size_t decodable = 0; + for (const auto& s : corpus) + decodable += decode_session(s).has_value(); + evo::Random random{20261007}; + const auto next = [&](std::size_t below) { + return static_cast(random.next() % std::max(below, 1)); + }; + std::size_t inputs = 0; + for (int round = 0; round < 4000; ++round) { + for (const auto& seed : corpus) { + auto input = seed; + switch (next(5)) { + case 0: // Flip bits. + for (std::size_t k = 0, n = 1 + next(4); k < n && !input.empty(); ++k) + input[next(input.size())] ^= static_cast(1U << next(8)); + break; + case 1: // Truncate. + input.resize(next(input.size() + 1)); + break; + case 2: // Extend. + for (std::size_t k = 0, n = 1 + next(32); k < n; ++k) + input.push_back(static_cast(next(256))); + break; + case 3: // Overwrite a byte with an edge value. + if (!input.empty()) + input[next(input.size())] = + std::array{0, 1, 0x7F, 0xFF}[next(4)]; + break; + default: // Random bytes. + input.assign(next(300), 0); + for (auto& b : input) + b = static_cast(next(256)); + } + if (LLVMFuzzerTestOneInput(input.data(), input.size()) != 0) + return 1; + ++inputs; + } + } + std::printf("session fuzz smoke inputs=%zu seeds=%zu decodable_seeds=%zu\n", inputs, + corpus.size(), decodable); + return 0; +} diff --git a/tests/quic_sessions.cpp b/tests/quic_sessions.cpp index 2bf8b2d..99d559c 100644 --- a/tests/quic_sessions.cpp +++ b/tests/quic_sessions.cpp @@ -10,6 +10,7 @@ #include "evo/server/region_sessions.hpp" #include "fixtures/fake_handoff_world.hpp" #include +#include #include #include #include @@ -944,6 +945,262 @@ void durable_control(const Files& f) { return std::ranges::find(ledger.released, alice_generation) != ledger.released.end(); })); } + +// M10.9c (ADR-0097): abuse against one region while an honest session is measured. Each +// round is one 50 ms tick: the abuse acts, the honest client sends one intention, and the +// server replicates. The honest session must keep at least 90 % of its snapshots and +// receipts, and the server's connections and retained state must stay bounded. +struct Service { + std::uint64_t ticks{}, views{}, sent{}, receipts{}; +}; +Service serve(Harness& h, RegionSessionClient& honest, std::size_t rounds, + const std::function& abuse) { + Service out; + std::uint64_t last_view = honest.view() ? honest.view()->tick : 0; + for (std::size_t round = 0; round < rounds; ++round) { + ++h.tick; + ++out.ticks; + abuse(round); + if (honest.send_intention(h.tick + 2, 100, 0)) + ++out.sent; + const auto end = Clock::now() + std::chrono::milliseconds{50}; + while (Clock::now() < end) { + h.pump(); + for (const auto& r : honest.take_intention_receipts()) + out.receipts += r.status == AdmitStatus::admitted; + if (const auto* v = honest.view(); v && v->tick != last_view) { + last_view = v->tick; + ++out.views; + } + std::this_thread::sleep_for(std::chrono::milliseconds{1}); + } + } + std::printf( + "abuse service ticks=%llu views=%llu sent=%llu admitted=%llu\n", + static_cast(out.ticks), static_cast(out.views), + static_cast(out.sent), static_cast(out.receipts)); + return out; +} +bool served(const Service& s) { + return s.views * 10 >= s.ticks * 9 && s.sent * 10 >= s.ticks * 9 && + s.receipts * 10 >= s.sent * 9; +} +std::unique_ptr honest_session(Harness& h) { + h.source = [&h](const SessionInterest&) { + ReplicationSource s; + s.identity = world_id; + s.field_revision = h.tick; + s.mask = (1U << 0) | (1U << 1) | (1U << 7); + for (std::int64_t x = -3; x <= 3; ++x) + for (std::int64_t y = -3; y <= 3; ++y) + s.environment.push_back(grid_cell(x, y, 30 + (h.tick % 7))); + return s; + }; + h.server->set_default_interest({0, 0, -7, 7}); + auto c = h.connect(h.issuer.grant(account(0xA0), 1)); + CHECK(h.settled(*c) && c->state() == RegionSessionState::established); + // Wait for the datagram channel and the first snapshot. + CHECK(h.until([&] { + ++h.tick; + return c->view() != nullptr && c->send_intention(h.tick + 2, 0, 0).has_value(); + })); + return c; +} + +// Handshake and Hello floods: many connections that send garbage, forged or no Hello. They +// are closed (protocol, unauthenticated, timeout) or refused at the connection limit; the +// region's connections never exceed the transport bound; the honest session is served. +void hello_flood(const Files& f) { + Harness h{f, 4, 64}; + auto honest = honest_session(h); + // A key the region does not trust (key id 7): its well-formed grants are refused. + const auto stranger = *GrantSigningKey::import(DeploymentEnvironment::dev, 7, [] { + std::array s{}; + s.back() = 0x2B; + return s; + }()); + // Every peer is polled each round and acts once connected: 0 sends garbage, 1 a + // well-formed Hello whose grant no trusted key signed, 2 stays silent until the deadline. + struct Peer { + std::unique_ptr endpoint; + std::size_t kind{}; + }; + std::vector peers; + std::size_t most_connections = 0; + std::array acted{}; + unsigned sent = 0; + const auto service = serve(h, *honest, 60, [&](std::size_t round) { + if (round < 40) + for (std::size_t k = 0; k < 4; ++k) + peers.push_back({h.raw(), (round * 4 + k) % 3}); + for (auto& peer : peers) + for (auto& e : peer.endpoint->poll()) { + if (e.kind != quic::EventKind::connected) + continue; + ++acted.at(peer.kind); + if (peer.kind == 0) + sent += peer.endpoint + ->send_message(e.connection, std::vector{9, 9, 9, 9}) + .has_value(); + if (peer.kind == 1) { + GrantClaims c; + c.grant_id = 9000 + round; + c.account = account(0xF0); + c.serial = 1; + c.world = world_id; + c.region = region; + c.issued_at = start; + c.expires_at = start + 60; + sent += peer.endpoint + ->send_message(e.connection, + encode_session(SessionHello{0, *stranger.sign(c)})) + .has_value(); + } + } + most_connections = std::max(most_connections, h.server->connections()); + }); + std::printf("abuse hello_flood peers=%zu most_connections=%zu connected garbage=%u " + "forged=%u silent=%u\n", + peers.size(), most_connections, acted[0], acted[1], acted[2]); + CHECK(sent == acted[0] + acted[1]); // Every garbage and forged message went out. + CHECK(served(service) && honest->state() == RegionSessionState::established); + CHECK(most_connections <= server::RegionSessionsConfig{}.transport.limits.max_connections); + peers.clear(); + CHECK(h.until([&] { return h.server->connections() == 1; })); + std::map reasons; + for (const auto& e : h.events) + if (e.kind == RegionSessionEvent::Kind::refused) + ++reasons[static_cast(e.reason)]; + for (const auto& [why, n] : reasons) + std::printf("abuse hello_flood refused reason=%u count=%u\n", why, n); + CHECK(h.has_event(RegionSessionEvent::Kind::refused, Reason::protocol) && + h.has_event(RegionSessionEvent::Kind::refused, Reason::unauthenticated) && + h.has_event(RegionSessionEvent::Kind::refused, Reason::timeout)); +} + +// Datagram flood from an authenticated peer: hundreds of intentions per tick for any tick +// (throttled per session: one per tick), then garbage, which closes it (protocol). The +// honest session keeps its receipts and snapshots. +void datagram_flood(const Files& f) { + Harness h{f, 4, 64}; + auto honest = honest_session(h); + auto peer = h.raw(); + quic::ConnectionId id = 0; + bool welcomed = false, closed = false; + std::optional reason; + std::uint64_t flood = 0, refused = 0, garbage = 0; + const auto drain = [&] { + for (auto& e : peer->poll()) { + if (e.kind == quic::EventKind::connected) { + id = e.connection; + CHECK(peer->send_message( + id, encode_session(SessionHello{0, h.issuer.grant(account(0xB0), 1)})) + .has_value()); + } else if (e.kind == quic::EventKind::message || e.kind == quic::EventKind::datagram) { + const auto m = decode_session(e.bytes); + if (m && std::holds_alternative(*m)) + welcomed = true; + if (m && std::holds_alternative(*m)) + refused += std::get(*m).status != AdmitStatus::admitted; + if (m && std::holds_alternative(*m)) + reason = std::get(*m).reason; + } else if (e.kind == quic::EventKind::closed) { + closed = true; + } + } + }; + CHECK(h.until([&] { + drain(); + return welcomed; + })); + std::uint64_t sequence = 0; + const auto service = serve(h, *honest, 40, [&](std::size_t round) { + drain(); + if (round < 30) + for (int k = 0; k < 400; ++k) { + SessionIntention in; + in.sequence = ++sequence; + in.tick = h.tick + 1 + static_cast(k % 8); + in.move_x = 100; + flood += peer->send_datagram(id, encode_session(in)).has_value(); + } + if (round == 30) + for (int k = 0; k < 50; ++k) + garbage += peer->send_datagram(id, std::vector(64, 0xEE)).has_value(); + }); + CHECK(h.until([&] { + drain(); + return closed || reason.has_value(); + })); + std::printf("abuse datagram_flood sent=%llu refused_receipts=%llu close=%u\n", + static_cast(flood), static_cast(refused), + static_cast(reason.value_or(Reason::connection_lost))); + CHECK(served(service) && honest->state() == RegionSessionState::established); + CHECK(flood > 1000 && garbage > 0 && reason == Reason::protocol); +} + +// A slow peer: established, then never polled (it reads nothing and acknowledges no +// snapshot). The server keeps at most its baselines for it and stays bounded; the honest +// session is served throughout. +void slow_peer(const Files& f) { + Harness h{f, 4, 64}; + auto honest = honest_session(h); + auto slow = h.connect(h.issuer.grant(account(0xC0), 1)); + CHECK(h.settled(*slow) && slow->state() == RegionSessionState::established); + CHECK(slow->set_interest({0, 0, -7, 7})); + h.forget(slow.get()); // From now on nobody polls it. + std::size_t most_retained = 0; + const auto service = serve(h, *honest, 80, [&](std::size_t) { + most_retained = std::max(most_retained, h.server->replication_stats().retained_entities); + }); + std::printf("abuse slow_peer most_retained_entities=%zu sessions=%zu\n", most_retained, + h.server->sessions()); + CHECK(served(service) && honest->state() == RegionSessionState::established); + // Two sessions, 49 cells each, at most 4 baselines (ADR-0089) plus the working state. + CHECK(most_retained <= std::size_t{2} * 49 * 5); + slow.reset(); + CHECK(h.until([&] { return h.server->sessions() == 1; }, std::chrono::milliseconds{15000})); +} + +// Connect/disconnect storm: 120 logins across 12 accounts, each closed politely or dropped +// mid-session; the region returns to the honest session alone, which is served throughout. +void storm(const Files& f) { + Harness h{f, 8, 1024}; + auto honest = honest_session(h); + std::vector> live; + std::array serials{}; + std::uint64_t opened = 0; + const auto service = serve(h, *honest, 60, [&](std::size_t round) { + if (round >= 40) + return; + for (int k = 0; k < 3; ++k) { + const auto who = (round * 3 + static_cast(k)) % serials.size(); + auto c = h.connect( + h.issuer.grant(account(static_cast(0xD0 + who)), ++serials.at(who))); + live.push_back(std::move(c)); + } + // Older ones leave: politely, or by vanishing (the transport notices). + while (live.size() > 6) { + auto& c = live.front(); + opened += c->state() == RegionSessionState::established; + if (opened % 2 == 0) + c->close(); + h.forget(c.get()); + live.erase(live.begin()); + } + }); + for (auto& c : live) { + h.forget(c.get()); + c->close(); + } + live.clear(); + std::printf("abuse storm logins=120 established_seen=%llu\n", + static_cast(opened)); + CHECK(served(service) && honest->state() == RegionSessionState::established); + CHECK(opened > 20); + CHECK(h.until([&] { return h.server->sessions() == 1 && h.server->connections() == 1; }, + std::chrono::milliseconds{15000})); +} } // namespace int main() try { @@ -955,6 +1212,10 @@ int main() try { snapshots_over_quic(files); ticket_login(files); two_region_handoff(files); + hello_flood(files); + datagram_flood(files); + slow_peer(files); + storm(files); std::filesystem::remove_all(files.dir); std::puts("quic session tests passed"); return 0; diff --git a/tests/region_m10_session_tests.cpp b/tests/region_m10_session_tests.cpp index 763e000..99ed6c2 100644 --- a/tests/region_m10_session_tests.cpp +++ b/tests/region_m10_session_tests.cpp @@ -422,6 +422,27 @@ void end_to_end() { } CHECK(marks.size() >= 2 && marks.back()[3] >= 1 && marks.back()[1] > marks.front()[1] && marks.back()[2] == marks.front()[2]); + // M10.9 (ADR-0097): a login from an existing bundle (as a dev renewal writes one), with + // no issuer key: grant 1 of a two-grant bundle for Dana. + const auto dana = account(0x53); + const auto bundle = s.region.root / "dana-grants.bin"; + Child g{{probe.string(), "grants", "--issuer-key", (s.region.root / "issuer.key").string(), + "--world", "7", "--frame", std::to_string(region_identity.frame), "--region", "151", + "--account", hex(dana), "--count", "2", "--lifetime", "900", "--out", + bundle.string()}}; + CHECK(g.wait_exit(30s) == 0); + Child q{{probe.string(), "run", "--connect", "127.0.0.1:" + std::to_string(server->port), + "--server-name", name, "--ca", (s.region.root / "ca.pem").string(), "--grants", + bundle.string(), "--grant", "1", "--intents", "2", "--snapshots", "2"}}; + code = -1; + for (const auto end = Clock::now() + 30s; Clock::now() < end && code < 0;) { + server->pump(); + q.pump(5ms); + if (q.printed("done") || q.printed("timeout") || q.printed("closed")) + code = q.wait_exit(10s); + } + CHECK(code == 0 && q.printed("grant 1 of 2") && q.printed("welcome ") && + q.printed("intention 1 0")); server->child->signal(SIGTERM); CHECK(server->child->wait_exit(30s) == 0); CHECK(server->child->printed("m10 opened ") && server->child->printed("m10 committed ") &&