Django过滤xss攻击

 

       XSS 是常见的跨站脚本攻击,而且这种类型的错误很不容易被发现或者被开发人员忽视,当然django 框架本身是有这方面的考虑的,比如在模板中自动开启了 escape, 即html转义。何谓转义?就是把html语言的关键字过滤掉。例如,<div>就是html的关键字,如果要在html页面上呈现<div>,其源代码就必须是&lt;div&gt。而如果关闭了转义,那就over 了

  举个例子,在评论框的地方没有用到富文本编辑器,而是让用户自己输入内容,如果某个用户输入了如下类似的东西:

这是我的评论,<script>alert('xss injection');</script>

  而我在模板中是这样使用的 {{ comment| safe }}, 由于使用了 safe filter ,所以这里会直接弹出对话框出来。这就是XSS 注入了。真实的项目中是不允许出现这样的情况的,用safe 的目的是为了更好的显示html标签等。

  因为django 自身有一系列的方法。这些方法在 django.utils.html  package中

from django.utils.html import escape, strip_tags, remove_tags

  

例如:

   使用strip_tags函数出现的string移除HTML标记:

# import the strip_tags
from django.utils.html import strip_tags
# simple string with html inside.
html = '<p>paragraph</p>'
print html # will produce: <p>paragraph</p>
stripped = strip_tags(html)
print stripped # will produce: paragraph

  

作为过滤同样适用:

{{ somevalue|striptags }}

  

移除特殊tags,你需要使用removetags

 

html = '<strong>Bold...</strong><p>paragraph....</p>'
stripped = removetags(html, 'strong') # removes the strong only.
stripped2 = removetags(html, 'strong p') # removes the strong AND p tags.

在template同样适用:

{{ value|removetags:"a span"|safe }}

  

下面来个懒省事的:

lxml模块有个clearhtml方法,通过下面这个代码就可以把内容过滤成干净的HTML内容。

from lxml.html.clean import clean_html
html = clean_html(html)

  

猜你喜欢

转载自www.cnblogs.com/Alex-as/p/8908538.html