Django框架中进行XSS过滤 防止用户输入恶意代码

Django框架中进行XSS过滤 防止用户输入恶意代码

Django框架中的后台编辑器 KindEditor的下载和基本使用这篇文章中,我们已经知道了如何进行文章添加,那么

class XssFilter():
	__inistance=None
	def __init__(self):
		self.valid_tags={
		"font":["size","color","face","style"],
		"b":[],
		"div":[],
		"span":[],
		"table":["border","cellspacing","cellpadding"],
		"th":["colspan","rowspan"],
		"ta":[],
		"a":[],
		"img":["src","alt","name"],
		"p":[],
		"pre":["class"],
		"hr":["class"],
		"strong":[],

		}
	def __new__(cls,*args,**kwargs):
		 if cls.__instance:
            return cls.__instance
        else:
            cls.__instance=object.__new__(cls,*args,**kwargs)
            return cls.__instance
    def process(self,content):
    	soup=BeautifulSoup(content,'lxml')
    	#遍历所有的HTML标签
    	for tag in soup.find_all():
    		#如果标签不在白名单中,隐藏
    		if tag,name not in self.valid_tags:
    			tag.hidden=True
    			if tag.name not in ["htnl","body"]:
    				tag.hidden=True
    				tag.clear()
				continue
			#判断标签的属性是否在白名单中,不在话清除掉
			attr_rules=self.valid_tags[tag.name]
			keys=list(tag.attrs.keys())
			for key in kyes:
				if key not in attr_rules:
					del tag[key]
		return soup.decode()
分享到 :

发表评论

登录... 后才能评论