实验代码:
#include<stdio.h>
#include<string.h>
#define PASSWORD "1234567" int verify_password(char *password)
{
int authenticated;
char buffer[]; // add local buf to be overflowed
authenticated=strcmp(password,PASSWORD);
strcpy(buffer, password); // overflow here
return authenticated;
} int main()
{
int valid_flag=;
char password[];
while(){
printf("Please input password: ");
scanf("%s",password);
valid_flag=verify_password(password);
if(valid_flag){
printf("Incorrect password!\n\n");
}
else
{
printf("Congratulation! You have passed the verification!\n\n\n");
break;
}
}
return ;
}
注意以上第 8 行和第 10 行的代码,对于猜测变量在内存的相对位置和溢出尝试有用。
栈帧
程序执行到 int verify_password(char *password) 时的栈帧如图:
(变量在内存中的位置可能因编译优化而与上图不一致)
可见 authenticated (int 类型,内存中为 DWORD,占 4 字节)恰在 buffer 的 “下方”,如果 buffer 越界,那么 buffer[8..11] 刚好能覆盖 authenticated !
如果输入的字符超过 7 个字符(null 会占第 8 个字符),则越界字符会覆盖 authenticated。若 authenticated 被覆盖为 0,则溢出成功。
TIPS:用 OllyDBG 调试时可在栈区用【右键→Go to EBP】快速定位当前的 EBP,如图:
TIPS:用 OllyDBG 调试时可用 F2 设置断点。
OllyDbg 调试可见,输入 8 位密码 12345678,当程序执行完第 10 行后,authenticated 的值恰好被 password 的第九位字符串结束符 \0 覆盖为 0x00000000
但需注意 authenticated 的值来源于第 9 行的 strcpy,如果输入的密码是 01234567,则 strcpy 返回 -1,authenticated 为 -1 的补码 0xFFFFFFFF,此时溢出后不能欺骗成功。