Format String Exploitation

Exploiting format string flaw

A Format String attack can occur when an input string data is processed by a vulnerable function so that attacker can pass the formats to exploit the stack values with the help of format string functions/printf() family functions.

Common Formats in Printf() Family

  1. %c — Formats a single character

  2. %d — Formats an integer in decimal value

  3. %f — Formats float in decimal value

  4. %p — Formats a pointer to address location

  5. %s — Formats a string

  6. %x — Formats a hexadecimal value

  7. %n — Number of bytes written

Vulnerable Functions to Format String

  1. printf()

  2. fprintf()

  3. sprintf()

  4. vprintf()

  5. snprintf()

  6. vsnprintf()

  7. vfprintf()

Vulnerable code example

Compiling this binary with GCC (no flags)

When we pass a normal string data, it prints it successfully

If we pass beyond the buffer it gets crashed. But if we pass string with format values, it gives us the random stack values which is being popped from it:

Other Scenarios

#include  <stdio.h> 
void main(int argc, char **argv)
{
	// This line is safe
	printf("%s\n", argv[1]);

	// This line is vulnerable
	printf(argv[1]);
}

./example "Hello World %p %p %p %p %p %p"
Hello World %p %p %p %p %p %p
Hello World 000E133E 000E133E 0057F000 CCCCCCCC CCCCCCCC CCCCCCCC

Mitigation

  1. Use format strings corresponding to the assigned variables

  2. Use of “%s” as format string can make the whole input as a single string

  3. Use arguments to call values and functions

  4. Defensive strategy like ‘format_gaurd’ can be used

References

Last updated