I was reading about %n
format specifier in C at this question. But when I tried the following program on different C++ compilers, it gave me different outputs.
As noted in the question Code Blocks
is indeed correct while Orwell Dev C++
is incorrect. Visual Studio on the other hand is non-conforming.
cppreferences C documentation for printf says says:
returns the number of characters written so far by this call to the function.
I don't see anything in the draft standard that makes this optional, C++ refers to the C standard with respect to printf
. MSDN documents this and says:
Because the %n format is inherently insecure, it is disabled by default. If %n is encountered in a format string, the invalid parameter handler is invoked, as described in Parameter Validation. To enable %n support, see _set_printf_count_output.
Why is the %n format is inherently insecure?
I am assuming that they consider it unsafe because of security issues such as those outlined in Format String Vulnerability documents one possible way to exploit this. It is predicated on the format string being controlled by user input. The paper gives the following example:
char user_input[100];
scanf("%s", user_input);
printf(user_input);
Retired Ninja linked to Bugtraq post which demonstrates an real example of such a bug ending up in an exploit in proftpd 1.2.0pre6
:
- ftp to host
- login (anonymous or no)
(this should be all on one line, no spaces)
ftp> ls aaaXXXX%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u %u%u%u%u%u%u%u%u%u%653300u%n
(replace the X's with the characters with ascii values 0xdc,0x4f,0x07,0x08 consecutively)
Lots of other nasties can easily be easily done with this. Since proftpd will pass on user input data to snprintf, argument attacks are easy.
The problem with Visual Studios approach is that it breaks portability. Other approaches include using flags like Wformat-security used by gcc which combined with -WError
can make it an error but you can choose this as part of your build process.
The Code Blocks output is correct.
The Orwell Dev C++ output is incorrect. Either that implementation is not non-conforming by default (read the documentation to see if there's a way to make it behave correctly), or it has a bug.
Microsoft's implementation is non-conforming by default. It disables the standard %n
format specifier to prevent some possible security problems (though there are no such problems in the code in your question). Apparently there are ways to re-enable it; see Shafik Yaghmour's answer.
The only potential problem I see with your program is that it doesn't print a newline at the end of its output, but that's not relevant to the %n
issue.