Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 318
qz_99 Avatar asked Apr 17 '26 21:04

qz_99


1 Answers

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'.
like image 166
user803422 Avatar answered Apr 19 '26 12:04

user803422



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!