我在使用 pelican 时注意到了这种行为:
Template('<p>{{text|striptags|striptags}}</p>').render(text='<script src="http://chezsoi.org"/>')
呈现为:
<script src="http://chezsoi.org"/>
我指望 striptags 输出没有任何 HTML 标签,这是错误的。 因此我的问题是:是否有内置 striptags 过滤器的“更安全”替代方案?
我知道一个快速的解决方案是将调用链接到 striptags:
'{{ <p>text|striptags|striptags|striptags }}</p>'
但如果攻击者控制了 text 内容,他们可以对字符串进行双重 HTML 转义,依此类推。
请您参考如下方法:
我很确定 striptags 过滤器旨在“美观地”删除标签(清理数据以获得纯纯文本),而不是作为一种防水的安全措施。
在安全方面(防止XSS),你应该使用Jinjas HTML escaping features .
您可以使用 |escape 过滤器(别名:|e)手动转义 HTML,或者使用 Environment 并打开 Jinja 的
<强>
autoescaping :
强>
>>> env = Environment(autoescape=True)
>>> template = env.from_string('<p>{{text}}</p>')
>>> template.render(text='<script src="http://chezsoi.org"/>')
u'<p><script src="http://chezsoi.org"/></p>'
>>> template.render(text='<script src="http://chezsoi.org"/>')
u'<p>&lt;script src="http://chezsoi.org"/&gt;</p>
另见 Security Considerations Flask 文档中的部分 - Flask 为此原因打开 Jinja 的自动转义,以防止 XSS。
Jinja 也将 likely make autoescaping the default future :
Autoescaping
[...] However autoescaping is not yet enabled by default though this will most likely change in the future
Notes on Autoescaping
In future versions of Jinja2 we might enable autoescaping by default for security reasons. As such you are encouraged to explicitly configure autoescaping now instead of relying on the default.
