Sanitize HTML filter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from BeautifulSoup import BeautifulSoup, Comment
register = template.Library()


def sanitize_html(value):
    valid_tags = 'p i strong b u a h1 h2 h3 pre br img'.split()
    valid_attrs = 'href src'.split()
    soup = BeautifulSoup(value)
    for comment in soup.findAll(
        text=lambda text: isinstance(text, Comment)):
        comment.extract()
    for tag in soup.findAll(True):
        if tag.name not in valid_tags:
            tag.hidden = True
        tag.attrs = [(attr, val) for attr, val in tag.attrs
                     if attr in valid_attrs]
    return soup.renderContents().decode('utf8').replace('javascript:', '')

register.filter('santize', sanitize_html)

More like this

  1. Sanitize HTML filter with tag/attribute whitelist and XSS protection by harrym 4 years, 8 months ago
  2. Sanitize text field HTML (here from the Dojo Toolkit Editor2 widget) by akaihola 7 years ago
  3. CleanCharField by DvD 6 years, 6 months ago
  4. A few jinja2 filters like django ones by brondsem 5 years, 1 month ago
  5. Template range filter by zalun 5 years, 1 month ago

Comments

chrominance (on July 30, 2007):

Might want to try changing the 'javascript' regex in the second-to-last line with this regex instead:

re.compile('j[\s]*(&#x.{1,7})?a[\s]*(&#x.{1,7})?v[\s]*(&#x.{1,7})?a[\s]*(&#x.{1,7})?
s[\s]*(&#x.{1,7})?c[\s]*(&#x.{1,7})?r[\s]*(&#x.{1,7})?i[\s]*(&#x.{1,7})?p[\s]*(&#x.{1,7})?t', re.IGNORECASE)

(all on one line, of course)

It's long and unwieldy but I think it catches the above issues, and then some (embedded entity tabs/linebreaks, for example).

#

schmiddy (on November 25, 2008):

Beware also of the typo on the last line. Author presumably meant to write "sanitize" instead of "santize".

#

(Forgotten your password?)