I’m learning about buffer overflows today and I came across many examples of programs which are vulnerable. The thing which makes me curious is, if there is any reason to work with program’s arguments like this:
int main(int argc, char *argv[])
{
char argument_buffer[100];
strcpy(argument_buffer, argv[1]);
if(strcmp(argument_buffer, "testArg") == 0)
{
printf("Hello!\n");
}
// ...
}
Instead of simply:
int main(int argc, char *argv[])
{
if(strcmp(argv[1], "testArg") == 0)
{
printf("Hello!\n");
}
}
Please notice that I know about cons of strcpy etc. – it’s just an example. My question is – is there any true reason for using temporary buffers to store arguments from argv? I assume there isn’t any, but therefore I’m curious, why is it present in overflow examples, while in the reality it is never used? Maybe because of pure theory.
IIRC argv and its contents were not guaranteed to be writable and stable on all platforms, in the old times. C89 / C90 / ANSI-C standarized some of the existing practices. Similar for envp[]. Could also be that the routine of copying was inspired by the absence of memory protection on older platforms (such as MS-DOS). Normally (and nowadays) the OS and/or CRT takes care of copying the args form the caller’s memory to the process’s private memory arena.