Format String Attack

A FormatStringAttack is a common class of attack on a CeeLanguage program that uses either the stdio functionality of the the ANSI C library (most commonly) or another system with similar functionality. The attack consists of providing a hostile format string which is then processed by the "printf engine", and which instructs said engine to do nasty things. Many recent Unix exploits are based on FormatStringAttacks; some Windows exploits may use them as well.

Consider the following innocuous-looking program:

 /* print arguments */
 #include <stdio.h>

int main (int argc, char **argv) { int i; for (i = 0; i < argc; ++i) { printf (argv[i]); printf ("\n"); } printf ("There were %d arguments\n", argc); return 0; }
If you don't see the problem immediately, it probably looks okay at first glance. But if someone were to install it SUID or use it as part of a network-accessible server, their box could be attacked. The line that permits the attack to occur is this one:

 printf (argv[i]);
printf expects its first argument to be a format string--an entity including InBandSignal. The character % is used in printf format strings to specify output conversions. Some output conversions, however, can modify the stack; the attacker can thus cause the program to exec a shell, giving the attacker the privileges of the running process.

The problem is the in-band signal. The obvious fix is to use this instead:

 printf ("%s", argv[i]);
In the latter case, the only format string is "%s", which is harmless. No matter what is contained in argv[i], it will all be interpreted as text. Alternatively, one could write:

 fputs(argv[i], stdout);
fputs always interprets its first argument as a plain string, not as a format string, so the vulnerability does not exist when using fputs.

See also SentinelPattern / SecurityExploits


CategoryCee


EditText of this page (last edited December 16, 2005) or FindPage with title or text search