Skip to content

Avoid catastrophic backtracking in hr regex #1056

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 24, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/change_log/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Under development: version 3.3.3 (a bug-fix release).

* Unify all block-level tags (#1047).
* Fix issue where some empty elements would have text rendered as `None` when using `md_in_html` (#1049).
* Avoid catastrophic backtracking in `hr` regex (#1055).

Oct 19, 2020: version 3.3.2 (a bug-fix release).

Expand Down
9 changes: 4 additions & 5 deletions markdown/blockprocessors.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,16 +496,15 @@ def run(self, parent, blocks):
class HRProcessor(BlockProcessor):
""" Process Horizontal Rules. """

RE = r'^[ ]{0,3}((-+[ ]{0,2}){3,}|(_+[ ]{0,2}){3,}|(\*+[ ]{0,2}){3,})[ ]*$'
# Python's re module doesn't officially support atomic grouping. However you can fake it.
# See https://stackoverflow.com/a/13577411/866026
RE = r'^[ ]{0,3}(?=(?P<atomicgroup>(-+[ ]{0,2}){3,}|(_+[ ]{0,2}){3,}|(\*+[ ]{0,2}){3,}))(?P=atomicgroup)[ ]*$'
# Detect hr on any line of a block.
SEARCH_RE = re.compile(RE, re.MULTILINE)

def test(self, parent, block):
m = self.SEARCH_RE.search(block)
# No atomic grouping in python so we simulate it here for performance.
# The regex only matches what would be in the atomic group - the HR.
# Then check if we are at end of block or if next char is a newline.
if m and (m.end() == len(block) or block[m.end()] == '\n'):
if m:
# Save match object on class instance so we can use it later.
self.match = m
return True
Expand Down
23 changes: 23 additions & 0 deletions tests/test_syntax/blocks/test_hr.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,3 +377,26 @@ def test_not_hr_2_underscores_spaces(self):

'<p>_ _</p>'
)

def test_2_consecutive_hr(self):
self.assertMarkdownRenders(
self.dedent(
"""
- - -
- - -
"""
),
self.dedent(
"""
<hr />
<hr />
"""
)
)

def test_not_hr_end_in_char(self):
self.assertMarkdownRenders(
'--------------------------------------c',

'<p>--------------------------------------c</p>'
)