Electron Security
Electron combinesNode.js and Browser Environments, which makes desktop applications very powerful, but also brings certain security risks.
Correct security policies can reduce the risks of XSS, remote code execution (RCE), and data leakage.
Security Checklist and Common Vulnerabilities
Security Checklist
- EnableContext isolation(
contextIsolation) - UsagePreload script(
preload.js) Exposing Secure APIs - Do not use Node.js modules directly in the renderer process.
- EnableSandbox mode(
sandbox: true) - ConfigurationContent Security Policy (CSP)
- Use IPC securely, verify origins and inputs.
- Limit the application's access to system permissions, following the principle of least privilege.
- Avoid Loading Untrusted Remote Content
Common Security Risks
- Remote Content Injection: Loading unknown URLs or HTML files may execute malicious JS.
- Unsafe IPC Calls: The renderer process can call any main process method.
- Arbitrary Node.js Execution: Enable in the Renderer Process
nodeIntegrationCan Be Exploited to Execute System Commands - XSS Attack: User Input Rendered Directly to the Page
- Dependency vulnerabilities: Using Outdated Third-Party Libraries
Context Isolation
contextIsolation in Detail
Context isolation allows the renderer process and the main process to run in different JS environments.
The web page JS in the renderer process cannot directly access Node.js APIs; instead, interfaces are exposed through secure preload scripts.
const mainWindow = new BrowserWindow({
webPreferences: {
contextIsolation: true, // 启用上下文隔离
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false // 禁止在渲染进程使用 Node.js
}
})
Why Context Isolation Is Needed
- Prevent loaded web pages or third-party scripts from directly accessing Node.js.
- Prevent attackers from gaining system privileges through XSS.
- Keep the renderer process handling only UI, while the main process handles system operations.
Migrating to an Isolated Context
- Usage
contextBridge.exposeInMainWorldExposing Secure APIs - Put all system operations in the main process and invoke them via IPC.
Example:
// preload.js
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('api', {
getData: () => ipcRenderer.invoke('get-data')
})
Renderer Process Only Callswindow.api.getData(), cannot directly operate the OS.
Sandbox Mode
Enable sandbox
Sandbox mode makes the renderer process run like an ordinary web page in the browser, completely isolated from the Node.js environment.
const mainWindow = new BrowserWindow({
webPreferences: {
sandbox: true,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
})
Sandbox Restrictions and Countermeasures
- Restriction: The renderer process cannot directly access Node.js modules.
- Countermeasure: Call secure methods provided by the main process via IPC.
- Advantage: Enhances security and prevents malicious scripts from damaging the system.
Content Security Policy (CSP)
CSP can prevent XSS and data injection attacks by restricting the sources of resources that web pages can load.
CSP Configuration Example
<meta http-equiv="Content-Security-Policy" content=" default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' https://api.example.com;">
Description:
default-src 'self': By default, only allow same-origin resourcesscript-src 'self': Only allow local scriptsstyle-src 'self' 'unsafe-inline': Allow Inline Stylesconnect-src: Restrict AJAX / WebSocket request domains
Preventing XSS Attacks
- Never directly use in the renderer process
innerHTMLDisplay User Input - Escape user input or use framework template rendering.
Secure IPC Communication
Verify Message Source
The main process should distinguish the origin of the renderer process to avoid arbitrary execution.
Example:
ipcMain.handle('do-action', (event, data) => {
if (event.senderFrame.url.startsWith('file://')) {
// 安全来源,执行操作
} else {
console.warn('不安全的 IPC 请求被阻止')
}
})
Input validation
- All data passed through IPC should have its type and scope validated.
- Avoid Injecting Malicious Commands or File Paths
function validateInput(data) {
if (typeof data !== 'string' || data.length > 100) throw new Error('非法输入')
return data
}
Principle of Least Privilege
- Only Expose Necessary Functionality to the Renderer Process
- Do not expose all Node.js APIs or system privileges.
- Use preload scripts to control the scope of interface access.
Summary
The core of Electron security best practices is:Isolation + Validation + Least Privilege:
- Isolation: Enable context isolation, sandbox mode
- verify: CSP, XSS protection, IPC input validation
- Limit permissions: Minimize renderer process privileges and only provide necessary APIs.
Following these principles can significantly reduce the risk of desktop applications being attacked or data being leaked.
other extensions