Format String Attacks

API, like printf, has issues with exploits

CharacterDescription
d, iSigned integer
uUnsigned integer
f, FDouble
e, EDouble in normal form (think IEEE 754 floating point standard)
g, GDouble in scientific notation
x, XUnsigned integer as a hex number
oUnsigned int in octal (ya, octal, some people still want to know this)
sNull terminated string
cCharacter (char data type)
pPointer to void…depends on implementation.
nDon’t print anything but write the number of characters successfully written so far into an int pointer

Invocation of printf

Insufficient Arguments to printf

  • In this case, once the program is done reading the value at memory address b, it will continue to read what is on the stack (where the “cursor” left off). In this case it will print whatever value is above the memory address of b.

**Exploiting Inconsistent printf

Crashing a Program

Printing Contents of Stack

Printing any Memory Location (1)

(2)

(3)

More Format Specifiers

  • Reduce the number of %x with %N$s
  • %n format specifier:
    • Returns the number of characters printed so far.
      • i is filled with 5 here
  • %hn format specifier (Will only use 16 bits, can be used to store large numbers):
    •  Used to write a short integer value into memory
    • It takes the number of characters printed so far by printf and writes that number, as a short integer, into a memory location that you specify as the target argument.

Overwrite an Arbitrary Location

  • Using the same approach to read data from any location, printf can be used to modify a location as well
    • Can be used to change function pointers as well as return addresses

With some Number

With Arbitrary Number

  • Arbitrary number in this case is %53x, as shown before %7$n

%n in printf

  • There are 16 characters before %n, so the value of c would be 16.

Recon

  • This basic level of reading stack data can be used for recon against a target program

  • Useful for reading usernames, passwords, return addresses, canary values, and other interesting data from the stack

  • What about using %n specifier to write arbitrary values in conjunction with the %0##x function used previously ???

Safe Code for printf