Partager via


Whatever Happened to sprintf(..., “%n”,...)?

You may have noticed that if your code calls functions in the sprintf family and the format template string uses the %n parameter, then it fails to run correctly after it is compiled with Visual Studio 2005. Why? Well, it's pretty simple, by default we disabled support for %n because it can be a security issue if arguments used by sprintf come from an attacker and are not validated correctly. It also turns out very few developers use %n.

%n means "write this number of characters written so far to the buffer at an address in the function argument list". If the attacker has a good deal of freedom when calling this function, then the attacker can essentially spray any value in memory.

If you must enable %n in your code, you need to call _set_printf_count_output.

Comments

  • Anonymous
    September 28, 2006
    Whatever Happened to sprintf(..., "%n", ...)? Strsafe.h: Safer String Handling in C Security

  • Anonymous
    October 02, 2006
    A couple of years ago, I replaced libc's %n handling with an abort() on one of my FreeBSD machines and I never had anything crash because of it (the machine is retired now). %n seems rare indeed.

  • Anonymous
    October 03, 2006
    PingBack from http://www.matasano.com/log/536/format-string-protection-disabling-n-by-default/

  • Anonymous
    October 24, 2006
    Does the same apply to the scanf family too?? I really don't see that %n is any great security exposure, over and above the inherent security flaws in sprintf itself. Can you think of an example where an attacker could take advantage of %n to do 'useful' damage to a system, because I'm not sure I can.

  • Anonymous
    October 24, 2006
    'useful' damage to a system?  lol.  like in the case of DoS?

  • Anonymous
    October 25, 2006
    >>scanf nope - sprintf only right now.