Reputation: 41002
Why this code is unsecured?
#include <stdio.h>
int main( int argc, char *argv[] )
{
printf(argv[1]);
printf("\n");
return 0;
}
Upvotes: 1
Views: 460
Reputation: 18227
Since poster asked for an example what %n
does:
The way a printf
format string can change memory is by using the %n
option; a specific value to be written can be obtained by using format-width specifiers "wisely". As a test:
#include <stdio.h>
int main(int argc, char **argv)
{
int *q = (int *)argv[0];
printf("%1$300000d%5$n",
123, // %1 - 1st param (formatted as '300000d')
0, // %2 - 2nd param (unused)
0, // %3 - 3rd param (unused)
0, // %4 - 4th param (unused)
argv[0]); // %5 - 5th param (written to via 'n')
printf("\nNow *q == %d\n", *q);
return 0;
}
If you run this and look a the last line of output, it'll print Now *q == 300000
(tested on Linux).
I'm using the rather-unknown positional format syntax (%
<pos>$
<fmt>) for printf()
here in order to show how one can skip arguments to choose which one to modify without needing to use any of the "noninteresting" ones.
I'll leave it to the readers experiments to figure out what printf()
treats as "arguments" for a call like printf(argv[1])
. The answer to that depends on the calling conventions (or related, the ABI for your system), and is different for 32/64bit Windows/Linux/MacOSX etc.
Upvotes: 1
Reputation: 1441
You can find a explanation here. https://www.owasp.org/index.php/Testing_for_Format_String
Upvotes: 1
Reputation: 64720
printf
will process its first parameter, looking for things like %d
and %s
.
Based on those values, it will get more data from the stack and print it out.
So if someone called your program:
a.out "%d %d %d %d %d %d %d %d %d %d %d %d"
They could view a section of your computer's callstack.
If they got even more creative with the format specifier, maybe they could dump something important, like a credit-card number or a password.
Upvotes: 5
Reputation: 145899
Look at what is a format string vulnerability:
http://en.wikipedia.org/wiki/Uncontrolled_format_string
Upvotes: 4
Reputation: 272687
Consider what the first argument of printf
controls (hint: printf
doesn't just read its input arguments).
Upvotes: 4