Skip to content

fix: prevent ReDoS in repeated extglobs with a star branch - #259

Closed
CodySwannGT wants to merge 6 commits into
micromatch:masterfrom
CodySwannGT:fix/repeated-extglob-star-redos
Closed

CodySwannGT wants to merge 6 commits into
micromatch:masterfrom
CodySwannGT:fix/repeated-extglob-star-redos

Conversation

@CodySwannGT

@CodySwannGT CodySwannGT commented Nov 17, 2026 •

Copy link
Copy Markdown

Problem

GHSA-fc5q-39xc-vjpf: a repeated extglob whose branch holds a top-level * nests one unbounded quantifier inside another. analyzeRepeatedExtglob only inspects multi-branch bodies and *(...) star sequences, so single-branch forms such as +(*) and +(*a) (and multi-branch ones like +(*a|b)) compile straight to (?:[^/]*?)+ / (?:[^/]*?a)+ and backtrack exponentially on a non-matching input.

Worst case over 'a'.repeat(24) plus one trailing character (/, !, b), Node 24:

pattern before after
+(*) 1422 ms 0.0 ms
+(*a) 296 ms 0.0 ms
*(*a) 293 ms 0.0 ms
+(*a*) 36798 ms 0.0 ms

Each additional character roughly doubles the "before" time.

Fix

