2017-06-02 42 views
2

一切我阅读使我相信,这应该引起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,但它不。为什么是这样?

+11

因为它是未定义的行为,所以任何事情都可能发生。 https://stackoverflow.com/documentation/c/364/undefined-behavior#t=201706020423447810219。 – Stargateur

+2

您预期堆栈溢出如何显示?当我运行这个时,我得到以下输出:'输入了错误的密码,未授予root权限... ***堆栈检测到***:./溢出终止 ' – merlin2011

+0

'p&password [8]'和'p&correctPassword'显示? – Ryan

回答

1

读取更多字节,那么您的缓冲区可以包含并不总是会导致运行时错误,但它是一个非常糟糕的和常见的错误(阅读本文about smashing the stack)。当我读到评论时,你添加了-fno-stack-protector让程序不打印*堆栈粉碎检测到*但这不是一个好主意。你应该使用scanf(" %8s",password)或类似的东西来限制你阅读的内容。

+0

[堆栈缓冲区溢出](https://en.wikipedia.org/wiki/Stack_buffer_overflow)确实是与[堆缓冲区溢出]相同的事情(https://en.wikipedia.org/wiki/Heap_overflow) – bradgonesurfing

+0

@bradgonesurfing我不明白我在说什么堆。你可以说得更详细点吗? – BetaRunner

+1

您批评术语“堆栈缓冲区溢出”是一个不正确的术语,声称它不同于“缓冲区溢出”。术语“堆栈缓冲区溢出”没有任何问题。它意味着恰好存在于已写入但在其范围外的堆栈上的缓冲区。 – bradgonesurfing

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 

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