参考文章:https://www.writesoftwarewell.com/content-security-policy/
什么是XSS
XSS(Cross Site Scripting)即跨站脚本攻击,即当前站点加载并执行了来自其他站点的js,导致Cookie泄漏等安全问题。
怎么产生
多发生在允许用户填写并展示给其他人查看的站点的页面上。用户填写的内容可能直接就是一段script引用
<script src="http://xxx.com/xxx.js"></script>
如果页面直接加载了这段内容,就会产生xss。
怎么解决
- 对用户输入中的特殊符号进行转义
less than symbol (<) with <
greater than symbol (>) with >
double quotes (") with "
single quote (’) with ’
ampersand (&) with &
- 使用nonce+CSP
<script nonce="dGhpcyBpcyBhIG5v==">alert("test")</script>
Content-Security-Policy: script-src ‘nonce-dGhpcyBpcyBhIG5v==’; style-src ‘nonce-dGhpcyBpcyBhIG5v==’
- 使用动态事件绑定
<script> function handle() {// click handler code}
</script><button onclick="handle();">Click Me</button>
修改为
<button id="submit-btn">Click Me</button><script nonce="token">
document.addEventListener('DOMContentLoaded', function () {document.getElementById('submit-btn').addEventListener('click', () => { // click handler code});
});
</script>
当指定csp策略时,
Content-Security-Policy: default-src ‘none’; script-src ‘nonce-randomValue’
οnclick="handle();"
将不会被执行