From b47604dcaac64af114bdcd3c2c68b9e1c6efc2f3 Mon Sep 17 00:00:00 2001 From: James Tucker Date: Fri, 23 Oct 2026 23:38:45 +0000 Subject: [PATCH] ssh/tailssh: make acceptEnv pattern matching linear time matchAcceptEnvPattern recursively retried each '*' suffix, which is exponential in the number of '*'s in an acceptEnv pattern (2.7s observed on a 400-byte crafted variable name). Replace it with an iterative matcher that only backtracks to the most recent '*', preserving the exact OpenSSH-style glob semantics. Cross-check it against a naive backtracking reference over random inputs, and pin the crafted backtracking case as a timing regression test. Updates tailscale/corp#50380 Signed-off-by: James Tucker (cherry picked from commit a819ec07535b65271e7739d6664fe0c4edbb60d4) --- ssh/tailssh/accept_env.go | 86 +++++++++++++++------------------- ssh/tailssh/accept_env_test.go | 77 ++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+), 48 deletions(-) diff --git a/ssh/tailssh/accept_env.go b/ssh/tailssh/accept_env.go index 8473282bc..9c6b48547 100644 --- a/ssh/tailssh/accept_env.go +++ b/ssh/tailssh/accept_env.go @@ -111,56 +111,46 @@ func matchAcceptEnv(acceptEnv []string, env string) bool { // matchAcceptEnvPattern returns true if the pattern matches against the target string. // Patterns may include * and ? wildcard characters which match against zero or one or // more characters and a single character respectively. +// +// Matching is iterative with a single backtracking point (the most recent +// '*'), so it runs in time linear in the target per '*' segment. A naive +// recursive matcher is exponential in the number of '*'s, and can be driven +// by attacker-supplied acceptEnv patterns and variable names. func matchAcceptEnvPattern(pattern string, target string) bool { - patternIdx := 0 - targetIdx := 0 - - for { - // If we are at the end of the pattern we can only have a match if we - // are also at the end of the target. - if patternIdx >= len(pattern) { - return targetIdx >= len(target) - } - - if pattern[patternIdx] == '*' { - // Optimization to skip through any repeated asterisks as they - // have the same net effect on our search. - for patternIdx < len(pattern) { - if pattern[patternIdx] != '*' { - break - } - - patternIdx++ - } - - // We are at the end of the pattern after matching the asterisk, - // implying a match. - if patternIdx >= len(pattern) { - return true - } - - // Search through the target sequentially for the next character - // from the pattern string, recursing into matchAcceptEnvPattern - // to try and find a match. - for ; targetIdx < len(target); targetIdx++ { - if matchAcceptEnvPattern(pattern[patternIdx:], target[targetIdx:]) { - return true - } - } - - // No match after searching through the entire target. + var ( + p, t int // current position in pattern and target + starP = -1 // index of the most recent '*' in the pattern + starT = -1 // position in the target where that '*' started matching + ) + for t < len(target) { + switch { + case p < len(pattern) && pattern[p] == '*': + // Register the most recent '*' before any literal match, so a + // '*' in the pattern is always a backtrack point even when the + // target has a literal '*' at the same position. + starP = p + starT = t + p++ + case p < len(pattern) && (pattern[p] == '?' || pattern[p] == target[t]): + // Match one character. + p++ + t++ + case starP >= 0: + // Mismatch: let the most recent '*' consume one more + // character of the target and retry the rest of the + // pattern from just after it. + p = starP + 1 + starT++ + t = starT + default: + // Mismatch with no '*' left to fall back on. return false } - - if targetIdx >= len(target) { - return false - } - - if pattern[patternIdx] != '?' && pattern[patternIdx] != target[targetIdx] { - return false - } - - patternIdx++ - targetIdx++ } + // The target is exhausted; the pattern must be too, modulo trailing '*'s, + // which match the empty string. + for p < len(pattern) && pattern[p] == '*' { + p++ + } + return p == len(pattern) } diff --git a/ssh/tailssh/accept_env_test.go b/ssh/tailssh/accept_env_test.go index d92193466..e70e5edb8 100644 --- a/ssh/tailssh/accept_env_test.go +++ b/ssh/tailssh/accept_env_test.go @@ -5,7 +5,10 @@ package tailssh import ( "fmt" + "math/rand/v2" + "strings" "testing" + "time" "github.com/google/go-cmp/cmp" ) @@ -265,3 +268,77 @@ func TestFilterEnv(t *testing.T) { }) } } + +// naiveMatchAcceptEnvPattern is a straightforward backtracking reference +// implementation of the acceptEnv wildcard semantics, used to cross-check +// matchAcceptEnvPattern. +func naiveMatchAcceptEnvPattern(pattern, target string) bool { + if pattern == "" { + return target == "" + } + switch pattern[0] { + case '*': + for i := 0; i <= len(target); i++ { + if naiveMatchAcceptEnvPattern(pattern[1:], target[i:]) { + return true + } + } + return false + case '?': + return len(target) >= 1 && naiveMatchAcceptEnvPattern(pattern[1:], target[1:]) + default: + return len(target) >= 1 && pattern[0] == target[0] && naiveMatchAcceptEnvPattern(pattern[1:], target[1:]) + } +} + +// TestMatchAcceptEnvPatternAgainstNaive checks matchAcceptEnvPattern against a +// naive backtracking reference matcher over random patterns and targets. +func TestMatchAcceptEnvPatternAgainstNaive(t *testing.T) { + // Patterns and targets are built from an alphabet containing literals, + // the wildcard characters themselves (as literals in the target), and a + // separator that commonly follows '*'s in acceptEnv patterns. + alphabet := []string{"a", "b", "_", "?", "*", "T"} + + rnd := rand.New(rand.NewPCG(1, 2)) + gen := func(maxLen int) string { + n := rnd.IntN(maxLen + 1) + var sb strings.Builder + for range n { + sb.WriteString(alphabet[rnd.IntN(len(alphabet))]) + } + return sb.String() + } + + for range 5000 { + pattern, target := gen(12), gen(20) + want := naiveMatchAcceptEnvPattern(pattern, target) + if got := matchAcceptEnvPattern(pattern, target); got != want { + t.Fatalf("matchAcceptEnvPattern(%q, %q) = %v; want %v", pattern, target, got, want) + } + } +} + +// TestMatchAcceptEnvPatternNoBacktrackingBlowup is a timing regression test: +// the recursive matcher took ~2.7s on this input at n=400. The iterative +// matcher must stay far below a generous bound. +func TestMatchAcceptEnvPatternNoBacktrackingBlowup(t *testing.T) { + pattern := "TS_*_*_*_*_*_TOKEN" + // No "TOKEN" suffix, so every '*' combination must be tried, but with + // many '_' separators for the '*'s to fan out over. + target := "TS_" + strings.Repeat("a_", 198) + "a" + if len(target) != 400 { + t.Fatalf("target len = %d, want 400", len(target)) + } + + start := time.Now() + got := matchAcceptEnvPattern(pattern, target) + elapsed := time.Since(start) + + if got { + t.Errorf("matchAcceptEnvPattern(%q, %q) = true; want false", pattern, target) + } + if elapsed > 100*time.Millisecond { + t.Errorf("matchAcceptEnvPattern took %v; want < 100ms", elapsed) + } + t.Logf("matched %d-byte target in %v", len(target), elapsed) +}