Skip to content

点击劫持(Clickjacking)

攻击者用透明 <iframe> 叠在正常按钮上,用户以为在点「领取优惠券」,实际点在背后的「确认转账」等按钮。


攻击页面示意(概念)

html
<style>
  iframe {
    position: absolute;
    opacity: 0.001;
    width: 400px;
    height: 300px;
    top: 100px;
    left: 100px;
  }
</style>
<button style="padding: 24px">点此抽奖</button>
<iframe src="https://victim.example/account/delete"></iframe>

防御一:frame-ancestors(CSP,推荐)

服务端响应头:

http
Content-Security-Policy: frame-ancestors 'none';

仅允许本站嵌入自身:

http
Content-Security-Policy: frame-ancestors 'self';

允许指定伙伴域名:

http
Content-Security-Policy: frame-ancestors 'self' https://partner.example;

防御二:X-Frame-Options(兼容旧环境)

http
X-Frame-Options: DENY

或:

http
X-Frame-Options: SAMEORIGIN

防御三:前端「破框」(仅辅助,可被绕过)

若检测到页面被嵌套在 iframe,可跳转顶层(注意:部分场景合法嵌入需要放行)。

js
if (window.top !== window.self) {
  window.top.location = window.self.location;
}

限制:不能替代响应头;攻击仍可用 sandbox + allow-forms 等技巧对抗(具体取决于浏览器策略),故必须以服务端头部为准。


Nginx 配置示例(静态站点)

nginx
location / {
    add_header Content-Security-Policy "frame-ancestors 'self'" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
}

小结

点击劫持的权威防线是 frame-ancestors / X-Frame-Options,告诉浏览器「禁止被谁嵌入」;前端脚本检测只能作为补充。