Reputation: 983
By causing buffer overflow we can overwrite the memory where flag value 0 is saved, so an even incorrect password will crack the code..
How will this happen internally? Could someone please explain in detail..how will this happen in memory practically?
#include<stdio.h>
int main(int argc, char *argv[])
{
int flag = 0;
char passwd[10];
memset(passwd,0,sizeof(passwd));
strcpy(passwd, argv[1]);
if(0 == strcmp("LinuxGeek", passwd))
{
flag = 1;
}
if(flag)
{
printf("\n Password cracked \n");
}
else
{
printf("\n Incorrect passwd \n");
}
return 0;
}
Upvotes: 2
Views: 379
Reputation: 30577
Local variables in C are typically allocated on the stack. Stacks tend to grow downwards in memory, so the storage for 'flag' will be immediately after the storage allocated for 'passwd'.
strcpy does not check that the amount of data being copied is not going to overflow the buffer into which the data is being copied. So, imagine that argv[1] is 11 chars exactly, this is what will happen:
Therefore, flag will be non-zero.
The exact behaivour will vary from compiler to compiler - but this is a typical scenario.
Use strncpy to avoid this.
Upvotes: 3
Reputation: 9930
Keep in mind that from a theoretical point of view, if the string stored in passwd
is overflowed, it invokes undefined behavior and the result is unpredictable.
Practically speaking, on a lot of modern platforms where local variables are stored on a stack, if your compiler places the flag
higher than the passwd
buffer, it could be overflowed by the strcpy
call.
I.e. your stack could look like this:
| ... |
+------------+
| flag | / \
+------------+ |
| passwd[10] | | increasing addresses
| ... |
If you write more than 10 bytes to passwd
, strcpy
simply writes over flag
.
Note that the behavior varies with compiler to compiler, platform to platform. This explanation covers what happens on common systems but know that it is theoretically possible to have a platform that doesn't use a stack so this explanation won't apply.
Upvotes: 6