Repository navigation
fix(sanitizer): avoid quadratic backtracking in CSS style declaration check (#610) - #616
Open
abu-tahir-0 wants to merge 2 commits into
Open
abu-tahir-0 wants to merge 2 commits into
abu-tahir-0 wants to merge 2 commits into
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Fixes #610. In
feedparser/sanitizer.py,HTMLSanitizer.sanitize_style()executes a global regular expression substitutionre.sub(r"\s*[-\w]+\s*:[^:;]*;?", "", style)after the initial character gauntlet.When a feed item contains a long
styleattribute 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. Whenstylecontains 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:
styleby semicolons (;).\s*[-\w]+\s*:[^:;]*usingre.fullmatch().changelog.d/.Because
re.fullmatchanchors to the start of each piece and checks pieces linearly, it completely prevents quadratic backtracking.Testing
test_hostile_style_is_parsed_quicklyintests/test_sanitizer.py(40,000 characters parses in ~0.03s vs ~30s).4316 passed, 8 skipped in 2.50sflake8,black, andmypyall clean.Impact
Eliminates a ReDoS vulnerability in feedparser's HTML sanitizer, safeguarding downstream applications against CPU exhaustion from untrusted feeds.