From f1d4f9e6dbb5b4b9f28e9d8404818fe45afaafdb Mon Sep 17 00:00:00 2001 From: Jason Huebert Date: Fri, 2 Oct 2026 22:16:33 -0500 Subject: [PATCH] fix: refuse patterns the regex engine cannot decide deterministically MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An adversarial pass over the pattern layer (differential fuzzing against the vendored engine, an exhaustive history-dependence sweep, and a CLI fuzz) turned up a pre-existing engine defect that makes a rule decide packets at random: re_compile() never fills in the `ch` byte of BEGIN/END/quantifier symbols, and matchone() compares that byte whenever such a symbol is used as an operand. Every pattern up to length 5 was enumerated over a metacharacter alphabet: 16,999 of 1,240,085 pattern/subject combinations answered differently depending on which pattern had been compiled before them. `sender=*Bot`, `sender=a**` and `sender=A^B` all match — or don't — according to the previous packet's rule. In a filter that either leaks the traffic a drop rule was meant to stop or silences it when it should not. Fixed in the wrapper, which already owns structural validation, rather than in the vendored engine (which stays byte-identical): - "nothing to repeat" — a '*', '+' or '?' with no repeatable symbol before it, including a quantifier on an anchor ('^*') and stacked quantifiers ('a**'). - "^ and $ must be at the pattern edges" — an anchor away from the edges of its own alternative. Per alternative, so '^a|b$' is fine. As with the empty alternative, both are add-time rules that matching also honours: a stored rule carrying such a pattern now matches nothing rather than guessing, and the reply names the offending field. The same fuzzing caught a bug in the new checker itself — it tested for the class end before the escape, so '[\]]' closed the class early and diverged from the engine's parse. Fixed, and the escape now takes precedence exactly as in splitAlternatives(). Tests: 220 filter cases (was 215). New NothingToRepeatRejected, AnchorsMustBeAtPatternEdges, AddRejectsPatternsTheEngineCannotDecide, StoredUndecidablePatternNeverMatches, and PatternMatchDeterminism.VerdictDoesNotDependOnEarlierPatterns, which primes the shared engine state and pins a stable verdict for every pattern in the table. Verified: full suite clean under ASan+UBSan; 479,676 differential cases with no unexplained disagreement; 1,240,085-case history-dependence sweep with zero escapes; 300k-line CLI fuzz with no overrun, bad reply or rule-list drift; all 34 patterns the guide shows still accepted; Xiao_S3_WIO_repeater builds (RAM unchanged at 20.6%). Fixing this at the source would mean a fourth documented modification to TinyRegex.cpp (have matchone() treat non-consuming symbols as non-matching instead of comparing that byte). Left alone pending a decision. --- AGENTS.md | 12 ++- FILTER.md | 18 +++- examples/simple_repeater/PatternMatch.cpp | 70 ++++++++++++++- examples/simple_repeater/PatternMatch.h | 6 ++ .../test_packet_filter/test_packet_filter.cpp | 85 +++++++++++++++++++ 5 files changed, 179 insertions(+), 12 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 45e21ad0..a8e6d8d9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,8 +45,12 @@ commit** — the guides are user-facing API documentation, not optional docs. - `TinyRegex.h/.cpp` — vendored kokke/tiny-regex-c + step budget (see Hard invariants; treat as upstream). - `PatternMatch.h/.cpp` — the user-facing pattern language: top-level `|` - alternation, structural validation, `FILTER_PATTERN_MAX_ALTS`; thin wrapper - over the vendored engine. + alternation, structural validation (empty alternative, nothing to repeat, + anchors at the edges), `FILTER_PATTERN_MAX_ALTS`; thin wrapper over the + vendored engine. The structural rules exist because the engine leaves the + operand of a bare quantifier and of a misplaced anchor uninitialised, so such + patterns match according to whatever was compiled before them — the wrapper + keeps a rule's verdict stable. - `CliUtil.h` — shared CLI helpers (`nextToken`, `radd`, `CLI_REPLY_MAX`) used by filter and battery CLIs alike. - `BatteryGate.h/.cpp` — low-battery forward suspension, `battery` CLI. @@ -55,7 +59,7 @@ commit** — the guides are user-facing API documentation, not optional docs. dispatch, lazy-save loop). - `main.cpp` — serial CLI entry (upstream + fork's buffer-hardening lines). -**Tests:** `test/test_packet_filter/` (215 behavior-level cases: matching, +**Tests:** `test/test_packet_filter/` (220 behavior-level cases: matching, content rules, limiter, persistence upgrades, CLI surface, TinyRegex, PatternMatch) and `test/test_battery_gate/`. Test-only shims: `NativeShim.h`, `NativeTestStubs.cpp`, `RegionMapStub.cpp`, `FilterTestHelpers.h`. @@ -179,7 +183,7 @@ FILTER.md: paths, added in the same commit. The suites are behavior-level (native googletest); reach them via the same CLI/`checkPacket`/`checkContent` entry points a user or the firmware would. -- Pure refactors keep both suites green **unchanged** — the suite (215 filter +- Pure refactors keep both suites green **unchanged** — the suite (220 filter cases) is the safety net that proves no behavior slipped. - Run both suites, then re-read the diff: diff --git a/FILTER.md b/FILTER.md index 74420816..25f597d3 100644 --- a/FILTER.md +++ b/FILTER.md @@ -733,9 +733,12 @@ is only needed for initial flashing and emergencies. change with the `logonly` → `forward` rename, so firmware that still says `logonly` reads `forward` rules and behaves identically (count, then forward). -- One intentional reinterpretation: in a stored pattern an unescaped `|` used - to mean a literal pipe and now means OR. Firmware from 2026-10 onwards reads - such a rule differently — write `\|` if you want a literal pipe. +- Two stored patterns are read differently by firmware from 2026-10 onwards. + An unescaped `|` used to mean a literal pipe and now means OR — write `\|` if + you want a literal pipe. And a bare quantifier (`*Bot`, `a**`) or a misplaced + anchor (`A^B`) is refused by `filter add` and matches nothing when stored: the + engine compared a byte it never set for those, so a rule built on one decided + packets differently from one packet to the next. - **Never lock out your own admin.** Rules are first-match-wins, so a broad early drop rule can silence remote admin login from your app (login replies ride the flood path). Before enabling any catch-all drop rule, add a @@ -787,6 +790,9 @@ Tips: - A quantifier applies only to the character right before it: `ab+` repeats the `b`, not `ab`. +- A quantifier needs something to repeat in front of it: `Bot\d+` is fine, + `*Bot` is refused with `Err - nothing to repeat`. Same for `^` and `$` — they + anchor at the edges of a pattern, so `A^B` is refused too. - `[Bot]` means one of the characters `B`, `o`, `t` — not the word `Bot`. - `\s` includes tabs and line breaks. If you want exactly one space, quote the pattern and type the space: `text="^RX OK$"`. @@ -833,7 +839,9 @@ as ordinary text rather than rejected: | You might try | What actually happens | Do this instead | |---|---|---| -| Groups: `sender=^(Alice\|Bob)$` | The `|` splits even inside the parentheses, so this matches a name *starting with* `(Alice` or *ending with* `Bob)` — not Alice, not Bob | `sender=^Alice$\|^Bob$` | +| Groups: `sender=^(Alice\|Bob)$` | The `|` splits even inside the parentheses, so this matches a name *starting with* `(Alice` or *ending with* `Bot)` — not Alice, not Bob | `sender=^Alice$\|^Bob$` | +| Quantifier with nothing to repeat: `sender=*Bot`, `sender=a**` | Rejected: `Err - nothing to repeat in sender regex`. Older firmware accepted it, but the engine compared a byte it never set and matched or not at random | `sender=Bot\d*` | +| Anchor away from an edge: `sender=A^B` | Rejected: `Err - ^ and $ must be at the pattern edges in sender regex`, same reason | `sender=^A.*B$` | | Counted repeat: `\d{3}` | Matches literal `{3}` | `\d\d\d` | | Case-insensitive: `/i`, `(?i)` | Not supported; always case-sensitive | `^[Bb][Oo][Tt]$` | | Word boundary: `\b` | Matches the literal letter `b` | See the word-boundary recipe below | @@ -952,6 +960,8 @@ filter stats | Pattern from an online tester misbehaves | Remove `/slashes/`, flags, groups, `{counts}`, `\b` — see the table above | | `Err - empty alternative in sender regex` | A `|` with nothing on one side — write `^A$\|^B$`, never end a pattern with a bare pipe | | `Err - too many alternatives (max 8) in text regex` | Fewer alternatives per pattern, a broader one (e.g. `^Bot`), or a second rule | +| `Err - nothing to repeat in sender regex` | A `*`, `+` or `?` with nothing repeatable in front of it — `Bot\d+`, not `*Bot` or `a**` | +| `Err - ^ and $ must be at the pattern edges in sender regex` | A `^` or `$` away from the start/end of the pattern — `^A.*B$`, not `A^B`; `[^a]` and `\$` are fine | | Wrote `^(A\|B)$` and nothing matches | There are no groups: the `|` splits anyway, so it means *starts with `(A`* **or** *ends with `B)`*. Write `^A$\|^B$` | | "Bad/long regex" error | Pattern too long (see [Limits](#limits-and-good-to-knows)) or broken syntax; shorten or simplify | | `aborted` counter grows | Pattern too complex — simplify it | diff --git a/examples/simple_repeater/PatternMatch.cpp b/examples/simple_repeater/PatternMatch.cpp index 710bedbb..0ca5c41e 100644 --- a/examples/simple_repeater/PatternMatch.cpp +++ b/examples/simple_repeater/PatternMatch.cpp @@ -47,6 +47,58 @@ static int splitAlternatives(const char* pattern, char* buf, size_t buf_sz) { return alts; } +// Why the engine cannot evaluate an alternative predictably. re_compile() +// never fills in the `ch` of BEGIN/END/quantifier symbols, and matchone() +// compares that byte whenever such a symbol is used as an operand — so these +// shapes match whatever the previously compiled pattern left behind, and a rule +// built on one decides packets differently from one packet to the next. The +// wrapper refuses them instead, both at add time and when matching. +enum AltDefect { + ALT_OK = 0, + ALT_NOTHING_TO_REPEAT, // '*', '+' or '?' with no repeatable symbol before it + ALT_ANCHOR_MISPLACED, // '^' or '$' that is not at an edge of the alternative +}; + +// Classify one alternative by scanning it the way the engine parses it: a '\' +// escape and a [...] class each hold literal bytes, and the escape is checked +// first so '[\]]' does not end the class early. Deterministic by construction — +// every byte is consumed exactly once, and the trailing '\' case the engine +// rejects is skipped rather than stepped over. +static AltDefect altDefect(const char* alt) { + enum { NONE, EDGE, QUANTIFIED, REPEATABLE } prev = NONE; // previous symbol + bool in_class = false; + for (size_t i = 0; alt[i]; i++) { + char c = alt[i]; + if (c == '\\') { + if (alt[i + 1]) i++; // the escaped byte is a literal + if (!in_class) prev = REPEATABLE; + continue; + } + if (in_class) { + if (c == ']') { in_class = false; prev = REPEATABLE; } // a class is repeatable + continue; + } + if (c == '[') { in_class = true; continue; } + if (c == '*' || c == '+' || c == '?') { + if (prev != REPEATABLE) return ALT_NOTHING_TO_REPEAT; + prev = QUANTIFIED; // a quantifier is not itself repeatable + continue; + } + if (c == '^') { + if (prev != NONE) return ALT_ANCHOR_MISPLACED; // only anchors at the start + prev = EDGE; + continue; + } + if (c == '$') { + if (alt[i + 1] != 0) return ALT_ANCHOR_MISPLACED; // only at the end + prev = EDGE; + continue; + } + prev = REPEATABLE; // ordinary char, '.', or a ']' outside a class + } + return ALT_OK; +} + bool patternValid(const char* pattern, char* err, size_t err_sz) { err[0] = 0; char buf[PATTERN_SPLIT_MAX]; @@ -65,6 +117,15 @@ bool patternValid(const char* pattern, char* err, size_t err_sz) { snprintf(err, err_sz, "empty alternative"); return false; } + switch (altDefect(alt)) { // say the actionable thing before "bad regex" + case ALT_NOTHING_TO_REPEAT: + snprintf(err, err_sz, "nothing to repeat"); + return false; + case ALT_ANCHOR_MISPLACED: + snprintf(err, err_sz, "^ and $ must be at the pattern edges"); + return false; + default: break; + } if (re_compile(alt) == NULL) return false; // engine rejects it: no reason given } return true; @@ -78,11 +139,12 @@ bool patternMatches(const char* pattern, const char* subject) { const char* alt = buf; for (int i = 0; i < alts; i++, alt += strlen(alt) + 1) { // Branches that cannot match are skipped rather than failing the whole - // pattern: an empty one would match everything, and `filter add` rejects - // both that and anything the engine refuses, so only a config stored - // before '|' was an alternation can hold one ("A||B") — the branches - // around it should keep working. + // pattern: an empty one would match everything, one the engine refuses is + // broken, and one the engine would decide by luck is worse. `filter add` + // rejects all three, so only a config stored before '|' was an alternation + // can hold one ("A||B") — the branches around it should keep working. if (alt[0] == 0) continue; + if (altDefect(alt) != ALT_OK) continue; re_t compiled = re_compile(alt); if (compiled == NULL) continue; int matchlength; diff --git a/examples/simple_repeater/PatternMatch.h b/examples/simple_repeater/PatternMatch.h index 4d1a8cd8..d6e2912f 100644 --- a/examples/simple_repeater/PatternMatch.h +++ b/examples/simple_repeater/PatternMatch.h @@ -20,6 +20,12 @@ // everything. Both are add-time rules only: when matching, a branch that // cannot match is skipped so a config stored before '|' was an alternation // keeps the branches it does have. +// - A quantifier needs something repeatable in front of it, and '^'/'$' only +// anchor at the edges of their own alternative: "*Bot", "a**", "A^B" and +// "^*$" are rejected. The engine leaves the operand of such a quantifier +// uninitialised, so it would match according to whichever pattern was +// compiled before it; these rules keep a rule's verdict stable. Like the +// empty alternative, matching skips them rather than guessing. // A pattern is stored as text and re-split on every evaluation, so the // compiled engine state never outlives one evaluation. Cost is bounded by the // alternatives a stored pattern can hold (one per '|', within its length diff --git a/test/test_packet_filter/test_packet_filter.cpp b/test/test_packet_filter/test_packet_filter.cpp index 0efe4a5a..257d80fc 100644 --- a/test/test_packet_filter/test_packet_filter.cpp +++ b/test/test_packet_filter/test_packet_filter.cpp @@ -284,6 +284,60 @@ TEST(PatternMatchValidation, EngineErrorsCarryNoReason) { EXPECT_EQ(why(deep_branch.c_str()), ""); } +TEST(PatternMatchValidation, NothingToRepeatRejected) { + // the engine leaves the operand of a bare quantifier uninitialised, so these + // used to match or not depending on whatever pattern was compiled before + EXPECT_EQ(why("*Bot"), "nothing to repeat"); + EXPECT_EQ(why("+"), "nothing to repeat"); + EXPECT_EQ(why("?x"), "nothing to repeat"); + EXPECT_EQ(why("a**"), "nothing to repeat"); + EXPECT_EQ(why("a?*"), "nothing to repeat"); + EXPECT_EQ(why("^*"), "nothing to repeat"); + EXPECT_EQ(why("a|*"), "nothing to repeat"); // second branch + // the shapes that do have something to repeat stay welcome + EXPECT_TRUE(accepted("a*b")); + EXPECT_TRUE(accepted("Bot[0-9]*")); + EXPECT_TRUE(accepted(".*OK")); + EXPECT_TRUE(accepted("^a?$")); + EXPECT_TRUE(accepted("[ab]*")); + EXPECT_TRUE(accepted("\\d+")); + EXPECT_TRUE(accepted("\\**")); // escaped '*' is a literal, and repeatable + EXPECT_TRUE(accepted("^Bot$|[0-9]*")); +} + +TEST(PatternMatchValidation, AnchorsMustBeAtPatternEdges) { + EXPECT_EQ(why("A^B"), "^ and $ must be at the pattern edges"); + EXPECT_EQ(why("A$B"), "^ and $ must be at the pattern edges"); + EXPECT_EQ(why("^^a"), "^ and $ must be at the pattern edges"); + EXPECT_EQ(why("a$$"), "^ and $ must be at the pattern edges"); + EXPECT_TRUE(accepted("^a$")); + EXPECT_TRUE(accepted("^$")); + EXPECT_TRUE(accepted("^a|b$")); // per alternative, not per pattern + EXPECT_TRUE(accepted("[^a]")); // '^' inside a class is a member + EXPECT_TRUE(accepted("a\\^b")); // escaped + EXPECT_TRUE(accepted("[$]")); +} + +TEST(PatternMatchDeterminism, VerdictDoesNotDependOnEarlierPatterns) { + // re_compile() reuses one static symbol array, and the engine compares the + // byte it never sets for BEGIN/END/quantifier symbols. Any pattern whose + // verdict could depend on what was compiled before it is refused now; this + // pins that down for the whole table, accepted patterns included. + const char* pats[] = {"*Bot", "?x", "a**", "^*", "A^B", "^Bot$", "Bot[0-9]+", + "^a|b$", "[^a]+", "\\d{3}", "^$", "a|", "x[ab|]y"}; + const char* primes[] = {"a*b*c*d*", "[xyz]", "^abc$", "\\w\\d", "z", "*", "?"}; + const char* subjects[] = {"", "a", "Bot", "Bot42", "a*b", "xxBotxx", "{3}"}; + for (const char* p : pats) { + for (const char* s : subjects) { + bool first = patternMatches(p, s); + for (const char* prime : primes) { + patternMatches(prime, "seed"); // dirty the shared engine state + EXPECT_EQ(patternMatches(p, s), first) << p << " after " << prime; + } + } + } +} + TEST(PatternMatchValidation, LegacyPipePatternsKeepTheirUsableBranches) { // A config stored by firmware that took '|' literally can hold a pattern the // new dialect refuses at add time ("A||B" compiled fine as literal text). @@ -2394,6 +2448,37 @@ TEST_F(FilterTest, AddRejectsAlternationStructure) { EXPECT_NE(cli(filter, "get 0").find("sender=Alice\\|Bob"), std::string::npos); } +TEST_F(FilterTest, AddRejectsPatternsTheEngineCannotDecide) { + // a bare quantifier or a misplaced anchor leaves the engine comparing an + // uninitialised byte, so the rule would decide packets at random + EXPECT_EQ(cli(filter, "add sender=*Bot"), "Err - nothing to repeat in sender regex"); + EXPECT_EQ(cli(filter, "add text=a**"), "Err - nothing to repeat in text regex"); + EXPECT_EQ(cli(filter, "add sender=A^B"), + "Err - ^ and $ must be at the pattern edges in sender regex"); + EXPECT_EQ(cli(filter, "add text=^Bot$|^PING$"), "OK - rule 0 added"); + EXPECT_EQ(cli(filter, "add sender=^Pong$ text=PING$|PONG$"), "OK - rule 1 added"); + auto chan = channelFromStore(filter, 0); + auto payload = makeGroupText("Pong", "PING"); + auto pkt = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, payload.len); + EXPECT_EQ(filter.checkContent(&pkt, PAYLOAD_TYPE_GRP_TXT, chan, payload.data, + payload.len, nullptr), + FILTER_ACT_DROP); // the good rules still work +} + +TEST_F(FilterTest, StoredUndecidablePatternNeverMatches) { + // firmware before the alternation accepted this; the engine would decide it + // by whatever it compiled last, so the rule now matches nothing (fail-open) + strcpy(filter.addRule()->sender, "*Bot"); + strcpy(filter.getRule(0)->text, "PING^"); + auto chan = channelFromStore(filter, 0); + auto payload = makeGroupText("Bot", "PING"); + auto pkt = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, payload.len); + EXPECT_EQ(filter.checkContent(&pkt, PAYLOAD_TYPE_GRP_TXT, chan, payload.data, + payload.len, nullptr), + FILTER_ACT_ALLOW); + EXPECT_EQ(filter.getRule(0)->hits, 0u); +} + TEST_F(FilterTest, AddPathRejectsEmptySegments) { // parseHexHash needs >= 2 hex chars, so empty chain segments must fail EXPECT_EQ(cli(filter, "add path=10>"), "Err - bad path spec");