Skip to content

Commit

Permalink
Fix XSS injection in image URLs (#603)
Browse files Browse the repository at this point in the history
  • Loading branch information
Crozzers committed Sep 22, 2024
1 parent 1e0fbf2 commit b633861
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
- [pull #590] Fix underscores within bold text getting emphasized (#589)
- [pull #591] Add Alerts extra
- [pull #595] Fix img alt text being processed as markdown (#594)
- [pull #604] Fix XSS injection in image URLs (#603)


## python-markdown2 2.5.0
Expand Down
25 changes: 20 additions & 5 deletions lib/markdown2.py
Original file line number Diff line number Diff line change
Expand Up @@ -1354,9 +1354,23 @@ def _is_comment(token):
is_html_markup = not is_html_markup
return ''.join(tokens)

def _unhash_html_spans(self, text: str) -> str:
for key, sanitized in list(self.html_spans.items()):
text = text.replace(key, sanitized)
def _unhash_html_spans(self, text: str, spans=True, code=False) -> str:
'''
Recursively unhash a block of text
Args:
spans: unhash anything from `self.html_spans`
code: unhash code blocks
'''
orig = ''
while text != orig:
if spans:
for key, sanitized in list(self.html_spans.items()):
text = text.replace(key, sanitized)
if code:
for code, key in list(self._code_table.items()):
text = text.replace(key, code)
orig = text
return text

def _sanitize_html(self, s: str) -> str:
Expand Down Expand Up @@ -1582,8 +1596,9 @@ def _do_links(self, text: str) -> str:

# We've got to encode these to avoid conflicting
# with italics/bold.
url = url.replace('*', self._escape_table['*']) \
.replace('_', self._escape_table['_'])
url = self._unhash_html_spans(url, code=True) \
.replace('*', self._escape_table['*']) \
.replace('_', self._escape_table['_'])
if title:
title_str = ' title="%s"' % (
_xml_escape_attr(title)
Expand Down
4 changes: 4 additions & 0 deletions test/tm-cases/issue603_xss.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<p><img src="code&gt;&quot; onerror=alert()//&lt;/code" alt="" /></p>

<p><img src="&quot; onerror=alert()//" alt="" />
<a href="#"></a></p>
1 change: 1 addition & 0 deletions test/tm-cases/issue603_xss.opts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"safe_mode": "escape"}
8 changes: 8 additions & 0 deletions test/tm-cases/issue603_xss.text
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
![](`" onerror=alert()//`)


![][XSS]
[][XSS]


[XSS]: " onerror=alert()//

0 comments on commit b633861

Please sign in to comment.