源代码如下:
/* Bomb program that is solved using a buffer overflow attack */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
/* Like gets, except that characters are typed as pairs of hex digits.
Nondigit characters are ignored. Stops when encounters newline */
char *getxs(char *dest)
{
__asm{
mov dword ptr [ebp+4], 004011b0h
}
int c;
int even = 1; /* Have read even number of digits */
int otherd = 0; /* Other hex digit of pair */
char *sp = dest;
while ((c = getchar()) != EOF && c != '/n') {
if (isxdigit(c)) {
int val;
if ('0' <= c && c <= '9')
val = c - '0';
else if ('A' <= c && c <= 'F')
val = c - 'A' + 10;
else
val = c - 'a' + 10;
if (even) {
otherd = val;
even = 0;
} else {
*sp++ = otherd * 16 + val;
even = 1;
}
}
}
*sp++ = '/0';
return dest;
}
/* My Function test 8*/
void MyFunction()
{
// int a = 0x804854a;
__asm{
// mov 4[ebp], 804854ah
// mov 4[ebp], 0804854ah
mov dword ptr [ebp+4],0040129ah
mov eax, -559038737
}
printf("This is in MyFunction!/n");
return;
}
/* $begin getbuf-c */
int getbuf()
{
char buf[12];
getxs(buf);
return 1;
}
void test()
{
int val;
printf("Type Hex string:");
/* __asm{
push eax
mov eax, esp
mov [esp - 1], eax
pop eax
push [esp - 2]
}*/
val = getbuf();
/* __asm{
mov esp, [esp]
add esp, -1
}*/
printf("getbuf returned 0x%x/n", val);
}
/* $end getbuf-c */
int main()
{
int buf[16];
/* This little hack is an attempt to get the stack to be in a
stable position
*/
int offset = (((int) buf) & 0xFFF);
int *space = (int *) malloc(offset);
*space = 0; /* So that don't get complaint of unused variable */
test();
return 0;
}
思路是:由于getxs没有检查数组长度,所以容易修改数组附近的指针。
所以,我们要让getbuf返回-559038737的值,就需要修改它的返回值,也就是eax的值。
我们在getxs中修改它的返回地址,使它返回到我们的函数MyFunction中,在MyFunction中修改eax的值,然后直接返回test。
这些需要我们得到关于MyFunction的地址,还有get返回test时的下一个地址。
但是在test的汇编中出现了_chkesp的指令,用来检查esp,所以执行时会出现异常。