安全模型与加固

本章目标

  • 理解 Electron 与浏览器安全模型的差异:为什么桌面端风险更高。
  • 掌握必开的四项配置与它们各自防住什么攻击。
  • 建立统一的 WebContents 安全策略,而不是在每个窗口里复制粘贴。
  • 会用 Electron Fuses 收紧运行时能力,降低被利用面。

为什么 Electron 安全更难

浏览器里的网页运行在严格沙箱中,默认不能读写文件、不能执行本地程序。Electron 应用则拥有这些能力,只是被进程边界隔开。一旦隔离配置被打开(例如 nodeIntegration: true),页面里的一个 XSS 就可能升级为:

  • 读取任意本地文件(SSH 密钥、浏览器 Cookie)。
  • 执行系统命令。
  • 窃取用户会话、上传本地数据。
  • 持久化驻留。

Electron 官方安全文档的核心观点是:不要加载不可信内容;如果必须加载,确保它没有 Node 能力,并且被沙箱与 CSP 约束。

安全基线:四项必开配置

1// src/main/windows/secure-window.ts
2import { BrowserWindow } from 'electron';
3import path from 'node:path';
4
5export function createSecureWindow(): BrowserWindow {
6  return new BrowserWindow({
7    width: 1280,
8    height: 800,
9    webPreferences: {
10      preload: path.join(__dirname, '../preload.js'),
11      contextIsolation: true,
12      sandbox: true,
13      nodeIntegration: false,
14      nodeIntegrationInWorker: false,
15      webSecurity: true,
16      allowRunningInsecureContent: false,
17      webviewTag: false,
18    },
19  });
20}
配置默认值作用关闭/开启的风险
contextIsolationtrue隔离页面与 preload 的 JS 上下文关闭后页面可篡改 preload 暴露的对象
sandboxtrue渲染进程运行在 OS 沙箱中关闭后渲染进程拥有更多系统能力
nodeIntegrationfalse页面是否可直接使用 Node开启后 XSS 等于任意代码执行
webSecuritytrue同源策略等浏览器安全策略关闭后跨域读取、混合内容风险

不要为了「方便」关闭这些开关。确实需要 Node 能力时,把逻辑放进主进程或 utilityProcess,通过 IPC 暴露最小接口。

统一加固入口

所有窗口都应该经过同一套策略。app.on('web-contents-created') 是集中处理的最佳位置。

1// src/main/security/harden.ts
2import { app, shell, WebContents } from 'electron';
3
4const TRUSTED_ORIGINS = new Set([
5  'https://app.example.com',
6  'file://',
7]);
8
9function isTrusted(url: string): boolean {
10  try {
11    const parsed = new URL(url);
12    if (parsed.protocol === 'file:') return true;
13    return TRUSTED_ORIGINS.has(parsed.origin);
14  } catch {
15    return false;
16  }
17}
18
19function hardenWebContents(contents: WebContents): void {
20  // 1. 禁止导航到不可信站点
21  contents.on('will-navigate', (event, url) => {
22    if (!isTrusted(url)) {
23      event.preventDefault();
24    }
25  });
26
27  // 2. 禁止页面自行开新窗口;外链交给系统浏览器
28  contents.setWindowOpenHandler(({ url }) => {
29    if (url.startsWith('https://')) {
30      shell.openExternal(url);
31    }
32    return { action: 'deny' };
33  });
34
35  // 3. 禁止挂载未配置的 webview
36  contents.on('will-attach-webview', (event, webPreferences) => {
37    delete webPreferences.preload;
38    webPreferences.nodeIntegration = false;
39    webPreferences.contextIsolation = true;
40    event.preventDefault();
41  });
42
43  // 4. 禁止页面使用危险协议
44  contents.on('will-frame-navigate', (details) => {
45    if (!isTrusted(details.url)) details.preventDefault();
46  });
47}
48
49app.on('web-contents-created', (_event, contents) => {
50  hardenWebContents(contents);
51});

will-frame-navigate 覆盖 iframe 导航,will-navigate 主要覆盖主框架。两者结合更稳妥。

