这是一个片段,它将删除不在白名单上的所有标签,以及不在属性白名单上的所有标签属性(因此您不能使用onclick
).
它是一个修改版本http://www.djangosnippets.org/snippets/205/ http://www.djangosnippets.org/snippets/205/,在属性值上使用正则表达式以防止人们使用href="javascript:..."
,以及其他描述于http://ha.ckers.org/xss.html http://ha.ckers.org/xss.html.
(e.g. <a href="ja	vascript:alert('hi')">
or <a href="ja vascript:alert('hi')">
, etc.)
正如你所看到的,它使用了(很棒的)美丽汤 http://www.crummy.com/software/BeautifulSoup/图书馆。
import re
from urlparse import urljoin
from BeautifulSoup import BeautifulSoup, Comment
def sanitizeHtml(value, base_url=None):
rjs = r'[\s]*(&#x.{1,7})?'.join(list('javascript:'))
rvb = r'[\s]*(&#x.{1,7})?'.join(list('vbscript:'))
re_scripts = re.compile('(%s)|(%s)' % (rjs, rvb), re.IGNORECASE)
validTags = 'p i strong b u a h1 h2 h3 pre br img'.split()
validAttrs = 'href src width height'.split()
urlAttrs = 'href src'.split() # Attributes which should have a URL
soup = BeautifulSoup(value)
for comment in soup.findAll(text=lambda text: isinstance(text, Comment)):
# Get rid of comments
comment.extract()
for tag in soup.findAll(True):
if tag.name not in validTags:
tag.hidden = True
attrs = tag.attrs
tag.attrs = []
for attr, val in attrs:
if attr in validAttrs:
val = re_scripts.sub('', val) # Remove scripts (vbs & js)
if attr in urlAttrs:
val = urljoin(base_url, val) # Calculate the absolute url
tag.attrs.append((attr, val))
return soup.renderContents().decode('utf8')
正如其他发帖者所说,几乎所有 Python 数据库库都会处理 SQL 注入,因此这应该可以涵盖您的情况。