Hacking - The Art of Exploitation, 2nd Edition

(Romina) #1

48 0x200


0x264 Format Strings...............................................................................


The printf() function can be used to print more than just fixed strings. This
function can also use format strings to print variables in many different for-
mats. A format string is just a character string with special escape sequences
that tell the function to insert variables printed in a specific format in place
of the escape sequence. The way the printf() function has been used in the
previous programs, the "Hello, world!\n" string technically is the format string;
however, it is devoid of special escape sequences. These escape sequences are
also called format parameters, and for each one found in the format string, the
function is expected to take an additional argument. Each format parameter
begins with a percent sign (%) and uses a single-character shorthand very
similar to formatting characters used by GDB’s examine command.

All of the preceding format parameters receive their data as values,
not pointers to values. There are also some format parameters that expect
pointers, such as the following.

The %s format parameter expects to be given a memory address; it prints
the data at that memory address until a null byte is encountered. The %n
format parameter is unique in that it actually writes data. It also expects to be
given a memory address, and it writes the number of bytes that have been
written so far into that memory address.
For now, our focus will just be the format parameters used for displaying
data. The fmt_strings.c program shows some examples of different format
parameters.

fmt_strings.c


#include <stdio.h>

int main() {
char string[10];
int A = -73;
unsigned int B = 31337;

strcpy(string, "sample");

Parameter Output Type
%d Decimal
%u Unsigned decimal
%x Hexadecimal

Parameter Output Type

%s String
%n Number of bytes written so far
Free download pdf