XSS攻击原理
XSS(Cross-Site Scripting)允许攻击者将恶意脚本注入到其他用户浏览的网页中。
三种类型
1. 反射型XSS
// 恶意URL
https://example.com/search?q=<script>alert('XSS')</script>
2. 存储型XSS(最危险)
攻击者将恶意脚本存储到数据库,每次用户访问页面时执行。
3. DOM型XSS
// 危险代码
document.getElementById('output').innerHTML = location.hash.substring(1);
防御措施
// 输出编码
function escapeHtml(text) {
return text.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
}
CSP配置:
Content-Security-Policy: default-src 'self'; script-src 'self'