Skip to content

fix(router): anchor every branch of a hostname regex segment - #1363

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
fix/anchor-hostname-regex
Sep 20, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
fix/anchor-hostname-regex

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 20, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1356.

The defect

Hostname regex segments were anchored by concatenating \A and \z around the operator's pattern
without grouping it. | is the lowest-precedence regex operator, so \Aa|b\z parses as
(\Aa)|(b\z) — each branch anchored at one end only, which re-opens exactly the substring match the
anchoring was added to prevent.

A frontend written /api|admin/.example.com also served apifoo.example.com and
xadmin.example.com. The operator has no way to notice: the frontend loads, sozu query frontends
shows exactly what they typed, and the extra hosts appear only if someone sends them.

With three branches it is worse than "one end only": ungrouped \Aa|b|c\z parses as
(\Aa)|(b)|(c\z), so the middle branch keeps neither anchor and matches as a bare substring
anywhere in the host.

The change

Five sites across two genuinely different code paths:

  • lib/src/router/mod.rs convert_regex_domain_rule now emits (?: … ) around each
    slash-delimited segment. Not around the whole result — the function assembles multiple segments,
    so \A(?:a|b\.example\.com)\z would have broken the intended match.
  • The four format!("\\A{s}\\z") sites in lib/src/router/pattern_trie.rs became one
    anchored_segment() helper. That string is also a regexps entry's identity (compared via
    Regex::as_str() at three of the four sites), so a second spelling would make a stored segment
    un-removable; the helper is the single source. It also removed a pre-existing duplicate format!.

