如何清理输入以避免django中的恶意属性?

时间:2015-04-20 06:41:23

标签: django django-templates beautifulsoup

我希望允许用户发布图片,因此需要将|safe添加到模板标记,并使用beautifulsoap将this代码段列入白名单。

但是,我想知道如何避免下列潜在的恶意属性?

<img src="puppy.png" onload="(function(){/* do bad stuff */}());" /> 

更新 请注意,上面链接的代码段有一些XSS漏洞,提到here

1 个答案:

答案 0 :(得分:5)

您还需要检查属性白名单。

使用美丽的汤3

def safe_html(html):

    tag_whitelist = ['img']
    attr_whitelist = ['src', 'alt', 'width', 'height']

    soup = BeautifulSoup(html)

    for tag in soup.findAll():
        if tag.name.lower() in tag_whitelist:
            tag.attrs = [a for a in tag.attrs if a[0].lower() in attr_whitelist]
        else:
            tag.unwrap()

    # scripts can be executed from comments in some cases (citation needed)
    comments = soup.findAll(text=lambda text:isinstance(text, Comment))
    for comment in comments:
        comment.extract()

    return unicode(soup)

使用美丽的汤4

def safe_html(html):

    tag_whitelist = ['img']
    attr_whitelist = ['src', 'alt', 'width', 'height']

    soup = BeautifulSoup(html)

    for tag in soup.find_all():
        if tag.name.lower() in tag_whitelist:
            tag.attrs = { name: value for name, value in tag.attrs.items() 
                if name.lower() in attr_whitelist }
        else:
            tag.unwrap()

    # scripts can be executed from comments in some cases (citation needed)
    comments = soup.find_all(text=lambda text:isinstance(text, Comment))
    for comment in comments:
        comment.extract()
    return unicode(soup)