Skip to content

Commit

Permalink
Merge pull request #48 from edx/dsheraz/js_href
Browse files Browse the repository at this point in the history
Clean anchor tags to counter XSS
  • Loading branch information
DawoudSheraz authored Feb 11, 2019
2 parents ee9861e + 0904b14 commit ba76071
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 1 deletion.
1 change: 1 addition & 0 deletions wiki/core/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import markdown
import bleach


class ArticleMarkdown(markdown.Markdown):

def __init__(self, article, *args, **kwargs):
Expand Down
12 changes: 12 additions & 0 deletions wiki/core/extensions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from markdown.extensions import Extension

from .processors import AnchorTagProcessor


class AnchorTagExtension(Extension):
"""
Custom extension to register anchor tag processor with Markdown.
"""

def extendMarkdown(self, md, md_globals):
md.treeprocessors.add('AnchorTagProcessor', AnchorTagProcessor(md), '>inline')
19 changes: 19 additions & 0 deletions wiki/core/processors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from markdown.treeprocessors import Treeprocessor


class AnchorTagProcessor(Treeprocessor):
"""
Custom treeprocessor to process the anchor tags in the HTML tree
"""

def run(self, root):
anchor_tags = root.findall('.//a')
for a_tag in anchor_tags:
if not self.is_href_valid(a_tag.get('href')):
a_tag.set('href', '#')

def is_href_valid(self, value):
"""
After mark down, validate if the JS is present inside the value of anchor tag.
"""
return not value.lower().startswith('javascript:')
3 changes: 2 additions & 1 deletion wiki/models/article.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from wiki.conf import settings
from wiki.core import article_markdown, permissions
from wiki.core.extensions import AnchorTagExtension
from wiki.core.plugins import registry as plugin_registry
from wiki import managers
from mptt.models import MPTTModel
Expand Down Expand Up @@ -188,7 +189,7 @@ def render(self, preview_content=None):
else:
content = self.current_revision.content
extensions = plugin_registry.get_markdown_extensions()
extensions += settings.MARKDOWN_EXTENSIONS
extensions += settings.MARKDOWN_EXTENSIONS + [AnchorTagExtension()]
return mark_safe(article_markdown(content, self, extensions=extensions))


Expand Down

0 comments on commit ba76071

Please sign in to comment.