Both paths compile the bare pattern first, so a malformed pattern such as a)(b cannot be rescued
into a valid \A(?:a)(b)\z.

Non-capturing is load-bearing. $HOST[n] exists on the hostname side: capture_cap_host is
DomainRule::Regex::captures_len() and extraction is caps.iter().skip(1). A capturing wrapper
shifts every index, silently rewriting wrong traffic. Pinned by assertions on captures_len and by
a rewrite test checking $HOST[1] → 42 and $HOST[0] → the whole host across all three of
Pre/Post/Tree, with $HOST[2] still refused as RouterError::InvalidHostRewrite.

Wider than the issue: the TCP pre-read SNI path carried the trie half

lib/src/protocol/tcp_preread/mod.rs:377 does domain_lookup(sni, ..) against operator-configured
routes, reaching the same pattern_trie::TrieNode regexps entries. It does not use
convert_regex_domain_rule, so it was not covered by the issue's analysis — but it carried the trie
half of this defect and inherits the grouped wrapper.

lib/src/tls.rs:637 walks that same trie — a separate TrieNode instance, not shared state —
and it is reachable too, though by a narrower route. Its entries are inserted at tls.rs:374 from
cert_to_add.names, which is the operator's names override when supplied and the parsed SAN/CN set
otherwise. A parsed DNS SAN cannot contain /; an operator-supplied name is not validated for it
— add_certificate's dry-run (tls.rs:326-336) rejects only an over-long name and a hard
InsertResult::Failed, neither of which a /x/ label triggers. So a certificate registered with an
operator-supplied regex-shaped name does land in the regexps list and does inherit this fix.

Nothing tests that path, and this changeset adds no test for it.

A repo-wide grep found no other \A anchoring construction outside lib/src/router/.

Tests

Four new behavioural tests, every one using a three-branch alternation, because a two-branch
alternation cannot express the clause: with two branches the first gets \A and the last gets \z,
so "every branch is anchored" has nothing to bite on. Asserted non-routing: zzbzz.example.com,
bzz.example.com, zzb.example.com, plus hand-built ungrouped controls proving they used to route.

An existing test that pinned the defect and asked in its own comment to be inverted was inverted,
not deleted
: an_alternating_regex_hostname_segment_is_still_anchored_at_one_end_only is now
an_alternating_regex_hostname_segment_is_anchored_on_every_branch, extended to three branches and
citing its old name.

Six mutations were run individually. Full unfixed baseline:

test result: FAILED. 104 passed; 8 failed; 0 ignored; 0 measured; 756 filtered out

Per-site, the two that matter most:

M5 anchored_segment wrapper made CAPTURING -> 2 failed
     left: Some("\A(cdn[0-9]+)\z")  right: Some("\A(?:cdn[0-9]+)\z")
     Tree: $HOST[1] ... left: Some("cdn42.internal")  right: Some("42.internal")
M2 anchored_segment drops pre-validation   -> 2 failed
     left: Some("\A(?:a)(b)\z")  right: None

The production bodies contain zero test-input literals, so the fix is not test-shaped.

Docs

doc/configure.md § "Regex hostname segments" claimed the segment "matches that whole segment and
nothing else" — corrected, with the narrowing note and the remediation. Its /api|admin/ →
apifoo/xadmin example and its /api.*|.*admin/ remediation are each asserted as an 8-row table:
every measured claim in the prose has an assertion behind it.

CHANGELOG.md gains a Security entry, and one stale in-release cross-reference — the #1357 path
entry, which described the hostname sites as ungrouped — was corrected.

Validation

BUILD=0 CLIPPY=0 TEST=0 FMT=0, test result: ok. 868 passed; 0 failed.
Also -p sozu 97 passed, -p sozu-command-lib 153 passed, and
tests::router_hostname_tests::test_malformed_hostnames_rejected by exact name.

Not reproduced against a live proxy; measured through the router's public surface, as the issue
states. The SNI inheritance is asserted by code reading — both call TrieNode::domain_lookup on the
same trie — not by a new SNI-level test.

A regex hostname segment was anchored by concatenating `\A` and `\z`
around the operator's pattern without grouping it. `|` is the
lowest-precedence regex operator, so `\Aa|b\z` parses as `(\Aa)|(b\z)`:
each branch keeps one anchor only, which re-opens the substring match the
anchoring exists to prevent. With three or more branches the middle ones
keep neither anchor and match as a bare substring anywhere at all.

Measured on the tree as it stood, `/a|b/.example.com` served
`axx.example.com` and `xxb.example.com`, `/a|b|c/.example.com` served
`zzbzz.example.com`, and `/api|admin/.example.com` served
`apifoo.example.com` and `xadmin.example.com` — none of which the
operator declared, and none visible in `sozu query frontends`.

Both hostname code paths carried it. `convert_regex_domain_rule` now
emits `(?:` … `)` around each slash-delimited segment of the whole-host
regex a Pre/Post rule matches against. `pattern_trie.rs`'s segment-insert
wrappers — the insert dedup scan, the insert create path,
`remove_recursive` and `lookup_mut` — are now one `anchored_segment`
helper building `\A(?:{segment})\z`; that
string is also a `regexps` entry's identity, compared through
`Regex::as_str()` by the insert dedup scan, `remove_recursive` and
`lookup_mut`, so a second spelling would make a stored segment
un-removable.

The literal-label arm of the same function carried the same defect, one
`else` away, and is closed with it. A label the operator did not wrap in
slashes was pushed into the assembly verbatim, so `/a/.x|y.com` assembled
to `\A(?:a)\.x|y\.com\z` and matched `a.xZZZ` and `ZZZy.com`. A literal
label is a literal, so the treatment is `regex::escape`, not a group:
grouping would confine the alternation while leaving `+`, `?`, `*`, `^`
and `$` live in the same arm, and `b+c` matching `bbbc` is the same
defect with a different operator. Escaping is a no-op in matching
behaviour for every label a real hostname can carry — an LDH label is
`[A-Za-z0-9-]`, of which `regex::escape` touches only `-`, and `\-` is
`-` outside a character class. Two deliberate behaviour changes fall out
for labels that are not valid hostname labels, both narrowing and both
measured: a literal `*` label was a quantifier over the preceding atom,
so `*./x/.example.com` assembled to `\A*\.(?:x)\.example\.com\z` whose
`\A*` repeats a zero-width assertion and matched empty at any offset,
taking `evil.attacker.x.example.com`; and a literal label carrying an
unbalanced `(` or `[` was rejected outright and is now accepted, matching
exactly the host that was typed.

That `*` change is scoped to Pre/Post, which is all this function feeds.
A trie-routed frontend keeps a `*` label in `TrieNode`'s wildcard slot and
is untouched, so one configured hostname now answers differently by
position: `*./x/.example.com` takes `zz.x.example.com` on the trie and no
longer on Pre/Post, while `*.x.example.com` routes on both.
`doc/configure.md` carries that table, and the remediation for Pre/Post is
to spell the label out as a regex segment, `/[^.]*/./x/.example.com`.

SNI route selection carried the defect too and is fixed with it:
`lib/src/protocol/tcp_preread` resolves the ClientHello SNI against this
very trie and its routes are operator-configured, so a route
`/a|b|c/.example.com` accepted the SNI `zzbzz.example.com`.
`lib/src/tls.rs` uses the same `TrieNode` type but keys it by certificate
SAN names, which cannot contain a `/`, so its regex arm is unreachable in
practice and no test is claimed for it.

Adding that SNI test surfaced a separate pre-existing defect, fixed here
because the test cannot pass without it. `tcp_preread`'s `decide` carried
a `debug_assert!` requiring `matched_sni_pattern` to be the SNI itself or
a `*.` wildcard. `TrieNode::domain_lookup` returns a third shape — a key
carrying `/regex/` segments — which the assertion did not admit, so a
debug build panicked the first time any regex-segment SNI route matched,
though routing itself was correct. It now admits that shape by checking
the literal tail after the rightmost `/`; the segments are not
re-derived, because the trie has already matched them.

The group is non-capturing, so `captures_len` and therefore every
`$HOST[n]` rewrite index are unchanged: `$HOST[1]` of
`/cdn([0-9]+)/.example.com` is still the operator's own group. Each regex
segment is compiled on its own before being wrapped, because the wrapper
supplies one `(` and one `)` and can balance an unbalanced segment:
`a)(b` is rejected by `Regex::new`, yet `\A(?:a)(b)\.example\.com\z`
compiles and matches `ab.example.com`.

This is the hostname half of the wrapper #1357 landed for path regexes,
and it narrows existing rules the same way: an operator relying on the
leaked hosts writes the wildcards out, `/api|admin/` becoming
`/api.*|.*admin/`. `doc/configure.md` now also names a pre-existing trap
that remediation walks into — a `.*` inside a segment does not stop at
the label boundary, and where it stops depends on the rule position, so
`[^.]*` is what a `Pre`/`Post` rule needs. The 1.x-to-2.0 upgrade note
and `CHANGELOG.md` are corrected in the same changeset.

`an_alternating_regex_hostname_segment_is_still_anchored_at_one_end_only`
pinned the defect and asked, in its own comment, to be inverted rather
than deleted when the fix landed. It is now
`an_alternating_regex_hostname_segment_is_anchored_on_every_branch`,
extended to the three-branch case: with exactly two branches "first and
last" is every branch there is, so two cannot express the claim.

Closes #1356.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the fix/anchor-hostname-regex branch from 085f9ea to 1841ab7 Compare September 20, 2026 11:14
@FlorentinDUBOIS
FlorentinDUBOIS merged commit b51d9f9 into main Sep 20, 2026
23 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/anchor-hostname-regex branch September 20, 2026 14:42
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 alternation in a hostname regex segment is only half-anchored, re-opening the substring match

1 participant