PageRenderTime 69ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/pip/_vendor/html5lib/sanitizer.py

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