|
| 1 | +import re |
| 2 | +from xml.sax.saxutils import escape, unescape |
| 3 | +from tokenizer import HTMLTokenizer |
| 4 | + |
| 5 | +class HTMLSanitizer(HTMLTokenizer): |
| 6 | + """ sanitization of XHTML+MathML+SVG and of inline style attributes.""" |
| 7 | + |
| 8 | + acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'b', |
| 9 | + 'big', 'blockquote', 'br', 'button', 'caption', 'center', 'cite', |
| 10 | + 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', |
| 11 | + 'em', 'fieldset', 'font', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', |
| 12 | + 'hr', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'map', |
| 13 | + 'menu', 'ol', 'optgroup', 'option', 'p', 'pre', 'q', 's', 'samp', |
| 14 | + 'select', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table', |
| 15 | + 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'tr', 'tt', 'u', |
| 16 | + 'ul', 'var'] |
| 17 | + |
| 18 | + mathml_elements = ['maction', 'math', 'merror', 'mfrac', 'mi', |
| 19 | + 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', |
| 20 | + 'mprescripts', 'mroot', 'mrow', 'mspace', 'msqrt', 'mstyle', 'msub', |
| 21 | + 'msubsup', 'msup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', |
| 22 | + 'munderover', 'none'] |
| 23 | + |
| 24 | + svg_elements = ['a', 'animate', 'animateColor', 'animateMotion', |
| 25 | + 'animateTransform', 'circle', 'defs', 'desc', 'ellipse', 'font-face', |
| 26 | + 'font-face-name', 'font-face-src', 'g', 'glyph', 'hkern', 'image', |
| 27 | + 'linearGradient', 'line', 'marker', 'metadata', 'missing-glyph', |
| 28 | + 'mpath', 'path', 'polygon', 'polyline', 'radialGradient', 'rect', |
| 29 | + 'set', 'stop', 'svg', 'switch', 'text', 'title', 'tspan', 'use'] |
| 30 | + |
| 31 | + acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey', |
| 32 | + 'action', 'align', 'alt', 'axis', 'border', 'cellpadding', |
| 33 | + 'cellspacing', 'char', 'charoff', 'charset', 'checked', 'cite', 'class', |
| 34 | + 'clear', 'cols', 'colspan', 'color', 'compact', 'coords', 'datetime', |
| 35 | + 'dir', 'disabled', 'enctype', 'for', 'frame', 'headers', 'height', |
| 36 | + 'href', 'hreflang', 'hspace', 'id', 'ismap', 'label', 'lang', |
| 37 | + 'longdesc', 'maxlength', 'media', 'method', 'multiple', 'name', |
| 38 | + 'nohref', 'noshade', 'nowrap', 'prompt', 'readonly', 'rel', 'rev', |
| 39 | + 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size', |
| 40 | + 'span', 'src', 'start', 'style', 'summary', 'tabindex', 'target', |
| 41 | + 'title', 'type', 'usemap', 'valign', 'value', 'vspace', 'width', |
| 42 | + 'xml:lang'] |
| 43 | + |
| 44 | + mathml_attributes = ['actiontype', 'align', 'columnalign', 'columnalign', |
| 45 | + 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'depth', |
| 46 | + 'display', 'displaystyle', 'equalcolumns', 'equalrows', 'fence', |
| 47 | + 'fontstyle', 'fontweight', 'frame', 'height', 'linethickness', 'lspace', |
| 48 | + 'mathbackground', 'mathcolor', 'mathvariant', 'mathvariant', 'maxsize', |
| 49 | + 'minsize', 'other', 'rowalign', 'rowalign', 'rowalign', 'rowlines', |
| 50 | + 'rowspacing', 'rowspan', 'rspace', 'scriptlevel', 'selection', |
| 51 | + 'separator', 'stretchy', 'width', 'width', 'xlink:href', 'xlink:show', |
| 52 | + 'xlink:type', 'xmlns', 'xmlns:xlink'] |
| 53 | + |
| 54 | + svg_attributes = ['accent-height', 'accumulate', 'additive', 'alphabetic', |
| 55 | + 'arabic-form', 'ascent', 'attributeName', 'attributeType', |
| 56 | + 'baseProfile', 'bbox', 'begin', 'by', 'calcMode', 'cap-height', |
| 57 | + 'class', 'color', 'color-rendering', 'content', 'cx', 'cy', 'd', 'dx', |
| 58 | + 'dy', 'descent', 'display', 'dur', 'end', 'fill', 'fill-rule', |
| 59 | + 'font-family', 'font-size', 'font-stretch', 'font-style', |
| 60 | + 'font-variant', 'font-weight', 'from', 'fx', 'fy', 'g1', 'g2', |
| 61 | + 'glyph-name', 'gradientUnits', 'hanging', 'height', 'horiz-adv-x', |
| 62 | + 'horiz-origin-x', 'id', 'ideographic', 'k', 'keyPoints', |
| 63 | + 'keySplines', 'keyTimes', 'lang', 'marker-end', 'marker-mid', |
| 64 | + 'marker-start', 'markerHeight', 'markerUnits', 'markerWidth', |
| 65 | + 'mathematical', 'max', 'min', 'name', 'offset', 'opacity', 'orient', |
| 66 | + 'origin', 'overline-position', 'overline-thickness', 'panose-1', |
| 67 | + 'path', 'pathLength', 'points', 'preserveAspectRatio', 'r', 'refX', |
| 68 | + 'refY', 'repeatCount', 'repeatDur', 'requiredExtensions', |
| 69 | + 'requiredFeatures', 'restart', 'rotate', 'rx', 'ry', 'slope', |
| 70 | + 'stemh', 'stemv', 'stop-color', 'stop-opacity', |
| 71 | + 'strikethrough-position', 'strikethrough-thickness', 'stroke', |
| 72 | + 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', |
| 73 | + 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', |
| 74 | + 'stroke-width', 'systemLanguage', 'target', 'text-anchor', 'to', |
| 75 | + 'transform', 'type', 'u1', 'u2', 'underline-position', |
| 76 | + 'underline-thickness', 'unicode', 'unicode-range', 'units-per-em', |
| 77 | + 'values', 'version', 'viewBox', 'visibility', 'width', 'widths', 'x', |
| 78 | + 'x-height', 'x1', 'x2', 'xlink:actuate', 'xlink:arcrole', |
| 79 | + 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', |
| 80 | + 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'xmlns', |
| 81 | + 'xmlns:xlink', 'y', 'y1', 'y2', 'zoomAndPan'] |
| 82 | + |
| 83 | + attr_val_is_uri = ['href', 'src', 'cite', 'action', 'longdesc', |
| 84 | + 'xlink:href'] |
| 85 | + |
| 86 | + acceptable_css_properties = ['azimuth', 'background-color', |
| 87 | + 'border-bottom-color', 'border-collapse', 'border-color', |
| 88 | + 'border-left-color', 'border-right-color', 'border-top-color', 'clear', |
| 89 | + 'color', 'cursor', 'direction', 'display', 'elevation', 'float', 'font', |
| 90 | + 'font-family', 'font-size', 'font-style', 'font-variant', 'font-weight', |
| 91 | + 'height', 'letter-spacing', 'line-height', 'overflow', 'pause', |
| 92 | + 'pause-after', 'pause-before', 'pitch', 'pitch-range', 'richness', |
| 93 | + 'speak', 'speak-header', 'speak-numeral', 'speak-punctuation', |
| 94 | + 'speech-rate', 'stress', 'text-align', 'text-decoration', 'text-indent', |
| 95 | + 'unicode-bidi', 'vertical-align', 'voice-family', 'volume', |
| 96 | + 'white-space', 'width'] |
| 97 | + |
| 98 | + acceptable_css_keywords = ['auto', 'aqua', 'black', 'block', 'blue', |
| 99 | + 'bold', 'both', 'bottom', 'brown', 'center', 'collapse', 'dashed', |
| 100 | + 'dotted', 'fuchsia', 'gray', 'green', '!important', 'italic', 'left', |
| 101 | + 'lime', 'maroon', 'medium', 'none', 'navy', 'normal', 'nowrap', 'olive', |
| 102 | + 'pointer', 'purple', 'red', 'right', 'solid', 'silver', 'teal', 'top', |
| 103 | + 'transparent', 'underline', 'white', 'yellow'] |
| 104 | + |
| 105 | + acceptable_svg_properties = [ 'fill', 'fill-opacity', 'fill-rule', |
| 106 | + 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', |
| 107 | + 'stroke-opacity'] |
| 108 | + |
| 109 | + acceptable_protocols = [ 'ed2k', 'ftp', 'http', 'https', 'irc', |
| 110 | + 'mailto', 'news', 'gopher', 'nntp', 'telnet', 'webcal', |
| 111 | + 'xmpp', 'callto', 'feed', 'urn', 'aim', 'rsync', 'tag', |
| 112 | + 'ssh', 'sftp', 'rtsp', 'afs' ] |
| 113 | + |
| 114 | + # subclasses may define their own versions of these constants |
| 115 | + allowed_elements = acceptable_elements + mathml_elements + svg_elements |
| 116 | + allowed_attributes = acceptable_attributes + mathml_attributes + svg_attributes |
| 117 | + allowed_css_properties = acceptable_css_properties |
| 118 | + allowed_css_keywords = acceptable_css_keywords |
| 119 | + allowed_svg_properties = acceptable_svg_properties |
| 120 | + allowed_protocols = acceptable_protocols |
| 121 | + |
| 122 | + # Sanitize the +html+, escaping all elements not in ALLOWED_ELEMENTS, and |
| 123 | + # stripping out all # attributes not in ALLOWED_ATTRIBUTES. Style |
| 124 | + # attributes are parsed, and a restricted set, # specified by |
| 125 | + # ALLOWED_CSS_PROPERTIES and ALLOWED_CSS_KEYWORDS, are allowed through. |
| 126 | + # attributes in ATTR_VAL_IS_URI are scanned, and only URI schemes specified |
| 127 | + # in ALLOWED_PROTOCOLS are allowed. |
| 128 | + # |
| 129 | + # sanitize_html('<script> do_nasty_stuff() </script>') |
| 130 | + # => <script> do_nasty_stuff() </script> |
| 131 | + # sanitize_html('<a href="javascript: sucker();">Click here for $100</a>') |
| 132 | + # => <a>Click here for $100</a> |
| 133 | + def __iter__(self): |
| 134 | + for token in HTMLTokenizer.__iter__(self): |
| 135 | + if token["type"] in ["StartTag", "EndTag", "EmptyTag"]: |
| 136 | + if token["name"] in self.allowed_elements: |
| 137 | + if token.has_key("data"): |
| 138 | + attrs = dict([[name,val] for name,val in token["data"][::-1] if name in self.allowed_attributes]) |
| 139 | + for attr in self.attr_val_is_uri: |
| 140 | + if not attrs.has_key(attr): continue |
| 141 | + val_unescaped = re.sub("[\000-\040\177-\240\s]+", '', unescape(attrs[attr])).lower() |
| 142 | + if re.match("^[a-z0-9][-+.a-z0-9]*:",val_unescaped) and (val_unescaped.split(':')[0] not in self.allowed_protocols): |
| 143 | + del attrs[attr] |
| 144 | + if attrs.has_key('style'): |
| 145 | + attrs['style'] = self.sanitize_css(attrs['style']) |
| 146 | + token["data"] = attrs.items() |
| 147 | + yield token |
| 148 | + else: |
| 149 | + if token["type"] == "EndTag": |
| 150 | + token["data"] = "</%s>" % token["name"] |
| 151 | + elif token["data"]: |
| 152 | + attrs = ''.join([' %s="%s"' % (k,escape(v)) for k,v in token["data"]]) |
| 153 | + token["data"] = "<%s%s>" % (token["name"],attrs) |
| 154 | + else: |
| 155 | + token["data"] = "<%s>" % token["name"] |
| 156 | + if token["type"] == "EmptyTag": |
| 157 | + token["data"]=token["data"][:-1] + "/>" |
| 158 | + token["type"] = "Characters" |
| 159 | + del token["name"] |
| 160 | + yield token |
| 161 | + else: |
| 162 | + yield token |
| 163 | + |
| 164 | + def sanitize_css(self, style): |
| 165 | + # disallow urls |
| 166 | + style=re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ',style) |
| 167 | + | <
F438
/tr>
| 168 | + # gauntlet |
| 169 | + if not re.match("""^([:,;#%.\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'|"[\s\w]+"|\([\d,\s]+\))*$""", style): return '' |
| 170 | + if not re.match("^(\s*[-\w]+\s*:\s*[^:;]*(;|$))*$", style): return '' |
| 171 | + |
| 172 | + clean = [] |
| 173 | + for prop,value in re.findall("([-\w]+)\s*:\s*([^:;]*)",style): |
| 174 | + if not value: continue |
| 175 | + if prop.lower() in self.allowed_css_properties: |
| 176 | + clean.append(prop + ': ' + value + ';') |
| 177 | + elif prop.split('-')[0].lower() in ['background','border','margin','padding']: |
| 178 | + for keyword in value.split(): |
| 179 | + if not keyword in self.acceptable_css_keywords and \ |
| 180 | + 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): |
| 181 | + break |
| 182 | + else: |
| 183 | + clean.append(prop + ': ' + value + ';') |
| 184 | + elif prop.lower() in self.allowed_svg_properties: |
| 185 | + clean.append(prop + ': ' + value + ';') |
| 186 | + |
| 187 | + return ' '.join(clean) |
0 commit comments