Files
@ e74aa69f6827
Branch filter:
Location: kallithea/kallithea/lib/markup_renderer.py
e74aa69f6827
8.4 KiB
text/x-python
lib: sanitize HTML for all types of README rendering, not only markdown
The repository summary page will display a rendered version of the
repository 'readme' based on its file extension. In commit 5746cc3b3fa5,
the rendered output was already sanitized when the input was markdown.
However, also readmes written in other formats, like ReStructuredText (RST)
or plain text could have content that we want sanitized.
Therefore, move the sanitizing one level up so it covers all renderers, for
now and the future.
This fixes an XSS issue when a repository readme contains javascript code,
which would be executed when the repository summary page is visited by a
user.
Reported by Bob Hogg <wombat@rwhogg.site> (thanks!).
The repository summary page will display a rendered version of the
repository 'readme' based on its file extension. In commit 5746cc3b3fa5,
the rendered output was already sanitized when the input was markdown.
However, also readmes written in other formats, like ReStructuredText (RST)
or plain text could have content that we want sanitized.
Therefore, move the sanitizing one level up so it covers all renderers, for
now and the future.
This fixes an XSS issue when a repository readme contains javascript code,
which would be executed when the repository summary page is visited by a
user.
Reported by Bob Hogg <wombat@rwhogg.site> (thanks!).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | # -*- coding: utf-8 -*-
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
kallithea.lib.markup_renderer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Renderer for markup languages with ability to parse using rst or markdown
This file was forked by the Kallithea project in July 2014.
Original author and date, and relevant copyright and licensing information is below:
:created_on: Oct 27, 2011
:author: marcink
:copyright: (c) 2013 RhodeCode GmbH, and others.
:license: GPLv3, see LICENSE.md for more details.
"""
import re
import logging
import traceback
import markdown as markdown_mod
import bleach
from kallithea.lib.utils2 import safe_unicode, MENTIONS_REGEX
log = logging.getLogger(__name__)
url_re = re.compile(r'''(\bhttps?://(?:[\da-zA-Z0-9@:.-]+)'''
r'''(?:[/a-zA-Z0-9_=@#~&+%.,:;?!*()-]*[/a-zA-Z0-9_=@#~])?)''')
class MarkupRenderer(object):
RESTRUCTUREDTEXT_DISALLOWED_DIRECTIVES = ['include', 'meta', 'raw']
MARKDOWN_PAT = re.compile(r'md|mkdn?|mdown|markdown', re.IGNORECASE)
RST_PAT = re.compile(r're?st', re.IGNORECASE)
PLAIN_PAT = re.compile(r'readme', re.IGNORECASE)
def _detect_renderer(self, source, filename=None):
"""
runs detection of what renderer should be used for generating html
from a markup language
filename can be also explicitly a renderer name
:param source:
:param filename:
"""
if MarkupRenderer.MARKDOWN_PAT.findall(filename):
detected_renderer = 'markdown'
elif MarkupRenderer.RST_PAT.findall(filename):
detected_renderer = 'rst'
elif MarkupRenderer.PLAIN_PAT.findall(filename):
detected_renderer = 'rst'
else:
detected_renderer = 'plain'
return getattr(MarkupRenderer, detected_renderer)
@classmethod
def _flavored_markdown(cls, text):
"""
Github style flavored markdown
:param text:
"""
from hashlib import md5
# Extract pre blocks.
extractions = {}
def pre_extraction_callback(matchobj):
digest = md5(matchobj.group(0)).hexdigest()
extractions[digest] = matchobj.group(0)
return "{gfm-extraction-%s}" % digest
pattern = re.compile(r'<pre>.*?</pre>', re.MULTILINE | re.DOTALL)
text = re.sub(pattern, pre_extraction_callback, text)
# Prevent foo_bar_baz from ending up with an italic word in the middle.
def italic_callback(matchobj):
s = matchobj.group(0)
if list(s).count('_') >= 2:
return s.replace('_', '\_')
return s
text = re.sub(r'^(?! {4}|\t)\w+_\w+_\w[\w_]*', italic_callback, text)
# In very clear cases, let newlines become <br /> tags.
def newline_callback(matchobj):
if len(matchobj.group(1)) == 1:
return matchobj.group(0).rstrip() + ' \n'
else:
return matchobj.group(0)
pattern = re.compile(r'^[\w\<][^\n]*(\n+)', re.MULTILINE)
text = re.sub(pattern, newline_callback, text)
# Insert pre block extractions.
def pre_insert_callback(matchobj):
return '\n\n' + extractions[matchobj.group(1)]
text = re.sub(r'{gfm-extraction-([0-9a-f]{32})\}',
pre_insert_callback, text)
return text
def render(self, source, filename=None):
"""
Renders a given filename using detected renderer
it detects renderers based on file extension or mimetype.
At last it will just do a simple html replacing new lines with <br/>
:param file_name:
:param source:
"""
renderer = self._detect_renderer(source, filename)
readme_data = renderer(source)
# Allow most HTML, while preventing XSS issues:
# no <script> tags, no onclick attributes, no javascript
# "protocol", and also limit styling to prevent defacing.
return bleach.clean(readme_data,
tags=['a', 'abbr', 'b', 'blockquote', 'br', 'code', 'dd',
'div', 'dl', 'dt', 'em', 'h1', 'h2', 'h3', 'h4', 'h5',
'h6', 'hr', 'i', 'img', 'li', 'ol', 'p', 'pre', 'span',
'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'th',
'thead', 'tr', 'ul'],
attributes=['class', 'id', 'style', 'label', 'title', 'alt', 'href', 'src'],
styles=['color'],
protocols=['http', 'https', 'mailto'],
)
@classmethod
def plain(cls, source, universal_newline=True):
source = safe_unicode(source)
if universal_newline:
newline = '\n'
source = newline.join(source.splitlines())
def url_func(match_obj):
url_full = match_obj.groups()[0]
return '<a href="%(url)s">%(url)s</a>' % ({'url': url_full})
source = url_re.sub(url_func, source)
return '<br />' + source.replace("\n", '<br />')
@classmethod
def markdown(cls, source, safe=True, flavored=False):
"""
Convert Markdown (possibly GitHub Flavored) to XSS safe HTML, possibly
with "safe" fall-back to plaintext.
>>> MarkupRenderer.markdown('''<img id="a" style="margin-top:-1000px;color:red" src="http://example.com/test.jpg">''')
u'<p><img id="a" src="http://example.com/test.jpg" style="color: red;"></p>'
>>> MarkupRenderer.markdown('''<img class="c d" src="file://localhost/test.jpg">''')
u'<p><img class="c d"></p>'
>>> MarkupRenderer.markdown('''<a href="foo">foo</a>''')
u'<p><a href="foo">foo</a></p>'
>>> MarkupRenderer.markdown('''<script>alert(1)</script>''')
u'<script>alert(1)</script>'
>>> MarkupRenderer.markdown('''<div onclick="alert(2)">yo</div>''')
u'<div>yo</div>'
>>> MarkupRenderer.markdown('''<a href="javascript:alert(3)">yo</a>''')
u'<p><a>yo</a></p>'
"""
source = safe_unicode(source)
try:
if flavored:
source = cls._flavored_markdown(source)
return markdown_mod.markdown(source, ['codehilite', 'extra'])
except Exception:
log.error(traceback.format_exc())
if safe:
log.debug('Falling back to render in plain mode')
return cls.plain(source)
else:
raise
@classmethod
def rst(cls, source, safe=True):
source = safe_unicode(source)
try:
from docutils.core import publish_parts
from docutils.parsers.rst import directives
docutils_settings = dict([(alias, None) for alias in
cls.RESTRUCTUREDTEXT_DISALLOWED_DIRECTIVES])
docutils_settings.update({'input_encoding': 'unicode',
'report_level': 4})
for k, v in docutils_settings.iteritems():
directives.register_directive(k, v)
parts = publish_parts(source=source,
writer_name="html4css1",
settings_overrides=docutils_settings)
return parts['html_title'] + parts["fragment"]
except ImportError:
log.warning('Install docutils to use this function')
return cls.plain(source)
except Exception:
log.error(traceback.format_exc())
if safe:
log.debug('Falling back to render in plain mode')
return cls.plain(source)
else:
raise
@classmethod
def rst_with_mentions(cls, source):
mention_pat = re.compile(MENTIONS_REGEX)
def wrapp(match_obj):
uname = match_obj.groups()[0]
return '\ **@%(uname)s**\ ' % {'uname': uname}
mention_hl = mention_pat.sub(wrapp, source).strip()
return cls.rst(mention_hl)
|