一.从 iframe 说起

利用iframe能够嵌入第三方页面,例如:

<iframe style="width: 800px; height: 600px;" src="https://www.baidu.com"/>

然而,并非所有第三方页面都能够通过iframe嵌入:

<iframe style="width: 800px; height: 600px;" src="https://github.com/join"/>

Github 登录页并没有像百度首页一样乖乖显示到iframe里,并且在 Console 面板输出了一行错误:

Refused to display ‘https://github.com/join’ in a frame because an ancestor violates the following Content Security Policy directive: “frame-ancestors ‘none'”.

这是为什么呢?

二.点击劫持与安全策略

没错,禁止页面被放在iframe里加载主要是为了防止点击劫持(Clickjacking):

具体的,对于点击劫持,主要有 3 项应对措施:

  • CSP(Content Security Policy,即内容安全策略)

  • X-Frame-Options

  • framekiller

服务端通过设置 HTTP 响应头来声明 CSP 和X-Frame-Options,例如:

# 不允许被嵌入,包括<frame>, <iframe>, <object>, <embed> 和 <applet>
Content-Security-Policy: frame-ancestors 'none'
# 只允许被同源的页面嵌入
Content-Security-Policy: frame-ancestors 'self'
# 只允许被白名单内的页面嵌入
Content-Security-Policy: frame-ancestors www.example.com# 不允许被嵌入,包括<frame>, <iframe>, <embed> 和 <object>
X-Frame-Options: deny
# 只允许被同源的页面嵌入
X-Frame-Options: sameorigin
# (已废弃)只允许被白名单内的页面嵌入
X-Frame-Options: allow-from www.example.com

P.S.同源是指协议、域名、端口号都完全相同,见Same-origin policy

P.S.另外,还有个与frame-ancestors长得很像的frame-src,但二者作用相反,后者用来限制当前页面中的<iframe><frame>所能加载的内容来源

至于 framekiller,则是在客户端执行一段 JavaScript,从而反客为主

// 原版
<script>
if(top != self) top.location.replace(location);
</script>// 增强版
<style> html{display:none;} </style>
<script>
if(self == top) {document.documentElement.style.display = 'block';
} else {top.location = self.location;
}
</script>

而 Github 登录页,同时设置了 CSP 和X-Frame-Options响应头:

Content-Security-Policy: frame-ancestors 'none';
X-Frame-Options: deny

因此无法通过iframe嵌入,那么,有办法打破这些限制吗?

三.思路

既然主要限制来自 HTTP 响应头,那么至少有两种思路:

  • 篡改响应头,使之满足iframe安全限制

  • 不直接加载源内容,绕过iframe安全限制

在资源响应到达终点之前的任意环节,拦截下来并改掉 CSP 与X-Frame-Options,比如在客户端收到响应时拦截篡改,或由代理服务转发篡改

而另一种思路很有意思,借助Chrome Headless加载源内容,转换为截图展示到iframe中。例如Browser Preview for VS Code:

Browser Preview is powered by Chrome Headless, and works by starting a headless Chrome instance in a new process. This enables a secure way to render web content inside VS Code, and enables interesting features such as in-editor debugging and more!

也就是说,通过 Chrome 正常加载页面,再将内容截图放到iframe里,因而不受上述(包括 framekiller 在内的)安全策略的限制。但这种方案也并非完美,存在另一些问题:

  • 全套交互事件都需要适配支持,例如双击、拖拽

  • 部分功能受限,例如无法拷贝文本,不支持播放音频等

四.解决方案

客户端拦截

Service Worker

要拦截篡改 HTTP 响应,最先想到的,自然是 Service Worker(一种Web Worker):

A service worker is an event-driven worker registered against an origin and a path. It takes the form of a JavaScript file that can control the web-page/site that it is associated with, intercepting and modifying navigation and resource requests.

(摘自Service Worker API)

注册 Service Worker 后能够拦截并修改资源请求,例如:

// 1.注册Service Worker
navigator.serviceWorker.register('./sw-proxy.js');// 2.拦截请求(sw-proxy.js)
self.addEventListener('fetch', async (event) => {const {request} = event;let response = await fetch(request);// 3.重新构造Responseresponse = new Response(response.body, response)// 4.篡改响应头response.headers.delete('Content-Security-Policy');response.headers.delete('X-Frame-Options');event.respondWith(Promise.resolve(originalResponse));
});

注意,Fetch Response 不允许直接修改请求头,需要重新构造一个,见Alter Headers

P.S.完整实现案例,可参考DannyMoerkerke/sw-proxy

WebRequest

如果是在 Electron 环境,还可以借助WebRequest API来拦截并篡改响应:

const { session } = require('electron')session.defaultSession.webRequest.onHeadersReceived((details, callback) => {callback({responseHeaders: {...details.responseHeaders,'Content-Security-Policy': ['default-src \'none\'']}})
})

(摘自CSP HTTP Header)

但与 Service Worker 类似,WebRequest 同样依赖客户端环境,而出于安全性考虑,这些能力在一些环境下会被禁掉,此时就需要从服务端寻找出路,比如通过代理服务转发

代理服务转发

基本思路是通过代理服务转发源请求和响应,在转发过程中修改响应头甚至响应体

具体实现上,分为 2 步:

  • 创建代理服务,篡改响应头字段

  • 客户端请求代理服务

以为 HTTPS 为例,代理服务简单实现如下:

