SkillSpector icon indicating copy to clipboard operation
SkillSpector copied to clipboard

fix(patterns): anchor MP2 regex to prevent catastrophic backtracking

Open mimran-khan opened this issue 5 months ago • 1 comments

Summary

The first MP2 pattern (Context Window Stuffing) uses a nested structure ((\S)(?!\2).{1,19}?)\1{20,} that is vulnerable to catastrophic backtracking (ReDoS). On non-matching inputs of moderate size (>500 chars), the regex engine explores exponential backtracking paths due to the lazy .{1,19}? quantifier inside a backreference-repeated group.

Changes

  • static_patterns_memory_poisoning.py: Replace the vulnerable pattern with (.{2,20}?)\1{20,} which detects repeated substrings without the expensive negative lookahead inside a repeated group.
  • New test file: tests/nodes/analyzers/test_mp2_regex_backtracking.py — validates both correct detection of repeated content and bounded execution time on adversarial inputs.

Before / After

# Before — exponential backtracking on non-matching input
(r"((\S)(?!\2).{1,19}?)\1{20,}", 0.8)

# After — linear-time matching, same detection capability
(r"(.{2,20}?)\1{20,}", 0.8)

Testing

  • 6 new tests: 3 for correct detection, 3 for bounded execution time
  • Full test suite passes (775 tests, excluding pre-existing upstream issue in test_llm_utils.py)

Fixes #151

mimran-khan avatar Jun 22 '26 20:06 mimran-khan

Both issues addressed:

  1. Lint fixed — removed unused signal and sys imports from test_mp2_regex_backtracking.py. ruff check passes clean.

  2. Whitespace-bearing stuffing false negative fixed — replaced len(set(captured.strip())) <= 1 with a whitespace-aware check: we now compute unique non-whitespace chars and only suppress when both (a) there's at most one unique non-whitespace char AND (b) no interior whitespace is present. This means:

    • "=" * 80 → suppressed ✓ (single non-ws char, no spaces)
    • "x " * 30 → detected ✓ (single non-ws char, but has interior whitespace = genuine stuffing)
    • "ab" * 30 → detected ✓ (multiple non-ws chars)
  3. Tests added: test_separator_line_not_detected (separators suppressed) and test_whitespace_bearing_stuffing_detected (space-bearing payloads not suppressed).

Branch rebased on latest main.

mimran-khan avatar Jun 23 '26 09:06 mimran-khan