网络安全
1. Web 安全攻击与防御
1.1 XSS (跨站脚本攻击)
反射型 XSS
// 攻击示例
http://example.com/search?q=<script>alert('XSS')</script>
// 防御方法
function escapeHtml(str) {
return str.replace(/[&<>"']/g, function(match) {
const escape = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return escape[match];
});
}
存储型 XSS
// 攻击示例
const comment = '<img src="x" onerror="alert(document.cookie)">';
// 防御方法
// 1. 输入过滤
const sanitize = require('xss');
const safeComment = sanitize(comment);
// 2. CSP 策略
Content-Security-Policy: default-src 'self'
DOM型 XSS
// 攻击示例
location.hash = '<script>alert(1)</script>';
document.write(location.hash.substring(1));
// 防御方法
// 1. 避免使用 innerHTML、document.write
element.textContent = userInput;
// 2. 使用 DOMPurify
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(dirty);
1.2 CSRF (跨站请求伪造)
攻击原理
<!-- 攻击示例 -->
<form action="http://bank.com/transfer" method="POST">
<input type="hidden" name="account" value="hacker"/>
<input type="hidden" name="amount" value="10000"/>
</form>
<script>document.forms[0].submit();</script>