strcpy() function interview question c programming

Question: Following is the code for very basic password protection. Can you break it without knowing the password?

int main(int argc, char *argv[])
    int flag = 0;
    char passwd[10];


    strcpy(passwd, argv[1]);

    if(0 == strcmp("LinuxGeek", passwd))
        flag = 1;

        printf("\n Password cracked \n");
        printf("\n Incorrect passwd \n");

    return 0;
Answer: Yes. The authentication logic in above password protector code can be compromised by exploiting the loophole of strcpy() function. This function copies the password supplied by user to the ‘passwd’ buffer without checking whether the length of password supplied can be accommodated by the ‘passwd’ buffer or not. So if a user supplies a random password of such a length that causes buffer overflow and overwrites the memory location containing the default value ’0′ of the ‘flag’ variable then even if the password matching condition fails, the check of flag being non-zero becomes true and hence the password protection is breached.
For example :
$ ./psswd aaaaaaaaaaaaa

 Password cracked
So you can see that though the password supplied in the above example is not correct but still it breached the password security through buffer overflow.
To avoid these kind of problems the function strncpy() should be used.
Note from author : These days the compilers internally detect the possibility of stack smashing and so they store variables on stack in such a way that stack smashing becomes very difficult. In my case also, the gcc does this by default so I had to use the the compile option ‘-fno-stack-protector’ to reproduce the above scenario. appreciates your contribution please mail us the questions you have to so that it will be useful to our job search community

No comments:

Top Blogs