防止网站被 iframe 嵌入
学习如何保护您的网站免受未授权的 iframe 嵌入,实现多层次的安全防护
HTTP 响应头防护
配置多层 HTTP 响应头防护机制:
- X-Frame-Options 基础防护
- Content-Security-Policy 增强防护
- Permissions-Policy 权限控制
- Cross-Origin-Opener-Policy 跨源防护
- Referrer-Policy 引用控制
响应头配置示例:
// 1. 基础防护配置
X-Frame-Options: DENY
Content-Security-Policy: frame-ancestors 'none';
// 2. 同源限制配置
X-Frame-Options: SAMEORIGIN
Content-Security-Policy: frame-ancestors 'self';
// 3. 白名单配置
X-Frame-Options: ALLOW-FROM https://trusted-site.com
Content-Security-Policy: frame-ancestors 'self' https://trusted-site.com;
// 4. 增强安全配置
Permissions-Policy: geolocation=(), camera=(), microphone=(), payment=(), usb=()
Cross-Origin-Opener-Policy: same-origin-allow-popups
Referrer-Policy: strict-origin-when-cross-origin
// 5. 完整的 CSP 配置
Content-Security-Policy:
frame-ancestors 'none';
default-src 'self';
script-src 'self' 'nonce-{random}' 'strict-dynamic';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
font-src 'self';
object-src 'none';
base-uri 'none';
form-action 'self';
connect-src 'self' https://api.example.com;
upgrade-insecure-requests;
客户端防护机制
实现多层客户端防护:
- JavaScript 检测与防护
- DOM 安全控制
- 事件监听与拦截
- 用户交互保护
- 多层次跳出框架机制
- 心跳检测与状态监控
防护代码示例:
class ClientSideProtection {
constructor(options = {}) {
this.options = {
allowedDomains: [],
protectionLevel: 'high',
maxBreakoutAttempts: 3,
heartbeatInterval: 1000,
...options
};
this.breakoutAttempts = 0;
this.init();
}
init() {
this.setupFrameDetection();
this.setupDOMProtection();
this.setupEventProtection();
this.monitorUserInteraction();
this.initializeBreakoutProtection();
}
initializeBreakoutProtection() {
// 设置心跳检测
this.setupHeartbeat();
// 监听存储事件
window.addEventListener('storage', this.handleStorageEvent.bind(this));
// 设置定期检查
this.setupPeriodicCheck();
}
setupHeartbeat() {
const heartbeatKey = 'frame_heartbeat';
setInterval(() => {
try {
localStorage.setItem(heartbeatKey, Date.now().toString());
} catch (e) {
console.warn('Heartbeat failed:', e);
}
}, this.options.heartbeatInterval);
}
setupPeriodicCheck() {
setInterval(() => {
if (!this.isTopWindow() && this.breakoutAttempts < this.options.maxBreakoutAttempts) {
this.breakOutFrame();
this.breakoutAttempts++;
}
}, 2000);
}
breakOutFrame() {
// 1. 基础跳出方法
this.basicBreakout();
// 2. 高级跳出方法
if (!this.isTopWindow()) {
this.advancedBreakout();
}
}
basicBreakout() {
try {
if (window.top !== window.self) {
window.top.location.href = window.self.location.href;
}
} catch (e) {
console.warn('Basic breakout failed:', e);
}
}
advancedBreakout() {
// 方法1: 使用 window.location
try {
window.location = document.location.href;
} catch (e) {
// 方法2: 使用 location.replace
try {
window.location.replace(document.location.href);
} catch (e2) {
// 方法3: 使用 document.write
this.documentWriteBreakout();
}
}
}
documentWriteBreakout() {
try {
document.write(`
<script>
window.onload = function() {
window.top.location = window.location;
}
</script>
`);
} catch (e) {
// 最后尝试递归跳出
this.recursiveBreakout();
}
}
recursiveBreakout(maxDepth = 10) {
let currentWindow = window;
let depth = 0;
while (currentWindow !== window.top && depth < maxDepth) {
try {
if (currentWindow.parent.location.href) {
currentWindow = currentWindow.parent;
depth++;
} else {
break;
}
} catch (e) {
break;
}
}
try {
currentWindow.location = document.location.href;
} catch (e) {
this.basicBreakout();
}
}
setupFrameDetection() {
if (window.self !== window.top) {
const parentDomain = this.getParentDomain();
if (!this.isAllowedDomain(parentDomain)) {
this.takeProtectiveAction();
}
}
}
setupDOMProtection() {
// 防止 DOM 篡改
const observer = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
if (this.isSuspiciousChange(mutation)) {
this.handleSuspiciousActivity(mutation);
}
});
});
observer.observe(document.body, {
childList: true,
subtree: true,
attributes: true
});
}
setupEventProtection() {
// 保护关键事件
const protectedEvents = ['copy', 'paste', 'cut', 'contextmenu'];
protectedEvents.forEach(eventType => {
document.addEventListener(eventType, (e) => {
if (this.shouldPreventEvent(e)) {
e.preventDefault();
}
}, true);
});
}
monitorUserInteraction() {
// 监控可疑的用户交互
document.addEventListener('click', (e) => {
if (this.isSuspiciousClick(e)) {
this.handleSuspiciousActivity({
type: 'suspicious_click',
details: {
x: e.clientX,
y: e.clientY,
target: e.target
}
});
}
}, true);
}
takeProtectiveAction() {
// 1. 显示警告覆盖层
this.showProtectionOverlay();
// 2. 禁用敏感功能
this.disableSensitiveFeatures();
// 3. 尝试跳出框架
if (this.options.protectionLevel === 'high') {
this.breakOutFrame();
}
// 4. 上报安全事件
this.reportSecurityEvent();
}
showProtectionOverlay() {
const overlay = document.createElement('div');
overlay.innerHTML = `
<div class="security-overlay">
<h1>安全警告</h1>
<p>检测到未授权的嵌入行为</p>
<a href="${window.location.href}" target="_top">
直接访问网站
</a>
</div>
`;
// 添加样式确保覆盖层始终可见
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(255,0,0,0.9);
z-index: 2147483647;
display: flex;
align-items: center;
justify-content: center;
color: white;
text-align: center;
`;
document.body.appendChild(overlay);
}
}
智能监控系统
建立全面的智能监控和分析体系:
- 机器学习异常检测
- 实时行为分析
- 威胁情报集成
- 自动响应机制
- 安全事件追踪
- 性能影响评估
智能监控示例:
class AdvancedSecurityMonitor {
constructor() {
this.mlModel = null;
this.threatIntel = new ThreatIntelligence();
this.metrics = new MetricsCollector();
this.init();
}
async init() {
// 加载机器学习模型
this.mlModel = await tf.loadLayersModel('/models/security-detection.json');
this.startMonitoring();
}
startMonitoring() {
// 性能监控
this.monitorPerformance();
// 行为分析
this.analyzeBehavior();
// 异常检测
this.detectAnomalies();
// 威胁评估
this.assessThreats();
}
async detectAnomalies() {
const features = this.extractFeatures();
const prediction = await this.mlModel.predict(features);
if (prediction > this.threshold) {
this.handleAnomaly({
type: 'ml_detection',
confidence: prediction,
features
});
}
}
assessThreats() {
const threats = this.threatIntel.analyze({
domain: window.location.hostname,
ip: this.clientIP,
userAgent: navigator.userAgent,
behaviors: this.behaviors
});
if (threats.length > 0) {
this.handleThreats(threats);
}
}
handleAnomaly(anomaly) {
// 1. 记录异常
this.logAnomaly(anomaly);
// 2. 评估风险
const risk = this.evaluateRisk(anomaly);
// 3. 采取行动
if (risk.level === 'high') {
this.takeProtectiveAction(risk);
}
// 4. 通知管理员
this.notifyAdmin({
type: 'anomaly_detected',
details: anomaly,
risk
});
}
}
最佳实践建议
全面的安全防护建议:
- 实施多层防护策略
- 定期安全评估和更新
- 建立应急响应机制
- 进行安全培训和演练
- 保持技术栈更新
- 遵循安全开发生命周期
- 制定完整的安全策略
- 建立安全事件处理流程
重要提示:
- 在实施防护措施需要平衡安全性和可用性
- 某些防护措施可能影响合法的嵌入场景
- 建议实施白名单机制允许受信任的来源
- 定期评估和更新安全策略的有效性
- 保持对新型安全威胁的警惕