You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

300 lines
17 KiB

  1. from __future__ import absolute_import, division, unicode_literals
  2. import re
  3. from xml.sax.saxutils import escape, unescape
  4. from six.moves import urllib_parse as urlparse
  5. from .tokenizer import HTMLTokenizer
  6. from .constants import tokenTypes
  7. content_type_rgx = re.compile(r'''
  8. ^
  9. # Match a content type <application>/<type>
  10. (?P<content_type>[-a-zA-Z0-9.]+/[-a-zA-Z0-9.]+)
  11. # Match any character set and encoding
  12. (?:(?:;charset=(?:[-a-zA-Z0-9]+)(?:;(?:base64))?)
  13. |(?:;(?:base64))?(?:;charset=(?:[-a-zA-Z0-9]+))?)
  14. # Assume the rest is data
  15. ,.*
  16. $
  17. ''',
  18. re.VERBOSE)
  19. class HTMLSanitizerMixin(object):
  20. """ sanitization of XHTML+MathML+SVG and of inline style attributes."""
  21. acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area',
  22. 'article', 'aside', 'audio', 'b', 'big', 'blockquote', 'br', 'button',
  23. 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup',
  24. 'command', 'datagrid', 'datalist', 'dd', 'del', 'details', 'dfn',
  25. 'dialog', 'dir', 'div', 'dl', 'dt', 'em', 'event-source', 'fieldset',
  26. 'figcaption', 'figure', 'footer', 'font', 'form', 'header', 'h1',
  27. 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'input', 'ins',
  28. 'keygen', 'kbd', 'label', 'legend', 'li', 'm', 'map', 'menu', 'meter',
  29. 'multicol', 'nav', 'nextid', 'ol', 'output', 'optgroup', 'option',
  30. 'p', 'pre', 'progress', 'q', 's', 'samp', 'section', 'select',
  31. 'small', 'sound', 'source', 'spacer', 'span', 'strike', 'strong',
  32. 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'time', 'tfoot',
  33. 'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var', 'video']
  34. mathml_elements = ['maction', 'math', 'merror', 'mfrac', 'mi',
  35. 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom',
  36. 'mprescripts', 'mroot', 'mrow', 'mspace', 'msqrt', 'mstyle', 'msub',
  37. 'msubsup', 'msup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder',
  38. 'munderover', 'none']
  39. svg_elements = ['a', 'animate', 'animateColor', 'animateMotion',
  40. 'animateTransform', 'clipPath', 'circle', 'defs', 'desc', 'ellipse',
  41. 'font-face', 'font-face-name', 'font-face-src', 'g', 'glyph', 'hkern',
  42. 'linearGradient', 'line', 'marker', 'metadata', 'missing-glyph',
  43. 'mpath', 'path', 'polygon', 'polyline', 'radialGradient', 'rect',
  44. 'set', 'stop', 'svg', 'switch', 'text', 'title', 'tspan', 'use']
  45. acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey',
  46. 'action', 'align', 'alt', 'autocomplete', 'autofocus', 'axis',
  47. 'background', 'balance', 'bgcolor', 'bgproperties', 'border',
  48. 'bordercolor', 'bordercolordark', 'bordercolorlight', 'bottompadding',
  49. 'cellpadding', 'cellspacing', 'ch', 'challenge', 'char', 'charoff',
  50. 'choff', 'charset', 'checked', 'cite', 'class', 'clear', 'color',
  51. 'cols', 'colspan', 'compact', 'contenteditable', 'controls', 'coords',
  52. 'data', 'datafld', 'datapagesize', 'datasrc', 'datetime', 'default',
  53. 'delay', 'dir', 'disabled', 'draggable', 'dynsrc', 'enctype', 'end',
  54. 'face', 'for', 'form', 'frame', 'galleryimg', 'gutter', 'headers',
  55. 'height', 'hidefocus', 'hidden', 'high', 'href', 'hreflang', 'hspace',
  56. 'icon', 'id', 'inputmode', 'ismap', 'keytype', 'label', 'leftspacing',
  57. 'lang', 'list', 'longdesc', 'loop', 'loopcount', 'loopend',
  58. 'loopstart', 'low', 'lowsrc', 'max', 'maxlength', 'media', 'method',
  59. 'min', 'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'open',
  60. 'optimum', 'pattern', 'ping', 'point-size', 'poster', 'pqg', 'preload',
  61. 'prompt', 'radiogroup', 'readonly', 'rel', 'repeat-max', 'repeat-min',
  62. 'replace', 'required', 'rev', 'rightspacing', 'rows', 'rowspan',
  63. 'rules', 'scope', 'selected', 'shape', 'size', 'span', 'src', 'start',
  64. 'step', 'style', 'summary', 'suppress', 'tabindex', 'target',
  65. 'template', 'title', 'toppadding', 'type', 'unselectable', 'usemap',
  66. 'urn', 'valign', 'value', 'variable', 'volume', 'vspace', 'vrml',
  67. 'width', 'wrap', 'xml:lang']
  68. mathml_attributes = ['actiontype', 'align', 'columnalign', 'columnalign',
  69. 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'depth',
  70. 'display', 'displaystyle', 'equalcolumns', 'equalrows', 'fence',
  71. 'fontstyle', 'fontweight', 'frame', 'height', 'linethickness', 'lspace',
  72. 'mathbackground', 'mathcolor', 'mathvariant', 'mathvariant', 'maxsize',
  73. 'minsize', 'other', 'rowalign', 'rowalign', 'rowalign', 'rowlines',
  74. 'rowspacing', 'rowspan', 'rspace', 'scriptlevel', 'selection',
  75. 'separator', 'stretchy', 'width', 'width', 'xlink:href', 'xlink:show',
  76. 'xlink:type', 'xmlns', 'xmlns:xlink']
  77. svg_attributes = ['accent-height', 'accumulate', 'additive', 'alphabetic',
  78. 'arabic-form', 'ascent', 'attributeName', 'attributeType',
  79. 'baseProfile', 'bbox', 'begin', 'by', 'calcMode', 'cap-height',
  80. 'class', 'clip-path', 'color', 'color-rendering', 'content', 'cx',
  81. 'cy', 'd', 'dx', 'dy', 'descent', 'display', 'dur', 'end', 'fill',
  82. 'fill-opacity', 'fill-rule', 'font-family', 'font-size',
  83. 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'from',
  84. 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'gradientUnits', 'hanging',
  85. 'height', 'horiz-adv-x', 'horiz-origin-x', 'id', 'ideographic', 'k',
  86. 'keyPoints', 'keySplines', 'keyTimes', 'lang', 'marker-end',
  87. 'marker-mid', 'marker-start', 'markerHeight', 'markerUnits',
  88. 'markerWidth', 'mathematical', 'max', 'min', 'name', 'offset',
  89. 'opacity', 'orient', 'origin', 'overline-position',
  90. 'overline-thickness', 'panose-1', 'path', 'pathLength', 'points',
  91. 'preserveAspectRatio', 'r', 'refX', 'refY', 'repeatCount',
  92. 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart',
  93. 'rotate', 'rx', 'ry', 'slope', 'stemh', 'stemv', 'stop-color',
  94. 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness',
  95. 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap',
  96. 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity',
  97. 'stroke-width', 'systemLanguage', 'target', 'text-anchor', 'to',
  98. 'transform', 'type', 'u1', 'u2', 'underline-position',
  99. 'underline-thickness', 'unicode', 'unicode-range', 'units-per-em',
  100. 'values', 'version', 'viewBox', 'visibility', 'width', 'widths', 'x',
  101. 'x-height', 'x1', 'x2', 'xlink:actuate', 'xlink:arcrole',
  102. 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type',
  103. 'xml:base', 'xml:lang', 'xml:space', 'xmlns', 'xmlns:xlink', 'y',
  104. 'y1', 'y2', 'zoomAndPan']
  105. attr_val_is_uri = ['href', 'src', 'cite', 'action', 'longdesc', 'poster', 'background', 'datasrc',
  106. 'dynsrc', 'lowsrc', 'ping', 'poster', 'xlink:href', 'xml:base']
  107. svg_attr_val_allows_ref = ['clip-path', 'color-profile', 'cursor', 'fill',
  108. 'filter', 'marker', 'marker-start', 'marker-mid', 'marker-end',
  109. 'mask', 'stroke']
  110. svg_allow_local_href = ['altGlyph', 'animate', 'animateColor',
  111. 'animateMotion', 'animateTransform', 'cursor', 'feImage', 'filter',
  112. 'linearGradient', 'pattern', 'radialGradient', 'textpath', 'tref',
  113. 'set', 'use']
  114. acceptable_css_properties = ['azimuth', 'background-color',
  115. 'border-bottom-color', 'border-collapse', 'border-color',
  116. 'border-left-color', 'border-right-color', 'border-top-color', 'clear',
  117. 'color', 'cursor', 'direction', 'display', 'elevation', 'float', 'font',
  118. 'font-family', 'font-size', 'font-style', 'font-variant', 'font-weight',
  119. 'height', 'letter-spacing', 'line-height', 'overflow', 'pause',
  120. 'pause-after', 'pause-before', 'pitch', 'pitch-range', 'richness',
  121. 'speak', 'speak-header', 'speak-numeral', 'speak-punctuation',
  122. 'speech-rate', 'stress', 'text-align', 'text-decoration', 'text-indent',
  123. 'unicode-bidi', 'vertical-align', 'voice-family', 'volume',
  124. 'white-space', 'width']
  125. acceptable_css_keywords = ['auto', 'aqua', 'black', 'block', 'blue',
  126. 'bold', 'both', 'bottom', 'brown', 'center', 'collapse', 'dashed',
  127. 'dotted', 'fuchsia', 'gray', 'green', '!important', 'italic', 'left',
  128. 'lime', 'maroon', 'medium', 'none', 'navy', 'normal', 'nowrap', 'olive',
  129. 'pointer', 'purple', 'red', 'right', 'solid', 'silver', 'teal', 'top',
  130. 'transparent', 'underline', 'white', 'yellow']
  131. acceptable_svg_properties = ['fill', 'fill-opacity', 'fill-rule',
  132. 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
  133. 'stroke-opacity']
  134. acceptable_protocols = ['ed2k', 'ftp', 'http', 'https', 'irc',
  135. 'mailto', 'news', 'gopher', 'nntp', 'telnet', 'webcal',
  136. 'xmpp', 'callto', 'feed', 'urn', 'aim', 'rsync', 'tag',
  137. 'ssh', 'sftp', 'rtsp', 'afs', 'data']
  138. acceptable_content_types = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'text/plain']
  139. # subclasses may define their own versions of these constants
  140. allowed_elements = acceptable_elements + mathml_elements + svg_elements
  141. allowed_attributes = acceptable_attributes + mathml_attributes + svg_attributes
  142. allowed_css_properties = acceptable_css_properties
  143. allowed_css_keywords = acceptable_css_keywords
  144. allowed_svg_properties = acceptable_svg_properties
  145. allowed_protocols = acceptable_protocols
  146. allowed_content_types = acceptable_content_types
  147. # Sanitize the +html+, escaping all elements not in ALLOWED_ELEMENTS, and
  148. # stripping out all # attributes not in ALLOWED_ATTRIBUTES. Style
  149. # attributes are parsed, and a restricted set, # specified by
  150. # ALLOWED_CSS_PROPERTIES and ALLOWED_CSS_KEYWORDS, are allowed through.
  151. # attributes in ATTR_VAL_IS_URI are scanned, and only URI schemes specified
  152. # in ALLOWED_PROTOCOLS are allowed.
  153. #
  154. # sanitize_html('<script> do_nasty_stuff() </script>')
  155. # => &lt;script> do_nasty_stuff() &lt;/script>
  156. # sanitize_html('<a href="javascript: sucker();">Click here for $100</a>')
  157. # => <a>Click here for $100</a>
  158. def sanitize_token(self, token):
  159. # accommodate filters which use token_type differently
  160. token_type = token["type"]
  161. if token_type in list(tokenTypes.keys()):
  162. token_type = tokenTypes[token_type]
  163. if token_type in (tokenTypes["StartTag"], tokenTypes["EndTag"],
  164. tokenTypes["EmptyTag"]):
  165. if token["name"] in self.allowed_elements:
  166. return self.allowed_token(token, token_type)
  167. else:
  168. return self.disallowed_token(token, token_type)
  169. elif token_type == tokenTypes["Comment"]:
  170. pass
  171. else:
  172. return token
  173. def allowed_token(self, token, token_type):
  174. if "data" in token:
  175. attrs = dict([(name, val) for name, val in
  176. token["data"][::-1]
  177. if name in self.allowed_attributes])
  178. for attr in self.attr_val_is_uri:
  179. if attr not in attrs:
  180. continue
  181. val_unescaped = re.sub("[`\000-\040\177-\240\s]+", '',
  182. unescape(attrs[attr])).lower()
  183. # remove replacement characters from unescaped characters
  184. val_unescaped = val_unescaped.replace("\ufffd", "")
  185. try:
  186. uri = urlparse.urlparse(val_unescaped)
  187. except ValueError:
  188. uri = None
  189. del attrs[attr]
  190. if uri and uri.scheme:
  191. if uri.scheme not in self.allowed_protocols:
  192. del attrs[attr]
  193. if uri.scheme == 'data':
  194. m = content_type_rgx.match(uri.path)
  195. if not m:
  196. del attrs[attr]
  197. elif m.group('content_type') not in self.allowed_content_types:
  198. del attrs[attr]
  199. for attr in self.svg_attr_val_allows_ref:
  200. if attr in attrs:
  201. attrs[attr] = re.sub(r'url\s*\(\s*[^#\s][^)]+?\)',
  202. ' ',
  203. unescape(attrs[attr]))
  204. if (token["name"] in self.svg_allow_local_href and
  205. 'xlink:href' in attrs and re.search('^\s*[^#\s].*',
  206. attrs['xlink:href'])):
  207. del attrs['xlink:href']
  208. if 'style' in attrs:
  209. attrs['style'] = self.sanitize_css(attrs['style'])
  210. token["data"] = [[name, val] for name, val in list(attrs.items())]
  211. return token
  212. def disallowed_token(self, token, token_type):
  213. if token_type == tokenTypes["EndTag"]:
  214. token["data"] = "</%s>" % token["name"]
  215. elif token["data"]:
  216. attrs = ''.join([' %s="%s"' % (k, escape(v)) for k, v in token["data"]])
  217. token["data"] = "<%s%s>" % (token["name"], attrs)
  218. else:
  219. token["data"] = "<%s>" % token["name"]
  220. if token.get("selfClosing"):
  221. token["data"] = token["data"][:-1] + "/>"
  222. if token["type"] in list(tokenTypes.keys()):
  223. token["type"] = "Characters"
  224. else:
  225. token["type"] = tokenTypes["Characters"]
  226. del token["name"]
  227. return token
  228. def sanitize_css(self, style):
  229. # disallow urls
  230. style = re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ', style)
  231. # gauntlet
  232. if not re.match("""^([:,;#%.\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'|"[\s\w]+"|\([\d,\s]+\))*$""", style):
  233. return ''
  234. if not re.match("^\s*([-\w]+\s*:[^:;]*(;\s*|$))*$", style):
  235. return ''
  236. clean = []
  237. for prop, value in re.findall("([-\w]+)\s*:\s*([^:;]*)", style):
  238. if not value:
  239. continue
  240. if prop.lower() in self.allowed_css_properties:
  241. clean.append(prop + ': ' + value + ';')
  242. elif prop.split('-')[0].lower() in ['background', 'border', 'margin',
  243. 'padding']:
  244. for keyword in value.split():
  245. if keyword not in self.acceptable_css_keywords and \
  246. not re.match("^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$", keyword):
  247. break
  248. else:
  249. clean.append(prop + ': ' + value + ';')
  250. elif prop.lower() in self.allowed_svg_properties:
  251. clean.append(prop + ': ' + value + ';')
  252. return ' '.join(clean)
  253. class HTMLSanitizer(HTMLTokenizer, HTMLSanitizerMixin):
  254. def __init__(self, stream, encoding=None, parseMeta=True, useChardet=True,
  255. lowercaseElementName=False, lowercaseAttrName=False, parser=None):
  256. # Change case matching defaults as we only output lowercase html anyway
  257. # This solution doesn't seem ideal...
  258. HTMLTokenizer.__init__(self, stream, encoding, parseMeta, useChardet,
  259. lowercaseElementName, lowercaseAttrName, parser=parser)
  260. def __iter__(self):
  261. for token in HTMLTokenizer.__iter__(self):
  262. token = self.sanitize_token(token)
  263. if token:
  264. yield token