Share via


Format String Bugs

Format string bugs are not exactly the same as a buffer overflow, but because they lead to the same problems, they are included in this section.

The basic problem of format string bugs stems from the fact that there is no realistic way for a function that takes a variable number of arguments to determine how many arguments were passed in. (The most common functions that take a variable number of arguments, including C run-time functions, are the printf family of calls.) What makes this problem interesting is that the %n format specifier writes the number of bytes that would have been written by the format string into the pointer supplied for that argument. With a bit of tinkering, you find that somewhat random bits of the memory space of the process are now overwritten with the bytes of the attacker. Exploiting such bugs is a little difficult on Windows systems because many of the chunks of memory you would like to write are located at 0x00ffffff or below—for example, the stack will normally be found in the range of approximately 0x00120000.

The fix to the problem is relatively simple: always pass in a format string to the printf family of functions. For example, printf(input); is exploitable, and printf("%s", input); is not exploitable.

Remember that if you allow attackers to start writing memory anywhere in your application, it is just a matter of time before they figure out how to turn it into a crash or execution of arbitrary code. This bug is fairly simple to avoid. Take special care if you have custom format strings stored to help with versions of your application in different languages. If you do, make sure that the strings cannot be written by unprivileged users.

Copyright © 2005 Microsoft Corporation.
All rights reserved.