您现在的位置是:网站首页 > 防止中间人攻击(MITM)文章详情
防止中间人攻击(MITM)
陈川
【
前端安全
】
24280人已围观
4348字
什么是中间人攻击
中间人攻击(Man-in-the-Middle Attack,简称MITM)是指攻击者在通信双方之间秘密拦截、篡改或伪造数据的行为。攻击者可以窃取敏感信息如登录凭证、信用卡号,或注入恶意代码。这种攻击可能发生在任何不安全的网络通信中,特别是未加密的HTTP连接。
中间人攻击的常见形式
1. ARP欺骗
攻击者发送伪造的ARP响应包,将自身MAC地址与目标IP绑定,使流量经过攻击者设备。例如在局域网中:
// 伪代码示例:ARP欺骗基本原理
function sendFakeARPResponse(targetIP, attackerMAC) {
// 伪造ARP响应包声称攻击者MAC地址对应目标IP
broadcastARPResponse(targetIP, attackerMAC);
}
2. DNS劫持
攻击者篡改DNS响应,将域名解析到恶意服务器。比如将www.example.com
解析到攻击者控制的IP:
# 恶意DNS记录示例
www.example.com. IN A 192.168.1.100
3. SSL剥离
强制将HTTPS连接降级为HTTP,常见于公共WiFi场景。攻击工具如sslstrip会实时修改响应头:
HTTP/1.1 302 Found
Location: http://example.com/login # 故意去掉"s"变成http
前端防御措施
1. 强制HTTPS
使用HSTS头确保所有连接必须加密:
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
配合前端重定向:
if (window.location.protocol === 'http:') {
window.location.href = 'https://' + window.location.host + window.location.pathname;
}
2. 内容安全策略(CSP)
防止脚本注入:
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'
动态添加meta标签作为备用:
const cspMeta = document.createElement('meta');
cspMeta.httpEquiv = 'Content-Security-Policy';
cspMeta.content = "default-src 'self'";
document.head.appendChild(cspMeta);
3. 证书锁定(Certificate Pinning)
在移动端应用中固定证书指纹:
// 伪代码示例:证书校验
function verifyCertificate(serverCert) {
const pinnedFingerprint = 'SHA256/AAAAAAAA...';
return serverCert.fingerprint === pinnedFingerprint;
}
4. 子资源完整性(SRI)
确保CDN资源未被篡改:
<script src="https://cdn.example.com/jquery.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8w"
crossorigin="anonymous"></script>
高级防御技术
1. WebSocket安全
加密WebSocket连接并验证来源:
const socket = new WebSocket('wss://example.com/ws');
socket.addEventListener('message', (event) => {
if (!validateMessageOrigin(event.origin)) {
socket.close();
return;
}
// 处理消息
});
2. 双向认证
客户端也提供证书:
# Nginx配置示例
ssl_client_certificate /path/to/ca.crt;
ssl_verify_client on;
3. 实时加密检测
前端监控协议安全性:
function checkConnectionSecurity() {
if (!window.crypto || !window.crypto.subtle) {
console.warn('Web Cryptography API not available');
}
if (window.location.protocol !== 'https:') {
reportInsecureConnection();
}
}
用户行为防护
1. 表单提交保护
敏感表单添加一次性令牌:
<form action="/transfer" method="POST">
<input type="hidden" name="csrf_token" value="a1b2c3d4">
<!-- 其他表单字段 -->
</form>
2. 输入验证
严格验证用户输入和API响应:
function sanitizeInput(input) {
return input.replace(/[<>"'&]/g, '');
}
fetch('/api/data')
.then(response => {
if (!response.headers.get('Content-Type').includes('application/json')) {
throw new Error('Invalid content type');
}
return response.json();
});
3. 安全头设置
组合多个安全头:
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
开发环境防护
1. 本地开发安全
禁用开发服务器的不安全选项:
// webpack-dev-server配置示例
module.exports = {
devServer: {
https: true,
disableHostCheck: false, // 必须保持false
headers: {
'X-XSS-Protection': '1; mode=block'
}
}
};
2. 依赖安全检查
使用npm audit检查漏洞:
npm audit --production
或集成到CI流程:
# GitHub Actions示例
- name: Audit dependencies
run: |
npm install
npm audit --audit-level=high
监控与响应
1. 异常报告
捕获并报告安全异常:
window.addEventListener('securitypolicyviolation', (e) => {
fetch('/report-violation', {
method: 'POST',
body: JSON.stringify({
violatedDirective: e.violatedDirective,
blockedURI: e.blockedURI
})
});
});
2. 网络状态监控
检测网络变更事件:
navigator.connection.addEventListener('change', () => {
if (navigator.connection.effectiveType === 'slow-2g') {
warnAboutNetworkQuality();
}
});
浏览器API的合理使用
1. 安全上下文限制
某些API仅在安全上下文可用:
if (window.isSecureContext) {
// 使用Web Crypto API等敏感功能
const key = await crypto.subtle.generateKey(...);
}
2. 权限API
谨慎请求用户权限:
navigator.permissions.query({name: 'geolocation'})
.then(permissionStatus => {
if (permissionStatus.state === 'granted') {
// 使用定位功能
}
});
上一篇: 前端如何检测 HTTPS 状态
下一篇: 证书安全与前端相关配置