Edgewall Software

source: trunk/genshi/filters/html.py

Last change on this file was 1175, checked in by hodgestar, 12 years ago

Revert accidental small docstring change from r1174.

  • Property svn:eol-style set to native
File size: 22.3 KB
RevLine 
[2]1# -*- coding: utf-8 -*-
2#
[1077]3# Copyright (C) 2006-2009 Edgewall Software
[2]4# All rights reserved.
5#
6# This software is licensed as described in the file COPYING, which
7# you should have received as part of this distribution. The terms
[287]8# are also available at http://genshi.edgewall.org/wiki/License.
[2]9#
10# This software consists of voluntary contributions made by many
11# individuals. For the exact contribution history, see the revision
[287]12# history and logs, available at http://genshi.edgewall.org/log/.
[2]13
14"""Implementation of a number of stream filters."""
15
[1079]16try:
17    any
18except NameError:
19    from genshi.util import any
[2]20import re
21
[495]22from genshi.core import Attrs, QName, stripentities
[682]23from genshi.core import END, START, TEXT, COMMENT
[2]24
[443]25__all__ = ['HTMLFormFiller', 'HTMLSanitizer']
[517]26__docformat__ = 'restructuredtext en'
[2]27
28
[340]29class HTMLFormFiller(object):
30    """A stream filter that can populate HTML forms from a dictionary of values.
31   
32    >>> from genshi.input import HTML
33    >>> html = HTML('''<form>
34    ...   <p><input type="text" name="foo" /></p>
[1158]35    ... </form>''', encoding='utf-8')
[340]36    >>> filler = HTMLFormFiller(data={'foo': 'bar'})
[1076]37    >>> print(html | filler)
[340]38    <form>
39      <p><input type="text" name="foo" value="bar"/></p>
40    </form>
41    """
42    # TODO: only select the first radio button, and the first select option
43    #       (if not in a multiple-select)
44    # TODO: only apply to elements in the XHTML namespace (or no namespace)?
45
[1050]46    def __init__(self, name=None, id=None, data=None, passwords=False):
[340]47        """Create the filter.
48       
[517]49        :param name: The name of the form that should be populated. If this
50                     parameter is given, only forms where the ``name`` attribute
51                     value matches the parameter are processed.
52        :param id: The ID of the form that should be populated. If this
53                   parameter is given, only forms where the ``id`` attribute
54                   value matches the parameter are processed.
55        :param data: The dictionary of form values, where the keys are the names
56                     of the form fields, and the values are the values to fill
57                     in.
[1050]58        :param passwords: Whether password input fields should be populated.
59                          This is off by default for security reasons (for
60                          example, a password may end up in the browser cache)
61        :note: Changed in 0.5.2: added the `passwords` option
[340]62        """
63        self.name = name
64        self.id = id
65        if data is None:
66            data = {}
67        self.data = data
[1050]68        self.passwords = passwords
[340]69
[531]70    def __call__(self, stream):
[342]71        """Apply the filter to the given stream.
72       
[517]73        :param stream: the markup event stream to filter
[342]74        """
[340]75        in_form = in_select = in_option = in_textarea = False
76        select_value = option_value = textarea_value = None
[698]77        option_start = None
78        option_text = []
79        no_option_value = False
[340]80
81        for kind, data, pos in stream:
82
83            if kind is START:
[424]84                tag, attrs = data
[340]85                tagname = tag.localname
86
87                if tagname == 'form' and (
[424]88                        self.name and attrs.get('name') == self.name or
89                        self.id and attrs.get('id') == self.id or
[340]90                        not (self.id or self.name)):
91                    in_form = True
92
93                elif in_form:
94                    if tagname == 'input':
[1063]95                        type = attrs.get('type', '').lower()
[340]96                        if type in ('checkbox', 'radio'):
[424]97                            name = attrs.get('name')
[571]98                            if name and name in self.data:
99                                value = self.data[name]
[424]100                                declval = attrs.get('value')
[340]101                                checked = False
102                                if isinstance(value, (list, tuple)):
[1134]103                                    if declval is not None:
[698]104                                        checked = declval in [unicode(v) for v
[507]105                                                              in value]
[340]106                                    else:
[1079]107                                        checked = any(value)
[340]108                                else:
[1134]109                                    if declval is not None:
[698]110                                        checked = declval == unicode(value)
[340]111                                    elif type == 'checkbox':
112                                        checked = bool(value)
113                                if checked:
[495]114                                    attrs |= [(QName('checked'), 'checked')]
[424]115                                elif 'checked' in attrs:
116                                    attrs -= 'checked'
[1063]117                        elif type in ('', 'hidden', 'text') \
[1050]118                                or type == 'password' and self.passwords:
[424]119                            name = attrs.get('name')
[571]120                            if name and name in self.data:
121                                value = self.data[name]
[340]122                                if isinstance(value, (list, tuple)):
123                                    value = value[0]
124                                if value is not None:
[1050]125                                    attrs |= [
126                                        (QName('value'), unicode(value))
127                                    ]
[340]128                    elif tagname == 'select':
[424]129                        name = attrs.get('name')
[571]130                        if name in self.data:
131                            select_value = self.data[name]
132                            in_select = True
[340]133                    elif tagname == 'textarea':
[424]134                        name = attrs.get('name')
[571]135                        if name in self.data:
136                            textarea_value = self.data.get(name)
137                            if isinstance(textarea_value, (list, tuple)):
138                                textarea_value = textarea_value[0]
139                            in_textarea = True
[340]140                    elif in_select and tagname == 'option':
141                        option_start = kind, data, pos
[424]142                        option_value = attrs.get('value')
[698]143                        if option_value is None:
144                            no_option_value = True
145                            option_value = ''
[340]146                        in_option = True
147                        continue
[424]148                yield kind, (tag, attrs), pos
[340]149
150            elif in_form and kind is TEXT:
151                if in_select and in_option:
[698]152                    if no_option_value:
153                        option_value += data
154                    option_text.append((kind, data, pos))
[340]155                    continue
156                elif in_textarea:
157                    continue
[424]158                yield kind, data, pos
[340]159
160            elif in_form and kind is END:
161                tagname = data.localname
162                if tagname == 'form':
163                    in_form = False
164                elif tagname == 'select':
165                    in_select = False
166                    select_value = None
167                elif in_select and tagname == 'option':
168                    if isinstance(select_value, (tuple, list)):
[698]169                        selected = option_value in [unicode(v) for v
[507]170                                                    in select_value]
[340]171                    else:
[698]172                        selected = option_value == unicode(select_value)
[424]173                    okind, (tag, attrs), opos = option_start
[340]174                    if selected:
[495]175                        attrs |= [(QName('selected'), 'selected')]
[424]176                    elif 'selected' in attrs:
177                        attrs -= 'selected'
178                    yield okind, (tag, attrs), opos
[340]179                    if option_text:
[698]180                        for event in option_text:
181                            yield event
[340]182                    in_option = False
[698]183                    no_option_value = False
184                    option_start = option_value = None
185                    option_text = []
[1133]186                elif in_textarea and tagname == 'textarea':
[340]187                    if textarea_value:
188                        yield TEXT, unicode(textarea_value), pos
[1133]189                        textarea_value = None
[340]190                    in_textarea = False
[424]191                yield kind, data, pos
[340]192
[424]193            else:
194                yield kind, data, pos
[340]195
196
[2]197class HTMLSanitizer(object):
198    """A filter that removes potentially dangerous HTML tags and attributes
199    from the stream.
[523]200   
201    >>> from genshi import HTML
[1158]202    >>> html = HTML('<div><script>alert(document.cookie)</script></div>', encoding='utf-8')
[1076]203    >>> print(html | HTMLSanitizer())
[523]204    <div/>
205   
206    The default set of safe tags and attributes can be modified when the filter
207    is instantiated. For example, to allow inline ``style`` attributes, the
208    following instantation would work:
209   
[1158]210    >>> html = HTML('<div style="background: #000"></div>', encoding='utf-8')
[523]211    >>> sanitizer = HTMLSanitizer(safe_attrs=HTMLSanitizer.SAFE_ATTRS | set(['style']))
[1076]212    >>> print(html | sanitizer)
[523]213    <div style="background: #000"/>
214   
215    Note that even in this case, the filter *does* attempt to remove dangerous
216    constructs from style attributes:
217
[1158]218    >>> html = HTML('<div style="background: url(javascript:void); color: #000"></div>', encoding='utf-8')
[1076]219    >>> print(html | sanitizer)
[523]220    <div style="color: #000"/>
221   
222    This handles HTML entities, unicode escapes in CSS and Javascript text, as
223    well as a lot of other things. However, the style tag is still excluded by
224    default because it is very hard for such sanitizing to be completely safe,
225    especially considering how much error recovery current web browsers perform.
[682]226   
[1049]227    It also does some basic filtering of CSS properties that may be used for
228    typical phishing attacks. For more sophisticated filtering, this class
229    provides a couple of hooks that can be overridden in sub-classes.
230   
[682]231    :warn: Note that this special processing of CSS is currently only applied to
232           style attributes, **not** style elements.
[1175]233    """
[2]234
[342]235    SAFE_TAGS = frozenset(['a', 'abbr', 'acronym', 'address', 'area', 'b',
[2]236        'big', 'blockquote', 'br', 'button', 'caption', 'center', 'cite',
237        'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt',
238        'em', 'fieldset', 'font', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
239        'hr', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'map',
240        'menu', 'ol', 'optgroup', 'option', 'p', 'pre', 'q', 's', 'samp',
241        'select', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table',
242        'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'tr', 'tt', 'u',
243        'ul', 'var'])
244
[342]245    SAFE_ATTRS = frozenset(['abbr', 'accept', 'accept-charset', 'accesskey',
[16]246        'action', 'align', 'alt', 'axis', 'bgcolor', 'border', 'cellpadding',
[2]247        'cellspacing', 'char', 'charoff', 'charset', 'checked', 'cite', 'class',
248        'clear', 'cols', 'colspan', 'color', 'compact', 'coords', 'datetime',
249        'dir', 'disabled', 'enctype', 'for', 'frame', 'headers', 'height',
250        'href', 'hreflang', 'hspace', 'id', 'ismap', 'label', 'lang',
251        'longdesc', 'maxlength', 'media', 'method', 'multiple', 'name',
252        'nohref', 'noshade', 'nowrap', 'prompt', 'readonly', 'rel', 'rev',
253        'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size',
[523]254        'span', 'src', 'start', 'summary', 'tabindex', 'target', 'title',
255        'type', 'usemap', 'valign', 'value', 'vspace', 'width'])
[342]256
[1174]257    SAFE_CSS = frozenset([
258        # CSS 3 properties <http://www.w3.org/TR/CSS/#properties>
259        'background', 'background-attachment', 'background-color',
260        'background-image', 'background-position', 'background-repeat',
261        'border', 'border-bottom', 'border-bottom-color',
262        'border-bottom-style', 'border-bottom-width', 'border-collapse',
263        'border-color', 'border-left', 'border-left-color',
264        'border-left-style', 'border-left-width', 'border-right',
265        'border-right-color', 'border-right-style', 'border-right-width',
266        'border-spacing', 'border-style', 'border-top', 'border-top-color',
267        'border-top-style', 'border-top-width', 'border-width', 'bottom',
268        'caption-side', 'clear', 'clip', 'color', 'content',
269        'counter-increment', 'counter-reset', 'cursor', 'direction', 'display',
270        'empty-cells', 'float', 'font', 'font-family', 'font-size',
271        'font-style', 'font-variant', 'font-weight', 'height', 'left',
272        'letter-spacing', 'line-height', 'list-style', 'list-style-image',
273        'list-style-position', 'list-style-type', 'margin', 'margin-bottom',
274        'margin-left', 'margin-right', 'margin-top', 'max-height', 'max-width',
275        'min-height', 'min-width', 'opacity', 'orphans', 'outline',
276        'outline-color', 'outline-style', 'outline-width', 'overflow',
277        'padding', 'padding-bottom', 'padding-left', 'padding-right',
278        'padding-top', 'page-break-after', 'page-break-before',
279        'page-break-inside', 'quotes', 'right', 'table-layout',
280        'text-align', 'text-decoration', 'text-indent', 'text-transform',
281        'top', 'unicode-bidi', 'vertical-align', 'visibility', 'white-space',
282        'widows', 'width', 'word-spacing', 'z-index',
283     ])
284
[342]285    SAFE_SCHEMES = frozenset(['file', 'ftp', 'http', 'https', 'mailto', None])
286
287    URI_ATTRS = frozenset(['action', 'background', 'dynsrc', 'href', 'lowsrc',
[2]288        'src'])
289
[342]290    def __init__(self, safe_tags=SAFE_TAGS, safe_attrs=SAFE_ATTRS,
[1174]291                 safe_schemes=SAFE_SCHEMES, uri_attrs=URI_ATTRS,
292                 safe_css=SAFE_CSS):
[342]293        """Create the sanitizer.
294       
295        The exact set of allowed elements and attributes can be configured.
296       
[517]297        :param safe_tags: a set of tag names that are considered safe
298        :param safe_attrs: a set of attribute names that are considered safe
299        :param safe_schemes: a set of URI schemes that are considered safe
300        :param uri_attrs: a set of names of attributes that contain URIs
[342]301        """
302        self.safe_tags = safe_tags
[1174]303        # The set of tag names that are considered safe.
[342]304        self.safe_attrs = safe_attrs
[1174]305        # The set of attribute names that are considered safe.
306        self.safe_css = safe_css
307        # The set of CSS properties that are considered safe.
[342]308        self.uri_attrs = uri_attrs
[1174]309        # The set of names of attributes that may contain URIs.
[342]310        self.safe_schemes = safe_schemes
[1174]311        # The set of URI schemes that are considered safe.
[342]312
[1174]313    # IE6 <http://heideri.ch/jso/#80>
314    _EXPRESSION_SEARCH = re.compile(u"""
315        [eE
316         \uFF25 # FULLWIDTH LATIN CAPITAL LETTER E
317         \uFF45 # FULLWIDTH LATIN SMALL LETTER E
318        ]
319        [xX
320         \uFF38 # FULLWIDTH LATIN CAPITAL LETTER X
321         \uFF58 # FULLWIDTH LATIN SMALL LETTER X
322        ]
323        [pP
324         \uFF30 # FULLWIDTH LATIN CAPITAL LETTER P
325         \uFF50 # FULLWIDTH LATIN SMALL LETTER P
326        ]
327        [rR
328         \u0280 # LATIN LETTER SMALL CAPITAL R
329         \uFF32 # FULLWIDTH LATIN CAPITAL LETTER R
330         \uFF52 # FULLWIDTH LATIN SMALL LETTER R
331        ]
332        [eE
333         \uFF25 # FULLWIDTH LATIN CAPITAL LETTER E
334         \uFF45 # FULLWIDTH LATIN SMALL LETTER E
335        ]
336        [sS
337         \uFF33 # FULLWIDTH LATIN CAPITAL LETTER S
338         \uFF53 # FULLWIDTH LATIN SMALL LETTER S
339        ]{2}
340        [iI
341         \u026A # LATIN LETTER SMALL CAPITAL I
342         \uFF29 # FULLWIDTH LATIN CAPITAL LETTER I
343         \uFF49 # FULLWIDTH LATIN SMALL LETTER I
344        ]
345        [oO
346         \uFF2F # FULLWIDTH LATIN CAPITAL LETTER O
347         \uFF4F # FULLWIDTH LATIN SMALL LETTER O
348        ]
349        [nN
350         \u0274 # LATIN LETTER SMALL CAPITAL N
351         \uFF2E # FULLWIDTH LATIN CAPITAL LETTER N
352         \uFF4E # FULLWIDTH LATIN SMALL LETTER N
353        ]
354        """, re.VERBOSE).search
355
356    # IE6 <http://openmya.hacker.jp/hasegawa/security/expression.txt>
357    #     7) Particular bit of Unicode characters
358    _URL_FINDITER = re.compile(
359        u'[Uu][Rr\u0280][Ll\u029F]\s*\(([^)]+)').finditer
360
[531]361    def __call__(self, stream):
[342]362        """Apply the filter to the given stream.
363       
[517]364        :param stream: the markup event stream to filter
[342]365        """
[2]366        waiting_for = None
367
368        for kind, data, pos in stream:
[74]369            if kind is START:
[2]370                if waiting_for:
371                    continue
[424]372                tag, attrs = data
[1049]373                if not self.is_safe_elem(tag, attrs):
[2]374                    waiting_for = tag
375                    continue
376
[424]377                new_attrs = []
378                for attr, value in attrs:
[132]379                    value = stripentities(value)
[342]380                    if attr not in self.safe_attrs:
[2]381                        continue
[342]382                    elif attr in self.uri_attrs:
[2]383                        # Don't allow URI schemes such as "javascript:"
[682]384                        if not self.is_safe_uri(value):
[2]385                            continue
386                    elif attr == 'style':
387                        # Remove dangerous CSS declarations from inline styles
[682]388                        decls = self.sanitize_css(value)
[2]389                        if not decls:
390                            continue
391                        value = '; '.join(decls)
[424]392                    new_attrs.append((attr, value))
[2]393
[424]394                yield kind, (tag, Attrs(new_attrs)), pos
[2]395
[74]396            elif kind is END:
[2]397                tag = data
398                if waiting_for:
399                    if waiting_for == tag:
400                        waiting_for = None
401                else:
402                    yield kind, data, pos
403
[682]404            elif kind is not COMMENT:
[2]405                if not waiting_for:
406                    yield kind, data, pos
[523]407
[1049]408    def is_safe_css(self, propname, value):
409        """Determine whether the given css property declaration is to be
410        considered safe for inclusion in the output.
411       
412        :param propname: the CSS property name
413        :param value: the value of the property
414        :return: whether the property value should be considered safe
415        :rtype: bool
416        :since: version 0.6
417        """
[1174]418        if propname not in self.safe_css:
[1049]419            return False
420        if propname.startswith('margin') and '-' in value:
421            # Negative margins can be used for phishing
422            return False
423        return True
424
425    def is_safe_elem(self, tag, attrs):
426        """Determine whether the given element should be considered safe for
427        inclusion in the output.
428       
429        :param tag: the tag name of the element
430        :type tag: QName
431        :param attrs: the element attributes
432        :type attrs: Attrs
433        :return: whether the element should be considered safe
434        :rtype: bool
435        :since: version 0.6
436        """
437        if tag not in self.safe_tags:
438            return False
439        if tag.localname == 'input':
440            input_type = attrs.get('type', '').lower()
441            if input_type == 'password':
442                return False
443        return True
444
[682]445    def is_safe_uri(self, uri):
446        """Determine whether the given URI is to be considered safe for
447        inclusion in the output.
448       
449        The default implementation checks whether the scheme of the URI is in
450        the set of allowed URIs (`safe_schemes`).
451       
452        >>> sanitizer = HTMLSanitizer()
453        >>> sanitizer.is_safe_uri('http://example.org/')
454        True
455        >>> sanitizer.is_safe_uri('javascript:alert(document.cookie)')
456        False
457       
458        :param uri: the URI to check
459        :return: `True` if the URI can be considered safe, `False` otherwise
460        :rtype: `bool`
[690]461        :since: version 0.4.3
[682]462        """
[1046]463        if '#' in uri:
464            uri = uri.split('#', 1)[0] # Strip out the fragment identifier
[682]465        if ':' not in uri:
466            return True # This is a relative URI
467        chars = [char for char in uri.split(':', 1)[0] if char.isalnum()]
468        return ''.join(chars).lower() in self.safe_schemes
469
470    def sanitize_css(self, text):
471        """Remove potentially dangerous property declarations from CSS code.
472       
473        In particular, properties using the CSS ``url()`` function with a scheme
474        that is not considered safe are removed:
475       
476        >>> sanitizer = HTMLSanitizer()
477        >>> sanitizer.sanitize_css(u'''
478        ...   background: url(javascript:alert("foo"));
479        ...   color: #000;
480        ... ''')
481        [u'color: #000']
482       
483        Also, the proprietary Internet Explorer function ``expression()`` is
484        always stripped:
485       
486        >>> sanitizer.sanitize_css(u'''
487        ...   background: #fff;
488        ...   color: #000;
489        ...   width: e/**/xpression(alert("foo"));
490        ... ''')
491        [u'background: #fff', u'color: #000']
492       
493        :param text: the CSS text; this is expected to be `unicode` and to not
494                     contain any character or numeric references
495        :return: a list of declarations that are considered safe
496        :rtype: `list`
[690]497        :since: version 0.4.3
[682]498        """
499        decls = []
500        text = self._strip_css_comments(self._replace_unicode_escapes(text))
[1079]501        for decl in text.split(';'):
[682]502            decl = decl.strip()
503            if not decl:
504                continue
[1049]505            try:
506                propname, value = decl.split(':', 1)
507            except ValueError:
508                continue
509            if not self.is_safe_css(propname.strip().lower(), value.strip()):
510                continue
[682]511            is_evil = False
[1174]512            if self._EXPRESSION_SEARCH(value):
[682]513                is_evil = True
[1174]514            for match in self._URL_FINDITER(value):
[682]515                if not self.is_safe_uri(match.group(1)):
516                    is_evil = True
517                    break
518            if not is_evil:
519                decls.append(decl.strip())
520        return decls
521
[523]522    _NORMALIZE_NEWLINES = re.compile(r'\r\n').sub
[1174]523    _UNICODE_ESCAPE = re.compile(
524        r"""\\([0-9a-fA-F]{1,6})\s?|\\([^\r\n\f0-9a-fA-F'"{};:()#*])""",
525        re.UNICODE).sub
[523]526
527    def _replace_unicode_escapes(self, text):
528        def _repl(match):
[1174]529            t = match.group(1)
530            if t:
531                return unichr(int(t, 16))
532            t = match.group(2)
533            if t == '\\':
534                return r'\\'
535            else:
536                return t
[523]537        return self._UNICODE_ESCAPE(_repl, self._NORMALIZE_NEWLINES('\n', text))
[667]538
539    _CSS_COMMENTS = re.compile(r'/\*.*?\*/').sub
540
541    def _strip_css_comments(self, text):
542        return self._CSS_COMMENTS('', text)
Note: See TracBrowser for help on using the repository browser.