天天看點

打破 iframe 安全限制的 3 種方案

關注「前端向後」微信公衆号,你将收獲一系列「用心原創」的高品質技術文章,主題包括但不限于前端、Node.js以及服務端技術

一.從 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):

打破 iframe 安全限制的 3 種方案

具體的,對于點選劫持,主要有 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;
  const response = await fetch(request);
  // 3.拷貝克隆請求
  // 4.篡改響應頭
  response.headers.delete('Content-Security-Policy');
  response.headers.delete('X-Frame-Options');

  event.respondWith(Promise.resolve(originalResponse));
});
           

複制

注意,Fetch Response 無法直接修改請求頭,需要手動拷貝克隆,見How to alter the headers of a Response?

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 安全限制的 3 種方案

iframe github login

參考資料

  • Clickjacking Defense Cheat Sheet
  • 6.3.2. frame-ancestors
  • CSP Cheat Sheet

聯系我

如果心中仍有疑問,請檢視原文并留下評論噢。(特别要緊的問題,可以直接微信聯系 ayqywx )