为什么我没有得到缓冲区溢出?

时间:2017-06-02 04:21:45

标签: c stack-overflow

我读到的所有内容都让我相信这会导致stack buffer overflow,但它不会:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    char password[8];
    int correctPassword = 0;

    printf("Password \n");
    gets(password);

    if(strcmp(password, "password"))
    {
        printf ("Wrong password entered, root privileges not granted... \n");
    }
    else
    {
        correctPassword = 1;
    }

    if(correctPassword)
    {
        printf ("Root privileges given to the user \n");
    }

    return 0;
}

但这是我的输出:

description

在这种情况下,testtesttesttesttest显然大于8个字符,并且根据source,它应该导致stack buffer overflow,但它不会。这是为什么?

2 个答案:

答案 0 :(得分:1)

读取更多字节,然后您的缓冲区可能包含赢得总是导致运行时错误,但这是一个非常糟糕且常见的错误(请阅读本文about smashing the stack)。正如我从评论中读到的那样,您添加了 -fno-stack-protector以使程序无法打印 *堆栈粉碎检测到* ,但这不是一个好主意。您应该使用scanf(" %8s",password)或类似内容来限制您阅读的内容。

答案 1 :(得分:1)

您的代码确实会导致堆栈上的缓冲区溢出,因为您已覆盖password缓冲区的已分配内存。看看提供输入后被覆盖的内存。

gcc -o Overflow Overflow.c -fno-stack-protector -g

gdb Overflow
(gdb) b 8
Breakpoint 1 at 0x4005cc: file Overflow.c, line 8.
(gdb) b 11
Breakpoint 2 at 0x4005e2: file Overflow.c, line 11.
(gdb) r
Starting program: /home/hq6/Code/SO/C/Overflow

Breakpoint 1, main (argc=1, argv=0x7fffffffde08) at Overflow.c:8
8       printf("Password \n");
(gdb) x/20x password
# Memory before overflow
0x7fffffffdd10: 0xffffde00  0x00007fff  0x00000000  0x00000000
0x7fffffffdd20: 0x00400630  0x00000000  0xf7a2e830  0x00007fff
0x7fffffffdd30: 0x00000000  0x00000000  0xffffde08  0x00007fff
0x7fffffffdd40: 0xf7ffcca0  0x00000001  0x004005b6  0x00000000
0x7fffffffdd50: 0x00000000  0x00000000  0x67fbace7  0x593e0a93
(gdb) c
Continuing.
Password
correctPassword

Breakpoint 2, main (argc=1, argv=0x7fffffffde08) at Overflow.c:11
11      if(strcmp(password, "password"))
(gdb) x/20x password
# Memory after overflow
0x7fffffffdd10: 0x72726f63  0x50746365  0x77737361  0x0064726f
0x7fffffffdd20: 0x00400630  0x00000000  0xf7a2e830  0x00007fff
0x7fffffffdd30: 0x00000000  0x00000000  0xffffde08  0x00007fff
0x7fffffffdd40: 0xf7ffcca0  0x00000001  0x004005b6  0x00000000
0x7fffffffdd50: 0x00000000  0x00000000  0x67fbace7  0x593e0a93

缓冲区溢出是否具有不良副作用是未定义的行为。