我正在通过一个实验室来演示一个利用缓冲区溢出的漏洞。我让它工作了,但有一个我不太理解的地方,我希望有人能为我解释一下。
这是利用漏洞的代码:
/* Vunlerable program: stack.c */
/* You can get this program from the lab’s website */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int bof(char *str)
{
char buffer[24];
/* The following statement has a buffer overflow problem */
strcpy(buffer, str); ➀
return 1;
}
int main(int argc, char **argv)
{
char str[517];
FILE *badfile;
badfile = fopen("badfile", "r");
fread(str, sizeof(char), 517, badfile);
bof(str);
printf("Returned Properly\n");
return 1;
}本实验的一个步骤是确定分配给buffer24的内存大小。为此,我所做的是在bof函数上运行gdb,我可以看到我的系统上分配的内存是0x20,即32位。
如果我改变缓冲区的大小,我可以运行gdb并找到分配的内存槽。但是,如果没有gdb,我应该知道有多少内存将分配给buffer24吗?如果我更改为buffer8,我是否应该一眼就知道32位系统上的内存块是什么,或者它是否因系统而异?如果我知道了,谁能解释一下。
发布于 2020-04-01 21:48:56
这取决于目标平台、编译器和编译标志。
例如,处于调试模式(-O0)的GCC 7.2 x86在16字节边界上对齐堆栈帧并分配帧指针(ebp)。
示例:(godbolt link)
bof(char*):
push ebp ; -4
mov ebp, esp
sub esp, 40 ; -40
sub esp, 8 ; -8
push DWORD PTR [ebp+8] ; -4
lea eax, [ebp-32] ; 32 bytes to top of stack frame
push eax ; -4
call strcpy ; stack is aligned to 16 bytes (-64)
add esp, 16
mov eax, 1
leave
ret在优化(-O2)的情况下,将省略帧指针,但堆栈仍在16字节(godbolt link)上对齐:
bof(char*):
sub esp, 52 ; -52
push DWORD PTR [esp+56] ; -4
lea eax, [esp+20] ; 36 bytes to top of stack frame
push eax ; -4
call strcpy ; stack is aligned to 16 bytes (-64)
mov eax, 1
add esp, 60
ret使用强制4字节堆栈对齐(-O2 -mpreferred-stack-boundary=2) (godbolt link):
bof(char*):
sub esp, 24 ; -24
push DWORD PTR [esp+28] ; -4
lea eax, [esp+4] ; 24 bytes to top of stack frame
push eax ; -4
call strcpy
mov eax, 1
add esp, 32
ret打开堆栈保护器(-O2 -fstack-protector-all) (godbolt link):
bof(char*):
sub esp, 52 ; -52
mov eax, DWORD PTR gs:20
mov DWORD PTR [esp+36], eax ; stack check value at -16 (-52+36)
xor eax, eax
push DWORD PTR [esp+56] ; -4
lea eax, [esp+16] ; 40 bytes to top of stack frame, leaving exactly 24 bytes to check value
push eax
call strcpy
add esp, 16
mov edx, DWORD PTR [esp+28]
xor edx, DWORD PTR gs:20
jne .L5
mov eax, 1
add esp, 44
ret
.L5:
call __stack_chk_fail其他编译器可能会产生完全不同的结果。
在现实生活中,通过分析指令并计算函数返回地址的字节数,可以在汇编模式下利用缓冲区溢出进行攻击,因此无论源代码是什么,或者它是如何编译的(这些信息通常都是不可用的)。
https://stackoverflow.com/questions/60967688
复制相似问题