Segurança
Para obter informações sobre como divulgar adequadamente uma vulnerabilidade do Electron, consulte SECURITY.md.
Para vulnerabilidades no Chromium upstream: O Electron mantém-se atualizado com lançamentos alternados do Chromium. Para obter mais informações, consulte o documento Cronogramas de Lançamento do Electron.
Prefácio
Como desenvolvedores da web, nós comumente aproveitamos da forte rede de segurança do navegador — os riscos associados com o código que escrevemos são relativamente pequenos. Nossos sites tem poderes limitados em uma caixa de areia e confiamos que nossos usuários desfrutam de num navegador construído por uma grande equipe de engenheiros os quais são capazes de responder rapidamente às ameaças de segurança recém-descobertas.
Ao trabalhar com Electron, é importante entender que Electron não é um navegador web. Isto permite que você construa aplicações desktop ricas com tecnologias web familiar, mas seu código exerce um poder muito maior. JavaScript pode acessar o sistema de arquivos, o shell do usuário e muito mais. Isto permite que você crie aplicativos nativos de alta qualidade, mas os riscos de segurança inerentes escalam com os poderes adicionais concedidos ao seu código.
Com isso em mente, esteja ciente de que exibir conteúdo arbitrário de fontes não confiáveis representa um grave risco de segurança que o Electron não pretende manipular. De fato, os mais populares aplicativos Electron (Atom, Slack, Visual Studio Code, etc.) mostram, primeiramente, conteúdo local (ou confiável, ou que é seguro e remoto, sem alguma interação com Node) — se a sua aplicação executa código de uma fonte online, é sua responsabilidade garantir que o código não seja malicioso.
Diretrizes gerais
Segurança é da responsabilidade de todos
É importante lembrar que a segurança do seu aplicativo Electron é o resultado da segurança geral da fundação do framework (Chromium, Node.js), o Electron em si, todas as dependências NPM e também seu código. Portanto, é sua responsabilidade seguir algumas das importantes boas práticas:
-
Mantenha sua aplicação atualizada com a última versão do framework Electron. Ao lançar seu produto, você também está enviando um pacote composto pelo Electron, Biblioteca Compartilhada do Chromium e Node.js. Vulnerabilidades afetando estes componentes podem afetar a segurança do seu aplicativo. Ao atualizar o Electron para a versão mais recente, você garante que as vulnerabilidades críticas (como nodeIntegration bypasses) já estão corrigidas e não podem ser exploradas em seu aplicativo. Para obter mais informações, consulte "Use uma versão atual do Electron".
-
Avalie suas dependências. O NPM fornece meio milhão de pacotes reutilizáveis, mas é sua responsabilidade escolher bibliotecas de terceiros confiáveis. Se você usar bibliotecas desatualizadas afetadas por vulnerabilidades conhecidas ou se depender de código mal mantido, a segurança do aplicativo pode estar comprometida.
-
Adote práticas seguras de codificação. A primeira linha de defesa para seu aplicativo é seu próprio código. Vulnerabilidades comuns na web, como "Cross-Site Scripting" (XSS), têm um impacto maior na segurança de aplicações Electron, portanto é altamente recomendado adotar as melhores práticas de desenvolvimento de software seguro e realizar testes de segurança.
Isolamento para conteúdo não confiável
Existe um problema de segurança sempre que você recebe código de uma fonte não confiável (por exemplo, de um servidor remoto) e o executa localmente. Por exemplo, considere um site remoto sendo exibido dentro de uma BrowserWindow
padrão. Se um invasor de alguma forma conseguir alterar esse conteúdo (seja atacando diretamente a fonte ou ficando entre o seu aplicativo e o destino real), ele poderá executar código nativo na máquina do usuário.
Em nenhuma circunstância você deve carregar e executar código remoto com a integração Node.js habilitada. Em vez disso, use apenas arquivos locais (empacotados junto com o seu aplicativo) para executar código Node.js. Para visualizar o conteúdo, utilize o <webview>
ou WebContentsView
e certifique-se de que desativou a opção nodeIntegration
e ative a opção contextIsolation
.
Os avisos e recomendações de segurança se encontram na programação do console. Apenas aparece quando o nome do binário é Electron, indicando que um programador está olhando para a console.
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.
Checklist: Security recommendations
You should at least follow these steps to improve the security of your application:
- Apenas carregar conteúdo seguro
- Desativar a integração do Node.js em todos os renderizadores que exibem conteúdo remoto
- Ativar isolamento de contexto em todos os renderizadores
- Enable process sandboxing
- Use
ses.setPermissionRequestHandler()
in all sessions that load remote content - Do not disable
webSecurity
- Define a
Content-Security-Policy
and use restrictive rules (i.e.script-src 'self'
) - Do not enable
allowRunningInsecureContent
- Do not enable experimental features
- Do not use
enableBlinkFeatures
<webview>
: Do not useallowpopups
<webview>
: Verify options and params- Disable or limit navigation
- Disable or limit creation of new windows
- Do not use
shell.openExternal
with untrusted content - Use uma versão atual do Electron
- 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. Para detalhes adicionais sobre fraquezas em potencial e erros de implementação quando desenvolver aplicativos usando o Electron, consulte este guia para desenvolvedores e auditores.
1. Apenas carregar conteúdo seguro
Any resources not included with your application should be loaded using a secure protocol like HTTPS
. In other words, do not use insecure protocols like HTTP
. Similarly, we recommend the use of WSS
over WS
, FTPS
over FTP
, and so on.
Por que?
HTTPS
has two main benefits:
- It ensures data integrity, asserting that the data was not modified while in transit between your application and the host.
- Isto criptografa o tráfego entre o usuário e o servidor de destino, tornando-o mais difícil de espionar as informações enviadas entre seu aplicativo e o servidor.
Como?
// Bad
browserWindow.loadURL('http://example.com')
// Good
browserWindow.loadURL('https://example.com')
<!-- Bad -->
<script crossorigin src="http://example.com/react.js"></script>
<link rel="stylesheet" href="http://example.com/style.css">
<!-- Good -->
<script crossorigin src="https://example.com/react.js"></script>
<link rel="stylesheet" href="https://example.com/style.css">
2. Do not enable Node.js integration for remote content
This recommendation is the default behavior in Electron since 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.
After this, you can grant additional permissions for specific hosts. Por Exemplo
Por que?
Um ataque cross-site-scripting (XSS) é mais perigoso se um invasor pode pular do processo de renderização e executar o código no computador do usuário. 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.
Como?
// Bad
const mainWindow = new BrowserWindow({
webPreferences: {
contextIsolation: false,
nodeIntegration: true,
nodeIntegrationInWorker: true
}
})
mainWindow.loadURL('https://example.com')
// Good
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(app.getAppPath(), 'preload.js')
}
})
mainWindow.loadURL('https://example.com')
<!-- Mau -->
<webview nodeIntegration src="page.html"></webview>
<!-- Bom -->
<webview src="page.html"></webview>
When disabling Node.js integration, you can still expose APIs to your website that do consume Node.js modules or features. 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. Enable Context Isolation
This recommendation is the default behavior in Electron since 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. Enable process sandboxing
Sandboxing is a Chromium feature that uses the operating system to significantly limit what renderer processes have access to. You should enable the sandbox in all renderers. Loading, reading or processing any untrusted content in an unsandboxed process, including the main process, is not advised.
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.
Por que?
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.
Como?
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. Do not disable webSecurity
This recommendation is Electron's default.
You may have already guessed that disabling the webSecurity
property on a renderer process (BrowserWindow
, WebContentsView
, or <webview>
) disables crucial security features.
Do not disable webSecurity
in production applications.
Por que?
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.
Como?
// Bad
const mainWindow = new BrowserWindow({
webPreferences: {
webSecurity: false
}
})
// Good
const mainWindow = new BrowserWindow()
<!-- Bad -->
<webview disablewebsecurity src="page.html"></webview>
<!-- Good -->
<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.
Por que?
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.
Como?
The following CSP will allow Electron to execute scripts from the current website and from apis.example.com
.
// Bad
Content-Security-Policy: '*'
// Good
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. Do not enable allowRunningInsecureContent
This recommendation is Electron's default.
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".
Por que?
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.
Como?
// Bad
const mainWindow = new BrowserWindow({
webPreferences: {
allowRunningInsecureContent: true
}
})
// Good
const mainWindow = new BrowserWindow({})
9. Do not enable experimental features
This recommendation is Electron's default.
Advanced users of Electron can enable experimental Chromium features using the experimentalFeatures
property.
Por que?
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.
Como?
// Bad
const mainWindow = new BrowserWindow({
webPreferences: {
experimentalFeatures: true
}
})
// Good
const mainWindow = new BrowserWindow({})
10. Do not use enableBlinkFeatures
This recommendation is Electron's default.
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.
Por que?
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.
Como?
// Bad
const mainWindow = new BrowserWindow({
webPreferences: {
enableBlinkFeatures: 'ExecCommandInJavaScript'
}
})
// Good
const mainWindow = new BrowserWindow()
11. Do not use allowpopups
for WebViews
This recommendation is Electron's default.
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.
Por que?
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.
Como?
<!-- Bad -->
<webview allowpopups src="page.html"></webview>
<!-- Good -->
<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.
Por que?
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.
Como?
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. Disable or limit navigation
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.
Por que?
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.
Como?
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. Disable or limit creation of new windows
If you have a known set of windows, it's a good idea to limit the creation of additional windows in your app.
Por que?
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.
Como?
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. Do not use shell.openExternal
with untrusted content
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.
Por que?
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.
Como?
// Bad
const { shell } = require('electron')
shell.openExternal(USER_CONTROLLED_DATA_HERE)
// Good
const { shell } = require('electron')
shell.openExternal('https://example.com/index.html')
16. Use uma versão atual do Electron
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.
Por que?
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.
Como?
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.
Por que?
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.
Como?
// 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.
Por que?
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.
Como?
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.
Por que?
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.
Como?
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.