简体   繁体   中英

Electron 'contextBridge'

To provide suitable levels of security when loading remote content, it is stated that a BrowserWindow 's contextIsolation and nodeIntegration options must be enabled and disabled respectively. In this scenario, Node/Electron APIs will not be available to the main renderer process. In order to expose specific functionality, the window's preload script may exploit Electron's contextBridge feature, providing the main renderer with access to selected Node/Electron APIs.

Despite information provided in the Electron docs, concrete examples of contextBridge usage are lacking overall. In general, existing documentation/tutorials do not focus on adopting secure practices when implementing an Electron app.

The following is a single contextBridge usage example I've managed to find online: https://github.com/reZach/secure-electron-template

Would you be able to provide additional resources/examples which might be useful for the implementation of a secure Electron app (which relies on the contextBridge functionality)?

Insight regarding contextBridge best practices is also highly appreciated.

I'm the author of the template, let me offer some background knowledge you might find helpful. Disclaimer : I'm not a security researcher, but this is scraped from multiple sources.

ContextBridge is important because it offers protection against passing values into the renderer process based off the old way .

Old way

const {
    ipcRenderer
} = require("electron");

window.send = function(channel, data){
    // whitelist channels
    let validChannels = ["toMain"];
    if (validChannels.includes(channel)) {
        ipcRenderer.send(channel, data);
    }
};

window.recieve = function(channel, func){
    let validChannels = ["fromMain"];
    if (validChannels.includes(channel)) {
        // Deliberately strip event as it includes `sender` 
        ipcRenderer.on(channel, (event, ...args) => func(...args));
    }
};

This code is vulnerable to the client opening the dev tools, and modifying the function definition of window.send and window.recieve . The client can then start to ping your ipcMain in your main.js script and then possibly do some damage because they could get around your whitelisting ipc channels in the preload js. This assumes you are whitelisting in your main.js too, but I've seen plenty of examples that are not and would be vulnerable to such an attack.

From the docs :

Function values are proxied to the other context and all other values are copied and frozen. Any data / primitives sent in the API object become immutable and updates on either side of the bridge do not result in an update on the other side.

In other words, because we use contextBridge.exposeInMainWorld , our renderer process cannot modify the definition of the functions we expose, protecting us from a possible security attack vector.

New way

const {
    contextBridge,
    ipcRenderer
} = require("electron");

// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
    "api", {
        send: (channel, data) => {
            // whitelist channels
            let validChannels = ["toMain"];
            if (validChannels.includes(channel)) {
                ipcRenderer.send(channel, data);
            }
        },
        receive: (channel, func) => {
            let validChannels = ["fromMain"];
            if (validChannels.includes(channel)) {
                // Deliberately strip event as it includes `sender` 
                ipcRenderer.on(channel, (event, ...args) => func(...args));
            }
        }
    }
);

Source

I had some trouble with this myself. My solution was this preload.js template

const { ipcRenderer, contextBridge } = require('electron')

const validChannels = ["toMain", "myRenderChannel"];

contextBridge.exposeInMainWorld(
  "api", {
    send: (channel, data) => {
        if (validChannels.includes(channel)) {
            ipcRenderer.send(channel, data);
        }
    },
    on: (channel, callback) => {
      if (validChannels.includes(channel)) {
        // Filtering the event param from ipcRenderer
        const newCallback = (_, data) => callback(data);
        ipcRenderer.on(channel, newCallback);
      }
    },
    once: (channel, callback) => { 
      if (validChannels.includes(channel)) {
        const newCallback = (_, data) => callback(data);
        ipcRenderer.once(channel, newCallback);
      }
    },
    removeListener: (channel, callback) => {
      if (validChannels.includes(channel)) {
        ipcRenderer.removeListener(channel, callback);
      }
    },
    removeAllListeners: (channel) => {
      if (validChannels.includes(channel)) {
        ipcRenderer.removeAllListeners(channel)
      }
    },
  }
);

Here are all the steps to set this up

  1. In your main electron index.js file, point to the preload script in your BrowserWindow config object:

 new BrowserWindow({ webPreferences: { preload: path.resolve(app.getAppPath(), 'preload.js') } })

  1. The preload.js needs to be in your app folder. I use webpack to compile everything, so the preload.js file is not where my js code is, it's in the app directory where electron-builder will compile the executable. Here's what the preload.js contains:

 process.once('loaded', () => { const { contextBridge, ipcRenderer, shell } = require('electron') contextBridge.exposeInMainWorld('electron', { on (eventName, callback) { ipcRenderer.on(eventName, callback) }, async invoke (eventName, ...params) { return await ipcRenderer.invoke(eventName, ...params) }, async shellOpenExternal (url) { await shell.openExternal(url) }, async shellOpenPath (file) { await shell.openPath(file) }, async shellTrashItem (file) { await shell.trashItem(file) } }) })

  1. All this is part of the node.js code. Now let's see how we use this code in our renderer code, the chrome client side code.

 window.electron.on('nodeJSEvent', (event, param1, param2) => { console.log('nodeJSEvent has been called with params', param1, param2) }) const foo = await window.electron.invoke('nodeJSEvent', param1, param2) console.log(foo) await window.electron.shellOpenExternal(url) await window.electron.shellOpenPath(file) await window.electron.shellTrashItem(file)

That's it. All this code is about giving the possibility to the client side code to call nodejs code that we define in the preload script.

Here's an example of a project that uses the contextBridge :

https://github.com/frederiksen/angular-electron-boilerplate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM