Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - why should someone copy argv string to a buffer?

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.

like image 237
Miroslav Mares Avatar asked Apr 20 '12 15:04

Miroslav Mares


People also ask

Why do we need argc?

Amongst other things, it allows for quick checking that the correct number of arguments has been passed. 2 ... argc shall be the number of arguments passed to the program from the environment in which the program is run. ....

What is argv [] in C?

The second parameter, argv (argument vector), is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.

How do you convert argv to INT?

argv[1] is a pointer to a string. You can print the string it points to using printf("%s\n", argv[1]); To get an integer from a string you have first to convert it. Use strtol to convert a string to an int .


2 Answers

One possible real-world example: a program that renames *.foo to *.bar; you'll need both the original file name and a copy of it with the .foo part changed to .bar for the call to rename().

like image 127
Niall C. Avatar answered Sep 30 '22 00:09

Niall C.


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.

like image 40
wildplasser Avatar answered Sep 30 '22 01:09

wildplasser