當(dāng)頁(yè)面中有用戶輸入行為并且沒(méi)有對(duì)輸入內(nèi)容進(jìn)行篩選時(shí),用戶完全可以在輸入內(nèi)容中加入一段腳本來(lái)獲取cookies中信息等等。
如何讓自己的web比較安全呢?
如何給自己的web做插值防御呢?
一 . html節(jié)點(diǎn)內(nèi)容或?qū)傩缘姆烙?/b>
小方法: 對(duì) '<' 、'>'、雙引號(hào)、單引號(hào)、'&' 進(jìn)行轉(zhuǎn)義等等
二 . 富文本的防御
· 方法:利用cheerio庫(kù) (node.js)
官網(wǎng):https://www.npmjs.com/package/cheerio
npm install cheerio ? ? ?//進(jìn)行安裝
使用方法: 白名單
var xssFilter=function(html){
? ? ? ? ? ? ?if(!html) return '';
? ? ? ? ? ? ?const cheerio = require('cheerio');
? ? ? ? ? ? ?const $= cheerio.load(html);
? ? ? ? ? ? ? var whiteList={? ? ? ? ? //白名單
? ? ? ? ? ? ? ? ? ? ? ? ?'img' : ['src'],
? ? ? ? ? ? ? ? ? ? ? ? ?'font' : ['color','size'],
? ? ? ? ? ? ? ? ? ? ? ? ? 'a' : ['href']
? ? ? ? ? ? ? };
? ? ? ? ? ? ? $('*').each(function(index,elem){
? ? ? ? ? ? ? ? ? ? ? ? if (!whiteList[elem.name]) {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?$(elem).remove(); ? ? ? ? ? ? ? ? ? //過(guò)濾掉白名單中沒(méi)有的標(biāo)簽
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?return;
? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ? for (var attr in elem.attribs) { ? ? ? ? ? ? ?//判斷屬性是否在白名單中
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if(whiteList[elem.name].indexOf(attr) === -1){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? $(elem).attr(attr,null);? //cheerio中attr方法 ---設(shè)為null時(shí)就會(huì)移除這個(gè)屬性
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ?});
};
· 也可以通過(guò)第三方插件 ?比如 https://github.com/leizongmin/js-xss
使用方法:?
var xssFilter2=function(html){
? ? ? ? ? ?if(!html) return '';
? ? ? ? ? ?var xss = require('xss');
? ? ? ? ? ?var ret = xss(html,{
? ? ? ? ? ? ? ? ? whiteList:{ ? ?// 白名單
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?img : ['src']
? ? ? ? ? ? ? ? ? ?},
? ? ? ? ? ? ? ? ? onIgnoreTag : function(){ ? ? ? ? ? ? ? ? ? ? ? ?// 不在白名單內(nèi)的標(biāo)簽的處理方法
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? return '';
? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? });
? ? ? ? ? return ret;
};