8000 Python sanitizer · awesome-python/html5lib-python@03459af · GitHub
[go: up one dir, main page]

Skip to content

Commit 03459af

Browse files
committed
Python sanitizer
--HG-- extra : convert_revision : svn%3Aacbfec75-9323-0410-a652-858a13e371e0/trunk%40606
1 parent d071325 commit 03459af

File tree

4 files changed

+414
-40
lines changed

4 files changed

+414
-40
lines changed

src/html5parser.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ class HTMLParser(object):
3737
"""HTML parser. Generates a tree structure from a stream of (possibly
3838
malformed) HTML"""
3939

40-
def __init__(self, strict = False, tree=simpletree.TreeBuilder):
40+
def __init__(self, strict = False, tree=simpletree.TreeBuilder, tokenizer=tokenizer.HTMLTokenizer):
4141
"""
4242
strict - raise an exception when a parse error is encountered
4343
@@ -50,6 +50,7 @@ def __init__(self, strict = False, tree=simpletree.TreeBuilder):
5050
self.strict = strict
5151

5252
self.tree = tree()
53+
self.tokenizer_class = tokenizer
5354
self.errors = []
5455

5556
self.phases = {
@@ -79,8 +80,8 @@ def _parse(self, stream, innerHTML=False, container="div",
7980
self.firstStartTag = False
8081
self.errors = []
8182

82-
self.tokenizer = tokenizer.HTMLTokenizer(stream, encoding,
83-
parseMeta=innerHTML)
83+
self.tokenizer = self.tokenizer_class(stream, encoding,
84+
parseMeta=innerHTML)
8485

8586
if innerHTML:
8687
self.innerHTML = container.lower()

src/sanitizer.py

Lines changed: 187 additions & 0 deletions
< F438 /tr>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
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+
# => &lt;script> do_nasty_stuff() &lt;/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+
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)

tests/test_parser.py

Lines changed: 35 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -113,49 +113,47 @@ def sortattrs(x):
113113
return "\n".join(lines)
114114

115115
class TestCase(unittest.TestCase):
116-
def runParserTest(self, innerHTML, input, expected, errors):
117-
for treeName, treeClass in treeTypes.iteritems():
118-
#XXX - move this out into the setup function
119-
#concatenate all consecutive character tokens into a single token
120-
p = html5parser.HTMLParser(tree = treeClass)
121-
if innerHTML:
122-
document = p.parseFragment(StringIO.StringIO(input), innerHTML)
123-
else:
124-
document = p.parse(StringIO.StringIO(input))
125-
output = convertTreeDump(p.tree.testSerializer(document))
126-
output = attrlist.sub(sortattrs, output)
127-
expected = attrlist.sub(sortattrs, expected)
128-
errorMsg = "\n".join(["\n\nTree:", treeName,
129-
"\nExpected:", expected,
130-
"\nRecieved:", output])
131-
self.assertEquals(expected, output, errorMsg)
132-
errStr = ["Line: %i Col: %i %s"%(line, col, message) for
133-
((line,col), message) in p.errors]
134-
errorMsg2 = "\n".join(["\n\nInput errors:\n" + "\n".join(errors),
135-
"Actual errors:\n" + "\n".join(errStr)])
136-
if checkParseErrors:
137-
self.assertEquals(len(p.errors), len(errors), errorMsg2)
138-
116+
def runParserTest(self, innerHTML, input, expected, errors, treeClass):
117+
#XXX - move this out into the setup function
118+
#concatenate all consecutive character tokens into a single token
119+
p = html5parser.HTMLParser(tree = treeClass)
120+
if innerHTML:
121+
document = p.parseFragment(StringIO.StringIO(input), innerHTML)
122+
else:
123+
document = p.parse(StringIO.StringIO(input))
124+
output = convertTreeDump(p.tree.testSerializer(document))
125+
output = attrlist.sub(sortattrs, output)
126+
expected = attrlist.sub(sortattrs, expected)
127+
errorMsg = "\n".join(["\n\nExpected:", expected,
128+
"\nRecieved:", output])
129+
self.assertEquals(expected, output, errorMsg)
130+
errStr = ["Line: %i Col: %i %s"%(line, col, message) for
131+
((line,col), message) in p.errors]
132+
errorMsg2 = "\n".join(["\n\nInput errors:\n" + "\n".join(errors),
133+
"Actual errors:\n" + "\n".join(errStr)])
134+
if checkParseErrors:
135+
self.assertEquals(len(p.errors), len(errors), errorMsg2)
136+
139137
def test_parser():
140-
for filename in glob.glob('tree-construction/*.dat'):
141-
f = open(filename)
142-
tests = f.read().split("#data\n")
143-
for test in tests:
144-
if test == "":
145-
continue
146-
test = "#data\n" + test
147-
innerHTML, input, expected, errors = parseTestcase(test)
148-
yield TestCase.runParserTest, innerHTML, input, expected, errors
138+
for name, cls in treeTypes.iteritems():
139+
for filename in glob.glob('tree-construction/*.dat'):
140+
f = open(filename)
141+
tests = f.read().split("#data\n")
142+
for test in tests:
143+
if test == "":
144+
continue
145+
test = "#data\n" + test
146+
innerHTML, input, expected, errors = parseTestcase(test)
147+
yield TestCase.runParserTest, innerHTML, input, expected, errors, name, cls
149148

150149
def buildTestSuite():
151150
tests = 0
152-
for func, innerHTML, input, expected, errors in test_parser():
151+
for func, innerHTML, input, expected, errors, treeName, treeCls in test_parser():
153152
tests += 1
154153
testName = 'test%d' % tests
155-
testFunc = lambda self, method=func, innerHTML=innerHTML, input=input, \
156-
expected=expected, errors=errors: \
157-
method(self, innerHTML, input, expected, errors)
158-
testFunc.__doc__ = 'Parser %s Input: %s'%(testName, input)
154+
testFunc = lambda self, method=func, innerHTML=innerHTML, input=input, expected=expected, \
155+
errors=errors, treeCls=treeCls: method(self, innerHTML, input, expected, errors, treeCls)
156+
testFunc.__doc__ = 'Parser %s Tree %s Input: %s'%(testName, treeName, input)
159157
instanceMethod = new.instancemethod(testFunc, None, TestCase)
160158
setattr(TestCase, testName, instanceMethod)
161159
return unittest.TestLoader().loadTestsFromTestCase(TestCase)

0 commit comments

Comments
 (0)
0