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

Jan*_*and 1 django beautifulsoup django-templates

我想允许用户发布图片,因此需要添加|safe到模板标签并使用beautifulsoap使用代码段将某些标签列入白名单.

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

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

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

Wen*_*zil 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)
Run Code Online (Sandbox Code Playgroud)

使用美丽的汤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)
Run Code Online (Sandbox Code Playgroud)