Безопасность
Для получения информации о том, как правильно устранять уязвимости Electron, загляни в SECURITY.md.
For upstream Chromium vulnerabilities: Electron keeps up to date with alternating Chromium releases. For more information, see the Electron Release Timelines document.
Preface
As web developers, we usually enjoy the strong security net of the browser — the risks associated with the code we write are relatively small. Наши веб-сайты имеют ограниченные полномочия в песочнице, и мы верим, что пользователи довольны браузером, созданным большой командой инженеров, которая может быстро реагировать на последние обнаруженные угрозы безопасности.
Когда вы работаете в среде Электрон, важно понимать, что это не веб браузер. Электрон позволяет создавать функционально развитые приложения для настольных компьютеров с помощью веб технологий, но ваш код обладает большими возможностями. JavaScript имеет доступ к файловой системе, пользовательским скриптам и т. д. Благодаря этим возможностям вы можете создавать высококачественные нативные приложения, но это так же множит риски увеличивающиеся с дополнительными полномочиями вашего кода.
Учтите что показ произвольного содержимого от недоверенных источников влечет за собой риски безопасности, которые Электрон не предназначен купировать. In fact, the most popular Electron apps (Atom, Slack, Visual Studio Code, etc) display primarily local content (or trusted, secure remote content without Node integration) — if your application executes code from an online source, it is your responsibility to ensure that the code is not malicious.
General guidelines
Security is everyone's responsibility
Важно помнить, что безопасность вашего Electron приложения является результатом общей безопасности основы платформы (Chromium, Node.js), самого Electron, всех NPM-зависимостей и вашего кода. Поэтому вы обязаны следовать нескольким важным рекомендациям:
-
Keep your application up-to-date with the latest Electron framework release. When releasing your product, you’re also shipping a bundle composed of Electron, Chromium shared library and Node.js. Vulnerabilities affecting these components may impact the security of your application. By updating Electron to the latest version, you ensure that critical vulnerabilities (such as nodeIntegration bypasses) are already patched and cannot be exploited in your application. For more information, see "Use a current version of Electron".
-
Оцените свои зависимости. В то время как NPM предоставляет полмиллиона многоразовых пакетов, вы несете ответственность за выбор надежных библиотек третьей стороны. If you use outdated libraries affected by known vulnerabilities or rely on poorly maintained code, your application security could be in jeopardy.
-
Используйте безопасные методы программирования Первая линия защиты вашей заявки — ваш собственный код. 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.
Isolation for untrusted content
Проблемы безопасности возникают всякий раз, когда вы получаете код из ненадежного источника (напр., удаленный сервер) и выполняете его локально. As an example, consider a remote website being displayed inside a default BrowserWindow
. 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
.
Security warnings and recommendations are printed to the developer console. They only show up when the binary's name is Electron, indicating that a developer is currently looking at the console.
Вы можете принудительно включить или выключить эти предупреждения в настройках ELECTRON_ENABLE_SECURITY_WARNINGS
или ELECTRON_DISABLE_SECURITY_WARNINGS
на любом process.env
или объекте window
.
Checklist: Security recommendations
You should at least follow these steps to improve the security of your application:
- Загружайте только безопасный контент
- Выключите Node.js интеграцию во всех видах (renderers) показывающих удаленный контент
- Enable context isolation in all renderers
- Enable process sandboxing
- Используйте
ses.setPermissionRequestHandler()
в сессиях с загрузкой удаленного контента - Не выключайте
webSecurity
- Определите
Content-Security-Policy
и используйте ограничительные правила (i.e.script-src 'self'
) - Не включайте
allowRunningInsecureContent
- Не включайте экспериментальные функции
- Не испольхуйте
enableBlinkFeatures
<webview>
: Не используйтеallowpopups
<webview>
: Verify options and params- Disable or limit navigation
- Disable or limit creation of new windows
- Do not use
shell.openExternal
with untrusted content - Использовать текущую версию 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. For additional details on potential weaknesses and implementation bugs when developing applications using Electron, please refer to this guide for developers and auditors.
1. Загружайте только безопасный контент
Все ресурсы не включенные в ваше приложение должны быть загружены с использованием безопасного протокола HTTPS
. Откажитесь от не безопасных протоколов, таких как HTTP
. Так же мы рекомендуем WSS
over WS
, FTPS
over FTP
, и т. п.
Почему?
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.
- 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.
Как?
// Плохо
browserWindow.loadURL('http://example.com')
// Хорошо
browserWindow.loadURL('https://example.com')
<!-- Плохо -->
<script crossorigin src="http://example.com/react.js"></script>
<link rel="stylesheet" href="http://example.com/style.css">
<!-- Хорошо -->
<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. 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.
After this, you can grant additional permissions for specific hosts. For example, if you are opening a BrowserWindow pointed at https://example.com/
, you can give that website exactly the abilities it needs, but no more.
Поч ему?
A cross-site-scripting (XSS) attack is more dangerous if an attacker can jump out of the renderer process and execute code on the user's computer. 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.
Как?
// 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')
<!-- Bad -->
<webview nodeIntegration src="page.html"></webview>
<!-- Good -->
<webview src="page.html"></webview>
При отключении интеграции с Node.js, можно по-прежнему использовать API на вашем сайте, которые используют модули или функции Node.js. 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.