权限请求处理

摄像头、麦克风、通知、剪贴板、地理位置等权限,默认应拒绝,只对可信来源按需放行。

1import { session } from 'electron';
2
3const ALLOWED_PERMISSIONS = new Set(['notifications', 'clipboard-read']);
4
5app.whenReady().then(() => {
6  session.defaultSession.setPermissionRequestHandler(
7    (webContents, permission, callback, details) => {
8      const url = details.requestingUrl;
9      const trusted = url.startsWith('https://app.example.com/');
10      callback(trusted && ALLOWED_PERMISSIONS.has(permission));
11    },
12  );
13
14  session.defaultSession.setPermissionCheckHandler(
15    (_webContents, permission, requestingOrigin) => {
16      return (
17        requestingOrigin === 'https://app.example.com' &&
18        ALLOWED_PERMISSIONS.has(permission)
19      );
20    },
21  );
22});

setPermissionRequestHandler 处理运行时请求,setPermissionCheckHandler 处理同步检查(例如 navigator.permissions.query)。两者要一致,否则会出现「检查通过但请求被拒」的诡异行为。

内容安全策略(CSP)

CSP 是防 XSS 的最后一道防线。推荐通过响应头设置,而不是只在 HTML 里写 meta。

1import { session } from 'electron';
2
3app.whenReady().then(() => {
4  session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
5    callback({
6      responseHeaders: {
7        ...details.responseHeaders,
8        'Content-Security-Policy': [
9          [
10            "default-src 'self'",
11            "script-src 'self'",
12            "style-src 'self' 'unsafe-inline'",
13            "img-src 'self' data: https:",
14            "connect-src 'self' https://api.example.com",
15            "object-src 'none'",
16            "base-uri 'none'",
17            "frame-ancestors 'none'",
18          ].join('; '),
19        ],
20      },
21    });
22  });
23});

本地页面也可以在 index.html 中声明:

1<meta
2  http-equiv="Content-Security-Policy"
3  content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; object-src 'none'"
4/>

注意:

  • 开发模式下 Vite/Webpack 的 HMR 需要 'unsafe-eval' 或额外连接源,生产环境必须收紧。
  • 不要把 script-src 配成 * 或 'unsafe-inline',那等于没有 CSP。
  • 远程内容与本地内容应使用不同的 session 与 CSP。

外部链接与文件

shell.openExternal 白名单

shell.openExternal 会把 URL 交给系统处理。如果 URL 是 file://、smb:// 或自定义协议,可能触发本地程序执行。

1import { shell } from 'electron';
2
3const EXTERNAL_PROTOCOLS = new Set(['https:', 'mailto:']);
4
5export async function openExternalSafely(url: string): Promise<void> {
6  const parsed = new URL(url);
7  if (!EXTERNAL_PROTOCOLS.has(parsed.protocol)) {
8    throw new Error(`blocked protocol: ${parsed.protocol}`);
9  }
10  await shell.openExternal(url);
11}

拖拽文件的真实路径

渲染进程拿到的 File 对象不再直接暴露本地路径。需要路径时使用 webUtils.getPathForFile:

1// preload.ts
2import { contextBridge, webUtils } from 'electron';
3
4contextBridge.exposeInMainWorld('api', {
5  getPathForFile: (file: File) => webUtils.getPathForFile(file),
6});

拿到路径后仍需在主进程按工作目录校验,不能直接信任。

远程内容隔离

如果应用必须加载第三方页面(登录页、帮助中心、插件页面),不要让它和主界面共享 session。

1import { BrowserWindow, session } from 'electron';
2
3const remoteSession = session.fromPartition('persist:remote', { cache: true });
4
5const win = new BrowserWindow({
6  webPreferences: {
7    session: remoteSession,
8    contextIsolation: true,
9    sandbox: true,
10    nodeIntegration: false,
11    preload: undefined,
12  },
13});
14
15win.loadURL('https://third-party.example.com/login');

