Search code examples
cbuffer-overflowstrcmp

Non Null-terminated value causing StrCmp to return 0?


I have the following code:

_Bool grantAccess(char *password){
    char goodPassWord[]= "goodpass";
    return (0 == strcmp(password, goodPassWord));

}

_Bool grantAccessExercise(void){
    char password[9];
    int allow = 0;

    printf("Please enter password: ");

    gets(password); 

    if (grantAccess(password)) {
         allow = 1;
    }

    return (allow != 0);
    }

When I enter any combination of 10 characters for password it overflows and overwrites the null-terminator. Can anyone explain why the non null-terminated value causes StrCmp to return 0?


Solution

  • Can anyone explain why the non null-terminated value causes StrCmp to return 0?

    This is not what happens.

    What happens is:

    • the buffer overflow over password overwrites bytes that are part of the stack-located variable allow
    • as a result, allow does no longer contain the value zero, but some other value.
    • the call to grantAccess() returns false, and allow is not modified.
    • at the end, allow contains the non-zero value due to the overflow.

    In order to verify that, I made a test as follows:

    • I entered password "0123456789"
    • I observed that allow == 57, which is the ASCII code of character '9'.