gpt4 book ai didi

javascript - 这种 sanitizer 容易受到 XSS 攻击吗?

转载 作者:行者123 更新时间:2023-11-30 16:38:11 25 4
gpt4 key购买 nike

要为 django 应用程序的文本字段提供一个简单而安全的编辑器,我有这个片段来将输入的 html 净化到 django 代码中:

from bs4 import BeautifulSoup

def sanitize_html(value):
tag_whitelist = ['img','b','strong','blockquote', 'a']
attr_whitelist = ['src', 'alt', 'width', 'height', 'href','class']
soup = BeautifulSoup(value)
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
try:
comments = soup.find_all(text=lambda text:isinstance(text, Comment))
for comment in comments:
comment.extract()
except:
pass
return unicode(soup)

我还使用此方法将在模型字段中输入 javascript 列入黑名单:

BADLIST = ['javascript']

def no_js (text):
if any(e in text for e in BADLIST):
raise ValidationError("Your text contains bad words!")
else:
return True

另一方面,在模板中我需要使用{{text| safe}} 以允许显示健康的 html 标签。

所以我想知道这些约束条件下,输入是否仍然容易受到 XSS 攻击?如果是这样,如何解决?

最佳答案

乍一看代码没问题,但检查安全漏洞并不是一件掉以轻心的事情,需要花费一些时间自行检查。

例如,测试是否提供了类似<script>alert('hello')</script> 的字符串被执行。除了这个简单的测试之外,还有很多事情要检查。有很多关于此事的文档。

此外,正如我在评论中提到的,我强烈建议您使用已建立的库来清理输入。这样的图书馆是bleach :

Bleach is a whitelist-based HTML sanitization and text linkification library. It is designed to take untrusted user input with some HTML.

Because Bleach uses html5lib to parse document fragments the same way browsers do, it is extremely resilient to unknown attacks, much more so than regular-expression-based sanitizers.

这样你至少可以确定你的攻击面更小,因为这个软件经过了更多的测试,你只需要担心你允许的 HTML 标签,而不是你的代码是否有效。

使用示例:

import bleach
mystring = bleach.clean(form.cleaned_data['mystring'],
tags=ALLOWED_TAGS,
attributes=ALLOWED_ATTRIBUTES,
styles=ALLOWED_STYLES,
strip=False, strip_comments=True)

关于javascript - 这种 sanitizer 容易受到 XSS 攻击吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32393003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com