Skip to content

fix(router): stop an exact-host rule attaching to a matching regex segment - #1367

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
fix/trie-exact-host-precedence
Sep 20, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
fix/trie-exact-host-precedence

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Closes #1351.

The leak

Adding an exact-hostname frontend after a regex hostname segment that matches it did not create an
exact-host rule. TrieNode::lookup_mut resolved a literal segment through the first regexps entry
whose pattern matched it, and add_tree_rule, Router::remove_tree_rule,
TcpListener::insert_sni_route and remove_sni_route all address a leaf through domain_lookup_mut
and insert only on None — so the exact host never got a node and its rule was appended to the regex
leaf's Vec, then served for every host that regex matched.

It was not declaration-order-dependent in production — it was universal

The issue says "Declaration order decides whether this happens at all". That is true of the direct API,
which is what its reproduction measures, and false of the production path.

The main process replays ConfigState into every worker from a BTreeMap<String, HttpFrontend> keyed
{address};{hostname};P{path}[;{method}]. / is 0x2F, below every character legal at the start of a
DNS label, so at the first differing byte a regex key always sorts before the exact host it matches.
The full chain was traced with no sort, partition or grouping anywhere:

write_initial_state_to_file -> produce_initial_state -> generate_requests
  -> for front in self.http_fronts.values()      (BTreeMap)
  -> protobuf InitialState.requests              (order-preserving)
  -> read_initial_state_from_file
  -> for request in state.requests { notify_proxys(request) }  -> add_tree_rule

So every worker took the adds in the leaking order, at every start — and a correct table built live by
an exact-first API sequence was re-corrupted at the next fork or upgrade. Deterministic and
universal for any configuration carrying an exact host and a matching regex segment on the same
listener address.

The fix, in two halves that must ship together

The add path. lookup_mut is now key-addressed: if !accept_wildcard { return None; } in front of
the regexps scan. This is the guard insert_sni_route already documented for the * slot — "an exact
key must never fall back to a sibling wildcard's entry" — extended to the regex list, which had nothing
equivalent. Fixing it in the trie also closes the identical latent bug on the TCP SNI route table.

The lookup path. lookup and lookup_with_path now share one backtracking walk,
TrieNode::lookup_recursive, so the order is stated once and the SNI and HTTP paths cannot drift. It
takes an accept predicate, and Router::lookup passes the same select_tree_rule it will run on the
winner — which turns the order into a search rather than a filter, closing the method-404 shape the
issue reports as its second finding.

Precedence, stated and asserted

Per level, most specific first: exact literal child → regex segments (declaration order among
overlapping) → * wildcard, leftmost label only
, with fall-through between every pair.

Four mutations were run; no transition survives:

wildcard above the regexps loop      -> 3 failed
exact-child arm without fallback     -> 2 failed
regexps loop without fallback        -> 3 failed
Router::lookup passing &mut |_| true -> 3 failed

Red on the unfixed tree with the tests alone injected: FAILED. 108 passed; 7 failed.

Cost, measured rather than argued

The unified walk backtracks over regex segments at every level, so it was measured on both axes.

Attacker-controlled dimension, configuration fixed at 30 nodes:

labels   8 -> 27.6us   16 -> 28.1us   32 -> 29.0us   64 -> 29.7us   128 -> 30.4us

1.10× for a 32× longer hostname. Cost is linear in configuration node count (~11-13 µs/node),
not in attacker input. Recursion depth is unchanged — one frame per label. No datapath DoS.

Operator impact

Two behaviours change. The narrowing is the fix: a rule written for one host stops being served to a
regex family. The broadening is the one to read: an exact frontend no longer shadows
*.example.com for paths it does not itself carry, so an operator using a narrow exact frontend as a
deny-by-404 shadow loses that. Both are in CHANGELOG.md, and doc/configure.md gains a
### Hostname precedence section stating the order.

No migration is needed: the two declaration orders now build the same table, so the same replay yields
corrected routing on the new binary.

Reach

lib/src/tls.rs and lib/src/protocol/tcp_preread/mod.rs walk separate TrieNode instances
sharing only generic method code, and both consume TrieNode::lookup, so certificate selection follows
the same order. The TCP SNI route trie provably cannot hold a regex segment — validate_sni_pattern
rejects / on every insert path, with tests. The certificate trie is not so closed: add_certificate
validates only length and a hard InsertResult::Failed, and its names may be an operator-supplied
override, so a regex-shaped name can land there. No test covers the new order on that path.

Validation

BUILD=0 CLIPPY=0 TEST=0 FMT=0, test result: ok. 871 passed; 0 failed.
Merged with fix/anchor-hostname-regex: builds, 880 passed, clippy clean.

…dence

`add_tree_rule` reaches the node a hostname owns through
`TrieNode::domain_lookup_mut` and inserts only when that answers `None`.
That resolver walked a literal segment through the first regex segment
matching it, so adding `test4.example.com` after `/test[0-9]/.example.com`
never created a node for the exact host: the rule was appended to the regex
segment's list and every host the pattern matches served it. A rule scoped
to one host answered for a family, while `sozu query frontends` showed
exactly what the operator had typed, and declaring the exact name first
avoided it entirely.

`lookup_mut` is key-addressed now: with `accept_wildcard: false` a literal
key may not resolve into a non-literal entry. That is the guard
`insert_sni_route` already documented for the `*` slot, extended to the
regex list, which had nothing equivalent; the `*` case and the trailing-`/`
case of the same function already matched by identity.

Hostname resolution is stated and asserted most specific first — exact
name, then regex segments in declaration order, then the `*` wildcard — in
one backtracking walk, `TrieNode::lookup_recursive`, that `lookup` and
`lookup_with_path` share so routing and SNI certificate selection cannot
disagree. The exact-child arm had no fallback and the wildcard was
consulted before the regex list; reordering without the fallback would
have broken a regex segment holding no value for the host it matched.
`Router::lookup` hands the trie the same `select_tree_rule` it runs on the
winner, so a hostname candidate whose rules all reject this path or method
is skipped rather than ending the lookup — which is the reported 404 where
a first-declared POST-only segment shadowed a later GET one.

This narrows routing for configurations where a family was being served an
exact host's rule and broadens it where a request now falls through to a
less specific frontend instead of missing; `CHANGELOG.md` states both and
`doc/configure.md` states the order under "Hostname precedence".

State replay needs no migration, and a new `command/src/state.rs` test pins
why: the `BTreeMap` key sorts a regex segment before the exact name it
matches, so a forked worker always took the leaking order and both orders
now build the same table. The leak was order-dependent only in one process,
which is how the report reproduced it; the corollary on an affected build is
that a correct table built live by an exact-first API sequence is
re-corrupted at the next fork.

The TCP SNI route table cannot hold a regex segment — `validate_sni_pattern`
rejects `/` — but the certificate trie can, through an operator-supplied
`names` override, so the reorder does reach certificate selection there.

Closes #1351

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the fix/trie-exact-host-precedence branch from 5875bb9 to 2ea3551 Compare September 20, 2026 11:46
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 8fed9b7 into main Sep 20, 2026
23 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/trie-exact-host-precedence branch September 20, 2026 15:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

router: an exact-hostname rule added after a matching regex segment attaches to the regex leaf and leaks to every host it matches

1 participant