From 5fe599c5b6810b6da2e3c6b67e8d8806391a6db8 Mon Sep 17 00:00:00 2001 From: TeTeHacko Date: Thu, 3 Dec 2026 21:52:50 +0100 Subject: [PATCH] Repeater: `filter flow` -- one table of forward-deny rules (channel, dest/src, login, advert, relay) with throttle, expiry and a rules CRC MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Changelog: Repeater: new `filter flow` forward-deny rules (channel, dest/src, login flood, advert, relay in path) with throttle, expiry and a rules CRC; `filter hash` and `filter path` remain as aliases Changelog-cs: Repeater: nová pravidla `filter flow` pro blokaci přeposílání (kanál, cíl/zdroj, login flood, advert, repeater v cestě) s throttle, expirací a CRC pravidel; `filter hash` a `filter path` zůstávají jako aliasy Changelog-topic: filter-flow Co-Authored-By: Claude Sonnet 5.5 --- README.md | 36 +- docs/tth-commands.md | 118 ++++- examples/simple_repeater/ChannelFilter.h | 383 +++++++++------ examples/simple_repeater/MyMesh.cpp | 21 +- examples/simple_repeater/MyMesh.h | 16 +- src/helpers/CommonCLI.h | 11 + src/helpers/FlowRules.h | 585 +++++++++++++++++++++++ test/test_flow_rules/test_flow_rules.cpp | 390 +++++++++++++++ test/vectors/flow_rules_vectors.json | 148 ++++++ test/vectors/gen_flow_rules_vectors.py | 106 ++++ 10 files changed, 1601 insertions(+), 213 deletions(-) create mode 100644 src/helpers/FlowRules.h create mode 100644 test/test_flow_rules/test_flow_rules.cpp create mode 100644 test/vectors/flow_rules_vectors.json create mode 100644 test/vectors/gen_flow_rules_vectors.py diff --git a/README.md b/README.md index acf4b0f59..4737fe56e 100644 --- a/README.md +++ b/README.md @@ -46,14 +46,17 @@ vypnuté, dokud je nezapnete. a `#hashtag` kanály), přestane přeposílat zprávy uvedených jmen odesílatelů (`filter add `, `filter del `, `filter list`). Jméno se dá podvrhnout: je to brzda na utrženého bota, ne bezpečnost. -* **Blokace přeposílání podle hashe kanálu** – `filter hash add [secs]`: - bez klíče, takže funguje i na soukromých kanálech; příjem se nemění, jen - přeposílání. S `s` se kanál neodřízne, ale přiškrtí (jeden paket za `s` - sekund). -* **Blokace přeposílání podle repeateru v cestě** – `filter path add ` - (prefix veřejného klíče, 2–4 bajty): nepřeposílá flood, který prošel - uvedeným repeaterem. Jednobajtové hopy se nikdy neshodují, protože jeden - bajt sdílí většina repeaterů meshe. +* **Pravidla blokace přeposílání – `filter flow`** (max 16, jen flood, příjem + se nemění, jen přeposílání, bez klíče, takže funguje i na soukromých + kanálech): druh `c` bajt kanálu, `r` cíl+zdroj (volitelně + první hop), `n` + cíl ANON_REQ (login flood), `a` prefix klíče z advertu, `p` repeater v cestě + (2–4 bajty; jednobajtové hopy se nikdy neshodují). Každé pravidlo má režim + (`block`, `throttle ` = jeden paket za `s` sekund, `dry` = jen počítá), + vlastní čítače, příznak `auto` a volitelnou expiraci (`ttl`/`expires`; + platí dřívější z absolutního času a odpočtu od startu). Výpis po stránkách + (`filter flow list [page]`), `add|del|clear` vrací `crc16` pravidel zvlášť + pro `auto` a statická. `filter hash add [secs]` a `filter path add ` + zůstávají jako aliasy. Popis: [docs/tth-commands.md](docs/tth-commands.md). * **Limit stáří zprávy** – `filter age ` / `filter age off` (volitelné, 1–10080 min): nepřeposílá skupinové zprávy na dešifrovaných kanálech, jejichž čas od odesílatele je starší; bez nastavených hodin repeateru neplatí. Posuzuje @@ -395,12 +398,17 @@ off until you turn them on. `#hashtag` channels), stop forwarding messages of listed sender names (`filter add `, `filter del `, `filter list`). Names are spoofable: it contains a runaway bot, it is not security. -* **Channel-hash deny-forward** -- `filter hash add [secs]`: keyless, - works on private channels too; reception is unaffected, only forwarding. - With `secs` the channel is throttled (one packet per `secs`) instead of cut. -* **Relay deny-forward** -- `filter path add ` (pubkey prefix, 2-4 - bytes): do not forward a flood that came through that repeater. 1-byte hops - never match, as one byte is shared by most repeaters of a mesh. +* **Forward-deny rules -- `filter flow`** (max 16, floods only; reception + is unaffected, only forwarding; keyless, so private channels too): kind `c` + channel byte, `r` dest+src (optionally + first hop), `n` ANON_REQ dest (login + flood), `a` advert pubkey prefix, `p` relay in the path (2-4 bytes; 1-byte + hops never match). Each rule has a mode (`block`, `throttle ` = one packet + per `s` seconds, `dry` = count only), its own counters, an `auto` flag and an + optional expiry (`ttl` / `expires`; whichever comes first of the absolute time + and a countdown from boot). Paged listing (`filter flow list [page]`); + `add|del|clear` reply with a `crc16` of the rules, auto and static sets + separately. `filter hash add [secs]` and `filter path add ` remain + as aliases. Details: [docs/tth-commands.md](docs/tth-commands.md). * **Message age limit** -- `filter age ` / `filter age off` (opt-in, 1-10080 min): do not forward group texts on the decrypted channels whose sender timestamp is older; inactive while the repeater clock is unset. It judges the sender's diff --git a/docs/tth-commands.md b/docs/tth-commands.md index 2e240b7aa..5edf4dd76 100644 --- a/docs/tth-commands.md +++ b/docs/tth-commands.md @@ -69,38 +69,110 @@ message: anyone can rename around it. | `filter del ` | remove a name from the deny list | | `filter clear` | empty the deny list | -### Channel-hash deny-forward -- `filter hash` (every repeater) +### Forward-deny rules -- `filter flow` (every repeater) -Keyless: the first byte of a group packet is the channel hash, in the clear, -so this works on private channels too. One byte is coarse -- every other -channel whose key hashes to the same byte is hit as well; check what else -lives on it before adding one. +One table of keyless rules (max 16) that replaces the former `filter hash` and +`filter path` (both remain as aliases, below). A rule makes this node not +re-air a matching **flood** packet; reception, rxlog and the pktfeed are +unaffected. Match is on what is in the clear: + +| kind | key (hex) | matches | +|---|---|---| +| `c` | 1 B channel byte | GRP_TXT / GRP_DATA. One byte is coarse: every other channel hashing to it is hit as well | +| `r` | `dest src` (2 B), optionally + first hop (4 B) | REQ / RESPONSE / TXT_MSG / PATH | +| `n` | `dest` (1 B), optionally + first hop (3 B) | ANON_REQ (login flood) | +| `a` | pubkey prefix, 4-8 B | ADVERT | +| `p` | relay pubkey prefix, 2-4 B | any hop of the path (a hop matches on the shorter of its width and the entry) | + +"First hop" is the 2-byte hash at the start of the path. **0-hop packets and +1-byte hops never match a rule that has it**, and kind `p` never matches a +1-byte hop (one byte is shared by most repeaters of a mesh). + +Per entry: a mode, a flag, counters and an optional expiry. + +* mode `block` (default), `throttle ` (1..65535: one packet per `s` + seconds passes, the rest is dropped; the window is RAM, the first match after + a boot passes) or `dry` (count only, never drops); +* flag `auto`: set by an agent, as opposed to static (inventory / by hand); + `clear` and the CRCs treat the two sets separately; +* counters `dropped` / `passed` (RAM, gone at reboot; `passed` counts throttle + passes, `dropped` of a `dry` entry counts what it WOULD have dropped; of + several matching rules only the first dropping one is charged); +* expiry `ttl ` (1..2000000, from now) or `expires `: an expired + entry is **removed**. The entry carries the absolute time AND the seconds + that were left when it was last written (written only on add/change, never + periodically); after a boot the entry ends at whichever comes first: the + absolute time (only while the node clock reads 2026 or later) or the + countdown of the saved seconds from boot. A cold start without GPS has a + clock behind by the age of the build, so the absolute time alone would + extend a block. `expires` with no valid clock is stored without a countdown + and can then end only by the absolute time. | command | what | |---|---| -| `filter hash [list]` | drops, passes by a throttle, the list (`43` blocked, `43/60` throttled) | -| `filter hash add [secs]` | block the byte, or with `secs` (1..65535) let one packet through per `secs`; re-adding changes the interval | -| `filter hash del ` | remove one byte | -| `filter hash clear` | empty the list | +| `filter flow add [block\|throttle \|dry] [auto] [ttl \|expires ]` | add; the same key again changes the entry (counters kept) | +| `filter flow del ` | remove one entry | +| `filter flow clear auto\|static\|all` | remove a set | +| `filter flow [list [page]]` | paged list | -A throttle's window lives in RAM: the first match after a boot passes. +Entries are kept **sorted by (kind, key)** -- kind as its ASCII letter, key +bytewise, a shorter key before a longer one it prefixes. The index in that +order is the `slot_id` and **moves on add/del/expiry**. A rule is a veto, not a +route: with several matches any dropping rule drops the packet, and a throttle +window is only spent by a packet that nothing else vetoes. -### Relay deny-forward -- `filter path` (every repeater) +`add`, `del` and `clear` reply (machine format, one line): -Do not re-air a flood whose path so far names a given relay: the tool for a -broken or hostile repeater whose owner cannot be reached. An entry is a pubkey -prefix of 2-4 bytes (4-8 hex digits). A hop hash is as wide as the packet's -SENDER chose (1-3 bytes), so a hop matches when it and the entry agree on the -shorter of the two -- and a **1-byte hop never matches**, since one byte is -shared by most repeaters of a mesh. Floods sent with 1-byte paths therefore -pass. Only flood packets; reception is unaffected, only forwarding. + OK n= a=: s=: + +`a=` is the number of `auto` entries and the CRC of that set, `s=` the same for +the static set; `crc16` is 4 upper-case hex digits. Errors start with `Err -`. + +CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, no reflection, no final XOR) +over the entries of one set in sorted order, each serialized as +`kind(1, ASCII) klen(1) key(klen) mode(1: 0 block, 1 throttle, 2 dry) +throttle_secs(2, big endian, 0 unless throttle) expires(4, big endian, 0 = none)`. +Counters, the remaining seconds and the `auto` flag are not part of it; an +empty set is `FFFF`. Test vectors and a Python reference: +`test/vectors/flow_rules_vectors.json`, `test/vectors/gen_flow_rules_vectors.py`. + +`list` replies are at most 149 characters (the RF reply limit is 150 B): + + flow / n= a=: s=: ... + = ,,,/, + = B | T | D = seconds to expiry, or - + +Entries are separated by a space, fields by a comma. Up to 4 entries a page, +fewer when long keys would not fit; the packing depends only on the rules (it +budgets the counters at their maximum), never on the counters, so `of` stays +put while counters tick. Displayed counters are capped at 99999. An empty +table: `flow 1/1 n=0 a=0:FFFF s=0:FFFF`. A page out of range: +`Err - page 1..`. The reader fetches page 1, then 2..`of`; if `n` or a +CRC differs between pages the table changed meanwhile -- start again. + +`filter dryrun on` forces every verdict (flow, age, sender) to count-only. + +Persisted in prefs (keys `f_fl0`..`f_fl15`). At the first boot after an update +the old `f_dhash*` / `f_dpath*` entries are moved into the table as static +kind `c` / `p` rules and the old fields are cleared (downgrading afterwards +loses them). + +#### Aliases `filter hash` and `filter path` + +Kept so existing configuration and the Ansible module `meshcore_filter_hash` +keep working; they act on static kind `c` / `p` entries. | command | what | |---|---| -| `filter path [list]` | drops and the list | -| `filter path add ` | deny a relay by its pubkey prefix, e.g. `c420` (up to 8 entries) | -| `filter path del ` | remove one entry | -| `filter path clear` | empty the list | +| `filter hash [list]` | `filter hash: dropped N, passed M, deny: 43 2E/60` -- sums of the kind-`c` counters; `43` blocked, `43/60` throttled, `43/dry` dry | +| `filter hash add [secs]` | `filter flow add c [throttle ]`; no `secs` / 0 = block; re-adding changes the interval | +| `filter hash del ` / `clear` | remove one byte / all STATIC `c` entries | +| `filter path [list]` | `filter path: dropped N, deny: c420 5f14c420` | +| `filter path add ` | `filter flow add p ` (2-4 bytes = 4-8 hex digits) | +| `filter path del ` / `clear` | remove one entry / all STATIC `p` entries | + +The table is shared: 16 entries in all, where `filter hash` had 8 and +`filter path` 8. The list order is now the sorted order, not the order of adding. ### Message age -- `filter age` (repeater with channel keys) @@ -118,7 +190,7 @@ clock reads before 2026; a clock running ahead makes everything look old. | command | what | |---|---| -| `filter dryrun [on\|off]` | count every `filter` verdict (sender, hash, path, age) but forward anyway -- try a rule on a live node before it bites; without an argument shows the state. Default: off | +| `filter dryrun [on\|off]` | count every `filter` verdict (sender, flow, age) but forward anyway -- try a rule on a live node before it bites; without an argument shows the state. Default: off | ## Radio watchdogs and board upkeep (all) diff --git a/examples/simple_repeater/ChannelFilter.h b/examples/simple_repeater/ChannelFilter.h index e61d0d2ce..9179c1e57 100644 --- a/examples/simple_repeater/ChannelFilter.h +++ b/examples/simple_repeater/ChannelFilter.h @@ -82,81 +82,199 @@ bool MyMesh::filterHandleCommand(const char* command, char* reply, int reply_max return true; } - strcpy(reply, "Err - filter [add|del |list|clear|hash|path|age|dryrun]"); + strcpy(reply, "Err - filter [add|del |list|clear|flow|hash|path|age|dryrun]"); return true; } #endif // FILTER_CHANNEL_PSKS // --------------------------------------------------------------------------- -// Keyless deny-forward by CHANNEL HASH -- independent of FILTER_CHANNEL_PSKS. +// Keyless deny-forward -- `filter flow` (tth #41, epic #45), independent of +// channel keys. ONE table of rules (FlowRules.h: kinds, matching, ordering, +// expiry, CRC, reply formats) replaces the former `filter hash` (14. 10. 2026, +// one private chat+bot = 43 % of CZ airtime) and `filter path` (tth #4); both +// stay as aliases onto kind c / kind p. // -// The deny list above needs the PSK, so it can never touch a private channel. -// This one needs nothing: payload[0] of GRP_TXT/GRP_DATA is the channel hash, -// in the clear, and a repeater can refuse to re-air every packet carrying it. -// Born 14. 10. 2026 for 0x43 (one private chat+bot = 43 % of the airtime on -// the CZ mesh, reflooded all the way to remote-mast); FairnessLimiter only -// throttled it blindly, and its group bucket (hash & 0x1F) collides with -// 0x23/0x63/... anyway. -// -// * Content-neutral and coarse: the hash is 1 byte, so a deny entry also -// hits every OTHER channel whose key happens to hash to the same byte. -// Check the analyzer for what else lives on a byte before denying it. -// * Only forwarding by THIS node: reception and rxlog/pktfeed capture -// (CoreScope feed) happen before routeRecvPacket(), so the evidence trail -// stays intact. -// * Runtime-editable over RF admin and persisted in prefs (f_dhash/f_dhash_n), -// so an incident response is `filter hash add 43`, not a mast reflash. -// -// THROTTLE (tth #3, 2. 11. 2026): an entry may carry an interval -- -// `filter hash add 43 60` lets one packet of that byte through per 60 s and -// drops the rest, so a chatty channel is tamed instead of cut off. The window -// state is RAM only (first match after boot passes) and only a pass moves it; -// see HashThrottle in src/helpers/ChannelGate.h. Interval 0 = block, as before. -// -// `filter dryrun on` counts every verdict of `filter` (hash, path, age, sender deny) -// but forwards anyway -- the way to try a new rule on a live mast. +// * Content-neutral and coarse: a channel byte also hits every OTHER channel +// whose key hashes to it; a 2-byte hop collides rarely, a 1-byte never +// matches. Check the analyzer before denying. +// * Only forwarding by THIS node, only FLOOD: reception and rxlog/pktfeed +// capture happen before routeRecvPacket(), so the evidence trail is intact. +// * Persisted in prefs (f_fl0..f_fl15, one packed record each). The expiry +// countdown is written only on add/change -- no periodic savePrefs() on a +// solar node. +// * `filter dryrun on` keeps every verdict count-only. -bool MyMesh::filterHashDenied(const mesh::Packet* packet) { - uint8_t n = _prefs.deny_hash_n; - if (n == 0) return false; +static_assert(sizeof(NodePrefs::flow_rec) == (size_t)FLOW_MAX * FLOW_REC_LEN, "flow_rec shape"); + +bool MyMesh::filterFlowDenied(const mesh::Packet* packet) { + if (flow_table.n == 0 || !packet->isRouteFlood()) return false; uint8_t type = packet->getPayloadType(); - if (type != PAYLOAD_TYPE_GRP_TXT && type != PAYLOAD_TYPE_GRP_DATA) return false; - if (packet->payload_len < 1) return false; - if (n > sizeof(_prefs.deny_hash)) n = sizeof(_prefs.deny_hash); - for (int i = 0; i < n; i++) { - if (_prefs.deny_hash[i] != packet->payload[0]) continue; - uint16_t secs = _prefs.deny_hash_secs[i]; - if (secs != 0 && hash_throttle.pass(i, secs, millis())) { - filter_hash_passed++; - return false; - } - filter_hash_dropped++; - return !_prefs.filter_dry_run; + if (type == PAYLOAD_TYPE_TRACE) return false; // its path field carries SNRs, not hops + FlowPkt p; + p.cls = FLOW_PKT_OTHER; + switch (type) { + case PAYLOAD_TYPE_GRP_TXT: + case PAYLOAD_TYPE_GRP_DATA: p.cls = FLOW_PKT_GROUP; break; + case PAYLOAD_TYPE_REQ: + case PAYLOAD_TYPE_RESPONSE: + case PAYLOAD_TYPE_TXT_MSG: + case PAYLOAD_TYPE_PATH: p.cls = FLOW_PKT_ADDR; break; + case PAYLOAD_TYPE_ANON_REQ: p.cls = FLOW_PKT_ANON; break; + case PAYLOAD_TYPE_ADVERT: p.cls = FLOW_PKT_ADVERT; break; } - return false; + p.payload = packet->payload; + p.payload_len = packet->payload_len > 255 ? 255 : (uint8_t)packet->payload_len; + p.path = packet->path; + p.hash_size = packet->getPathHashSize(); + p.hop_count = packet->getPathHashCount(); + uint32_t now_ms = millis(); + flow_table.expire(now_ms, getRTCClock()->getCurrentTime()); + return flow_table.verdict(p, now_ms, _prefs.filter_dry_run != 0); } -// `filter hash` -- show list + counters (passed = let through by a throttle); -// `filter hash add [secs]` -- block (no secs / 0) or throttle to one -// packet per secs; re-adding a listed byte changes its interval; -// `filter hash del `; `filter hash clear`. -// Listing: `43` = blocked, `43/60` = throttled to one per 60 s. The Ansible -// module (tth.meshcore.meshcore_filter_hash) parses this line -- keep the -// "filter hash: dropped N, passed M, deny:" shape stable. +// prefs -> table. Then the one-time migration: entries still sitting in the +// legacy f_dhash*/f_dpath* prefs become static kind c / kind p rules and the +// legacy fields are zeroed, so it never runs twice. +void MyMesh::flowLoad() { + flow_table.clearAll(); + uint32_t now_ms = millis(); + for (int i = 0; i < FLOW_MAX; i++) { + FlowRule r; + if (flowUnpack(_prefs.flow_rec[i], r)) flow_table.add(r, now_ms); + } + bool migrated = false; + uint8_t nh = _prefs.deny_hash_n > sizeof(_prefs.deny_hash) ? sizeof(_prefs.deny_hash) : _prefs.deny_hash_n; + for (uint8_t i = 0; i < nh; i++) { + FlowRule r; + memset(&r, 0, sizeof(r)); + r.kind = FLOW_KIND_C; r.klen = 1; r.key[0] = _prefs.deny_hash[i]; + r.secs = _prefs.deny_hash_secs[i]; + r.mode = r.secs ? FLOW_THROTTLE : FLOW_BLOCK; + flow_table.add(r, now_ms); + migrated = true; + } + uint8_t np = _prefs.deny_path_n > PATH_DENY_SLOTS ? PATH_DENY_SLOTS : _prefs.deny_path_n; + for (uint8_t i = 0; i < np; i++) { + FlowRule r; + memset(&r, 0, sizeof(r)); + r.kind = FLOW_KIND_P; r.klen = _prefs.deny_path_len[i]; + if (!flowKeyLenOk(r.kind, r.klen)) continue; + memcpy(r.key, _prefs.deny_path[i], r.klen); + flow_table.add(r, now_ms); + migrated = true; + } + if (_prefs.deny_hash_n || _prefs.deny_path_n) { + _prefs.deny_hash_n = 0; + _prefs.deny_path_n = 0; + memset(_prefs.deny_hash, 0, sizeof(_prefs.deny_hash)); + memset(_prefs.deny_hash_secs, 0, sizeof(_prefs.deny_hash_secs)); + memset(_prefs.deny_path, 0, sizeof(_prefs.deny_path)); + memset(_prefs.deny_path_len, 0, sizeof(_prefs.deny_path_len)); + migrated = true; + } + flow_table.expire(now_ms, getRTCClock()->getCurrentTime()); + if (migrated) flowPersist(); +} + +// table -> prefs -> flash. The remaining time of expiring entries is written +// here and nowhere else (on add / del / clear / migration). +void MyMesh::flowPersist() { + uint32_t now_ms = millis(); + memset(_prefs.flow_rec, 0, sizeof(_prefs.flow_rec)); + for (int i = 0; i < flow_table.n; i++) { + FlowRule r = flow_table.e[i].r; + if (flow_table.e[i].has_deadline) { + int32_t d = (int32_t)(flow_table.e[i].deadline_ms - now_ms); + r.remain = d > 1000 ? (uint32_t)d / 1000u : 1; + } + flowPack(r, _prefs.flow_rec[i]); + } + savePrefs(); +} + +// `filter flow list [page]` | `add [block|throttle |dry] [auto] +// [ttl |expires ]` | `del ` | `clear auto|static|all`. +// add|del|clear reply `OK n= a=: s=:` (auto +// and static sets separately); list pages are formatted by flowListPage(). +bool MyMesh::filterFlowHandleCommand(const char* command, char* reply, int reply_max) { + if (memcmp(command, "filter flow", 11) != 0 || (command[11] != 0 && command[11] != ' ')) return false; + const char* arg = (command[11] == ' ') ? &command[12] : ""; + while (*arg == ' ') arg++; + uint32_t now_ms = millis(), now = getRTCClock()->getCurrentTime(); + flow_table.expire(now_ms, now); + if (reply_max > FLOW_REPLY_MAX) reply_max = FLOW_REPLY_MAX; // pages are packed for the RF limit + + if (arg[0] == 0 || strncmp(arg, "list", 4) == 0) { + int page = 1; + if (arg[0] != 0) { + const char* p = arg + 4; + const char* t; + size_t n = flowToken(&p, &t); + uint32_t v; + if (n > 0 && (!flowParseNum(t, n, 99, &v) || v == 0)) { + strcpy(reply, "Err - filter flow list [page]"); + return true; + } + if (n > 0) page = (int)v; + } + if (!flowListPage(flow_table, page, now_ms, now, reply, reply_max)) { + snprintf(reply, reply_max, "Err - page 1..%d", flowPageCount(flow_table, now_ms, now)); + } + return true; + } + + const char* verb = NULL; + if (strncmp(arg, "add ", 4) == 0) { + FlowSpec s; + const char* err = flowParseAdd(arg + 4, &s); + if (!err) err = flowResolveExpiry(&s, now); + if (err) { snprintf(reply, reply_max, "%s", err); return true; } + FlowResult r = flow_table.add(s.r, now_ms); + if (r == FLOW_FULL) { snprintf(reply, reply_max, "Err - full (%d)", FLOW_MAX); return true; } + if (r == FLOW_BAD) { strcpy(reply, "Err - bad rule"); return true; } + verb = r == FLOW_OK ? "add" : (r == FLOW_CHANGED ? "change" : "same"); + if (r != FLOW_SAME) flowPersist(); + } else if (strncmp(arg, "del ", 4) == 0) { + const char* p = arg + 4; + uint8_t kind, key[FLOW_KEY_MAX], klen; + const char* err = flowParseKey(&p, &kind, key, &klen); + if (err) { snprintf(reply, reply_max, "%s", err); return true; } + if (flow_table.del(kind, key, klen) != FLOW_OK) { strcpy(reply, "Err - not listed"); return true; } + flowPersist(); + verb = "del"; + } else if (strncmp(arg, "clear ", 6) == 0) { + int which = strcmp(arg + 6, "auto") == 0 ? 0 : strcmp(arg + 6, "static") == 0 ? 1 : strcmp(arg + 6, "all") == 0 ? 2 : -1; + if (which < 0) { strcpy(reply, "Err - filter flow clear auto|static|all"); return true; } + if (flow_table.clear(which) > 0) flowPersist(); + verb = "clear"; + } else { + strcpy(reply, "Err - filter flow [list [page]|add ...|del |clear auto|static|all]"); + return true; + } + int len = snprintf(reply, reply_max, "OK %s ", verb); + flowSummary(flow_table, &reply[len], reply_max - len); + return true; +} + +// `filter hash` -- alias onto kind c (static rules), reply shape kept for the +// Ansible module tth.meshcore.meshcore_filter_hash: "filter hash: dropped N, +// passed M, deny: 43 2E/60" (`43` blocked, `43/60` throttled; a dry or auto +// entry made by `filter flow` shows as `43/dry` / is listed like the rest). +// dropped/passed are sums of the per-entry counters (RAM, reset by a reboot or +// by removing the entry). `filter hash clear` removes the STATIC c entries only. bool MyMesh::filterHashHandleCommand(const char* command, char* reply, int reply_max) { if (memcmp(command, "filter hash", 11) != 0 || (command[11] != 0 && command[11] != ' ')) return false; const char* arg = (command[11] == ' ') ? &command[12] : ""; - uint8_t n = _prefs.deny_hash_n; - if (n > sizeof(_prefs.deny_hash)) n = sizeof(_prefs.deny_hash); + uint32_t now_ms = millis(); if (strcmp(arg, "clear") == 0) { - _prefs.deny_hash_n = 0; - memset(_prefs.deny_hash, 0, sizeof(_prefs.deny_hash)); - memset(_prefs.deny_hash_secs, 0, sizeof(_prefs.deny_hash_secs)); - hash_throttle.reset(); - savePrefs(); + for (int i = flow_table.n - 1; i >= 0; i--) { + const FlowRule& r = flow_table.e[i].r; + if (r.kind == FLOW_KIND_C && !(r.flags & FLOW_FLAG_AUTO)) flow_table.del(r.kind, r.key, r.klen); + } + flowPersist(); strcpy(reply, "OK - hash deny list cleared"); return true; } @@ -182,35 +300,21 @@ bool MyMesh::filterHashHandleCommand(const char* command, char* reply, int reply return true; } } - int at = -1; - for (int i = 0; i < n; i++) { - if (_prefs.deny_hash[i] == (uint8_t)v) { at = i; break; } - } + uint8_t key = (uint8_t)v; if (is_add) { - if (at >= 0) { - if (_prefs.deny_hash_secs[at] == (uint16_t)secs) { strcpy(reply, "Err - already listed"); return true; } - _prefs.deny_hash_secs[at] = (uint16_t)secs; // change of interval - hash_throttle.reset(at); - } else { - if (n >= sizeof(_prefs.deny_hash)) { strcpy(reply, "Err - list full"); return true; } - _prefs.deny_hash[n] = (uint8_t)v; - _prefs.deny_hash_secs[n] = (uint16_t)secs; - hash_throttle.reset(n); - n++; - } - } else { - if (at < 0) { strcpy(reply, "Err - not listed"); return true; } - for (int i = at; i + 1 < n; i++) { - _prefs.deny_hash[i] = _prefs.deny_hash[i + 1]; - _prefs.deny_hash_secs[i] = _prefs.deny_hash_secs[i + 1]; - } - hash_throttle.remove(at); - --n; - _prefs.deny_hash[n] = 0; - _prefs.deny_hash_secs[n] = 0; + FlowRule r; + memset(&r, 0, sizeof(r)); + r.kind = FLOW_KIND_C; r.klen = 1; r.key[0] = key; + r.secs = (uint16_t)secs; + r.mode = secs ? FLOW_THROTTLE : FLOW_BLOCK; + FlowResult res = flow_table.add(r, now_ms); + if (res == FLOW_SAME) { strcpy(reply, "Err - already listed"); return true; } + if (res == FLOW_FULL) { strcpy(reply, "Err - list full"); return true; } + } else if (flow_table.del(FLOW_KIND_C, &key, 1) != FLOW_OK) { + strcpy(reply, "Err - not listed"); + return true; } - _prefs.deny_hash_n = n; - savePrefs(); + flowPersist(); // fall through to the listing as the reply } else if (arg[0] != 0 && strcmp(arg, "list") != 0) { strcpy(reply, "Err - filter hash [add [secs]|del |list|clear]"); @@ -218,60 +322,35 @@ bool MyMesh::filterHashHandleCommand(const char* command, char* reply, int reply } int len = snprintf(reply, reply_max, "filter hash: dropped %u, passed %u, deny:", - filter_hash_dropped, filter_hash_passed); - if (n == 0 && len < reply_max) len += snprintf(&reply[len], reply_max - len, " (nic)"); - for (int i = 0; i < n && len < reply_max; i++) { - if (_prefs.deny_hash_secs[i]) { - len += snprintf(&reply[len], reply_max - len, " %02X/%u", _prefs.deny_hash[i], _prefs.deny_hash_secs[i]); - } else { - len += snprintf(&reply[len], reply_max - len, " %02X", _prefs.deny_hash[i]); - } + (unsigned)flow_table.totalDropped(FLOW_KIND_C), (unsigned)flow_table.totalPassed(FLOW_KIND_C)); + bool any = false; + for (int i = 0; i < flow_table.n && len < reply_max; i++) { + const FlowRule& r = flow_table.e[i].r; + if (r.kind != FLOW_KIND_C) continue; + any = true; + if (r.mode == FLOW_THROTTLE) len += snprintf(&reply[len], reply_max - len, " %02X/%u", r.key[0], r.secs); + else if (r.mode == FLOW_DRY) len += snprintf(&reply[len], reply_max - len, " %02X/dry", r.key[0]); + else len += snprintf(&reply[len], reply_max - len, " %02X", r.key[0]); } + if (!any && len < reply_max) snprintf(&reply[len], reply_max - len, " (nic)"); return true; } -// --------------------------------------------------------------------------- -// Deny-forward by RELAY -- `filter path` (tth #4), independent of channel keys. -// -// A flood whose path so far names a denied relay is not re-aired by this node. -// Matching rules and why 1-byte hops never match: pathDenyMatch() in -// src/helpers/ChannelGate.h. Only FLOOD packets: a direct packet's path is the -// route still ahead, and it was addressed to us on purpose. Reception and -// rxlog/pktfeed capture are untouched, as with the other filters. -// Persisted in prefs (f_dpath, f_dpath_l, f_dpath_n); honours `filter dryrun`. - -static_assert(sizeof(NodePrefs::deny_path) == PATH_DENY_SLOTS * PATH_DENY_MAX_BYTES, "deny_path shape"); -static_assert(sizeof(NodePrefs::deny_path_len) == PATH_DENY_SLOTS, "deny_path_len shape"); - -bool MyMesh::filterPathDenied(const mesh::Packet* packet) { - if (_prefs.deny_path_n == 0 || !packet->isRouteFlood()) return false; - int at = pathDenyMatch(packet->path, packet->getPathHashSize(), packet->getPathHashCount(), - _prefs.deny_path, _prefs.deny_path_len, _prefs.deny_path_n); - if (at < 0) return false; - filter_path_dropped++; - return !_prefs.filter_dry_run; -} - -static int pathDenyFormat(char* dest, int max, const uint8_t* b, uint8_t len) { - int n = 0; - for (uint8_t i = 0; i < len && n < max; i++) n += snprintf(&dest[n], max - n, "%02X", b[i]); - return n; -} - // `filter path [list]` -- drops + list; `filter path add ` -- deny a relay -// by its pubkey prefix (4..8 hex digits); `filter path del `; `filter path clear`. +// by its pubkey prefix (4..8 hex digits = kind p, static); `filter path del `; +// `filter path clear` (static p entries only). bool MyMesh::filterPathHandleCommand(const char* command, char* reply, int reply_max) { if (memcmp(command, "filter path", 11) != 0 || (command[11] != 0 && command[11] != ' ')) return false; const char* arg = (command[11] == ' ') ? &command[12] : ""; - uint8_t n = _prefs.deny_path_n; - if (n > PATH_DENY_SLOTS) n = PATH_DENY_SLOTS; + uint32_t now_ms = millis(); if (strcmp(arg, "clear") == 0) { - _prefs.deny_path_n = 0; - memset(_prefs.deny_path, 0, sizeof(_prefs.deny_path)); - memset(_prefs.deny_path_len, 0, sizeof(_prefs.deny_path_len)); - savePrefs(); + for (int i = flow_table.n - 1; i >= 0; i--) { + const FlowRule& r = flow_table.e[i].r; + if (r.kind == FLOW_KIND_P && !(r.flags & FLOW_FLAG_AUTO)) flow_table.del(r.kind, r.key, r.klen); + } + flowPersist(); strcpy(reply, "OK - path deny list cleared"); return true; } @@ -279,49 +358,43 @@ bool MyMesh::filterPathHandleCommand(const char* command, char* reply, int reply bool is_add = strncmp(arg, "add ", 4) == 0; bool is_del = strncmp(arg, "del ", 4) == 0; if (is_add || is_del) { - uint8_t b[PATH_DENY_MAX_BYTES]; - uint8_t len = pathDenyParse(arg + 4, b); - if (len == 0) { + FlowRule r; + memset(&r, 0, sizeof(r)); + r.kind = FLOW_KIND_P; + const char* h = arg + 4; + r.klen = flowParseHex(h, strlen(h), r.key, 4); + if (!flowKeyLenOk(r.kind, r.klen)) { strcpy(reply, "Err - 2..4 byte hex prefix, e.g. c420"); return true; } - int at = -1; - for (int i = 0; i < n; i++) { - if (_prefs.deny_path_len[i] == len && memcmp(_prefs.deny_path[i], b, len) == 0) { at = i; break; } - } + r.mode = FLOW_BLOCK; if (is_add) { - if (at >= 0) { strcpy(reply, "Err - already listed"); return true; } - if (n >= PATH_DENY_SLOTS) { strcpy(reply, "Err - list full"); return true; } - memset(_prefs.deny_path[n], 0, PATH_DENY_MAX_BYTES); - memcpy(_prefs.deny_path[n], b, len); - _prefs.deny_path_len[n] = len; - n++; - } else { - if (at < 0) { strcpy(reply, "Err - not listed"); return true; } - for (int i = at; i + 1 < n; i++) { - memcpy(_prefs.deny_path[i], _prefs.deny_path[i + 1], PATH_DENY_MAX_BYTES); - _prefs.deny_path_len[i] = _prefs.deny_path_len[i + 1]; - } - --n; - memset(_prefs.deny_path[n], 0, PATH_DENY_MAX_BYTES); - _prefs.deny_path_len[n] = 0; + FlowResult res = flow_table.add(r, now_ms); + if (res == FLOW_SAME) { strcpy(reply, "Err - already listed"); return true; } + if (res == FLOW_FULL) { strcpy(reply, "Err - list full"); return true; } + } else if (flow_table.del(r.kind, r.key, r.klen) != FLOW_OK) { + strcpy(reply, "Err - not listed"); + return true; } - _prefs.deny_path_n = n; - savePrefs(); + flowPersist(); // fall through to the listing as the reply } else if (arg[0] != 0 && strcmp(arg, "list") != 0) { strcpy(reply, "Err - filter path [add |del |list|clear]"); return true; } - int len = snprintf(reply, reply_max, "filter path: dropped %u%s, deny:", filter_path_dropped, + int len = snprintf(reply, reply_max, "filter path: dropped %u%s, deny:", (unsigned)flow_table.totalDropped(FLOW_KIND_P), _prefs.filter_dry_run ? " DRY-RUN" : ""); - if (n == 0 && len < reply_max) len += snprintf(&reply[len], reply_max - len, " (nic)"); - for (int i = 0; i < n && len + 1 < reply_max; i++) { + bool any = false; + for (int i = 0; i < flow_table.n && len + 1 < reply_max; i++) { + const FlowRule& r = flow_table.e[i].r; + if (r.kind != FLOW_KIND_P) continue; + any = true; reply[len++] = ' '; reply[len] = 0; - len += pathDenyFormat(&reply[len], reply_max - len, _prefs.deny_path[i], _prefs.deny_path_len[i]); + len += flowHex(&reply[len], reply_max - len, r.key, r.klen); } + if (!any && len < reply_max) snprintf(&reply[len], reply_max - len, " (nic)"); return true; } diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 6afbc455f..27fc7485e 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -867,17 +867,13 @@ bool MyMesh::allowPacketForward(const mesh::Packet *packet) { return false; } } - // CUSTOM (TeTeHacko): keyless channel-hash deny list / throttle (`filter hash`). + // CUSTOM (TeTeHacko): `filter flow` -- forward-deny rules (channel byte, dest/src, + // login dest, advert prefix, relay in path; `filter hash|path` are aliases). // LAST of the checks here, so a throttle pass is only spent on a packet that // would otherwise go out; and before takeForwardingRateLimit() in // routeRecvPacket(), so a vetoed packet does not eat FairnessLimiter tokens. - if (filterHashDenied(packet)) { - MESH_DEBUG_PRINTLN("allowPacketForward: channel hash %02X on deny list", packet->payload[0]); - return false; - } - // CUSTOM (TeTeHacko): `filter path` -- a flood that came through a denied relay. - if (filterPathDenied(packet)) { - MESH_DEBUG_PRINTLN("allowPacketForward: denied relay in path"); + if (filterFlowDenied(packet)) { + MESH_DEBUG_PRINTLN("allowPacketForward: filter flow rule matched"); return false; } return true; @@ -1570,9 +1566,6 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc #define RADIO_SILENCE_MIN_DEFAULT 0 #endif _prefs.radio_silence_min = RADIO_SILENCE_MIN_DEFAULT; - filter_hash_dropped = 0; - filter_hash_passed = 0; - filter_path_dropped = 0; _prefs.interference_threshold = 0; // disabled _prefs.cad_enabled = 0; // hardware CAD before TX (off by default; 'set cad on') _prefs.loop_detect = LOOP_DETECT_MINIMAL; @@ -1614,6 +1607,7 @@ void MyMesh::begin(FILESYSTEM *fs) { _fs = fs; // load persisted prefs _cli.loadPrefs(_fs); + flowLoad(); // CUSTOM (TeTeHacko): `filter flow` rules acl.load(_fs, self_id); // Apply any persisted runtime cap tuning (0 = build default). Do this before @@ -2012,8 +2006,9 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply // CUSTOM (TeTeHacko): `bot` — read-only channel bot diagnostics. See ChannelBot.h. if (botHandleCommand(command, reply)) return; #endif - // CUSTOM (TeTeHacko): `filter hash [add|del |clear]` — keyless channel-hash - // deny list. Before filterHandleCommand(), which would claim any `filter ...`. + // CUSTOM (TeTeHacko): `filter flow ...` (and its aliases `filter hash|path ...`) -- + // keyless forward-deny rules. Before filterHandleCommand(), which would claim any `filter ...`. + if (filterFlowHandleCommand(command, reply, reply_max)) return; if (filterHashHandleCommand(command, reply, reply_max)) return; // CUSTOM (TeTeHacko): `filter path [add|del |clear]` -- relay deny list. if (filterPathHandleCommand(command, reply, reply_max)) return; diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index 065c1a3b7..7b4bfb1a4 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -37,6 +37,7 @@ #include #include #include +#include #include #include #include "RateLimiter.h" @@ -213,10 +214,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { // CUSTOM (TeTeHacko): token-bucket limiter over FORWARDED traffic (port of // upstream proposal #1502). Kill switch: _prefs.fairness_enabled. FairnessLimiter fairness_limiter; - uint32_t filter_hash_dropped; // forwards vetoed by the channel-hash deny list - uint32_t filter_hash_passed; // throttled entries: forwards let through within budget - HashThrottle hash_throttle; // per-entry windows of `filter hash add ` - uint32_t filter_path_dropped; // floods vetoed because a denied relay is in their path + FlowTable flow_table; // `filter flow` rules + counters (also behind `filter hash|path`) unsigned long next_fair_sender_normal_refill, next_fair_sender_low_refill, next_fair_group_refill; uint32_t pending_discover_tag; unsigned long pending_discover_until; @@ -336,10 +334,12 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { // CUSTOM (TeTeHacko): `fairness [on|off|grid|cap ...|refill ...]` CLI. Defined in MyMesh.cpp. bool fairnessHandleCommand(const char* command, char* reply, int reply_max); // CUSTOM (TeTeHacko): keyless deny-forward by channel hash. Definitions in ChannelFilter.h. - bool filterHashDenied(const mesh::Packet* packet); - bool filterHashHandleCommand(const char* command, char* reply, int reply_max); - bool filterPathDenied(const mesh::Packet* packet); - bool filterPathHandleCommand(const char* command, char* reply, int reply_max); + bool filterFlowDenied(const mesh::Packet* packet); + bool filterFlowHandleCommand(const char* command, char* reply, int reply_max); + bool filterHashHandleCommand(const char* command, char* reply, int reply_max); // alias onto kind c + bool filterPathHandleCommand(const char* command, char* reply, int reply_max); // alias onto kind p + void flowLoad(); // prefs -> flow_table (+ one-time migration of f_dhash*/f_dpath*) + void flowPersist(); // flow_table -> prefs, then savePrefs() // `filter dryrun [on|off]` and `filter age [|off]`. Definitions in ChannelFilter.h. bool filterMiscHandleCommand(const char* command, char* reply, int reply_max); // Refill interval in ms: persisted pref (seconds) if set, else the build default. diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index a300b8d0e..52cf4f31a 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -97,6 +97,11 @@ public: uint8_t deny_path[8][4]; uint8_t deny_path_len[8]; // significant bytes per row, 0 = unused uint8_t deny_path_n = 0; + // `filter flow` rules, one packed FLOW_REC_LEN (22) byte record per entry, all + // zero = unused (FlowRules.h flowPack). One key per record: the config reader + // holds a token of at most 63 bytes. The legacy deny_hash/deny_path above are + // only read, to migrate once at boot (examples/simple_repeater/ChannelFilter.h). + uint8_t flow_rec[16][22]; uint16_t filter_age_min = 0; // drop decrypted group texts older than this; 0 = off uint8_t filter_dry_run = 0; // count `filter` verdicts, forward anyway // Battery state as an icon on the advertised name (see BatteryIcon.h). @@ -281,6 +286,11 @@ private: def("f_dpath", (void*)_parent->deny_path, sizeof(_parent->deny_path)); def("f_dpath_l", (void*)_parent->deny_path_len, sizeof(_parent->deny_path_len)); def("f_dpath_n", _parent->deny_path_n); + for (int i = 0; i < 16; i++) { + char k[8]; + snprintf(k, sizeof(k), "f_fl%d", i); + def(k, (void*)_parent->flow_rec[i], sizeof(_parent->flow_rec[i])); + } def("f_age", _parent->filter_age_min); def("f_dry", _parent->filter_dry_run); def("fair_gcap", _parent->fair_group_cap); @@ -343,6 +353,7 @@ public: memset(deny_hash_secs, 0, sizeof(deny_hash_secs)); memset(deny_path, 0, sizeof(deny_path)); memset(deny_path_len, 0, sizeof(deny_path_len)); + memset(flow_rec, 0, sizeof(flow_rec)); } CommonRadioPrefs* getRadioPrefs() { return &radio; } diff --git a/src/helpers/FlowRules.h b/src/helpers/FlowRules.h new file mode 100644 index 000000000..93f12f1cd --- /dev/null +++ b/src/helpers/FlowRules.h @@ -0,0 +1,585 @@ +#pragma once + +// CUSTOM (TeTeHacko): `filter flow` -- ONE table of forward-deny rules that +// replaces `filter hash` (kind c) and `filter path` (kind p) and adds the +// other ways one node can crowd a mesh out (tth #41, epic #45). Header-only and +// free of mesh/Arduino types so the table, the matching, the expiry and the +// rule CRC all run in the native tests; the glue (prefs, CLI, hook in +// allowPacketForward) lives in examples/simple_repeater/ChannelFilter.h. +// +// KINDS (FLOOD packets only; matched on what is in the clear) +// c channel byte GRP_TXT / GRP_DATA payload[0] 1 B +// r dest src [+hop] REQ / RESPONSE / TXT_MSG / PATH payload[0..1] 2 B or 4 B +// n dest [+hop] ANON_REQ payload[0] (login flood) 1 B or 3 B +// a pubkey prefix ADVERT payload[0..] 4..8 B +// p relay in the path any hop of path[] 2..4 B +// "+hop" = the FIRST hop of the path, 2 bytes. 0-hop packets and packets with +// 1-byte hops never match a rule that has it (a 1-byte hash collides with most +// of the mesh). Kind p ignores 1-byte hops entirely, for the same reason. +// +// ENTRY: mode (block | throttle | dry), flag `auto` (1 bit: set by an agent, +// as opposed to static = inventory/hand), optional expiry, RAM counters. +// * Entries are kept SORTED by (kind, key) -- kind as its ASCII letter, key +// bytewise, shorter key first on a common prefix. Max FLOW_MAX = 16. The +// index in that array is the `slot_id`; it moves on add/del. +// * EXPIRY (two clocks, whichever comes first): absolute unix `expires` +// (honoured only while the node clock is >= FLOW_CLOCK_VALID_FROM) and the +// `remain` seconds that were left when the rule was last persisted, +// counted down from boot by uptime. A cold start without GPS/bridge has a +// clock behind by the age of the build, so the absolute time alone would +// extend a block. `remain` is written only on add/change. +// * Expired entries are REMOVED (the `auto` CRC changes with them). +// * RULES CRC: CRC-16/CCITT-FALSE over the canonical serialization of the +// sorted entries of one set (auto | static): per entry +// kind(1, ASCII) klen(1) key(klen) mode(1: 0 block, 1 throttle, 2 dry) +// throttle_secs(2, BE; 0 unless throttle) expires(4, BE; 0 = none) +// Counters, `remain` and the auto flag are NOT part of it. The reference +// implementation and vectors: test/vectors/flow_rules_vectors.json. + +#include +#include +#include +#include + +// The table code is only ever called from a handful of places; left to the +// optimizer it was inlined into each of them (+23 KB of flash on nRF52). +#if defined(__GNUC__) + #define FLOW_NOINLINE __attribute__((noinline)) +#else + #define FLOW_NOINLINE +#endif + +#define FLOW_MAX 16 +#define FLOW_KEY_MAX 8 +#define FLOW_REC_LEN 22 // packed record, see flowPack() +#define FLOW_TTL_MAX 2000000UL // ~23 days; keeps the ms countdown wrap-safe +#define FLOW_CLOCK_VALID_FROM 1767225600UL // 2026-01-01, same as MSG_AGE_CLOCK_VALID_FROM + +#define FLOW_KIND_C 'c' +#define FLOW_KIND_R 'r' +#define FLOW_KIND_N 'n' +#define FLOW_KIND_A 'a' +#define FLOW_KIND_P 'p' + +#define FLOW_BLOCK 0 +#define FLOW_THROTTLE 1 +#define FLOW_DRY 2 + +#define FLOW_FLAG_AUTO 0x01 + +// Packet classes the glue maps payload types onto. +#define FLOW_PKT_OTHER 0 +#define FLOW_PKT_GROUP 1 // GRP_TXT, GRP_DATA +#define FLOW_PKT_ADDR 2 // REQ, RESPONSE, TXT_MSG, PATH (dest, src, MAC) +#define FLOW_PKT_ANON 3 // ANON_REQ (dest, pubkey, MAC) +#define FLOW_PKT_ADVERT 4 // ADVERT (pubkey ...) + +struct FlowPkt { + uint8_t cls; + const uint8_t* payload; + uint8_t payload_len; + const uint8_t* path; // hop_count hashes of hash_size bytes + uint8_t hash_size; + uint8_t hop_count; +}; + +struct FlowRule { + uint8_t kind; + uint8_t klen; + uint8_t key[FLOW_KEY_MAX]; + uint8_t mode; + uint8_t flags; + uint16_t secs; // throttle interval + uint32_t expires; // absolute unix, 0 = none + uint32_t remain; // seconds left when last persisted, 0 = none +}; + +struct FlowEntry { + FlowRule r; + uint32_t dropped, passed; // RAM only + uint32_t last_ms; // throttle window + uint32_t deadline_ms; // uptime countdown of `remain` + uint8_t armed; + uint8_t has_deadline; +}; + +inline bool flowClockValid(uint32_t now_unix) { return now_unix >= FLOW_CLOCK_VALID_FROM; } + +inline bool flowKeyLenOk(uint8_t kind, uint8_t klen) { + switch (kind) { + case FLOW_KIND_C: return klen == 1; + case FLOW_KIND_R: return klen == 2 || klen == 4; + case FLOW_KIND_N: return klen == 1 || klen == 3; + case FLOW_KIND_A: return klen >= 4 && klen <= FLOW_KEY_MAX; + case FLOW_KIND_P: return klen >= 2 && klen <= 4; + } + return false; +} + +inline FLOW_NOINLINE uint16_t flowCrc16(uint16_t crc, const uint8_t* d, size_t n) { // CCITT-FALSE + while (n--) { + crc ^= (uint16_t)(*d++) << 8; + for (int i = 0; i < 8; i++) crc = (crc & 0x8000) ? (uint16_t)((crc << 1) ^ 0x1021) : (uint16_t)(crc << 1); + } + return crc; +} + +// Canonical bytes of one rule (see header). Returns the length. +inline FLOW_NOINLINE uint8_t flowCanonical(const FlowRule& r, uint8_t* out) { + uint8_t n = 0; + out[n++] = r.kind; + out[n++] = r.klen; + for (uint8_t i = 0; i < r.klen; i++) out[n++] = r.key[i]; + out[n++] = r.mode; + uint16_t s = (r.mode == FLOW_THROTTLE) ? r.secs : 0; + out[n++] = (uint8_t)(s >> 8); + out[n++] = (uint8_t)s; + out[n++] = (uint8_t)(r.expires >> 24); + out[n++] = (uint8_t)(r.expires >> 16); + out[n++] = (uint8_t)(r.expires >> 8); + out[n++] = (uint8_t)r.expires; + return n; +} + +// Fixed-size record for prefs (one hex blob per entry, FLOW_REC_LEN bytes). +inline FLOW_NOINLINE void flowPack(const FlowRule& r, uint8_t* o) { + memset(o, 0, FLOW_REC_LEN); + o[0] = r.kind; o[1] = r.klen; + memcpy(&o[2], r.key, FLOW_KEY_MAX); + o[10] = r.mode; o[11] = r.flags; + o[12] = (uint8_t)(r.secs >> 8); o[13] = (uint8_t)r.secs; + for (int i = 0; i < 4; i++) { o[14 + i] = (uint8_t)(r.expires >> (24 - 8 * i)); o[18 + i] = (uint8_t)(r.remain >> (24 - 8 * i)); } +} + +inline FLOW_NOINLINE bool flowUnpack(const uint8_t* o, FlowRule& r) { + memset(&r, 0, sizeof(r)); + r.kind = o[0]; r.klen = o[1]; + if (!flowKeyLenOk(r.kind, r.klen)) return false; + memcpy(r.key, &o[2], FLOW_KEY_MAX); + for (uint8_t i = r.klen; i < FLOW_KEY_MAX; i++) r.key[i] = 0; + r.mode = o[10]; r.flags = o[11]; + if (r.mode > FLOW_DRY) return false; + r.secs = ((uint16_t)o[12] << 8) | o[13]; + if (r.mode == FLOW_THROTTLE && r.secs == 0) return false; + for (int i = 0; i < 4; i++) { r.expires = (r.expires << 8) | o[14 + i]; r.remain = (r.remain << 8) | o[18 + i]; } + if (r.remain > FLOW_TTL_MAX) r.remain = FLOW_TTL_MAX; + return true; +} + +// Does the packet's path carry a hop that matches the prefix `k` (2..4 bytes)? +// Compared on the shorter of hop width and prefix; 1-byte hops never match. +inline bool flowRelayInPath(const FlowPkt& p, const uint8_t* key, uint8_t klen) { + if (p.hash_size < 2 || p.path == NULL) return false; + uint8_t k = klen > p.hash_size ? p.hash_size : klen; + for (uint8_t h = 0; h < p.hop_count; h++) { + if (memcmp(&p.path[h * p.hash_size], key, k) == 0) return true; + } + return false; +} + +inline FLOW_NOINLINE bool flowRuleMatches(const FlowRule& r, const FlowPkt& p) { + switch (r.kind) { + case FLOW_KIND_C: + return p.cls == FLOW_PKT_GROUP && p.payload_len >= 1 && p.payload[0] == r.key[0]; + case FLOW_KIND_R: + case FLOW_KIND_N: { + uint8_t base = (r.kind == FLOW_KIND_R) ? 2 : 1; + if (p.cls != (r.kind == FLOW_KIND_R ? FLOW_PKT_ADDR : FLOW_PKT_ANON) || p.payload_len < base) return false; + if (memcmp(p.payload, r.key, base) != 0) return false; + if (r.klen > base) { // first hop, 2 bytes + if (p.hash_size < 2 || p.hop_count < 1 || p.path == NULL) return false; + return memcmp(p.path, &r.key[base], 2) == 0; + } + return true; + } + case FLOW_KIND_A: + return p.cls == FLOW_PKT_ADVERT && p.payload_len >= r.klen && memcmp(p.payload, r.key, r.klen) == 0; + case FLOW_KIND_P: + return flowRelayInPath(p, r.key, r.klen); + } + return false; +} + +// (kind, key) order: kind byte, then key bytewise, shorter first. +inline int flowKeyCmp(uint8_t ka, const uint8_t* a, uint8_t la, uint8_t kb, const uint8_t* b, uint8_t lb) { + if (ka != kb) return ka < kb ? -1 : 1; + uint8_t m = la < lb ? la : lb; + int c = memcmp(a, b, m); + if (c != 0) return c < 0 ? -1 : 1; + if (la == lb) return 0; + return la < lb ? -1 : 1; +} + +enum FlowResult { FLOW_OK, FLOW_CHANGED, FLOW_SAME, FLOW_FULL, FLOW_BAD, FLOW_NOT_FOUND }; + +class FlowTable { +public: + FlowEntry e[FLOW_MAX]; + uint8_t n = 0; + + void clearAll() { n = 0; memset(e, 0, sizeof(e)); } + + FLOW_NOINLINE int find(uint8_t kind, const uint8_t* key, uint8_t klen) const { + for (uint8_t i = 0; i < n; i++) { + if (flowKeyCmp(e[i].r.kind, e[i].r.key, e[i].r.klen, kind, key, klen) == 0) return i; + } + return -1; + } + + // Insert in order, or update in place. Counters survive an update; the + // throttle window and the expiry countdown restart. + FLOW_NOINLINE FlowResult add(const FlowRule& r, uint32_t now_ms) { + if (!flowKeyLenOk(r.kind, r.klen) || r.mode > FLOW_DRY) return FLOW_BAD; + if (r.mode == FLOW_THROTTLE && r.secs == 0) return FLOW_BAD; + FlowRule nr = r; + if (nr.mode != FLOW_THROTTLE) nr.secs = 0; + for (uint8_t i = nr.klen; i < FLOW_KEY_MAX; i++) nr.key[i] = 0; + int at = find(nr.kind, nr.key, nr.klen); + FlowResult res = FLOW_OK; + if (at >= 0) { + const FlowRule& o = e[at].r; + if (o.mode == nr.mode && o.secs == nr.secs && o.flags == nr.flags && o.expires == nr.expires && + o.remain == nr.remain) { + return FLOW_SAME; + } + res = FLOW_CHANGED; + } else { + if (n >= FLOW_MAX) return FLOW_FULL; + at = 0; + while (at < n && flowKeyCmp(e[at].r.kind, e[at].r.key, e[at].r.klen, nr.kind, nr.key, nr.klen) < 0) at++; + memmove(&e[at + 1], &e[at], (size_t)(n - at) * sizeof(FlowEntry)); + memset(&e[at], 0, sizeof(FlowEntry)); + n++; + } + e[at].r = nr; + e[at].armed = 0; + e[at].has_deadline = nr.remain > 0; + e[at].deadline_ms = now_ms + nr.remain * 1000u; + return res; + } + + FLOW_NOINLINE FlowResult del(uint8_t kind, const uint8_t* key, uint8_t klen) { + int at = find(kind, key, klen); + if (at < 0) return FLOW_NOT_FOUND; + removeAt(at); + return FLOW_OK; + } + + // which: 0 = auto only, 1 = static only, 2 = all. Returns how many went. + FLOW_NOINLINE int clear(int which) { + int removed = 0; + for (int i = n - 1; i >= 0; i--) { + bool is_auto = (e[i].r.flags & FLOW_FLAG_AUTO) != 0; + if (which == 2 || (which == 0) == is_auto) { removeAt(i); removed++; } + } + return removed; + } + + // Seconds left on entry i (min of both clocks); false = no expiry. + FLOW_NOINLINE bool remaining(int i, uint32_t now_ms, uint32_t now_unix, uint32_t* secs) const { + bool have = false; + uint32_t best = 0; + const FlowEntry& x = e[i]; + if (x.r.expires != 0 && flowClockValid(now_unix)) { + best = x.r.expires > now_unix ? x.r.expires - now_unix : 0; + have = true; + } + if (x.has_deadline) { + int32_t d = (int32_t)(x.deadline_ms - now_ms); + uint32_t s = d > 0 ? (uint32_t)d / 1000u : 0; + if (!have || s < best) best = s; + have = true; + } + if (secs) *secs = best; + return have; + } + + // Drop entries whose time is up. Returns how many (a change of the auto CRC). + FLOW_NOINLINE int expire(uint32_t now_ms, uint32_t now_unix) { + int removed = 0; + for (int i = n - 1; i >= 0; i--) { + const FlowEntry& x = e[i]; + bool gone = false; + if (x.r.expires != 0 && flowClockValid(now_unix) && now_unix >= x.r.expires) gone = true; + if (x.has_deadline && (int32_t)(now_ms - x.deadline_ms) >= 0) gone = true; + if (gone) { removeAt(i); removed++; } + } + return removed; + } + + // Count + CRC of one set: is_auto selects auto or static entries. + FLOW_NOINLINE uint16_t crc(bool is_auto, int* count) const { + uint16_t c = 0xFFFF; + int k = 0; + uint8_t buf[3 + FLOW_KEY_MAX + 7]; + for (uint8_t i = 0; i < n; i++) { + if (((e[i].r.flags & FLOW_FLAG_AUTO) != 0) != is_auto) continue; + c = flowCrc16(c, buf, flowCanonical(e[i].r, buf)); + k++; + } + if (count) *count = k; + return c; + } + + // true = do not forward. Every matching rule counts; block / closed throttle + // window drop (the first such rule is charged), dry only counts. A throttle + // window is spent only when no other rule vetoes the packet. global_dry + // (`filter dryrun`) keeps all counting but never drops. + FLOW_NOINLINE bool verdict(const FlowPkt& p, uint32_t now_ms, bool global_dry) { + int drop_at = -1; + uint16_t matched = 0; + for (uint8_t i = 0; i < n; i++) { + if (!flowRuleMatches(e[i].r, p)) continue; + matched |= (uint16_t)(1u << i); + if (e[i].r.mode == FLOW_DRY) { e[i].dropped++; continue; } + if (drop_at < 0 && !windowOpen(i, now_ms)) drop_at = i; + } + if (drop_at >= 0) { + e[drop_at].dropped++; + return !global_dry; + } + for (uint8_t i = 0; i < n; i++) { + if (!(matched & (1u << i)) || e[i].r.mode != FLOW_THROTTLE) continue; + e[i].armed = 1; + e[i].last_ms = now_ms; + e[i].passed++; + } + return false; + } + + uint32_t totalDropped(uint8_t kind) const { + uint32_t s = 0; + for (uint8_t i = 0; i < n; i++) if (e[i].r.kind == kind) s += e[i].dropped; + return s; + } + uint32_t totalPassed(uint8_t kind) const { + uint32_t s = 0; + for (uint8_t i = 0; i < n; i++) if (e[i].r.kind == kind) s += e[i].passed; + return s; + } + +private: + bool windowOpen(int i, uint32_t now_ms) const { + const FlowRule& r = e[i].r; + if (r.mode == FLOW_DRY) return true; + if (r.mode == FLOW_BLOCK) return false; + return !e[i].armed || (uint32_t)(now_ms - e[i].last_ms) >= (uint32_t)r.secs * 1000u; + } + void removeAt(int at) { + memmove(&e[at], &e[at + 1], (size_t)(n - at - 1) * sizeof(FlowEntry)); + n--; + memset(&e[n], 0, sizeof(FlowEntry)); + } +}; + +// --------------------------------------------------------------------------- +// Parsing: ` [block|throttle |dry] [auto] [ttl |expires ]` + +struct FlowSpec { + FlowRule r; + bool has_ttl, has_expires; + uint32_t ttl; // seconds +}; + +// "a1b2" / "0xA1B2" -> bytes; returns count (0 = invalid, odd digits, > max). +inline FLOW_NOINLINE uint8_t flowParseHex(const char* s, size_t slen, uint8_t* out, uint8_t max) { + if (slen >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) { s += 2; slen -= 2; } + if (slen == 0 || slen % 2 != 0 || slen > 2u * max) return 0; + for (size_t i = 0; i < slen; i++) { + char c = s[i]; + uint8_t v; + if (c >= '0' && c <= '9') v = c - '0'; + else if (c >= 'a' && c <= 'f') v = c - 'a' + 10; + else if (c >= 'A' && c <= 'F') v = c - 'A' + 10; + else return 0; + if (i % 2 == 0) out[i / 2] = v << 4; else out[i / 2] |= v; + } + return (uint8_t)(slen / 2); +} + +// Split the next blank-separated token off *p. Returns its length (0 = none). +inline size_t flowToken(const char** p, const char** tok) { + while (**p == ' ') (*p)++; + *tok = *p; + while (**p != 0 && **p != ' ') (*p)++; + return (size_t)(*p - *tok); +} + +inline bool flowTokIs(const char* t, size_t n, const char* w) { return strlen(w) == n && memcmp(t, w, n) == 0; } + +// Parses a decimal into *v; false on junk / overflow past `max`. +inline bool flowParseNum(const char* t, size_t n, uint32_t max, uint32_t* v) { + if (n == 0 || n > 10) return false; + uint64_t x = 0; + for (size_t i = 0; i < n; i++) { + if (t[i] < '0' || t[i] > '9') return false; + x = x * 10 + (t[i] - '0'); + } + if (x > max) return false; + *v = (uint32_t)x; + return true; +} + +// Kind + key only (for `del`). Returns NULL on success, else an error text. +inline const char* flowParseKey(const char** p, uint8_t* kind, uint8_t* key, uint8_t* klen) { + const char* t; + size_t n = flowToken(p, &t); + if (n != 1 || (t[0] != 'c' && t[0] != 'r' && t[0] != 'n' && t[0] != 'a' && t[0] != 'p')) { + return "Err - kind c|r|n|a|p"; + } + *kind = (uint8_t)t[0]; + n = flowToken(p, &t); + *klen = flowParseHex(t, n, key, FLOW_KEY_MAX); + if (*klen == 0 || !flowKeyLenOk(*kind, *klen)) { + return "Err - key: c 1B, r 2|4B, n 1|3B, a 4-8B, p 2-4B (hex)"; + } + return NULL; +} + +inline const char* flowParseAdd(const char* args, FlowSpec* s) { + memset(s, 0, sizeof(*s)); + const char* p = args; + uint8_t kind, key[FLOW_KEY_MAX], klen; + const char* err = flowParseKey(&p, &kind, key, &klen); + if (err) return err; + s->r.kind = kind; s->r.klen = klen; + memcpy(s->r.key, key, klen); + bool mode_set = false; + const char* t; + size_t n; + while ((n = flowToken(&p, &t)) > 0) { + uint32_t v; + if (flowTokIs(t, n, "block") || flowTokIs(t, n, "dry") || flowTokIs(t, n, "throttle")) { + if (mode_set) return "Err - one mode only"; + mode_set = true; + if (flowTokIs(t, n, "block")) s->r.mode = FLOW_BLOCK; + else if (flowTokIs(t, n, "dry")) s->r.mode = FLOW_DRY; + else { + n = flowToken(&p, &t); + if (!flowParseNum(t, n, 65535, &v) || v == 0) return "Err - throttle <1..65535 s>"; + s->r.mode = FLOW_THROTTLE; + s->r.secs = (uint16_t)v; + } + } else if (flowTokIs(t, n, "auto")) { + s->r.flags |= FLOW_FLAG_AUTO; + } else if (flowTokIs(t, n, "ttl")) { + n = flowToken(&p, &t); + if (s->has_ttl || s->has_expires || !flowParseNum(t, n, FLOW_TTL_MAX, &v) || v == 0) { + return "Err - ttl <1..2000000 s>, not with expires"; + } + s->has_ttl = true; s->ttl = v; + } else if (flowTokIs(t, n, "expires")) { + n = flowToken(&p, &t); + if (s->has_ttl || s->has_expires || !flowParseNum(t, n, 0xFFFFFFFFu, &v) || v == 0) { + return "Err - expires , not with ttl"; + } + s->has_expires = true; s->r.expires = v; + } else { + return "Err - [block|throttle |dry] [auto] [ttl |expires ]"; + } + } + return NULL; +} + +// Turn ttl / expires into the stored pair (expires, remain). NULL = ok. +inline const char* flowResolveExpiry(FlowSpec* s, uint32_t now_unix) { + bool valid = flowClockValid(now_unix); + if (s->has_ttl) { + s->r.remain = s->ttl; + s->r.expires = valid ? now_unix + s->ttl : 0; + } else if (s->has_expires) { + if (valid) { + if (s->r.expires <= now_unix) return "Err - already expired"; + uint32_t left = s->r.expires - now_unix; + s->r.remain = left > FLOW_TTL_MAX ? FLOW_TTL_MAX : left; + } else { + s->r.remain = 0; // no usable clock: only the absolute time can end it + } + } + return NULL; +} + +// --------------------------------------------------------------------------- +// Replies (RF CLI limit 150 B). Formats are documented in docs/tth-commands.md. + +#define FLOW_REPLY_MAX 150 +#define FLOW_PAGE_ENTRIES 4 + +inline int flowHex(char* d, int max, const uint8_t* b, uint8_t len) { + int n = 0; + for (uint8_t i = 0; i < len && n + 2 < max; i++) n += snprintf(&d[n], max - n, "%02X", b[i]); + return n; +} + +// `a=:` of both sets, shared by add|del|clear replies and list pages. +inline FLOW_NOINLINE int flowSummary(const FlowTable& t, char* d, int max) { + int ca, cs; + uint16_t ra = t.crc(true, &ca), rs = t.crc(false, &cs); + return snprintf(d, max, "n=%d a=%d:%04X s=%d:%04X", (int)t.n, ca, ra, cs, rs); +} + +// One entry: `,,,/,` +// mode B | T | D ; left = seconds to expiry or `-`. +// worst = true renders the longest the counters / expiry can get, for page packing. +inline FLOW_NOINLINE int flowEntryText(const FlowTable& t, int i, uint32_t now_ms, uint32_t now_unix, bool worst, char* d, + int max) { + const FlowEntry& x = t.e[i]; + int n = 0; + d[n++] = (char)x.r.kind; + n += flowHex(&d[n], max - n, x.r.key, x.r.klen); + if (x.r.mode == FLOW_BLOCK) n += snprintf(&d[n], max - n, ",B"); + else if (x.r.mode == FLOW_DRY) n += snprintf(&d[n], max - n, ",D"); + else n += snprintf(&d[n], max - n, ",T%u", (unsigned)x.r.secs); + uint32_t dr = x.dropped > 99999 ? 99999 : x.dropped, pa = x.passed > 99999 ? 99999 : x.passed; + if (worst) dr = pa = 99999; + n += snprintf(&d[n], max - n, ",%c,%u/%u,", (x.r.flags & FLOW_FLAG_AUTO) ? 'A' : 'S', (unsigned)dr, (unsigned)pa); + uint32_t left; + bool has = t.remaining(i, now_ms, now_unix, &left); + if (!has) n += snprintf(&d[n], max - n, "-"); + else n += snprintf(&d[n], max - n, "%lu", (unsigned long)(worst ? 9999999UL : left)); + return n; +} + +// Entries [from, to) of page `page` (1-based). Packing depends only on the +// rules (worst-case counters), never on the counters, so `of` is stable. +inline FLOW_NOINLINE int flowPageCount(const FlowTable& t, uint32_t now_ms, uint32_t now_unix) { + char b[48]; + int pages = 0, i = 0; + while (i < t.n || pages == 0) { + int used = 0, k = 0; + while (i < t.n && k < FLOW_PAGE_ENTRIES) { + int w = flowEntryText(t, i, now_ms, now_unix, true, b, sizeof(b)) + 1; + if (k > 0 && used + w > 112) break; + used += w; k++; i++; + } + pages++; + if (t.n == 0) break; + } + return pages; +} + +// Returns false if page is out of range. +inline FLOW_NOINLINE bool flowListPage(const FlowTable& t, int page, uint32_t now_ms, uint32_t now_unix, char* d, int max) { + int pages = flowPageCount(t, now_ms, now_unix); + if (page < 1 || page > pages) return false; + char b[48]; + int pg = 1, i = 0, from = 0, to = 0; + while (pg <= page) { + from = i; + int used = 0, k = 0; + while (i < t.n && k < FLOW_PAGE_ENTRIES) { + int w = flowEntryText(t, i, now_ms, now_unix, true, b, sizeof(b)) + 1; + if (k > 0 && used + w > 112) break; + used += w; k++; i++; + } + to = i; + pg++; + } + int len = snprintf(d, max, "flow %d/%d ", page, pages); + len += flowSummary(t, &d[len], max - len); + for (int j = from; j < to && len + 1 < max; j++) { + d[len++] = ' '; + len += flowEntryText(t, j, now_ms, now_unix, false, &d[len], max - len); + } + return true; +} diff --git a/test/test_flow_rules/test_flow_rules.cpp b/test/test_flow_rules/test_flow_rules.cpp new file mode 100644 index 000000000..406df7578 --- /dev/null +++ b/test/test_flow_rules/test_flow_rules.cpp @@ -0,0 +1,390 @@ +#include +#include +#include "helpers/FlowRules.h" + +static FlowRule R(uint8_t kind, const char* hex, uint8_t mode = FLOW_BLOCK, uint16_t secs = 0, bool au = false, + uint32_t expires = 0, uint32_t remain = 0) { + FlowRule r; + memset(&r, 0, sizeof(r)); + r.kind = kind; + r.klen = flowParseHex(hex, strlen(hex), r.key, FLOW_KEY_MAX); + r.mode = mode; r.secs = secs; r.flags = au ? FLOW_FLAG_AUTO : 0; r.expires = expires; r.remain = remain; + return r; +} + +static const uint32_t T0 = 1800000000UL; // valid clock + +// ── CRC / canonical form / vectors ─────────────────────────────────────────── + +TEST(FlowCrc, CheckValue) { + const uint8_t d[] = {'1','2','3','4','5','6','7','8','9'}; + EXPECT_EQ(0x29B1, flowCrc16(0xFFFF, d, 9)); +} + +TEST(FlowCrc, VectorsMatchPythonReference) { // test/vectors/flow_rules_vectors.json + FlowTable t; + EXPECT_EQ(FLOW_OK, t.add(R('c', "43"), 0)); + int c; EXPECT_EQ(0xCE67, t.crc(false, &c)); EXPECT_EQ(1, c); + EXPECT_EQ(0xFFFF, t.crc(true, &c)); EXPECT_EQ(0, c); + + FlowTable u; // insertion order differs from the sorted order + u.add(R('p', "c420"), 0); u.add(R('c', "43", FLOW_THROTTLE, 60), 0); u.add(R('a', "11223344", FLOW_DRY), 0); + u.add(R('r', "1a2b"), 0); u.add(R('r', "1a2b3c4d"), 0); u.add(R('n', "99"), 0); + EXPECT_EQ(0x7592, u.crc(false, &c)); EXPECT_EQ(6, c); + EXPECT_EQ('a', u.e[0].r.kind); EXPECT_EQ('c', u.e[1].r.kind); EXPECT_EQ('n', u.e[2].r.kind); + EXPECT_EQ(2, u.e[3].r.kind == 'p' ? 2 : 0); // p before r + EXPECT_EQ(2, u.e[4].r.klen); EXPECT_EQ(4, u.e[5].r.klen); // r 1a2b before r 1a2b3c4d + + FlowTable v; + v.add(R('c', "2e", FLOW_THROTTLE, 300), 0); + v.add(R('r', "8b2c", FLOW_BLOCK, 0, true, 1800000000), 0); + v.add(R('r', "8b2c02f8", FLOW_DRY, 0, true, 1800003600), 0); + v.add(R('p', "5f14c420"), 0); + EXPECT_EQ(0x8FC9, v.crc(true, &c)); EXPECT_EQ(2, c); + EXPECT_EQ(0x6CEB, v.crc(false, &c)); EXPECT_EQ(2, c); +} + +TEST(FlowCrc, CountersAndRemainDoNotCount) { + FlowTable a, b; + a.add(R('c', "43", FLOW_BLOCK, 0, true, T0 + 100, 100), 0); + b.add(R('c', "43", FLOW_BLOCK, 0, true, T0 + 100, 7), 5000); + FlowPkt p = {FLOW_PKT_GROUP, (const uint8_t*)"\x43", 1, NULL, 1, 0}; + a.verdict(p, 1, false); + int c; + EXPECT_EQ(a.crc(true, &c), b.crc(true, &c)); +} + +TEST(FlowCrc, PackUnpackRoundtrip) { + FlowRule r = R('r', "8b2c02f8", FLOW_THROTTLE, 77, true, 1800000123, 4000), o; + uint8_t rec[FLOW_REC_LEN]; + flowPack(r, rec); + ASSERT_TRUE(flowUnpack(rec, o)); + uint8_t a[24], b[24]; + EXPECT_EQ(flowCanonical(r, a), flowCanonical(o, b)); + EXPECT_EQ(0, memcmp(a, b, flowCanonical(r, a))); + EXPECT_EQ(4000u, o.remain); + EXPECT_EQ(FLOW_FLAG_AUTO, o.flags); + uint8_t zero[FLOW_REC_LEN] = {0}; + EXPECT_FALSE(flowUnpack(zero, o)); +} + +// ── ordering / capacity ────────────────────────────────────────────────────── + +TEST(FlowTable, SortedAndUnique) { + FlowTable t; + EXPECT_EQ(FLOW_OK, t.add(R('r', "0202"), 0)); + EXPECT_EQ(FLOW_OK, t.add(R('c', "ff"), 0)); + EXPECT_EQ(FLOW_OK, t.add(R('c', "01"), 0)); + EXPECT_EQ(FLOW_SAME, t.add(R('c', "01"), 0)); + EXPECT_EQ(FLOW_CHANGED, t.add(R('c', "01", FLOW_DRY), 0)); + ASSERT_EQ(3, t.n); + EXPECT_EQ(0x01, t.e[0].r.key[0]); + EXPECT_EQ(0xFF, t.e[1].r.key[0]); + EXPECT_EQ('r', t.e[2].r.kind); + EXPECT_EQ(0, t.find('c', t.e[0].r.key, 1)); + EXPECT_EQ(FLOW_OK, t.del('c', t.e[0].r.key, 1)); + EXPECT_EQ(2, t.n); + EXPECT_EQ(0xFF, t.e[0].r.key[0]); +} + +TEST(FlowTable, MaxSixteen) { + FlowTable t; + for (int i = 0; i < FLOW_MAX; i++) { + uint8_t k = (uint8_t)(0x10 + i); + FlowRule r = R('c', "00"); r.key[0] = k; + EXPECT_EQ(FLOW_OK, t.add(r, 0)); + } + EXPECT_EQ(FLOW_FULL, t.add(R('n', "01"), 0)); + FlowRule ch = R('c', "00"); ch.key[0] = 0x10; ch.mode = FLOW_DRY; + EXPECT_EQ(FLOW_CHANGED, t.add(ch, 0)); // update of an existing key still works when full +} + +TEST(FlowTable, BadRulesRefused) { + FlowTable t; + EXPECT_EQ(FLOW_BAD, t.add(R('c', "4343"), 0)); + EXPECT_EQ(FLOW_BAD, t.add(R('p', "43"), 0)); + EXPECT_EQ(FLOW_BAD, t.add(R('a', "010203"), 0)); + EXPECT_EQ(FLOW_BAD, t.add(R('r', "010203"), 0)); + EXPECT_EQ(FLOW_BAD, t.add(R('c', "43", FLOW_THROTTLE, 0), 0)); +} + +TEST(FlowTable, ClearSets) { + FlowTable t; + t.add(R('c', "01", FLOW_BLOCK, 0, true), 0); t.add(R('c', "02"), 0); t.add(R('c', "03", FLOW_BLOCK, 0, true), 0); + EXPECT_EQ(2, t.clear(0)); + ASSERT_EQ(1, t.n); + EXPECT_EQ(0x02, t.e[0].r.key[0]); + t.add(R('c', "04", FLOW_BLOCK, 0, true), 0); + EXPECT_EQ(1, t.clear(1)); + EXPECT_EQ(1, t.n); + EXPECT_EQ(1, t.clear(2)); + EXPECT_EQ(0, t.n); +} + +// ── matching ───────────────────────────────────────────────────────────────── + +static FlowPkt pkt(uint8_t cls, const uint8_t* payload, uint8_t plen, const uint8_t* path = NULL, uint8_t hs = 1, + uint8_t hops = 0) { + FlowPkt p = {cls, payload, plen, path, hs, hops}; + return p; +} + +TEST(FlowMatch, ChannelByte) { + FlowTable t; t.add(R('c', "43"), 0); + uint8_t pl[] = {0x43, 1, 2}, other[] = {0x44, 1, 2}; + EXPECT_TRUE(t.verdict(pkt(FLOW_PKT_GROUP, pl, 3), 0, false)); + EXPECT_FALSE(t.verdict(pkt(FLOW_PKT_GROUP, other, 3), 0, false)); + EXPECT_FALSE(t.verdict(pkt(FLOW_PKT_ADDR, pl, 3), 0, false)); // wrong class + EXPECT_EQ(1u, t.e[0].dropped); +} + +TEST(FlowMatch, DestSrcAndFirstHop) { + FlowTable t; t.add(R('r', "8b2c"), 0); t.add(R('r', "8b2c02f8"), 0); + uint8_t pl[] = {0x8b, 0x2c, 9, 9}; + uint8_t hop2[] = {0x02, 0xf8, 0x77, 0x77}; + uint8_t hop2x[] = {0x02, 0xf9}; + uint8_t hop1[] = {0x02}; + // 2-byte rule matches any route; the 4-byte rule only with that first hop + EXPECT_TRUE(t.verdict(pkt(FLOW_PKT_ADDR, pl, 4), 0, false)); + EXPECT_EQ(1u, t.e[0].dropped); EXPECT_EQ(0u, t.e[1].dropped); // 8b2c < 8b2c02f8 : e[0] is the short one + EXPECT_TRUE(t.verdict(pkt(FLOW_PKT_ADDR, pl, 4, hop2, 2, 2), 0, false)); + EXPECT_EQ(2u, t.e[0].dropped); EXPECT_EQ(0u, t.e[1].dropped); // only the FIRST dropping rule is charged + FlowTable u; u.add(R('r', "8b2c02f8"), 0); + EXPECT_TRUE(u.verdict(pkt(FLOW_PKT_ADDR, pl, 4, hop2, 2, 2), 0, false)); + EXPECT_FALSE(u.verdict(pkt(FLOW_PKT_ADDR, pl, 4, hop2x, 2, 1), 0, false)); // other first hop + EXPECT_FALSE(u.verdict(pkt(FLOW_PKT_ADDR, pl, 4), 0, false)); // 0 hops + EXPECT_FALSE(u.verdict(pkt(FLOW_PKT_ADDR, pl, 4, hop1, 1, 1), 0, false)); // 1-byte hop + uint8_t other[] = {0x8b, 0x2d, 9}; + EXPECT_FALSE(u.verdict(pkt(FLOW_PKT_ADDR, other, 3, hop2, 2, 2), 0, false)); +} + +TEST(FlowMatch, AnonRequest) { + FlowTable t; t.add(R('n', "5a"), 0); t.add(R('n', "6b02f8"), 0); + uint8_t pl[] = {0x5a, 1, 2, 3}, pl2[] = {0x6b, 1, 2}; + uint8_t hop[] = {0x02, 0xf8}; + EXPECT_TRUE(t.verdict(pkt(FLOW_PKT_ANON, pl, 4), 0, false)); + EXPECT_FALSE(t.verdict(pkt(FLOW_PKT_ANON, pl2, 3), 0, false)); // needs the hop + EXPECT_TRUE(t.verdict(pkt(FLOW_PKT_ANON, pl2, 3, hop, 2, 1), 0, false)); + EXPECT_FALSE(t.verdict(pkt(FLOW_PKT_ADDR, pl, 4), 0, false)); // REQ is not ANON_REQ +} + +TEST(FlowMatch, AdvertPrefix) { + FlowTable t; t.add(R('a', "11223344"), 0); + uint8_t pl[40] = {0x11, 0x22, 0x33, 0x44, 0x55}, bad[40] = {0x11, 0x22, 0x33, 0x45}; + EXPECT_TRUE(t.verdict(pkt(FLOW_PKT_ADVERT, pl, 40), 0, false)); + EXPECT_FALSE(t.verdict(pkt(FLOW_PKT_ADVERT, bad, 40), 0, false)); + EXPECT_FALSE(t.verdict(pkt(FLOW_PKT_ADVERT, pl, 3), 0, false)); // truncated +} + +TEST(FlowMatch, RelayInPath) { + FlowTable t; t.add(R('p', "c420"), 0); t.add(R('p', "5f14c420"), 0); + uint8_t path2[] = {0x11, 0x11, 0xc4, 0x20, 0x33, 0x33}; + uint8_t path1[] = {0xc4, 0x20}; // as 1-byte hops + uint8_t pl[] = {0}; + EXPECT_TRUE(t.verdict(pkt(FLOW_PKT_OTHER, pl, 1, path2, 2, 3), 0, false)); + EXPECT_FALSE(t.verdict(pkt(FLOW_PKT_OTHER, pl, 1, path1, 1, 2), 0, false)); // 1-byte hops never match + EXPECT_FALSE(t.verdict(pkt(FLOW_PKT_OTHER, pl, 1, NULL, 2, 0), 0, false)); // 0 hops + uint8_t path4[] = {0x5f, 0x14, 0xc4, 0x20}; + EXPECT_TRUE(t.verdict(pkt(FLOW_PKT_OTHER, pl, 1, path4, 4, 1), 0, false)); + uint8_t path3[] = {0xc4, 0x20, 0x99}; // 3-byte hop: compared on the 2 bytes of the c420 rule + EXPECT_TRUE(t.verdict(pkt(FLOW_PKT_OTHER, pl, 1, path3, 3, 1), 0, false)); +} + +// ── modes, throttle, dry ───────────────────────────────────────────────────── + +TEST(FlowVerdict, ThrottleOnePerWindowAndCounters) { + FlowTable t; t.add(R('c', "43", FLOW_THROTTLE, 60), 0); + uint8_t pl[] = {0x43}; + FlowPkt p = pkt(FLOW_PKT_GROUP, pl, 1); + EXPECT_FALSE(t.verdict(p, 1000, false)); // first match passes + EXPECT_TRUE(t.verdict(p, 30000, false)); + EXPECT_TRUE(t.verdict(p, 60999, false)); // hammering does not extend it + EXPECT_FALSE(t.verdict(p, 61000, false)); + EXPECT_EQ(2u, t.e[0].passed); EXPECT_EQ(2u, t.e[0].dropped); +} + +TEST(FlowVerdict, DryRuleCountsButForwards) { + FlowTable t; t.add(R('c', "43", FLOW_DRY), 0); + uint8_t pl[] = {0x43}; + EXPECT_FALSE(t.verdict(pkt(FLOW_PKT_GROUP, pl, 1), 0, false)); + EXPECT_EQ(1u, t.e[0].dropped); +} + +TEST(FlowVerdict, GlobalDryrunCountsButForwards) { + FlowTable t; t.add(R('c', "43"), 0); + uint8_t pl[] = {0x43}; + EXPECT_FALSE(t.verdict(pkt(FLOW_PKT_GROUP, pl, 1), 0, true)); + EXPECT_EQ(1u, t.e[0].dropped); +} + +TEST(FlowVerdict, BlockElsewhereDoesNotSpendThrottleWindow) { + FlowTable t; t.add(R('c', "43", FLOW_THROTTLE, 60), 0); t.add(R('p', "c420"), 0); + uint8_t pl[] = {0x43}, path[] = {0xc4, 0x20}; + // matches both: the p block vetoes, the c throttle window stays unspent + EXPECT_TRUE(t.verdict(pkt(FLOW_PKT_GROUP, pl, 1, path, 2, 1), 0, false)); + EXPECT_EQ(0u, t.e[0].passed); + EXPECT_FALSE(t.verdict(pkt(FLOW_PKT_GROUP, pl, 1), 1, false)); + EXPECT_EQ(1u, t.e[0].passed); +} + +TEST(FlowVerdict, InsertKeepsCountersWithTheirEntry) { + FlowTable t; t.add(R('p', "c420"), 0); + uint8_t pl[] = {0}, path[] = {0xc4, 0x20}; + t.verdict(pkt(FLOW_PKT_OTHER, pl, 1, path, 2, 1), 0, false); + t.add(R('a', "01020304"), 0); // sorts before, shifts the p entry + ASSERT_EQ('p', t.e[1].r.kind); + EXPECT_EQ(1u, t.e[1].dropped); + EXPECT_EQ(0u, t.e[0].dropped); +} + +// ── expiry ─────────────────────────────────────────────────────────────────── + +TEST(FlowExpiry, AbsoluteTimeWhenClockValid) { + FlowTable t; t.add(R('c', "43", FLOW_BLOCK, 0, true, T0 + 100, 100), 0); + EXPECT_EQ(0, t.expire(50000, T0 + 99)); + EXPECT_EQ(1, t.expire(50000, T0 + 100)); + EXPECT_EQ(0, t.n); +} + +TEST(FlowExpiry, ColdStartClockBehindCountdownWins) { + // Persisted with 1 h left; node rebooted, clock still at build time (behind by + // days, but valid) -- the absolute time would add days to the block. + FlowTable t; t.add(R('c', "43", FLOW_BLOCK, 0, true, T0 + 3600, 3600), 0); + uint32_t behind = T0 - 5 * 86400; + EXPECT_EQ(0, t.expire(3599u * 1000u, behind)); + EXPECT_EQ(1, t.expire(3600u * 1000u, behind)); +} + +TEST(FlowExpiry, ClockUnsetOnlyCountdownCounts) { + FlowTable t; t.add(R('c', "43", FLOW_BLOCK, 0, true, 5000, 60), 0); // abs far in the "past" + EXPECT_EQ(0, t.expire(59000, 1715000000)); // 2024: abs time ignored + EXPECT_EQ(1, t.expire(60000, 1715000000)); +} + +TEST(FlowExpiry, AbsoluteOnlyWithoutClockNeverExpires) { + FlowTable t; t.add(R('c', "43", FLOW_BLOCK, 0, true, T0 + 10, 0), 0); + EXPECT_EQ(0, t.expire(0x7FFFFFFFu, 1715000000)); + EXPECT_EQ(1, t.expire(0x7FFFFFFFu, T0 + 10)); +} + +TEST(FlowExpiry, CountdownSurvivesMillisWrap) { + FlowTable t; t.add(R('c', "43", FLOW_BLOCK, 0, true, 0, 100), 0xFFFFFFF0u); // deadline wraps to 99.9 s + EXPECT_EQ(0, t.expire(50000, 0)); + EXPECT_EQ(1, t.expire(100000, 0)); +} + +TEST(FlowExpiry, RemainingIsMinOfBoth) { + FlowTable t; t.add(R('c', "43", FLOW_BLOCK, 0, true, T0 + 1000, 400), 0); + uint32_t s; + ASSERT_TRUE(t.remaining(0, 100000, T0, &s)); + EXPECT_EQ(300u, s); + ASSERT_TRUE(t.remaining(0, 100000, 0, &s)); // clock unset: countdown only + EXPECT_EQ(300u, s); + FlowTable u; u.add(R('c', "43"), 0); + EXPECT_FALSE(u.remaining(0, 0, T0, &s)); +} + +TEST(FlowExpiry, ExpiredEntryChangesAutoCrc) { + FlowTable t; t.add(R('c', "43", FLOW_BLOCK, 0, true, 0, 10), 0); t.add(R('c', "44", FLOW_BLOCK, 0, true), 0); + int c; uint16_t before = t.crc(true, &c); + EXPECT_EQ(1, t.expire(10000, 0)); + EXPECT_NE(before, t.crc(true, &c)); + EXPECT_EQ(1, c); +} + +// ── parsing ────────────────────────────────────────────────────────────────── + +TEST(FlowParse, AddForms) { + FlowSpec s; + EXPECT_EQ(nullptr, flowParseAdd("c 43", &s)); + EXPECT_EQ(FLOW_BLOCK, s.r.mode); + EXPECT_EQ(nullptr, flowParseAdd("r 8b2c02f8 throttle 120 auto ttl 604800", &s)); + EXPECT_EQ(FLOW_THROTTLE, s.r.mode); EXPECT_EQ(120, s.r.secs); + EXPECT_EQ(FLOW_FLAG_AUTO, s.r.flags); EXPECT_TRUE(s.has_ttl); EXPECT_EQ(604800u, s.ttl); + EXPECT_EQ(4, s.r.klen); + EXPECT_EQ(nullptr, flowParseAdd("p 0xC420 dry expires 1800000000", &s)); + EXPECT_EQ(FLOW_DRY, s.r.mode); EXPECT_TRUE(s.has_expires); + EXPECT_EQ(nullptr, flowParseAdd("a 11223344 auto", &s)); +} + +TEST(FlowParse, Rejects) { + FlowSpec s; + EXPECT_NE(nullptr, flowParseAdd("x 43", &s)); + EXPECT_NE(nullptr, flowParseAdd("c 4343", &s)); + EXPECT_NE(nullptr, flowParseAdd("p 43", &s)); + EXPECT_NE(nullptr, flowParseAdd("c 4", &s)); + EXPECT_NE(nullptr, flowParseAdd("c 43 throttle", &s)); + EXPECT_NE(nullptr, flowParseAdd("c 43 throttle 0", &s)); + EXPECT_NE(nullptr, flowParseAdd("c 43 block dry", &s)); + EXPECT_NE(nullptr, flowParseAdd("c 43 ttl 10 expires 1800000000", &s)); + EXPECT_NE(nullptr, flowParseAdd("c 43 ttl 3000000", &s)); + EXPECT_NE(nullptr, flowParseAdd("c 43 frobnicate", &s)); +} + +TEST(FlowParse, ResolveExpiry) { + FlowSpec s; + ASSERT_EQ(NULL, flowParseAdd("c 43 ttl 100", &s)); + EXPECT_EQ(nullptr, flowResolveExpiry(&s, T0)); + EXPECT_EQ(T0 + 100, s.r.expires); EXPECT_EQ(100u, s.r.remain); + ASSERT_EQ(NULL, flowParseAdd("c 43 ttl 100", &s)); + EXPECT_EQ(nullptr, flowResolveExpiry(&s, 1715000000)); // clock unset + EXPECT_EQ(0u, s.r.expires); EXPECT_EQ(100u, s.r.remain); + ASSERT_EQ(NULL, flowParseAdd("c 43 expires 1800000500", &s)); + EXPECT_EQ(nullptr, flowResolveExpiry(&s, T0)); + EXPECT_EQ(500u, s.r.remain); + ASSERT_EQ(NULL, flowParseAdd("c 43 expires 1800000500", &s)); + EXPECT_NE(nullptr, flowResolveExpiry(&s, T0 + 500)); +} + +// ── replies ────────────────────────────────────────────────────────────────── + +TEST(FlowReply, SummaryShape) { + FlowTable t; t.add(R('c', "43", FLOW_BLOCK, 0, true), 0); t.add(R('c', "44"), 0); + char b[64]; + flowSummary(t, b, sizeof(b)); + EXPECT_STREQ("n=2 a=1:CE67 s=1:", std::string(b).substr(0, 17).c_str()); +} + +TEST(FlowReply, ListPagesFitAndAreStable) { + FlowTable t; + for (int i = 0; i < FLOW_MAX; i++) { + FlowRule r = R('a', "00000000", i % 3 == 0 ? FLOW_THROTTLE : FLOW_BLOCK, 65535, i % 2 == 0, T0 + 7 * 86400, 1999999); + r.klen = (i % 2) ? 8 : 4; + r.key[0] = (uint8_t)i; + ASSERT_EQ(FLOW_OK, t.add(r, 0)); + } + for (int i = 0; i < t.n; i++) { t.e[i].dropped = 4000000000u; t.e[i].passed = 4000000000u; } + int pages = flowPageCount(t, 1000, T0); + EXPECT_GE(pages, 4); + int seen = 0; + char b[FLOW_REPLY_MAX]; + for (int p = 1; p <= pages; p++) { + ASSERT_TRUE(flowListPage(t, p, 1000, T0, b, sizeof(b))); + EXPECT_LT(strlen(b), (size_t)FLOW_REPLY_MAX - 1) << b; + char head[16]; snprintf(head, sizeof(head), "flow %d/%d ", p, pages); + EXPECT_EQ(0, strncmp(b, head, strlen(head))) << b; + for (const char* c = b; (c = strchr(c, ',')) != NULL; c++) seen++; + } + EXPECT_EQ(t.n * 4, seen); // four commas per entry: every entry shown exactly once + EXPECT_FALSE(flowListPage(t, 0, 1000, T0, b, sizeof(b))); + EXPECT_FALSE(flowListPage(t, pages + 1, 1000, T0, b, sizeof(b))); + // counters changing must not move page boundaries + for (int i = 0; i < t.n; i++) { t.e[i].dropped = 0; t.e[i].passed = 0; } + EXPECT_EQ(pages, flowPageCount(t, 1000, T0)); +} + +TEST(FlowReply, TypicalFourPerPageAndEmpty) { + FlowTable t; + char b[FLOW_REPLY_MAX]; + ASSERT_TRUE(flowListPage(t, 1, 0, T0, b, sizeof(b))); + EXPECT_STREQ("flow 1/1 n=0 a=0:FFFF s=0:FFFF", b); + for (int i = 0; i < 9; i++) { FlowRule r = R('c', "00"); r.key[0] = (uint8_t)(0x40 + i); t.add(r, 0); } + EXPECT_EQ(3, flowPageCount(t, 0, T0)); + ASSERT_TRUE(flowListPage(t, 1, 0, T0, b, sizeof(b))); + EXPECT_NE(nullptr, strstr(b, "c40,B,S,0/0,- c41,B,S,0/0,- c42,B,S,0/0,- c43,B,S,0/0,-")); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/test/vectors/flow_rules_vectors.json b/test/vectors/flow_rules_vectors.json new file mode 100644 index 000000000..6edcce141 --- /dev/null +++ b/test/vectors/flow_rules_vectors.json @@ -0,0 +1,148 @@ +{ + "crc16": { + "name": "CRC-16/CCITT-FALSE", + "poly": "1021", + "init": "FFFF", + "check_123456789": "29B1" + }, + "cases": [ + { + "name": "empty", + "entries": [], + "sorted": [], + "auto": { + "count": 0, + "canonical": "", + "crc16": "FFFF" + }, + "static": { + "count": 0, + "canonical": "", + "crc16": "FFFF" + } + }, + { + "name": "one_static_channel", + "entries": [ + { + "kind": "c", + "key": "43", + "mode": "block" + } + ], + "sorted": [ + "c43" + ], + "auto": { + "count": 0, + "canonical": "", + "crc16": "FFFF" + }, + "static": { + "count": 1, + "canonical": "63014300000000000000", + "crc16": "CE67" + } + }, + { + "name": "insertion_order_does_not_matter", + "entries": [ + { + "kind": "p", + "key": "c420", + "mode": "block" + }, + { + "kind": "c", + "key": "43", + "mode": "throttle", + "secs": 60 + }, + { + "kind": "a", + "key": "11223344", + "mode": "dry" + }, + { + "kind": "r", + "key": "1a2b", + "mode": "block" + }, + { + "kind": "r", + "key": "1a2b3c4d", + "mode": "block" + }, + { + "kind": "n", + "key": "99", + "mode": "block" + } + ], + "sorted": [ + "a11223344", + "c43", + "n99", + "pc420", + "r1a2b", + "r1a2b3c4d" + ], + "auto": { + "count": 0, + "canonical": "", + "crc16": "FFFF" + }, + "static": { + "count": 6, + "canonical": "6104112233440200000000000063014301003c000000006e0199000000000000007002c4200000000000000072021a2b0000000000000072041a2b3c4d00000000000000", + "crc16": "7592" + } + }, + { + "name": "auto_and_static_sets", + "entries": [ + { + "kind": "c", + "key": "2e", + "mode": "throttle", + "secs": 300 + }, + { + "kind": "r", + "key": "8b2c", + "mode": "block", + "auto": true, + "expires": 1800000000 + }, + { + "kind": "r", + "key": "8b2c02f8", + "mode": "dry", + "auto": true, + "expires": 1800003600 + }, + { + "kind": "p", + "key": "5f14c420", + "mode": "block" + } + ], + "sorted": [ + "c2e", + "p5f14c420", + "r8b2c", + "r8b2c02f8" + ], + "auto": { + "count": 2, + "canonical": "72028b2c0000006b49d20072048b2c02f80200006b49e010", + "crc16": "8FC9" + }, + "static": { + "count": 2, + "canonical": "63012e01012c0000000070045f14c42000000000000000", + "crc16": "6CEB" + } + } + ] +} diff --git a/test/vectors/gen_flow_rules_vectors.py b/test/vectors/gen_flow_rules_vectors.py new file mode 100644 index 000000000..529345f7e --- /dev/null +++ b/test/vectors/gen_flow_rules_vectors.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""Reference implementation + generator of test/vectors/flow_rules_vectors.json. + +Canonical serialization and CRC of `filter flow` rule sets (see +src/helpers/FlowRules.h). The firmware test (test/test_flow_rules) hard-codes +the same cases and expected CRCs; keep the two in step. `--check` verifies that +the JSON on disk is what this script would write. +""" +import json +import pathlib +import sys + +MODE = {"block": 0, "throttle": 1, "dry": 2} + + +def crc16_ccitt_false(data: bytes) -> int: + crc = 0xFFFF + for b in data: + crc ^= b << 8 + for _ in range(8): + crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF + return crc + + +def sort_key(e): + # kind as ASCII letter, key bytewise, shorter first on a common prefix + return (ord(e["kind"]), bytes.fromhex(e["key"])) + + +def canonical(e) -> bytes: + key = bytes.fromhex(e["key"]) + secs = e.get("secs", 0) if e["mode"] == "throttle" else 0 + return ( + e["kind"].encode() + + bytes([len(key)]) + + key + + bytes([MODE[e["mode"]]]) + + secs.to_bytes(2, "big") + + e.get("expires", 0).to_bytes(4, "big") + ) + + +def rules_crc16(entries, auto: bool): + sel = sorted((e for e in entries if bool(e.get("auto", False)) == auto), key=sort_key) + blob = b"".join(canonical(e) for e in sel) + return len(sel), blob.hex(), f"{crc16_ccitt_false(blob):04X}" + + +CASES = [ + ("empty", []), + ("one_static_channel", [{"kind": "c", "key": "43", "mode": "block"}]), + ( + "insertion_order_does_not_matter", + [ + {"kind": "p", "key": "c420", "mode": "block"}, + {"kind": "c", "key": "43", "mode": "throttle", "secs": 60}, + {"kind": "a", "key": "11223344", "mode": "dry"}, + {"kind": "r", "key": "1a2b", "mode": "block"}, + {"kind": "r", "key": "1a2b3c4d", "mode": "block"}, + {"kind": "n", "key": "99", "mode": "block"}, + ], + ), + ( + "auto_and_static_sets", + [ + {"kind": "c", "key": "2e", "mode": "throttle", "secs": 300}, + {"kind": "r", "key": "8b2c", "mode": "block", "auto": True, "expires": 1800000000}, + {"kind": "r", "key": "8b2c02f8", "mode": "dry", "auto": True, "expires": 1800003600}, + {"kind": "p", "key": "5f14c420", "mode": "block"}, + ], + ), +] + + +def build(): + out = { + "crc16": { + "name": "CRC-16/CCITT-FALSE", + "poly": "1021", + "init": "FFFF", + "check_123456789": f"{crc16_ccitt_false(b'123456789'):04X}", + }, + "cases": [], + } + for name, entries in CASES: + ca, ha, ra = rules_crc16(entries, True) + cs, hs, rs = rules_crc16(entries, False) + out["cases"].append( + { + "name": name, + "entries": entries, + "sorted": [f'{e["kind"]}{e["key"]}' for e in sorted(entries, key=sort_key)], + "auto": {"count": ca, "canonical": ha, "crc16": ra}, + "static": {"count": cs, "canonical": hs, "crc16": rs}, + } + ) + return out + + +if __name__ == "__main__": + path = pathlib.Path(__file__).with_name("flow_rules_vectors.json") + text = json.dumps(build(), indent=2) + "\n" + if "--check" in sys.argv: + sys.exit(0 if path.read_text() == text else 1) + path.write_text(text) + print(path)