Skip to content

fix(sanitizer): avoid quadratic backtracking in CSS style declaration check (#610) - #616

Open
abu-tahir-0 wants to merge 2 commits into
kurtmckee:mainfrom
abu-tahir-0:fix/sanitizer-style-redos
Open

abu-tahir-0 wants to merge 2 commits into
kurtmckee:mainfrom
abu-tahir-0:fix/sanitizer-style-redos

Conversation

@abu-tahir-0

Copy link
Copy Markdown

Problem

Fixes #610. In feedparser/sanitizer.py, HTMLSanitizer.sanitize_style() executes a global regular expression substitution re.sub(r"\s*[-\w]+\s*:[^:;]*;?", "", style) after the initial character gauntlet.

When a feed item contains a long style attribute consisting of word characters without a colon (:), the first gauntlet succeeds, but the second regex attempts to match [-\w]+ at every character offset and backtracks on each failure looking for :. This results in O(n²) quadratic-time execution, allowing a crafted feed to pin the CPU for tens of seconds (e.g., 40,000 characters took ~30s).

Root Cause

The global re.sub() attempts matching across all offsets in the string. When style contains no colons, each offset initiates a greedy match of [-\w]+ followed by backtracking, repeating for every character position.

Solution

Validate declaration pieces individually rather than using a global substitution:

  1. Split style by semicolons (;).
  2. Verify that every preceding piece matches \s*[-\w]+\s*:[^:;]* using re.fullmatch().
  3. Verify that the trailing piece is either whitespace or a valid declaration.
  4. Add a changelog fragment in changelog.d/.

Because re.fullmatch anchors to the start of each piece and checks pieces linearly, it completely prevents quadratic backtracking.

Testing

  • Added regression test test_hostile_style_is_parsed_quickly in tests/test_sanitizer.py (40,000 characters parses in ~0.03s vs ~30s).
  • Added parameterized unit tests covering valid styles, invalid styles, and empty declarations.
  • Ran full test suite locally:
    4316 passed, 8 skipped in 2.50s
  • Checked linters & type checkers: flake8, black, and mypy all clean.

Impact

Eliminates a ReDoS vulnerability in feedparser's HTML sanitizer, safeguarding downstream applications against CPU exhaustion from untrusted feeds.

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.

Second ReDoS in the sanitizer: quadratic CSS style gauntlet (separate from #562)

1 participant