CodeWalk

点击劫持(Clickjacking)攻击与 X-Frame-Options 防御

作者:Yahuda · 2026-05-30 12:55

请解释点击劫持(Clickjacking/UI Redress)攻击的原理,以及 X-Frame-Options 和 CSP frame-ancestors 两种防御机制的配置方式。

回答

Yahuda

点击劫持原理

<!-- 攻击者页面 -->
<style>
  iframe {
    position: absolute;
    top: -100px; left: -100px;
    opacity: 0.0001;
    z-index: 100;
  }
  .button {
    position: absolute;
    top: 200px; left: 200px;
  }
</style>
<div class="button">点我领奖</div>
<iframe src="https://bank.com/transfer?to=attacker&amount=10000"></iframe>
  • 攻击者用透明 iframe 覆盖合法页面,诱骗用户点击
  • 用户以为在点击正常按钮,实际在操作 iframe 中的敏感功能

防御方案

1. X-Frame-Options(HTTP 响应头)

X-Frame-Options: DENY          # 完全禁止 iframe 加载
X-Frame-Options: SAMEORIGIN    # 同源可加载 iframe
  • 较早的防御方式(IE8+)
  • 缺点:粒度粗,不支持多个域名白名单

2. CSP frame-ancestors(推荐)

Content-Security-Policy: frame-ancestors 'none';                    # 禁止 iframe
Content-Security-Policy: frame-ancestors 'self';                    # 仅同源
Content-Security-Policy: frame-ancestors https://trusted.com;      # 指定域名
  • CSP Level 2 标准,比 X-Frame-Options 更灵活
  • 支持多个源,支持通配符
  • 同时设置时 frame-ancestors 优先级更高

3. JavaScript 防御(辅助)

if (top !== self) { top.location.href = self.location.href; }
// 但可被沙箱 iframe 的 sandbox 属性绕过

最佳实践:同时设置 X-Frame-Options: SAMEORIGIN + CSP: frame-ancestors 'self'