原则:

  1. 远程内容不挂 preload。
  2. 使用独立分区,隔离 Cookie 与缓存。
  3. 远程内容不能直接调用主进程 IPC;需要通信时由主进程做中转与校验。
  4. 登录完成后只回传必要的结果,不回传整个页面上下文。

Electron Fuses

Fuses 是打包时写入二进制的开关,用来关闭一些「运行时可选但生产不需要」的能力。即使用户拿到安装包,也无法通过命令行重新打开。

1npm install --save-dev @electron/fuses
1// forge.config.ts 或打包脚本中
2import { flipFuses, FuseVersion, FuseV1Options } from '@electron/fuses';
3
4await flipFuses(electronPath, {
5  version: FuseVersion.V1,
6  [FuseV1Options.RunAsNode]: false,
7  [FuseV1Options.EnableCookieEncryption]: true,
8  [FuseV1Options.EnableNodeOptionsEnvironmentVariable]: false,
9  [FuseV1Options.EnableNodeCliInspectArguments]: false,
10  [FuseV1Options.EnableEmbeddedAsarIntegrityValidation]: true,
11  [FuseV1Options.OnlyLoadAppFromAsar]: true,
12});
Fuse建议作用
RunAsNodefalse禁止把 Electron 当 Node 执行任意脚本
EnableNodeOptionsEnvironmentVariablefalse禁止通过 NODE_OPTIONS 注入参数
EnableNodeCliInspectArgumentsfalse禁止用 --inspect 附加调试器
EnableCookieEncryptiontrue加密 Cookie 存储
EnableEmbeddedAsarIntegrityValidationtrue校验 asar 完整性
OnlyLoadAppFromAsartrue只从 asar 加载应用代码

开启 OnlyLoadAppFromAsar 后,asar: false 或解包目录的加载方式会失效,需要确认构建配置一致。开发阶段通常不启用 Fuses,生产构建时再打开。

WebView 与自定义协议

webviewTag 默认关闭,建议保持关闭。它等于在页面里开了一个新的渲染上下文,配置不当会绕过主窗口的安全策略。

如果必须使用自定义协议:

1import { protocol, net } from 'electron';
2import path from 'node:path';
3import { pathToFileURL } from 'node:url';
4
5protocol.handle('app', (request) => {
6  const url = new URL(request.url);
7  const filePath = path.join(__dirname, '../renderer', url.pathname);
8  return net.fetch(pathToFileURL(filePath).toString());
9});

必须做路径归一化与白名单校验,防止 app://../../etc/passwd 这类穿越。

依赖与版本安全

Electron 的安全依赖三部分:

  1. Electron 本身:Chromium 漏洞由 Electron 版本更新修复,关注 Electron 发布时间线,尽量使用受支持的稳定版本。
  2. npm 依赖:使用 npm audit/pnpm audit,锁定版本,审查 postinstall 脚本。
  3. 原生模块与二进制:只从可信源下载,校验签名与哈希。

建议在 CI 中加入:

1npm audit --omit=dev
2npx @electron/fuses read --app ./release/mac/MyApp.app

安全检查清单

检查项通过标准
渲染进程 Node 能力nodeIntegration: false
上下文隔离contextIsolation: true
沙箱sandbox: true,不要为 preload 关闭
导航管控will-navigate、will-frame-navigate 均拦截
新窗口setWindowOpenHandler 返回 deny
权限默认拒绝,白名单放行
CSP生产环境无 unsafe-eval、无通配符
外链协议白名单,禁止 file:/自定义协议
远程内容独立 session、无 preload、无 IPC
webviewwebviewTag: false
Fuses生产包关闭调试与 RunAsNode
依赖无高危漏洞,Electron 版本受支持

本章小结

  • Electron 的安全风险来自「Web 内容 + 系统能力」的组合,隔离配置是第一道防线。
  • 四项必开配置:contextIsolation、sandbox、nodeIntegration: false、webSecurity。
  • 用 web-contents-created 统一加固所有页面,避免遗漏。
  • CSP、权限处理、导航拦截、外链白名单要一起使用。
  • Fuses 把生产环境不需要的能力从二进制层面关掉,是最后一道保险。

参考资料