const https = require("https");
const querystring = require("querystring");
const url = require("url");const port = 10101;
// 1.创建代理服务
https.createServer(onRequest).listen(port);function onRequest(req, res) {const originUrl = url.parse(req.url);const qs = querystring.parse(originUrl.query);const targetUrl = qs["target"];const target = url.parse(targetUrl);const options = {hostname: target.hostname,port: 80,path: url.format(target),method: "GET"};// 2.代发请求const proxy = https.request(options, _res => {// 3.修改响应头const fieldsToRemove = ["x-frame-options", "content-security-policy"];Object.keys(_res.headers).forEach(field => {if (!fieldsToRemove.includes(field.toLocaleLowerCase())) {res.setHeader(field, _res.headers[field]);}});_res.pipe(res, {end: true});});req.pipe(proxy, {end: true});
}

客户端iframe不再直接请求源资源,而是通过代理服务去取:

<iframe style="width: 400px; height: 300px;" src="http://localhost:10101/?target=https%3A%2F%2Fgithub.com%2Fjoin"/>

如此这般,Github 登录页就能在iframe里乖乖显示出来了:

iframe github login

an ancestor violates the following Content Security Policy directive: “frame-ancestors ‘none‘”.相关推荐

  1. because it violates the following Content Security Policy directive: “default-src ‘none‘“

    在打开页面时浏览器报如下错误: Refused to load the script 'http://xx.xx.xx.xx:xxxxx/livereload.js?snipver=1' becaus ...

  2. Refused to execute inline script because it violates the following Content Security Policy directive

    版权声明 本文原创作者:谷哥的小弟 作者博客地址:http://blog.csdn.net/lfdfhl 问题描述 在利用表单向后台提交数据时,前端页面报错: Refused to execute i ...

  3. Vue打包后出现的bug -favicon.ico' because it violates the following Content Security Policy direc

    打开vue的项目,但是页面显示的是Cannot GET,打开控制台之后,发现有一篇红色报错. //Refused to load the image 'http://localhost:8080/fa ...

  4. uni-app - Refused to display ‘xxx‘ in a frame because an ancestor violates the following Content Sec

    报错原因 整体流程的话,就是将网页通过 web-view 组件内嵌到 App 中(非小程序),其中有跳转微信公众号的需求,不料却收到了以下报错. 我又不是打包小程序,就套壳个 App ,比较疑惑为什么 ...

  5. violates Content Security Policy报错1

    index.html:1 Refused to load the script 'https://webapi.amap.com/maps?v=1.4.13&key=b7063c0343460 ...

  6. 正当防卫CSP(content security policy)

    同源策略致使不同域名下的资源不可互相访问,起到安全保护的作用,但这一策略有时会防卫过当,将安全可信的脚本也误认为不安全因素后报错: because it violates the following ...

  7. Content Security Policy的学习理解

    以下内容转载自 http://www.cnblogs.com/alisecurity/p/5924023.html 跨域脚本攻击 XSS 是最常见.危害最大的网页安全漏洞. 为了防止它们,要采取很多编 ...

  8. Content Security Policy 入门教程

    From: http://www.ruanyifeng.com/blog/2016/09/csp.html 跨域脚本攻击 XSS 是最常见.危害最大的网页安全漏洞. 为了防止它们,要采取很多编程措施, ...

  9. Refused to load the image 'URL' because it violates the following content security polity diretive

    转载地址:https://www.cnblogs.com/xiaoxiaoluoye/p/6945044.html 深入学习地址:https://www.cnblogs.com/Hwangzhiyou ...

  10. 内容安全策略(Content Security Policy)

    内容安全策略(Content Security Policy) 内容安全策略(Content Security Policy)是一种声明的安全机制,可以让网站运营者能够控制遵循CSP的用户代理(通常是 ...

最新文章

  1. Day 19: EmberJS 入门指南
  2. 解决alibaba-dubbo调用findFirstNonLoopbackHostInfo导致启动慢
  3. Cisco 3560 配置DHCP Relay实例
  4. 两种方式实现节流函数
  5. IntelliJ检查给出“无法解析符号”但仍编译代码
  6. 减小数据泄密负面影响的办法
  7. 如何在photoshop中等比例缩放一张图
  8. 微信商户平台所有产品总结
  9. 轻量级openpose解析
  10. 矩阵分析与应用-1.2-向量空间_内积空间与线性映射
  11. 永久性删除的文件怎么恢复,怎么还原文件
  12. 20191025 前端开发日报
  13. 使用 RTSCapture 类可以防止帧处理速度小于接收速度而导致花屏或者断流(崩溃)opencv-python RTSP
  14. coTurn 运行在Windows平台的方法
  15. smartforms以PDF打印预览
  16. 利用eeglab处理采集的脑电信号
  17. 聚焦科技创新产业升级 中国联通和腾讯签署新战略合作协议
  18. [JVM]了断局: 类加载机制
  19. 在IIS7、IIS7.5中应用程序池最优配置方案
  20. Nvidia 显卡 Failed to initialize NVML Driver/library version

热门文章

  1. 手机游戏公司设定的客户群体是大学生和农民工
  2. unity检测范围内敌人_Unity判断周围是否有敌人
  3. Unity敌人生成器
  4. 盘点安卓手机被吐槽最多的三大奇葩设计
  5. 6-3近期工作总结、下一步工作安排及技术知识
  6. Zookeeper + ActiveMQ 集群整合
  7. WSJ Merkel Top On Forbes' Most Powerful Women List For 4th Year
  8. 大疆的这个可编程教育机器人,可真不是个一般的机器人
  9. re,正则表达式,requests,爬取小猪短租网
  10. idea 删除当一行或者选中行的快捷键