Cross Site Scripting
跨站腳本javascript
<div> #{content} </div> <div> <div> <script></script> </div> </div>
<img src="#{image}" /> <img src="1" onerror="alert(1)" />
<script> var data = "#{data}"; var data = "hello;alert(1);""; </script>
ctx.set('X-XSS-Protection',1)//默認開啓瀏覽器防禦
html
< <
和> >
var escapeHtml = function(str) { if (!str) return ""; str = str.replace(/</g, "<"); str = str.replace(/>/g, ">"); return str; };
"&quto;
var escapeHtmlProerty = function(str) { if (!str) return ""; str = str.replace(/"/g, "&quto"); str = str.replace(/'/g, "'"); str = str.replace(/ /g, " "); return str; };
對&
進行轉義,要放在前面str = str.replace(/&/g, "&");
前端
var escapeForJs = function(str) { if (!str) return ""; str = str.replace(/\\/g, "\\\\"); str = str.replace(/"/g, '\\"'); return str; };
也能夠這也樣處理,轉爲 json 格式:
forForJs: JSON.stringfy(ctx.query.from)
對\
進行轉義,要放在前面java
var xssFilter = function(html) { if (!html) return ""; html = html.replace(/<\s*\/?script\s*>/g, ""); html = html.replace(/javascript:[^'"]/g, ""); html = html.replace(/onerror\s*=\s[^'"]?[^'"]*['"]?>/g, ""); return html; };
cheerio
READMEnpm install cheerio
var xssFilter = function(html) { if (!html) return ""; var cheerio = require("cheerio"); var $ = cheerio.load(html); // 白名單 var whiteList = { img: ["src"] }; $("*").each(function(index, elem) { console.log("this is elem", elem); //在終端打印DOM樹結構 if (!switchList[elem.name]) { $(elem).remove(); return; } for (var attr in elem.attribs) { if (whiteList[elem.name].indexOf(attr) === -1) { $(elem).attr(attr, null); } } }); console.log(html, $.html()); };
還能夠使用第三方插件xss
,這樣就不用了本身配置白名單了,固然這個插件確定也容許用戶本身定義白名單,運行npm install xss
,該插件有本身的語法git
var xssFilter = function(html) { if (!html) return ""; var xss = require("xss"); var ret = xss(html, { whiteList: { img: ["src"], a: ["herf"], font: ["size", "color"] }, onIgnoreTag: function() { return ""; } }); console.log(html, $.html()); return ret; };
CSP 指的是內容安全策略,爲了緩解很大一部分潛在的跨站腳本問題,瀏覽器的擴展程序系統引入了內容安全策略(CSP)的通常概念。這將引入一些至關嚴格的策略,會使擴展程序在默認狀況下更加安全,開發者能夠建立並強制應用一些規則,管理網站容許加載的內容github
ctx.set(
Content-Security-Policy,
default-src 'self')
npm