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 (6)

  1. Whatever Happened to sprintf(…, "%n", …)? Strsafe.h: Safer String Handling in C Security

  2. Steven Alexander Jr. says:

    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.

  3. Steve Pitts says:

    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.

  4. DaveZero says:

    ‘useful’ damage to a system?  lol.  like in the case of DoS?

  5. >>scanf

    nope – sprintf only right now.