Assume I have the following program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (int argc, char **argv)
{
char buf [100];
snprintf ( buf, sizeof buf, argv [1] ) ;
buf [ sizeof buf -1 ] = 0;
printf ( "%s \n" , buf ) ;
return 0 ;
}
If I compile and run it:
gcc test.c -o test
./test %p%p%p
(nil)0x4006d00x7f67e05b7ab0
I can see the stack values, meaning that it is affected by the format string vulnerability.
Now, let's slightly modify the above code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (int argc, char **argv)
{
char buf [100];
printf ( "%s \n" , argv[1] ) ;
return 0 ;
}
If I re-compile it and re-run it, the vulnerability is gone:
gcc test.c -o test
./test %p%p%p
%p%p%p
Why is this happening, what changed from the first example?
Also, in the first example, shouldn't the %s in the printf consider buf as a string? Why is such code still affected by the format string vulnerability?