XSS跨站脚本攻击:原理、分类与防御

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, '&amp;')
             .replace(/</g, '&lt;')
             .replace(/>/g, '&gt;');
}

CSP配置:

Content-Security-Policy: default-src 'self'; script-src 'self'