codey modey
codey modey

Reputation: 983

Regarding security flaw in strcpy

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

Answers (2)

harmic
harmic

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:

  • the first 10 chars will go into passwd
  • char 11 will go into the first byte of storage for flag
  • the terminating null character will go into the second byte of storage for flag

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

tangrs
tangrs

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

Related Questions