Skip to content

fix(syntax): stop crashes and hangs from deep or malformed shell input - #876

Merged
ewhauser merged 7 commits into
mainfrom
claude/fix-shell-crashes-review-7f23ca
Oct 19, 2026
Merged

ewhauser merged 7 commits into
mainfrom
claude/fix-shell-crashes-review-7f23ca

Conversation

@ewhauser

@ewhauser ewhauser commented Oct 19, 2026 •

Copy link
Copy Markdown
Owner

Fixes the parser, AST-walk, arithmetic and pattern findings from the security review against 83b31f1. Two of them were fatal Go stack overflows: recover() can't catch those, so they killed the embedding process.

What changed

Arithmetic recursion (critical)

  • Array subscripts call Arithm again, and each call restarted its depth count at 0. Self-referencing values recursed until the process died, e.g.:
    • x="x[x]"; echo $((x))
    • a=(); i="a[i]"; echo ${a[i]}
    • x='y=x'; echo $((x))
  • A shared counter on expand.Config now stops these with bash's error, e.g. x[x]: expression recursion level exceeded (error token is "x[x]").

Parser and Walk nesting (critical)

  • Nothing limited nesting depth. $(( followed by 100k (, or deep ( (, { , $(, ${x:-, [[ ! … or unary -, overflowed the stack in the parser or in Walk. Tiny scripts could reach this through eval.
  • The parser now fails with a ParseError (nesting exceeds the maximum depth of N) in two cases:
    • past syntax.MaxNestingDepth (16000) nested constructs;
    • past syntax.MaxTreeDepth (50000) tree levels. Operator lists like a && b && … are built in a loop but still add a level per operator, and the interpreter recursed on them.
  • Pattern and heredoc sub-parsers now inherit the nesting depth. Before, [[ x == $([[ x == $(… got past the limit.
  • syntax.Walk keeps an explicit stack and visits nodes in exactly the old order; a test checks it against a copy of the old recursive version.
  • StmtsSeq no longer yields again after its consumer stops (that panicked with range-over-func).

Unbalanced extglob from variables (medium)

  • With extglob on, a pattern like "*(", "@(a|" or "+(a" made pattern.Regexp emit an invalid regex that leaked its NUL end marker. Callers then panicked in regexp.MustCompile, aborting the whole execution.
  • Like bash, an unterminated group and everything after it now match literally. This applies to both pattern package copies and to the negated-extglob matcher. Callers use regexp.Compile.

${%} (low)

  • The printer now writes the original ${%} instead of ${} (e.g. in declare -f), and Minify no longer dereferences the nil Param.
  • Quoted "${%}" panicked at expansion; it now reports ${%}: bad substitution.

case patterns with backquotes (found by FuzzParsePrint)

  • Any backquote substitution in a case pattern made the parser loop forever, even case i in `;. Backquote substitutions are now parsed in full, as bash does, and the token-skip loop stops if the lexer stops advancing.

For reviewers

  • Limit values: they sit above the runtime depth budgets from fix(interp): bound shell nesting, budgets, and variable memory #875, which expect 10000 nested subshells and 5000-stage pipelines to parse and then stop at run time. Probing at nesting 20000 and tree depth 100000 found no crashes.
  • SPEC.md §9.1 documents the new limits. They are a deliberate sandbox divergence: bash accepts deeper input, for example 20k nested arithmetic parens.
  • Walk cost: Walk is about 20% slower on nvm.sh, with fewer allocations. The extra tree-depth walk after parsing only runs when a parse saw at least 256 levels of nesting or chained operators.
  • Error behavior: after a recursion error, gbash keeps running the script, while bash aborts it. That matches how gbash already handles other arithmetic errors.
$ gbash -c 'x="x[x]"; echo $((x))'
x[x]: expression recursion level exceeded (error token is "x[x]")
$ gbash -c 'o=$(printf "%.0s(" {1..99999}); c=${o//(/)}; eval "echo \$((${o}1${c}))"; echo after'
gbash: line 1: nesting exceeds the maximum depth of 16000
after
$ gbash -c 'shopt -s extglob; p="*("; echo $p; [[ "*(" == $p ]] && echo match'
*(
match

Testing

  • Each fix has a regression test that fails or crashes on main.
  • go test ./shell/... ./internal/shellpattern/... passes.
  • make lint reports 0 issues.
  • The full make conformance-test had 0 failures. It ran before the case fix; the case, arith, glob and dbracket conformance files pass on top of it.
  • Fuzzers ran with no new failures: FuzzParsePrint, FuzzParseAdversarial and FuzzParseAttackMutations for 45 s each; FuzzQuote, FuzzRuntimeScript, FuzzMalformedScript and FuzzAttackMutations for 30 s each.
  • go test ./... failures are unrelated:
    • the diff and ripgrep oracle tests need the Nix env vars;
    • scripts/bench-compare fails the same way on main;
    • two tail -f CLI tests failed under load and pass on rerun.

Known follow-ups (not in this PR, and none crash)

  • Nested patterns: deeply nested extglob in [[ ]] and nested $(case …) in case patterns still parse in exponential time. A separate change is in progress.
  • Slow deep input: deep nested subscripts such as a[a[…]] and deep [[ == ]] patterns re-scan the rest of the input at every level, so input near the limit can take tens of seconds to reject.
  • Long sums: $((1+1+…)) with 100k terms is slow to evaluate.

Deeply nested input such as $(( followed by 100k parentheses, or long
a && b && ... lists, overflowed the goroutine stack in the parser, in
Walk or in the interpreter, a fatal error recover() cannot catch.

The parser now fails with a ParseError past MaxNestingDepth (1000)
nested constructs, including shell parts re-parsed by pattern and
heredoc sub-parsers, and past MaxTreeDepth (10000) tree levels built by
operator lists. Walk keeps its own stack. StmtsSeq no longer yields
again after its consumer stops.
With extglob on, a pattern such as "*(" or "@(a|" from a variable made
pattern.Regexp emit an invalid regular expression that leaked its NUL
end marker, and callers panicked in regexp.MustCompile, aborting the
whole execution. Like bash, an unterminated group and everything after
it now match literally, in both pattern package copies and in the
negated-extglob matcher, and callers compile with regexp.Compile.
The parser keeps ${%} with a nil Param so it fails at runtime like bash.
Minify dereferenced that Param (found by FuzzParsePrint), the printer
rendered it as ${}, for example in declare -f output, and quoted
expansion panicked in the array-field path. The printer now writes the
original source and expansion reports "${%}: bad substitution".
After scanning a case pattern, the parser skipped tokens up to the end of
the pattern, but the lexer never moves past a backquote token on its own,
so any backquote substitution in a case pattern, and even "case i in `;",
spun forever (found by FuzzParsePrint). Backquote substitutions are now
consumed as a whole, and the skip loop stops when the lexer stalls.
@ewhauser
ewhauser enabled auto-merge (squash) October 19, 2026 20:39
The interpreter budgets merged from main stop deep subshell nesting at
run time and expect 10000 nested subshells and 5000-stage pipelines to
parse. Raise MaxNestingDepth to 16000 and MaxTreeDepth to 50000, which
probing shows stay far from the goroutine stack limit, and test that
pattern and heredoc sub-parsers inherit the depth by starting near the
limit instead of parsing very deep input.
@ewhauser
ewhauser merged commit 3e89dee into main Oct 19, 2026
18 checks passed
@ewhauser
ewhauser deleted the claude/fix-shell-crashes-review-7f23ca branch October 19, 2026 21:15
@ewhauser ewhauser mentioned this pull request Oct 20, 2026
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.

1 participant