Reputation: 10582
Everything I read leads me to believe that this should cause a stack buffer overflow, but it does not:
#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;
}
But here is my output:
in this case, testtesttesttesttest is clearly larger than 8 characters, and, according to the source, it should cause a stack buffer overflow, but it does not. Why is this?
Upvotes: 2
Views: 667
Reputation: 75545
Your code does cause a buffer overflow on the stack, in the sense that you have overwritten the allocated memory for the password
buffer. Behold the memory that has been overwritten after you provide the input.
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
Whether or not a buffer overflow has undesirable side effects is undefined behavior.
Upvotes: 1
Reputation: 733
Reading more bytes then your buffer can contain won't always lead to a run-time error but it's a very bad and common error (read this article about smashing the stack). As I read from comments you added -fno-stack-protector to get the program to not print * stack smashing detected * but that's not a good idea. You should use scanf(" %8s",password)
or something similar to limit the dimension of what you read.
Upvotes: 1