Sicherheit
Informationen dazu, wie sie eine Electron-Sicherheitslücke richtig melden können, finden Sie unter SECURITY.md.
Schaue die für mehr Informationen das Electron Release Timelines Dokument an.
Vorwort
Als Webentwickler genießen wir normalerweise das starke Sicherheitsnetz des Browsers - die Risiken, die mit dem von uns geschriebenen Code verbunden sind, sind relativ gering. Unseren Websites werden in einer Sandbox mit begrenzten Befugnissen ausgeführt und wir vertrauen darauf, dass unsere Benutzer einen Browser verwenden, der von einem großen Team von Ingenieuren entwickelt wurde und der in der Lage ist, schnell auf neu entdeckte Sicherheitsbedrohungen zu reagieren.
Bei der Arbeit mit Electron ist es wichtig zu verstehen, dass Electron kein Webbrowser ist. Es erlaubt Ihnen, funktionstüchtige Desktop-Anwendungen mit vertrauten Web-Technologien zu erstellen, aber Ihr Code hat viel mehr Kraft. JavaScript kann auf das Dateisystem, die Benutzer-Shell und einiges mehr zugreifen. Dies erlaubt Ihnen, hochqualitative native Anwendungen zu erstellen, aber die inhärenten Sicherheitsrisiken skalieren mit den zusätzlichen Befugnissen, die Ihrem Code gewährt werden.
Vor diesem Hintergrund sollten Sie sich bewusst sein, dass die Anzeige willkürlicher Inhalte aus nicht vertrauenswürdigen Quellen ein ernstes Sicherheitsrisiko darstellt, dass Electron nicht vollständig verhindern kann. Tatsächlich zeigen die beliebtesten Electron-Anwendungen (Atom, Slack, Visual Studio Code usw.) hauptsächlich lokale Inhalte an (oder vertrauenswürdige, sichere Remote-Inhalte ohne Node Integration) - wenn deine Anwendung Code aus einer Online-Quelle ausführt, ist es deine Verantwortung, sicherzustellen, dass der Code nicht bösartig ist.
Generelle Richtlinien
Sicherheit liegt in der Verantwortung aller
. Somit liegt es in ihrer Verantwortung einige Best Practices zu befolgen:
-
Halte deine Applikation auf dem neusten Stand mit dem aktuellen Electron Framework Release. Wenn du dein Produkt veröffentlichts, lieferst du ebenso ein Bündel aus Electron, Chromium Shared Library und Node.js. Schwachstellen, die diese Komponenten betreffen können die Sicherheit Ihrer Anwendung beeinträchtigen. Per Update Electron auf den neuesten Stand bringen Für mehr Informationen, Siehe "Die aktuelle Version von Electron benutzen".
-
Evaluate your dependencies. While NPM provides half a million reusable packages, it is your responsibility to choose trusted 3rd-party libraries. If you use outdated libraries affected by known vulnerabilities or rely on poorly maintained code, your application security could be in jeopardy.
-
Adopt secure coding practices. The first line of defense for your application is your own code. Common web vulnerabilities, such as Cross-Site Scripting (XSS), have a higher security impact on Electron applications hence it is highly recommended to adopt secure software development best practices and perform security testing.
Isolierung für nicht vertrauenswürdige Inhalte
Ein Sicherheitsproblem besteht immer dann, wenn du Code von einer nicht vertrauenswürdigen Quelle (z. B. einem Remote-Server) erhältst und ihn lokal ausführst. Nehmen wir als Beispiel eine Remote-Website, die in einem BrowserWindow
angezeigt wird. If an attacker somehow manages to change said content (either by attacking the source directly, or by sitting between your app and the actual destination), they will be able to execute native code on the user's machine.
Under no circumstances should you load and execute remote code with Node.js integration enabled. Instead, use only local files (packaged together with your application) to execute Node.js code. To display remote content, use the <webview>
tag or a WebContentsView
and make sure to disable the nodeIntegration
and enable contextIsolation
.
Sicherheitswarnungen und Empfehlungen werden in der Entwicklerkonsole ausgegeben. Diese werden nur angezeigt, wenn der Name der Binärdatei Electron lautet, was bedeutet, dass ein Entwickler gerade auf die Konsole schaut.
You can force-enable or force-disable these warnings by setting ELECTRON_ENABLE_SECURITY_WARNINGS
or ELECTRON_DISABLE_SECURITY_WARNINGS
on either process.env
or the window
object.
Checkliste: Sicherheitsempfehlungen
Du solltest zumindest diese Schritte befolgen, um die Sicherheit deiner Anwendung zu verbessern:
- Nur sichere Inhalte laden
- Deaktiviere die Node.js-Integration in allen Renderern, die Remote-Inhalte anzeigen
- Kontext-Isolation in allen Renderern aktivieren
- Prozess-Sandboxing aktivieren
ses.setPermissionRequestHandler()
in allen Sitzungen verwenden, die Remote-Inhalte ladenwebSecurity
nicht deaktivieren- Definiere ein
Content-Security-Policy
und verwende restriktive Regeln (z.B.script-src 'self'
) allowRunningInsecureContent
nicht aktivieren- Experimentelle Funktionen nicht aktivieren
enableBlinkFeatures
nicht verwenden<webview>
:allowpopups
nicht verwenden<webview>
: Optionen und Parameter überprüfen- Navigation deaktivieren oder beschränken
- Deaktiviere oder beschränke die Erstellung neuer Fenster
shell.openExternal
nicht mit nicht vertrauenswürdigen Inhalten verwenden- Aktuelle Version von Electron verwenden
- Validate the
sender
of all IPC messages - Avoid usage of the
file://
protocol and prefer usage of custom protocols - Check which fuses you can change
To automate the detection of misconfigurations and insecure patterns, it is possible to use Electronegativity. For additional details on potential weaknesses and implementation bugs when developing applications using Electron, please refer to this guide for developers and auditors.
1. Nur sichere Inhalte laden
Alle Ressourcen, die nicht in deiner Anwendung enthalten sind, sollten über ein sicheres Protokoll wie HTTPS
geladen werden. Mit anderen Worten: Verwende keine unsicheren Protokolle wie HTTP
. Similarly, we recommend the use of WSS
over WS
, FTPS
over FTP
, and so on.
Warum?
HTTPS
hat zwei wesentliche Vorteile:
- It ensures data integrity, asserting that the data was not modified while in transit between your application and the host.
- It encrypts the traffic between your user and the destination host, making it more difficult to eavesdrop on the information sent between your app and the host.
Wie?
// Schlecht
browserWindow.loadURL('http://example.com')
// Gut
browserWindow.loadURL('https://example.com')
<!-- Schlecht -->
<script crossorigin src="http://example.com/react.js"></script>
<link rel="stylesheet" href="http://example.com/style.css">
<!-- Gut -->
<script crossorigin src="https://example.com/react.js"></script>
<link rel="stylesheet" href="https://example.com/style.css">
2. Node.js-Integration für Remote-Inhalte nicht aktivieren
Diese Empfehlung ist das Standardverhalten in Electron seit 5.0.0.
It is paramount that you do not enable Node.js integration in any renderer (BrowserWindow
, WebContentsView
, or <webview>
) that loads remote content. The goal is to limit the powers you grant to remote content, thus making it dramatically more difficult for an attacker to harm your users should they gain the ability to execute JavaScript on your website.
Danach können Sie zusätzliche Berechtigungen für bestimmte Hosts erteilen. Zum Beispiel, wenn Sie ein BrowserWindow öffnen, das auf https://example.com/
zeigt, können Sie dieser Website genau die Fähigkeiten geben, welche sie benötigt.
Warum?
Eine Cross-Site-Scripting (XSS) ist gefährlicher, wenn ein Angreifer aus dem Renderer-Prozess ausbrechen und Code auf dem Computer des Benutzers ausführen kann. Cross-site-scripting attacks are fairly common - and while an issue, their power is usually limited to messing with the website that they are executed on. Disabling Node.js integration helps prevent an XSS from being escalated into a so-called "Remote Code Execution" (RCE) attack.
Wie?
// Schlecht
const mainWindow = new BrowserWindow({
webPreferences: {
contextIsolation: false,
nodeIntegration: true,
nodeIntegrationInWorker: true
}
})
mainWindow.loadURL('https://example.com')
// Gut
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(app.getAppPath(), 'preload.js')
}
})
mainWindow.loadURL('https://example.com')
<!-- Schlecht -->
<webview nodeIntegration src="page.html"></webview>
<!-- Gut -->
<webview src="page.html"></webview>
Wenn die Node.js-Integration deaktivierst, kannst du immer noch APIs für deine Website bereitstellen, die Node.js-Module oder -Funktionen verwenden. Preload scripts continue to have access to require
and other Node.js features, allowing developers to expose a custom API to remotely loaded content via the contextBridge API.
3. Kontext-Isolation aktivieren
Diese Empfehlung ist das Standardverhalten in Electron seit 12.0.0.
Context isolation is an Electron feature that allows developers to run code in preload scripts and in Electron APIs in a dedicated JavaScript context. In practice, that means that global objects like Array.prototype.push
or JSON.parse
cannot be modified by scripts running in the renderer process.
Electron uses the same technology as Chromium's Content Scripts to enable this behavior.
Even when nodeIntegration: false
is used, to truly enforce strong isolation and prevent the use of Node primitives contextIsolation
must also be used.
For more information on what contextIsolation
is and how to enable it please see our dedicated Context Isolation document.
4. Prozess-Sandboxing aktivieren
Sandboxing is a Chromium feature that uses the operating system to significantly limit what renderer processes have access to. Sie sollten die die Sandbox in allen Renderern aktivieren. Das Laden, Lesen oder Verarbeiten von nicht vertrauenswürdigen Inhalten in einem nicht gesandboxten Prozess, einschließlich des Hauptprozesses, wird nicht empfohlen.
For more information on what Process Sandboxing is and how to enable it please see our dedicated Process Sandboxing document.
5. Handle session permission requests from remote content
You may have seen permission requests while using Chrome: they pop up whenever the website attempts to use a feature that the user has to manually approve ( like notifications).
The API is based on the Chromium permissions API and implements the same types of permissions.
Warum?
By default, Electron will automatically approve all permission requests unless the developer has manually configured a custom handler. While a solid default, security-conscious developers might want to assume the very opposite.
Wie?
const { session } = require('electron')
const { URL } = require('url')
session
.fromPartition('some-partition')
.setPermissionRequestHandler((webContents, permission, callback) => {
const parsedUrl = new URL(webContents.getURL())
if (permission === 'notifications') {
// Approves the permissions request
callback(true)
}
// Verify URL
if (parsedUrl.protocol !== 'https:' || parsedUrl.host !== 'example.com') {
// Denies the permissions request
return callback(false)
}
})
6. webSecurity
nicht deaktivieren
Diese Empfehlung ist die Standardeinstellung von Electron.
You may have already guessed that disabling the webSecurity
property on a renderer process (BrowserWindow
, WebContentsView
, or <webview>
) disables crucial security features.
Deaktiviere webSecurity
in Produktionsanwendungen nicht.
Warum?
Disabling webSecurity
will disable the same-origin policy and set allowRunningInsecureContent
property to true
. In other words, it allows the execution of insecure code from different domains.
Wie?
// Schlecht
const mainWindow = new BrowserWindow({
webPreferences: {
webSecurity: false
}
})
// Gut
const mainWindow = new BrowserWindow()
<!-- Schlecht -->
<webview disablewebsecurity src="page.html"></webview>
<!-- Gut -->
<webview src="page.html"></webview>
7. Define a Content Security Policy
A Content Security Policy (CSP) is an additional layer of protection against cross-site-scripting attacks and data injection attacks. We recommend that they be enabled by any website you load inside Electron.
Warum?
CSP allows the server serving content to restrict and control the resources Electron can load for that given web page. https://example.com
should be allowed to load scripts from the origins you defined while scripts from https://evil.attacker.com
should not be allowed to run. Defining a CSP is an easy way to improve your application's security.
Wie?
The following CSP will allow Electron to execute scripts from the current website and from apis.example.com
.
// Schlecht
Content-Security-Policy: '*'
// Gut
Content-Security-Policy: script-src 'self' https://apis.example.com
CSP HTTP headers
Electron respects the Content-Security-Policy
HTTP header which can be set using Electron's webRequest.onHeadersReceived
handler:
const { session } = require('electron')
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
callback({
responseHeaders: {
...details.responseHeaders,
'Content-Security-Policy': ['default-src \'none\'']
}
})
})
CSP meta tag
CSP's preferred delivery mechanism is an HTTP header. However, it is not possible to use this method when loading a resource using the file://
protocol. It can be useful in some cases to set a policy on a page directly in the markup using a <meta>
tag:
<meta http-equiv="Content-Security-Policy" content="default-src 'none'">
8. allowRunningInsecureContent
nicht aktivieren
Diese Empfehlung ist die Standardeinstellung von Electron.
By default, Electron will not allow websites loaded over HTTPS
to load and execute scripts, CSS, or plugins from insecure sources (HTTP
). Setting the property allowRunningInsecureContent
to true
disables that protection.
Loading the initial HTML of a website over HTTPS
and attempting to load subsequent resources via HTTP
is also known as "mixed content".
Warum?
Loading content over HTTPS
assures the authenticity and integrity of the loaded resources while encrypting the traffic itself. See the section on only displaying secure content for more details.
Wie?
// Schlecht
const mainWindow = new BrowserWindow({
webPreferences: {
allowRunningInsecureContent: true
}
})
// Gut
const mainWindow = new BrowserWindow({})
9. Experimentelle Funktionen nicht aktivieren
Diese Empfehlung ist die Standardeinstellung von Electron.
Advanced users of Electron can enable experimental Chromium features using the experimentalFeatures
property.
Warum?
Experimental features are, as the name suggests, experimental and have not been enabled for all Chromium users. Furthermore, their impact on Electron as a whole has likely not been tested.
Legitimate use cases exist, but unless you know what you are doing, you should not enable this property.
Wie?
// Schlecht
const mainWindow = new BrowserWindow({
webPreferences: {
experimentalFeatures: true
}
})
// Gut
const mainWindow = new BrowserWindow({})
10. enableBlinkFeatures
nicht verwenden
Diese Empfehlung ist die Standardeinstellung von Electron.
Blink is the name of the rendering engine behind Chromium. As with experimentalFeatures
, the enableBlinkFeatures
property allows developers to enable features that have been disabled by default.
Warum?
Generally speaking, there are likely good reasons if a feature was not enabled by default. Legitimate use cases for enabling specific features exist. As a developer, you should know exactly why you need to enable a feature, what the ramifications are, and how it impacts the security of your application. Under no circumstances should you enable features speculatively.
Wie?
// Schlecht
const mainWindow = new BrowserWindow({
webPreferences: {
enableBlinkFeatures: 'ExecCommandInJavaScript'
}
})
// Gut
const mainWindow = new BrowserWindow()
11. Do not use allowpopups
for WebViews
Diese Empfehlung ist die Standardeinstellung von Electron.
If you are using <webview>
, you might need the pages and scripts loaded in your <webview>
tag to open new windows. The allowpopups
attribute enables them to create new BrowserWindows
using the window.open()
method. <webview>
tags are otherwise not allowed to create new windows.
Warum?
If you do not need popups, you are better off not allowing the creation of new BrowserWindows
by default. This follows the principle of minimally required access: Don't let a website create new popups unless you know it needs that feature.
Wie?
<!-- Schlecht -->
<webview allowpopups src="page.html"></webview>
<!-- Gut -->
<webview src="page.html"></webview>
12. Verify WebView options before creation
A WebView created in a renderer process that does not have Node.js integration enabled will not be able to enable integration itself. However, a WebView will always create an independent renderer process with its own webPreferences
.
It is a good idea to control the creation of new <webview>
tags from the main process and to verify that their webPreferences do not disable security features.
Warum?
Since <webview>
live in the DOM, they can be created by a script running on your website even if Node.js integration is otherwise disabled.
Electron enables developers to disable various security features that control a renderer process. In most cases, developers do not need to disable any of those features - and you should therefore not allow different configurations for newly created <webview>
tags.
Wie?
Before a <webview>
tag is attached, Electron will fire the will-attach-webview
event on the hosting webContents
. Use the event to prevent the creation of webViews
with possibly insecure options.
app.on('web-contents-created', (event, contents) => {
contents.on('will-attach-webview', (event, webPreferences, params) => {
// Strip away preload scripts if unused or verify their location is legitimate
delete webPreferences.preload
// Disable Node.js integration
webPreferences.nodeIntegration = false
// Verify URL being loaded
if (!params.src.startsWith('https://example.com/')) {
event.preventDefault()
}
})
})
Again, this list merely minimizes the risk, but does not remove it. If your goal is to display a website, a browser will be a more secure option.
13. Navigation deaktivieren oder beschränken
If your app has no need to navigate or only needs to navigate to known pages, it is a good idea to limit navigation outright to that known scope, disallowing any other kinds of navigation.
Warum?
Navigation is a common attack vector. If an attacker can convince your app to navigate away from its current page, they can possibly force your app to open web sites on the Internet. Even if your webContents
are configured to be more secure (like having nodeIntegration
disabled or contextIsolation
enabled), getting your app to open a random web site will make the work of exploiting your app a lot easier.
A common attack pattern is that the attacker convinces your app's users to interact with the app in such a way that it navigates to one of the attacker's pages. This is usually done via links, plugins, or other user-generated content.
Wie?
If your app has no need for navigation, you can call event.preventDefault()
in a will-navigate
handler. If you know which pages your app might navigate to, check the URL in the event handler and only let navigation occur if it matches the URLs you're expecting.
We recommend that you use Node's parser for URLs. Simple string comparisons can sometimes be fooled - a startsWith('https://example.com')
test would let https://example.com.attacker.com
through.
const { URL } = require('url')
const { app } = require('electron')
app.on('web-contents-created', (event, contents) => {
contents.on('will-navigate', (event, navigationUrl) => {
const parsedUrl = new URL(navigationUrl)
if (parsedUrl.origin !== 'https://example.com') {
event.preventDefault()
}
})
})
14. Deaktiviere oder beschränke die Erstellung neuer Fenster
If you have a known set of windows, it's a good idea to limit the creation of additional windows in your app.
Warum?
Much like navigation, the creation of new webContents
is a common attack vector. Attackers attempt to convince your app to create new windows, frames, or other renderer processes with more privileges than they had before; or with pages opened that they couldn't open before.
If you have no need to create windows in addition to the ones you know you'll need to create, disabling the creation buys you a little bit of extra security at no cost. This is commonly the case for apps that open one BrowserWindow
and do not need to open an arbitrary number of additional windows at runtime.
Wie?
webContents
will delegate to its window open handler before creating new windows. The handler will receive, amongst other parameters, the url
the window was requested to open and the options used to create it. We recommend that you register a handler to monitor the creation of windows, and deny any unexpected window creation.
const { app, shell } = require('electron')
app.on('web-contents-created', (event, contents) => {
contents.setWindowOpenHandler(({ url }) => {
// In this example, we'll ask the operating system
// to open this event's url in the default browser.
//
// See the following item for considerations regarding what
// URLs should be allowed through to shell.openExternal.
if (isSafeForExternalOpen(url)) {
setImmediate(() => {
shell.openExternal(url)
})
}
return { action: 'deny' }
})
})
15. shell.openExternal
nicht mit nicht vertrauenswürdigen Inhalten verwenden
The shell module's openExternal
API allows opening a given protocol URI with the desktop's native utilities. On macOS, for instance, this function is similar to the open
terminal command utility and will open the specific application based on the URI and filetype association.
Warum?
Improper use of openExternal
can be leveraged to compromise the user's host. When openExternal is used with untrusted content, it can be leveraged to execute arbitrary commands.
Wie?
// Bad
const { shell } = require('electron')
shell.openExternal(USER_CONTROLLED_DATA_HERE)
// Good
const { shell } = require('electron')
shell.openExternal('https://example.com/index.html')
16. Aktuelle Version von Electron verwenden
You should strive for always using the latest available version of Electron. Whenever a new major version is released, you should attempt to update your app as quickly as possible.
Warum?
An application built with an older version of Electron, Chromium, and Node.js is an easier target than an application that is using more recent versions of those components. Generally speaking, security issues and exploits for older versions of Chromium and Node.js are more widely available.
Both Chromium and Node.js are impressive feats of engineering built by thousands of talented developers. Given their popularity, their security is carefully tested and analyzed by equally skilled security researchers. Many of those researchers disclose vulnerabilities responsibly, which generally means that researchers will give Chromium and Node.js some time to fix issues before publishing them. Your application will be more secure if it is running a recent version of Electron (and thus, Chromium and Node.js) for which potential security issues are not as widely known.
Wie?
Migrate your app one major version at a time, while referring to Electron's Breaking Changes document to see if any code needs to be updated.
17. Validate the sender
of all IPC messages
You should always validate incoming IPC messages sender
property to ensure you aren't performing actions or sending information to untrusted renderers.
Warum?
All Web Frames can in theory send IPC messages to the main process, including iframes and child windows in some scenarios. If you have an IPC message that returns user data to the sender via event.reply
or performs privileged actions that the renderer can't natively, you should ensure you aren't listening to third party web frames.
You should be validating the sender
of all IPC messages by default.
Wie?
// Bad
ipcMain.handle('get-secrets', () => {
return getSecrets()
})
// Good
ipcMain.handle('get-secrets', (e) => {
if (!validateSender(e.senderFrame)) return null
return getSecrets()
})
function validateSender (frame) {
// Value the host of the URL using an actual URL parser and an allowlist
if ((new URL(frame.url)).host === 'electronjs.org') return true
return false
}
18. Avoid usage of the file://
protocol and prefer usage of custom protocols
You should serve local pages from a custom protocol instead of the file://
protocol.
Warum?
The file://
protocol gets more privileges in Electron than in a web browser and even in browsers it is treated differently to http/https URLs. Using a custom protocol allows you to be more aligned with classic web url behavior while retaining even more control about what can be loaded and when.
Pages running on file://
have unilateral access to every file on your machine meaning that XSS issues can be used to load arbitrary files from the users machine. Using a custom protocol prevents issues like this as you can limit the protocol to only serving a specific set of files.
Wie?
Follow the protocol.handle
examples to learn how to serve files / content from a custom protocol.
19. Check which fuses you can change
Electron ships with a number of options that can be useful but a large portion of applications probably don't need. In order to avoid having to build your own version of Electron, these can be turned off or on using Fuses.
Warum?
Some fuses, like runAsNode
and nodeCliInspect
, allow the application to behave differently when run from the command line using specific environment variables or CLI arguments. These can be used to execute commands on the device through your application.
This can let external scripts run commands that they potentially would not be allowed to, but that your application might have the rights for.
Wie?
We've made a module, @electron/fuses
, to make flipping these fuses easy. Check out the README of that module for more details on usage and potential error cases, and refer to How do I flip the fuses? in our documentation.