Category: Overflow Difficulty: An introductory course

What You Should Not Do

You need to print a string, so you call printf(mystring). This can lead to problems if the string can be constructed by an attacker. By crafting the string using formatting characters that expect additional parameters to printf(), the program can inappropriately read data off the stack, and even write over values on the stack!
int main(int argc, char **argv)
{
    if(argc <= 1)
        printf("error, no arguments (other than program name)!");
    else
    {
        printf(argv[1]);
    }
}
If argv[1] contains any special format string characters, then printf() will look for additional arguments to fill in the formatting characters. A carefully crafted attack could exploit this. It also affects other *printf() functions including sprintf(), snprintf(), fprintf, etc.

What You Should Do

When using one of the *printf() functions, always use a format string, such as printf("%s",mystring). This way formatting characters cannot be arbitrarily injected into printf.
int main(int argc, char **argv)
{
    if(argc <= 1)
        error, no arguments (other than program name)!
    else
    {
printf("%s",argv[1]);
    }
}
By statically specifying the format string, no one else can put arbitrary formatting characters in.

Concept Map

This example refers to the point N (When using format string functions, make sure that the format string can be authenticated/trusted).This maps to 8 (When performing input validation take into account how programs invoked with those arguments could interpret them). This further maps to "Input Validation", in the concept map.

 

JSN Teki template designed by JoomlaShine.com