集成富文本编辑器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 ...
随机推荐
- 一步步教你如何进行Xilinx SerDes调试
FPGA SERDES的应用需要考虑到板级硬件,SERDES参数和使用,应用协议等方面.由于这种复杂性,SERDES的调试工作对很多工程师来说是一个挑战.本文将描述SERDES的一般调试方法,便于工程 ...
- Emmet:HTML/CSS编写插件
http://www.iteye.com/news/27580 用法: http://docs.emmet.io/cheat-sheet/ sublime 2 添加:1. Ctrl+Alt+p -&g ...
- 网页CSS font-size使用em替代px
px和em都是长度单位,区别是,px的值是固定的,em的值是相对的,并且em会继承父级元素的字体大小. 任意浏览器的默认字体高都是16px.所以未经调整的浏览器都符合: 1em=16px.那么12px ...
- 时间序列 R 读书笔记 04 Forecasting: principles and practice
本章開始学习<Forecasting: principles and practice> 1 getting started 1.1 事件的可预言性 一个时间能不能被预言主要取决于以下三点 ...
- Google Chrome v48.0.2564.
http://www.pcpop.com/doc/1/1819/1819996.shtml 摘要:谷歌浏览器Chrome Stable 稳定版迎来例行升级,新版本号为v48.0.2564.82,上一版 ...
- spring boot 多层级mapper
mapper目录结构: mapper ----dev -------produce 在 application.properties 文件中配置 mybatis.mapper-location ...
- Java对象类型的判断
instanceof 判断某个对象是否是某个类的实例或者某个类的子类的实例.它的判断方式大概是这样的: public<T> boolean function(Object obj, Cla ...
- linux嵌入式大神的博客文章---持续更新中
linux kernel子系统相关博客:http://www.wowotech.net/ 经典博文: http://blog.csdn.net/zqixiao_09 http://blog.china ...
- BitMap、Geo、HyperLogLog
前言 Reids 在 Web 应用的开发中使用非常广泛,几乎所有的后端技术都会有涉及到 Redis 的使用.Redis 种除了常见的字符串 String.字典 Hash.列表 List.集合 Set. ...
- 本地调试远程api tag
当你在本地开发js且需要跨域调用远程接口的时候.可按照下列步骤设置你的chrome. 1.创建chrome快捷方式. 2.右键属性新的快捷方式,在目标一栏后面追加 "--args ...