集成富文本编辑器XSS预防过滤措施
# https://github.com/phith0n/python-xss-filter import re
import copy
from html.parser import HTMLParser class XSSHtml(HTMLParser):
allow_tags = ['a', 'img', 'br', 'strong', 'b', 'code', 'pre',
'p', 'div', 'em', 'span', 'h1', 'h2', 'h3', 'h4',
'h5', 'h6', 'blockquote', 'ul', 'ol', 'tr', 'th', 'td',
'hr', 'li', 'u', 'embed', 's', 'table', 'thead', 'tbody',
'caption', 'small', 'q', 'sup', 'sub', 'font']
common_attrs = ["style", "class", "name"]
nonend_tags = ["img", "hr", "br", "embed"]
tags_own_attrs = {
"img": ["src", "width", "height", "alt", "align"],
"a": ["href", "target", "rel", "title"],
"embed": ["src", "width", "height", "type", "allowfullscreen", "loop", "play", "wmode", "menu"],
"table": ["border", "cellpadding", "cellspacing"],
"font": ["color"]
} def __init__(self, allows=[]):
HTMLParser.__init__(self)
self.allow_tags = allows if allows else self.allow_tags
self.result = []
self.start = []
self.data = [] def __enter__(self):
return self def __exit__(self, exc_type, exc_val, exc_tb):
super().close() def clean(self, content):
self.feed(content)
return self.get_html() def get_html(self):
"""
Get the safe html code
"""
for i in range(0, len(self.result)):
if self.result[i].strip('\n'):
self.data.append(self.result[i])
return ''.join(self.data) def handle_startendtag(self, tag, attrs):
self.handle_starttag(tag, attrs) def handle_starttag(self, tag, attrs):
if tag not in self.allow_tags:
return
end_diagonal = ' /' if tag in self.nonend_tags else ''
if not end_diagonal:
self.start.append(tag)
attdict = {}
for attr in attrs:
attdict[attr[0]] = attr[1] attdict = self._wash_attr(attdict, tag)
if hasattr(self, "node_%s" % tag):
attdict = getattr(self, "node_%s" % tag)(attdict)
else:
attdict = self.node_default(attdict) attrs = []
for (key, value) in attdict.items():
attrs.append('%s="%s"' % (key, self._htmlspecialchars(value)))
attrs = (' ' + ' '.join(attrs)) if attrs else ''
self.result.append('<' + tag + attrs + end_diagonal + '>') def handle_endtag(self, tag):
if self.start and tag == self.start[len(self.start) - 1]:
self.result.append('</' + tag + '>')
self.start.pop() def handle_data(self, data):
self.result.append(self._htmlspecialchars(data)) def handle_entityref(self, name):
if name.isalpha():
self.result.append("&%s;" % name) def handle_charref(self, name):
if name.isdigit():
self.result.append("&#%s;" % name) def node_default(self, attrs):
attrs = self._common_attr(attrs)
return attrs def node_a(self, attrs):
attrs = self._common_attr(attrs)
attrs = self._get_link(attrs, "href")
attrs = self._set_attr_default(attrs, "target", "_blank")
attrs = self._limit_attr(attrs, {
"target": ["_blank", "_self"]
})
return attrs def node_embed(self, attrs):
attrs = self._common_attr(attrs)
attrs = self._get_link(attrs, "src")
attrs = self._limit_attr(attrs, {
"type": ["application/x-shockwave-flash"],
"wmode": ["transparent", "window", "opaque"],
"play": ["true", "false"],
"loop": ["true", "false"],
"menu": ["true", "false"],
"allowfullscreen": ["true", "false"]
})
attrs["allowscriptaccess"] = "never"
attrs["allownetworking"] = "none"
return attrs def _true_url(self, url):
prog = re.compile(r"^(http|https|ftp)://.+", re.I | re.S)
if prog.match(url):
return url
else:
return "http://%s" % url def _true_style(self, style):
if style:
style = re.sub(r"(\\|&#|/\*|\*/)", "_", style)
style = re.sub(r"e.*x.*p.*r.*e.*s.*s.*i.*o.*n", "_", style)
return style def _get_style(self, attrs):
if "style" in attrs:
attrs["style"] = self._true_style(attrs.get("style"))
return attrs def _get_link(self, attrs, name):
if name in attrs:
attrs[name] = self._true_url(attrs[name])
return attrs def _wash_attr(self, attrs, tag):
if tag in self.tags_own_attrs:
other = self.tags_own_attrs.get(tag)
else:
other = []
if attrs:
for key, value in copy.deepcopy(attrs).items():
if key not in self.common_attrs + other:
del attrs[key]
return attrs def _common_attr(self, attrs):
attrs = self._get_style(attrs)
return attrs def _set_attr_default(self, attrs, name, default=''):
if name not in attrs:
attrs[name] = default
return attrs def _limit_attr(self, attrs, limit={}):
for (key, value) in limit.items():
if key in attrs and attrs[key] not in value:
del attrs[key]
return attrs def _htmlspecialchars(self, html):
return html.replace("<", "<") \
.replace(">", ">") \
.replace('"', """) \
.replace("'", "'") if "__main__" == __name__:
with XSSHtml() as parser:
ret = parser.clean("""<p><img src=1 onerror=alert(/xss/)></p><div class="left">
<a href='javascript:prompt(1)'><br />hehe</a></div>
<p id="test" onmouseover="alert(1)">>M<svg>
<a href="https://www.baidu.com" target="self">MM</a></p>
<embed src='javascript:alert(/hehe/)' allowscriptaccess=always />
<img onerror=alert(1) src=#>""")
print(ret)
from urlparse import urlparse import bleach class XSSFilter(object):
tags = ['p', 'div', 'img', 'br', 'span', 'pre', 'code', 'blockquote', 'ol', 'ul', 'li']
styles = [
'max-width', 'color', 'margin', 'line-height', 'display', 'padding', 'background-color',
'display', 'border-left', 'font-family', 'white-space', 'font-size'
] @staticmethod
def allowed_src(tag, name, value):
if name in ('style', 'src', 'alt', 'data-w-e'):
return True
if name == 'src':
p = urlparse(value)
return XSSFilter._trusted_url(p)
return False @classmethod
def clean(cls, html):
return bleach.clean(html, tags=cls.tags, attributes=cls.allowed_src, styles=cls.styles) @classmethod
def _trusted_url(cls, url):
return url.netloc == 'xxxx.xxxx.com' or 'static/gif' in url.path
集成富文本编辑器XSS预防过滤措施的更多相关文章
- AngularJS集成富文本编辑器
最近在Angular中需要集成富文本编辑器,本来已经集成好百度的UEditor,后台觉得配置太多,让我弄个别的,然后就找到了wangEditor,这个配置和上手都要简单一些,下面来看看具体操作步骤吧: ...
- yii2集成富文本编辑器redactor
作者:白狼 出处:http://www.manks.top/article/yii2_redactor本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保 ...
- nodejs后台集成富文本编辑器(ueditor)
1 下载ueditor nodejs版本 2 复制public目录下面的文件 到项目静态资源public文件夹下 3 在项目根目录创建ueditor文件夹 要复制进来的内容为 4 在根目录的 uedi ...
- Xadmin集成富文本编辑器ueditor
在xadmin中通过自定义插件,实现富文本编辑器,效果如下: 1.首先,pip安装ueditor的Django版本: pip install DjangoUeditor 2.之后需要添加到项目的set ...
- django—xadmin中集成富文本编辑器ueditor
一.安装 pip命令安装,由于ueditor为百度开发的一款富文本编辑框,现已停止维护,如果解释器为python2,则直接pip install djangoueditor 解压包安装,python3 ...
- django后台集成富文本编辑器Tinymce的使用
富文本编辑器Tinymce是使用步骤: 1.首先去python的模块包的网站下载一个django-tinymce的包 2.下载上图的安装包,然后解压,进入文件夹,执行: (pychrm直接运行命令pi ...
- Django使用xadmin集成富文本编辑器Ueditor(方法二)
一.xadmin的安装与配置1.安装xadmin,其中第一种在python3中安装不成功,推荐第二种或者第三种 方式一:pip install xadmin 方式二:pip install git+g ...
- 关于EasyUI与富文本编辑器结合使用的问题(kindueditor与uueditor)
最近使用easyui玩玩项目,在结合富文本编辑器时遇到了一些问题,很多人(在网上看到)集成富文本编辑器时常常不能显示, 第一次打开编辑的时候没有问题,但是第二次打开就出错了.为此我进行了一些调试研究. ...
- 「newbee-mall新蜂商城开源啦」 页面优化,最新版 wangEditor 富文本编辑器整合案例
大家比较关心的新蜂商城 Vue3 版本目前已经开发了大部分内容,相信很快就能够开源出来让大家尝鲜了,先让大家看看当前的开发进度: 开源仓库地址为 https://github.com/newbee-l ...
随机推荐
- vc2010, fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt解决办法
是因为安其它软件的时候更新了.net framework,导致vc2010出了问题. 解决办法是在系统里搜索cvtres.exe,会搜到很多,把其中 Microsoft Visual Studio 1 ...
- hdu1584 A strange lift (电梯最短路径问题)
A strange lift Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) T ...
- zombie process
僵尸进程:子进程退出后,父进程还没有回收子进程的资源,那么这个子进程就处于僵尸状态.Q1:“资源”是些什么?Q2:父进程如何回收子进程的资源? 内核为每个终止子进程保存了一定量的信息,所以当终止进程的 ...
- sendmail发件人邮箱设定命令
sendmail发件人邮箱设定命令 以前就碰到过设置发件人后缀的方式,这次迁移服务器居然忘记,从头开始记录下 1:第一种方法,修改/etc/hosts,据说sendmail使用hosts里面的本地 ...
- maven项目工程报错:cannot be resolved to a type
1.在本地仓库中,搜索“_maven.repositories”所有匹配项,并彻底删除 2.然后再删除“.lastUpdated”所有匹配项 3.最后再重新在eclipse中执行操作:update d ...
- 【转载】使用SoapUI 测试Web Service
转载地址:使用SoapUI 测试Web Service 如何测试写好的Webservice?你当然可以写代码来测试,但还是太麻烦,你得花时间去学习各语言的关于Webservice调用的相关API. ...
- samba实现文件共享
很多时候,做嵌入式开发,都是在windows上安装虚拟,在虚拟机中安装Linux操作系统.这个时候,我们经常需要Linux操作系统下有一个目录能在windows下自由访问.要想实现这个功能我们只需要在 ...
- LeetCode406. Queue Reconstruction by Height Add to List
Description Suppose you have a random list of people standing in a queue. Each person is described b ...
- 【转】Monkey测试4——Monkey命令行可用的全部选项
Monkey命令行可用的全部选项 常规 --help 列出简单的用法. -v 命令行的每一个-v将增加反馈信息的级别. Level 0(缺省值)除启动提示.测试完成和最终结果之外,提供较少信息. Le ...
- Xcode中授权普通成员
问题: 在普通用户账户下使用系统的Xcode在编译通过时候会提示” Developer Tools Access“需控制另一进程,需要输入“Developer Tools”组用户名密码才能继续调试 解 ...