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