Electron 安全性
核对 Electron 安全检查清单、上下文隔离、沙箱模式、内容安全策略(CSP)、防 XSS 与最小权限 IPC 校验实践。
学完这一章,你能够
- 核对 Electron 安全检查清单、上下文隔离、沙箱模式、内容安全策略(CSP)、防 XSS 与最小权限 IPC 校验实践。
安全检查清单与常见攻击面
Electron 融合 Chromium 渲染能力与 Node.js 系统权限,若边界失守容易诱发 XSS、远程代码执行(RCE)或敏感数据泄露。基线安全检查清单包含八项:开启上下文隔离(`contextIsolation: true`)、通过 `preload.js` 暴露受控 API、禁止渲染进程直接使用 Node.js、启用沙箱(`sandbox: true`)、配置内容安全策略(CSP)、校验 IPC 来源与入参、贯彻最小权限原则,以及避免加载不可信远程内容。
实战中最常见的五类安全隐患分别是:加载未知 URL 或 HTML 引发的远程内容注入、缺少鉴权导致渲染进程任意调用主进程方法的不安全 IPC、启用 `nodeIntegration` 导致的系统命令执行、直接把用户输入写入 DOM 触发的 XSS,以及长期未升级第三方依赖引入的已知漏洞。
上下文隔离与沙箱模式
上下文隔离让预加载脚本与渲染进程页面运行在相互独立的 JavaScript 执行上下文中,阻止第三方脚本或 XSS 载荷篡改原型链并触达 Node.js API,确保渲染进程仅承担 UI 展示而主进程负责系统操作。迁移时应在 `BrowserWindow` 的 `webPreferences` 中设置 `contextIsolation: true`、`nodeIntegration: false` 与 `preload`,在 `preload.js` 内借助 `contextBridge.exposeInMainWorld('api', { getData })` 仅暴露必要方法供页面调用 `window.api.getData()`。
开启 `sandbox: true` 后,渲染进程在操作系统级沙箱中以普通网页权限运行,完全隔离 Node.js 模块;所有文件或系统能力一律通过预加载桥接经 IPC 委托主进程执行。本站离线实测(`web_preferences_isolation_sandbox_audit` 与 `least_privilege_preload_contract`)核验了加固配置 0 项告警、危险配置检出 4 项违规,以及冻结后的 `window.api` 仅暴露 `['getData']` 且阻断未授权 `exec-shell` 通道。
内容安全策略(CSP)、防 XSS 与安全 IPC 校验
在页面 `<meta http-equiv="Content-Security-Policy">`(或主进程响应头)中配置 CSP 可限制脚本与连接来源:`default-src 'self'` 约定默认同源,`script-src 'self'` 拒绝外部及内联脚本,`style-src 'self' 'unsafe-inline'` 控制样式来源,`img-src 'self' data:` 与 `connect-src 'self' https://api.example.com` 限定图片与网络域。同时禁止对用户输入直接使用 `innerHTML`,应做 HTML 转义或交由框架安全模板渲染。本站实测(`csp_policy_parser_and_xss_guard`)解析了 5 条 CSP 指令,确认拦截远端脚本且将 `<img src=x onerror="alert(1)">` 转义为无害实体文本。
安全 IPC 的核心在于“隔离 + 验证 + 限权”:主进程在 `ipcMain.handle` 中检查 `event.senderFrame.url` 仅放行受信任本地来源,对全部输入执行类型、长度(如 `typeof data === 'string'` 且 `data.length <= 100`)与路径穿越/命令注入校验,并对 `shell.openExternal` 限制仅允许 `https:`/`mailto:` 协议。本站实测(`ipc_sender_and_input_validation`)验证了可信 `file://` 放行、恶意域 `https://evil.example` 与超长/穿越载荷 `../etc/passwd` 拦截,以及外部链接协议白名单阻断 `file://` 和 `javascript:`。
离线实测 BrowserWindow 安全配置审计、CSP 指令解析、XSS 转义与 IPC 最小权限校验
展开查看收起
function auditWebPreferences(prefs) {
const issues = [];
if (prefs.contextIsolation !== true) issues.push('contextIsolation_disabled');
if (prefs.nodeIntegration !== false) issues.push('nodeIntegration_enabled');
if (prefs.sandbox !== true) issues.push('sandbox_disabled');
if (!prefs.preload) issues.push('missing_preload');
return { safe: issues.length === 0, issues };
}
function caseWebPreferencesIsolationSandboxAudit() {
const hardened = auditWebPreferences({
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
preload: '/app/preload.js',
});
const risky = auditWebPreferences({
contextIsolation: false,
nodeIntegration: true,
sandbox: false,
preload: '',
});
const actual = {
hardenedSafe: hardened.safe,
hardenedIssues: hardened.issues.length,
riskySafe: risky.safe,
riskyIssues: risky.issues,
};
const expected = {
hardenedSafe: true,
hardenedIssues: 0,
riskySafe: false,
riskyIssues: ['contextIsolation_disabled', 'nodeIntegration_enabled', 'sandbox_disabled', 'missing_preload'],
};
return { name: 'web_preferences_isolation_sandbox_audit', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
function parseCsp(content) {
const directives = {};
for (const part of content.split(';')) {
const tokens = part.trim().split(/\s+/).filter(Boolean);
if (tokens.length > 0) directives[tokens[0]] = tokens.slice(1);
}
return directives;
}
function escapeHtml(raw) {
return raw
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll("'", ''');
}
function caseCspPolicyParserAndXssGuard() {
const cspText = `
default-src 'self';
script-src 'self';
style-src 'self' 'unsafe-inline';
img-src 'self' data:;
connect-src 'self' https://api.example.com;
`;
const directives = parseCsp(cspText);
const canConnectApi = directives['connect-src'].includes('https://api.example.com');
const blocksRemoteScript = directives['script-src'].length === 1 && directives['script-src'][0] === "'self'";
const escaped = escapeHtml('<img src=x onerror="alert(1)">');
const actual = {
directiveCount: Object.keys(directives).length,
defaultSrc: directives['default-src'],
blocksRemoteScript,
canConnectApi,
escapedPayload: escaped,
};
const expected = {
directiveCount: 5,
defaultSrc: ["'self'"],
blocksRemoteScript: true,
canConnectApi: true,
escapedPayload: '<img src=x onerror="alert(1)">',
};
return { name: 'csp_policy_parser_and_xss_guard', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
function validateIpcRequest(senderUrl, data) {
if (!senderUrl.startsWith('file://') && !senderUrl.startsWith('app://')) {
return { allowed: false, reason: 'untrusted_sender' };
}
if (typeof data !== 'string' || data.length === 0 || data.length > 100) {
return { allowed: false, reason: 'invalid_input' };
}
if (data.includes('..') || /[;&|`]/.test(data)) {
return { allowed: false, reason: 'injection_risk' };
}
return { allowed: true, sanitized: data.trim() };
}
function isSafeExternalUrl(rawUrl) {
try {
const parsed = new URL(rawUrl);
return parsed.protocol === 'https:' || parsed.protocol === 'mailto:';
} catch {
return false;
}
}
function caseIpcSenderAndInputValidation() {
const ok = validateIpcRequest('file:///app/index.html', 'note-alpha');
const badOrigin = validateIpcRequest('https://evil.example/page.html', 'note-alpha');
const badLen = validateIpcRequest('file:///app/index.html', 'a'.repeat(101));
const badTraversal = validateIpcRequest('file:///app/index.html', '../etc/passwd');
const actual = {
okAllowed: ok.allowed,
badOriginReason: badOrigin.reason,
badLenReason: badLen.reason,
badTraversalReason: badTraversal.reason,
httpsExternalAllowed: isSafeExternalUrl('https://www.electronjs.org/docs/latest/tutorial/security'),
fileExternalAllowed: isSafeExternalUrl('file:///C:/Windows/System32/calc.exe'),
jsExternalAllowed: isSafeExternalUrl('javascript:alert(1)'),
};
const expected = {
okAllowed: true,
badOriginReason: 'untrusted_sender',
badLenReason: 'invalid_input',
badTraversalReason: 'injection_risk',
httpsExternalAllowed: true,
fileExternalAllowed: false,
jsExternalAllowed: false,
};
return { name: 'ipc_sender_and_input_validation', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
function caseLeastPrivilegePreloadContract() {
const allowedChannels = new Set(['get-data']);
const invoked = [];
const ipcRendererMock = {
invoke: (channel, payload) => {
if (!allowedChannels.has(channel)) throw new Error(`blocked:${channel}`);
invoked.push(channel);
return { channel, payload, ok: true };
},
};
const mainWorld = {};
const exposeInMainWorld = (key, api) => {
mainWorld[key] = Object.freeze({ ...api });
};
exposeInMainWorld('api', {
getData: () => ipcRendererMock.invoke('get-data', null),
});
const result = mainWorld.api.getData();
let blockedRawAccess = false;
try {
ipcRendererMock.invoke('exec-shell', 'whoami');
} catch (err) {
blockedRawAccess = err.message === 'blocked:exec-shell';
}
const actual = {
exposedKeys: Object.keys(mainWorld.api),
isFrozen: Object.isFrozen(mainWorld.api),
hasRawIpcRenderer: 'ipcRenderer' in mainWorld.api,
getDataOk: result.ok,
blockedRawAccess,
invoked,
};
const expected = {
exposedKeys: ['getData'],
isFrozen: true,
hasRawIpcRenderer: false,
getDataOk: true,
blockedRawAccess: true,
invoked: ['get-data'],
};
return { name: 'least_privilege_preload_contract', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
const cases = [
caseWebPreferencesIsolationSandboxAudit(),
caseCspPolicyParserAndXssGuard(),
caseIpcSenderAndInputValidation(),
caseLeastPrivilegePreloadContract(),
];
console.log(JSON.stringify({ version: process.version, cases }));
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
隔离与沙箱限制了渲染进程直接调用 Node.js,但若页面被加载了不可信 iframe 或遭遇 XSS,恶意脚本仍可调用暴露出的桥接接口;因此主进程必须二次验证调用来源与参数边界,防止越权操作与路径/命令注入。