Match suffix rules at label boundaries

Suffix rules are stored as-is, just reversed in a critbit trie.

So the longest prefix can end inside a DNS label, and hide a
shorter rule that actually matches the name.

To handle that and prevent adversarial names with many labels to
cause many repeated searches, we allowed only two lookups per match.
That was designed for common usage patterns, where names were
expected to be domain names, not host names.

But there's a clean way to prevent an unbounded number of matches
and properly match any rules: just append a dot to the stored suffix
keys (and reversed query names). It acts as a label separator, so
the longest prefix can find the specific valid suffix with as ingle
lookup.

Fixes #3305
This commit is contained in:
Frank Denis 2026-08-01 08:13:48 +02:00
parent 610904bba8
commit 0de84ad05b

View file

@ -109,7 +109,8 @@ func (patternMatcher *PatternMatcher) Add(pattern string, val any, position int)
case PatternTypePrefix:
patternMatcher.prefixes.Insert([]byte(pattern), val)
case PatternTypeSuffix:
patternMatcher.suffixes.Insert([]byte(StringReverse(pattern)), val)
// The trie key gets an extra dot to mark the label boundary.
patternMatcher.suffixes.Insert([]byte(StringReverse(pattern)+"."), val)
case PatternTypeExact:
patternMatcher.exact[pattern] = val
default:
@ -127,21 +128,9 @@ func (patternMatcher *PatternMatcher) Eval(qName string) (reject bool, reason st
return true, qName, xval
}
revQname := StringReverse(qName)
revQname := StringReverse(qName) + "."
if match, xval, found := patternMatcher.suffixes.LongestPrefix([]byte(revQname)); found {
if len(match) == len(revQname) || revQname[len(match)] == '.' {
return true, "*." + StringReverse(string(match)), xval
}
if len(match) < len(revQname) && len(revQname) > 0 {
if i := strings.LastIndex(revQname, "."); i > 0 {
pName := revQname[:i]
if match, xval2, found := patternMatcher.suffixes.LongestPrefix([]byte(pName)); found {
if len(match) == len(pName) || pName[len(match)] == '.' {
return true, "*." + StringReverse(string(match)), xval2
}
}
}
}
return true, "*." + StringReverse(string(match[:len(match)-1])), xval
}
if match, xval, found := patternMatcher.prefixes.LongestPrefix([]byte(qName)); found {