Branches are scanned for a top-level * (not one that opens a nested *(, nor one inside brackets, quotes or parens). When one is found:

  • If every branch is a slash-free segment sequence (plain characters, ?, *, brackets without /) and the starred branches all end with *, every copy after the first starred copy is absorbed by that trailing *. The repeat is rewritten to (?:N)*(?:S|N) for +(...) and (?:N)*(?:S)? for *(...), where S are the starred branches and N the star-free ones. Leading stars mirror this. With no star-free branch the repeat is simply dropped: +(*a) becomes (?:[^/]*?a), *(*a) becomes (?:[^/]*?a)?. A single starred branch absorbs the repeat wherever its * is.
  • Otherwise (+(a*|*b), +(a*b|a), +(a/*), nested extglobs) the extglob is literalized, like the other risky repeated extglobs.
  • A * hidden in a nested group counts too (second commit): +(@(*)), +(@(*a)), +(@(*)|b), +(!(*)) and +(!(a)) backtracked just as badly through a nested @()/!()/?()/+()/*(). A * at any depth and any nested !( (whose output always ends in a star) are treated as unbounded. @(x) and ?(x) around one alternative are unwrapped before deciding, and a lone !(x) behaves like a branch ending in *, so +(@(*)) and +(!(a)) are still rewritten rather than literalized. A leading run of single-character *(c)/+(c) groups whose copies can overlap (+(*(a)a)) is literalized; +(*(a)b) and *(*(of*(o)x)o) are left alone.
  • Repeats hidden in @() and ambiguous alternations (third commit): a whole-branch @(...) is checked as its own branches, so +(@(+([ab]))) hits the nested-repeat limit like +(+([ab])) and +(@(*(a))) compiles like +(*(a)). Branches that can split the same text into copies in two ways (+([ab]|b), +(a|b|ab), +(*(ab)c|abc), +(a*([ab]))) backtrack exponentially without any * wildcard; a Sardinas-Patterson check over character sets (nested groups expanded to none, one or two copies, capped at 64 texts per branch) finds them and they are literalized like +(a|aa). Unambiguous alternations (+(js|ts|jsx), +(foo|far), *(f*(o))) are unchanged; maxExtglobRecursion above 0 counts nested repeats once.
  • Syntax the check cannot model fails closed (fourth commit): the ambiguity check used to skip branches it could not read, so braces, ranges, quotes and POSIX classes slipped through, and +({a,a}), +({a,b}|b), +(a|a{b,}), +(a|"a"), +(a|[[:alpha:]]), +({a..b}|a) and +([a-b]{,a}) still backtracked exponentially. So did a regex escape (+(\w|a), since \w reaches the regex as a class), a bare +, which inside an extglob is a regex quantifier (+(a+)), a bare group (+((a|a))) and a bracket without regex characters, which compiles to its literal text or the class. The check now reads only plain characters, ?, escaped symbols, brackets (both outputs), POSIX classes (as any character), / and groups; any other branch is treated as risky and literalized. It follows flags (case folding under i, astral characters under u), nocase, posix, literalBrackets, nobracket and unescape, and gives up instead of truncating past 64 texts per branch. Collateral: an unambiguous branch with a brace or quote, such as +({a,b}), is now literalized too.
  • A + after a risky glob group (fifth commit): when + does not open an extglob (+(?, or + not before (), it reaches the regex as a quantifier on the group before it, so !(a)+(?(c)) compiled to (?:(?!a)[^/]*?)+ and hung, as did @(a|a)+ and {a,a}+. That + is now literal, as bash reads it, after a closed !(), ?(), +() or *(), after an @() whose body is risky as a repeat, and after a brace group whose elements are. @(js|ts)+, the brace Kleene plus {ab,c}+ (tested in test/braces.js) and plain regex groups such as (a|b)+ keep their quantifier. *, ?, @ and ! after a group never quantify it.
  • The rewrite keeps the pattern's meaning (sixth commit). Alternatives keep their spaces when an @() is flattened (+(@(red| red)) matches red). A rewritten repeat writes the copy it matches last with its own groups, in branch order, and earlier copies without capturing, so capture: true exec arrays keep upstream's layout (a value can differ only for an input that splits into copies in more than one way, where the original's choice is an artifact of backtracking order). With regex: true a * after ] or ) is a quantifier, not a wildcard, so +([a]*|b) is not absorbed. The rewrite is built from the current tokens, so +(***log) no longer matches dir/log through a globstar a later star turned back into a star. A flattened @() is opened in the output too, so +(@(log*|txt)) is rewritten instead of turning literal. The literal fallback escapes backslashes, so +(log\w|cache) matches its own text. Alternatives are capped before they are paired and only +/* repeats are analysed, so a 4,096-way alternation compiles instead of running out of memory. A + after a star or globstar stays literal (with capture, *+ inside an extglob became ([^/]*?)+), and with regex: true a * after a risky glob group is read as a glob star.
  • maxExtglobRecursion: false keeps the old output, as before.

The rewritten regex is built from the body's existing regex output, split per branch with splitTopLevel, and falls back to literalization if the branch count does not line up.

Evidence

  • Full mocha suite passes (2025 tests, including the new ones in test/options.maxExtglobRecursion.js). The new timing tests hang on the unpatched parser; the nested-group one also hangs on the first commit alone, the hidden-repeat/ambiguous-alternation one on the first two, the unmodelled-syntax one on the first three, and the plus-after-group one on the first four. The sixth commit's tests (spaces, flattened @(), globstar, capture layout, regex quantifier, backslash literal, wide alternation, plus after a captured star) fail on the first five.
  • Capture differential (sixth commit): 6,000 random nested extglobs under {}, capture, nocase, dot, regex and regex + capture, compared with the unpatched parser by exec on every string of length 0 to 3 over a b x space / . [ ]: no rewritten form matches a different set of strings, and none changes the number or position of capture groups; the only differences are capture values on inputs with more than one split into copies. A further 2 × 20,000 random patterns under capture, regex, regex + literalBrackets: false, regex + capture and capture + nocase find nothing that grows except patterns where (? opens a plain regex group (*(?(...)...)+), which this PR leaves to regex semantics like (a|a)+.
  • Syntax fuzzing (3,000 random nested extglobs over braces, ranges, quotes, POSIX classes, escapes, groups, a+ and / brackets, run under {}, nocase, windows, posix: false, literalBrackets true and false, unescape, flags: 'iu' and dot) finds no pattern slower than 1.5 s on 4.0.7 or 2.3.x; before the fourth commit 297 (4.0.x) and 265 (2.3.x) of them hung. A further 8 × 20,000 random nested extglobs (with braces, quotes, POSIX classes, escapes and groups, under four option sets, timed at 12, 16 and 20 characters) find nothing that grows; before the fifth commit 23 (4.0.x) and 26 (2.3.x) of about 48,000 did, each a + after an extglob or brace group, or (one, 2.3.x only) the dropped text below. On 2.3.x the same change also needs the 4.x fix for the text dropped after a bracket once an earlier extglob is literalized (+(a|aa)|+([a]b|a) compiled to (?:[a]|a)+). With maxExtglobRecursion: 1, which opts into nested repeats, five such as +(*(ab)) remain slow, as that option intends.
  • A generated class of 1240 patterns (10 starred atoms such as *, *a, *(a)a, ?(a)*, each bare and inside one or two of @ ! ? + *, repeated by +/*, alone and beside |b) all finish under 1.5 s on 30-character non-matching inputs; before the second commit 332 of them did not. Random fuzzing (7,200 nested extglob patterns plus 4,000 alternation-focused ones, inputs up to 90 characters) finds no pattern slower than 1.5 s on 4.0.7 or 2.3.x; before the third commit the alternation-focused set had 17-20 per 800.
  • Differential check of nested-group bodies (@(*), @(*a)|b, !(a), !(*), !(f), @(@(*)), *(a)b, ... 18 bodies, 864 forms with the same contexts and options as below): 0 mismatches; 108 forms become literals: those of *(a)a and @(*(a)a), and the 12 capture forms of @(*(a)), which keeps its group that way (on 2.3.x, whose class keeps only the first star sequence, all 48 of its forms). Of 17 alternation bodies (816 forms), the ambiguous ones become literals and every other form compiles exactly as before.
  • Differential check of patched against unpatched: 1584 pattern forms (33 repeated-extglob bodies × +/* × 6 surrounding contexts × options {}, {dot}, {capture}, {nocase}) against all 19608 strings of length 0 to 5 over a b . / x [ ]. Every rewritten form matched exactly the same strings as before (0 mismatches). The only behaviour changes are the 240 forms that are now literalized, which come from 5 bodies: a*|*b, *a|b*, a*b|a, *a|@(b) and *(a)*.
  • The same change applies cleanly to the 2.3.x line (lib/parse.js at 2.3.2), passes that line's suite (1972 tests; the 2.3.x port keeps @(*(a)) literal, as above) and gives the same 0-mismatch differential result there.

🤖 Generated with Claude Code

A top-level `*` inside `+(...)` or `*(...)` nests one unbounded
quantifier inside another, including in a single-branch extglob such as
`+(*)` or `+(*a)`, which analyzeRepeatedExtglob did not inspect. When
every branch is a slash-free segment sequence and the starred branches
all end (or all start) with `*`, rewrite the repeat into an equivalent
form without nested quantifiers; otherwise literalize the extglob like
other risky repeated extglobs.
@DaleMckeown

Copy link
Copy Markdown

See #235 (comment).

@msalaheldincontractor-wsl

Copy link
Copy Markdown

Reviewed from the diff; I did not run this branch. For reference, on master (9fab7bf, Node 22) each of +(*), +(*a), *(*), *(*a), +(*)a and the two-branch +(*a|*b) takes more than 3 s for isMatch('a'.repeat(28) + '/', pattern).

  • This is the most general approach of the open fixes. Any top-level * marks the extglob risky, and the absorbable shapes (all starred branches trailing, all leading, or one starred branch) get a rewritten regex. That covers all six patterns above.
  • When absorbRepeat returns nothing (starred branches that mix leading and trailing stars, such as +(*a|b*), or a starred branch that fails isSegmentSequence), the extglob is marked risky with no safeOutput. extglobClose then emits it as escaped literal text, so +(*a|b*) would match only the string +(*a|b*), not xa or bx. That's a silent change in matching rather than a slowdown. Is it intended? Either way, a test for that case would document it.

The star scan skipped everything inside parentheses, so `+(@(*))`,
`+(@(*a))`, `+(!(*))` and `+(!(a))` still nested an unbounded quantifier
inside the repeat and backtracked catastrophically. Count a `*` at any
depth and any nested `!(` as unbounded. Unwrap `@(x)` and `?(x)` around a
single alternative before deciding, treat a lone `!(x)` like a branch
ending in `*` so it can still be absorbed, and literalize a leading run of
single-character `*(c)`/`+(c)` groups whose copies can overlap, such as
`+(*(a)a)` and `+(@(*(a)))`.
A whole-branch @(...) group is now checked as its own branches, so
+(@(+([ab]))) hits the nested-repeat limit like +(+([ab])) and
+(@(*(a))) compiles like +(*(a)). Repeated branches that can split the
same text into copies in two ways, such as +([ab]|b), +(a|b|ab),
+(*(ab)c|abc) and +(a*([ab])), backtrack exponentially on a failing
match; a Sardinas-Patterson check over character sets (with nested
groups expanded to none, one or two copies, capped at 64 texts per
branch) finds them, and they are literalized like +(a|aa). Unambiguous
alternations such as +(js|ts|jsx) and *(f*(o)) are unchanged, and a
maxExtglobRecursion above 0 keeps nested repeats counted once.
The ambiguity check skipped branches it could not read, so braces,
ranges, quotes and POSIX classes slipped through: +({a,a}),
+({a,b}|b), +(a|a{b,}), +(a|"a"), +(a|[[:alpha:]]), +({a..b}|a) and
+([a-b]{,a}) still backtracked exponentially. So did a regex escape
(+(\w|a)), a bare + that is a regex quantifier inside an extglob
(+(a+)), a bare group (+((a|a))) and a bracket without regex
characters, which compiles to its literal text or the class.

The check now models only syntax known to compile to itself and treats
any other branch as risky. It follows the flags, nocase, posix,
literalBrackets, nobracket and unescape options, and gives up rather
than truncating past 64 texts per branch.
When `+` does not open an extglob (`+(?`, or `+` not before `(`), it
reaches the regex as a quantifier on the group before it. After a
negation that nests quantifiers: `!(a)+(?(c))` compiled to
`(?:(?!a)[^/]*?)+` and backtracked exponentially, as did `@(a|a)+` and
`{a,a}+`. That `+` is now literal, as bash reads it, after a closed
`!()`, `?()`, `+()` or `*()`, after an `@()` whose body is risky as a
repeat, and after a brace group whose elements are. `@(js|ts)+`, the
brace Kleene plus `{ab,c}+` and plain regex groups such as `(a|b)+` keep
their quantifier.
- Keep spaces when flattening @() alternatives, so +(@(red| red)) still
  matches " red".
- Write the copy a rewritten repeat matches last with its own groups, in
  branch order, and earlier copies without capturing, so capture arrays
  keep their layout.
- With regex: true, a `*` after `]` or `)` is a quantifier, not a wildcard,
  so +([a]*|b) is not absorbed; it nests a quantifier and stays literal.
- Build the rewrite from the current tokens, so +(***log) no longer picks
  up a globstar a later star turned back into a star.
- Open a flattened @() group in the output too, so +(@(log*|txt)) is
  rewritten instead of turning literal.
- Escape backslashes in the literal fallback, so it matches its own text.
- Cap alternatives before pairing them, and analyse only + and * repeats,
  so a 4,096-way alternation compiles without running out of memory.
- Keep a + after a star or globstar literal (with capture, `*+` became
  `([^/]*?)+`), and with regex: true read a `*` after a risky glob group as
  a glob star.
@CodySwannGT

Copy link
Copy Markdown
Author

Closing: understood that patterns like these are a property of globs being regular expressions, not a vulnerability, and that the answer is not to accept untrusted patterns. Thanks for the explanation.

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.

3 participants