使用 Python 清理用户输入

2024-03-11

针对基于 Python 的 Web 应用程序清理用户输入的最佳方法是什么?是否有一个函数可以删除 HTML 字符和任何其他必要的字符组合以防止XSS http://en.wikipedia.org/wiki/Cross-site_scripting还是SQL注入攻击?


这是一个片段,它将删除不在白名单上的所有标签,以及不在属性白名单上的所有标签属性(因此您不能使用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&#x09;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 注入,因此这应该可以涵盖您的情况。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Python 清理用户输入 的相关文章

随机推荐