Format String Attacks
Overview of the attack
Format string attacks exploit unsafe use of certain string manipulation functions. By allowing user-input into the format string used by these functions, a website exposes itself to these attacks. A successful attack could result in the attacker gaining full control over the website process’s memory. This could be used to run arbitrary code on the web server.
What makes a site vulnerable to the attack?
Websites may be vulnerable if they make use of the string manipulation functions in certain languages (e.g. PHP) which are based on the corresponding C/C++ functions in which these languages are written. The functions typically take an argument called a format string which may contain conversion characters, and further arguments which are added into the format string in accordance with the conversion characters. If the website includes user-input directly in the format string, an attacker may be able to insert conversion characters of his choosing.
Impact of the attack
By being able to insert conversion characters into the format string, the attacker can potentially achieve a number of aims. He may be able to read multiple values from the stack (which may contain data in use by the program), using the %x modifier. He may be able to read character strings from arbitrary memory locations, using the %s modifier. Most significantly, he may be able to write to arbitrary memory locations, using the %n modifier. The last of these could allow the attacker to run arbitrary code on the web server.
Example of the attack
An example of the attack occurs through a simple and common programming shortcut / error. Suppose the website tries to print out a name supplied by the user. The code written to do so may look something like this:
<?php printf($name); ?>
By placing conversion characters in the inputted value for name, the attacker may be able to carry out an attack. For instance, entering the name as %x will cause the first value in the stack to be printed.
Preventing the attack
To prevent format string attacks, the use of vulnerable functions, such as fprintf, printf and sprintf should be avoided where possible. When this is not possible, their use should be carefully checked. User-input should not, as a rule, be used in the format string. If user-input to the resulting string is required it should be placed in a later argument and entered into the format string using an appropriate conversion character. Regardless of where it is put, it is wise to check that the user-input is of the form expected.
A more correct version of the example code is as follows:
<?php printf("%s", $name); ?>