用于XSS过滤的Python库?

Mat*_*mer 12 python xss

是否有一个良好的,积极维护的python库可用于过滤恶意输入,如XSS?

Pau*_*aul 9

如果您正在使用Web框架和像Jinja2这样的模板引擎,那么模板引擎或框架可能就是为此而构建的.

cgi模块中有一些东西可以帮助你:

cgi.escape('malicious code here'),请参阅:http://docs.python.org/library/cgi.html#cgi.escape

Jinja2还提供了转义:

from jinja2 import utils
str(utils.escape('malicious code here'))
Run Code Online (Sandbox Code Playgroud)

  • 从 Python 3.4+ 开始,stdlib 中有 `html.escape`! (3认同)

Nol*_*rin 1

Strip -o-Gram库看起来相当不错。我还没有正确检查过它,但看起来它做得很好(即可以将您指定的 HTML 标签列入白名单,以及转义任何令人讨厌的 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)
Run Code Online (Sandbox Code Playgroud)

希望有帮助。

  • 您不能仅仅相信攻击者会添加漂亮的标签。除非 strip-o-gram 适用于大量编码的标签(请参阅 rsnake 的列表:http://ha.ckers.org/xss.html),否则这将不起作用。 (2认同)