我刚刚尝试在 VS2010 上编译几个 C++ 片段,并在 IDA Pro 上分析了可执行文件。我注意到的是,他们中的大多数在开始时都有以下类似的内容(在调用 __security_check_cookie 后不久)
xor eax, ebp
类似的东西
xor ecx, ebp
在底部。为什么会这样?编译器优化已关闭。
最佳答案
这些是缓冲区溢出保护方法,与编译器优化无关。 MSVC 将(如果您指定 /GS
开关)将安全 cookie 推送到返回地址附近的堆栈上,以便它可以检测到堆栈损坏的常见情况。
堆栈损坏可能是由以下错误代码引起的:
char buff[5];
strcpy (buff, "Man, this string is waaay too long!!");
或恶意用户利用不良编码实践,例如使用 scanf ("%s", myBuff)
进行用户输入。像这样精心设计的攻击可能会诱使您的程序做您可能不希望它做的事情。
通过在返回地址附近放置一个 cookie,可以防止大量错误(和攻击 vector ),这仅仅是因为内存损坏在本质上往往是连续的。换句话说,如果您已经覆盖了返回地址,那可能是因为您开始在 cookie 的一侧写入,并且一直损坏到 cookie 另一侧的返回地址的内存(因此 cookie 将被覆盖以及)。
它没有捕捉到所有个错误,因为你可能有一些类似的代码:
char buff[5];
buff[87] = 'x';
这可能会损坏返回地址而不接触 cookie。但它会捕获所有那些依赖于输入比预期更长的字符串的恶意软件,这些恶意软件会破坏返回地址(包括 cookie)。
您可能在代码中看到的序列类似于:
mov eax, dword ptr ds:___sec_cookie ; fixed value.
xor eax, ebp ; adjust based on base pointer.
mov [ebp+SOMETHING], eax ; store adjusted value.
根据当前基指针自定义cookie。
这将改变每个堆栈级别实际放入堆栈的内容(也取决于参数计数和大小),并且可能是通过确保 变量来进一步保护代码免受恶意意图的尝试 签名被写入堆栈而不是一个固定值(否则攻击者可以输入字符包括一个有效的cookie)。
最后的序列会像这样运行:
mov ecx, [ebp+SOMETHING] ; get the adjusted cookie.
xor ecx, ebp ; un-adjust it, since
; ((N xor X) xor X) == N.
call @__sec_check_cookie ; check the cookie.
这基本上只是上面描述的相反过程。 @__sec_check_cookie
调用只有在 ecx
设置为正确的 cookie 值时才会返回。否则会引发故障,已确认 here :
The
__security_check_cookie()
routine is straightforward: if the cookie was unchanged, it executes theRET
instruction and ends the function call. If the cookie fails to match, the routine callsreport_failure()
.The
report_failure()
function then calls__security_error_handler()
. Both functions are defined in theseccook.c
file of the C run-time (CRT) source files.CRT support is needed to make these security checks work. When a security check failure occurs, control of the program is passed to
__security_error_handler()
, which is summarized here:
void __cdecl __security_error_handler(int code, void *data)
{
if (user_handler != NULL) {
__try {
user_handler(code, data);
} __except (EXCEPTION_EXECUTE_HANDLER) {}
} else {
//...prepare outmsg...
__crtMessageBoxA(
outmsg,
"Microsoft Visual C++ Runtime Library",
MB_OK|MB_ICONHAND|MB_SETFOREGROUND|MB_TASKMODAL);
}
_exit(3);
}
By default, an application that fails a security check displays a dialog that states "Buffer overrun detected!". When the dialog is dismissed, the application terminates.
关于c++ - "xor eax, ebp"在 C++ 编译器输出中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6354829/