I was exploring around with C regarding strncpy since most people says that it is safer than strcpy (Additional parameter, length, to avoid buffer overflows). I also wanted to find out the effects of non-null terminated strings on a program. This is a snippet of the code that I have.
char password[5]="1234\0"; //Global variable
int main(int argc, char* argv[])
{
int length = 5;
char temp[5];
strncpy(temp, argv[1], length); //Possible problems?
/* Safer alternative */
//strncpy(temp, argv[1], length-1);
//temp[4] = '\0';
if(strncmp(password, temp, length) == 0) {
printf("Success! \n");
}
else {
printf("Error! Password is incorrect: %s\n", temp);
}
return 0;
}
As you can see, strncpy copies 5 characters and this will lead to non-null termination of variable temp if len(argv[1]) >= 5. I'm looking to see if I can use this property to read other memory regions such as the global variable password.
I've read up on strncpy being problematic causing the adjacent buffers to be affected if the string is not null-terminated, causing the next buffer to be read when it is referenced. Exploring Adjacent Memory: http://www.securiteam.com/securityreviews/5PP030KEUM.html