Python XSS过滤库?

14 投票
3 回答
18496 浏览
提问于 2025-04-15 11:47

有没有一个好用的、正在维护的Python库,可以用来过滤像XSS这样的恶意输入呢?

3 个回答

1

Strip-o-Gram这个库看起来挺不错的。我还没有仔细研究过,但它的功能似乎很强大(也就是说,它可以允许你指定的HTML标签,同时也能处理一些不安全的内容)。

下面是从那个页面上引用的一个使用示例:

  from stripogram import html2text, html2safehtml
  mylumpofdodgyhtml # a lump of dodgy html ;-)
  # Only allow <b>, <a>, <i>, <br>, and <p> tags
  mylumpofcoolcleancollectedhtml = html2safehtml(mylumpofdodgyhtml,valid_tags=("b", "a", "i", "br", "p"))
  # Don't process <img> tags, just strip them out. Use an indent of 4 spaces 
  # and a page that's 80 characters wide.
  mylumpoftext = html2text(mylumpofcoolcleancollectedhtml,ignore_tags=("img",),indent_width=4,page_width=80)

希望这对你有帮助。

3

你可以很简单地在Python中编写防止XSS攻击的代码,比如可以参考这个链接:http://code.activestate.com/recipes/496942/,里面有一段很有用的示例代码。

14

如果你在使用一个网页框架和像Jinja2这样的模板引擎,可能这个模板引擎或框架里已经内置了一些功能来处理这个问题。

在cgi模块里有一些可以帮助你的东西:

cgi.escape('恶意代码在这里'),详细信息可以查看:http://docs.python.org/library/cgi.html#cgi.escape

另外,Jinja2也提供了转义功能:

from jinja2 import utils
str(utils.escape('malicious code here'))

撰写回答