tags:

views:

308

answers:

2

i have been reading about a function that can overwrite its return address.

void foo(const char* input)
{
    char buf[10];

    //What? No extra arguments supplied to printf?
    //It's a cheap trick to view the stack 8-)
    //We'll see this trick again when we look at format strings.
    printf("My stack looks like:\n%p\n%p\n%p\n%p\n%p\n% p\n\n"); //%p ie expect pointers

    //Pass the user input straight to secure code public enemy #1.
    strcpy(buf, input);
    printf("%s\n", buf);

    printf("Now the stack looks like:\n%p\n%p\n%p\n%p\n%p\n%p\n\n");
}  

It was sugggested that this is how the stack would look like

Address of foo = 00401000

My stack looks like:
00000000
00000000
7FFDF000
0012FF80
0040108A <-- We want to overwrite the return address for foo.
00410EDE

Question:
-. Why did the author arbitrarily choose the second last value as the return address of foo()?

-. Are values added to the stack from the bottom or from the top?

  • apart from the function return address, what are the other values i apparently see on the stack? ie why isn't it filled with zeros

Thanks.

+1  A: 

The one above it is the previous EBP (0012FF80). The value above the prev-EBP is always the return address.

(This obviously assumes a non-FPO binary and 32bit Windows)1.

If you recall, the prologue looks like:

push ebp      ; back up the previous ebp on the stack
mov ebp, esp  ; set up the new frame pointer

and when a function is called, e.g.

call 0x00401000

The current EIP is pushed on the stack (used as the return address), so the stack after the prologue looks like:

[ebp+0xc]  ; contains parameter 1, etc
[ebp+0x8]  ; contains parameter 0
[ebp+0x4]  ; contains return address
[ebp]      ; contains prev-EBP

So for each %p, printf uses the next 4 bytes starting from [ebp+0xc] (the first %p parameter). Eventually you hit the previous EBP value stored on the stack, which is (0012FF80) and then the next one is the Return Address.

Note these addresses must 'make sense', which they clearly do here (though it may not be 'clear' for all).

Re Q2) The stack grows down. So when you push eax, 4 is subtracted from esp, then the value of eax is moved to [esp], equivalently in code:

push eax
;  <=>
sub esp, 4
mov [esp], eax

  1. The book is Writing Secure Code, yes?
Alex
yes. Second edition
Dr Deo
A fine choice. [padding]
Alex
A: 

printf("My stack looks like:\n%p\n%p\n%p\n%p\n%p\n% p\n\n" , what ,,,,,)

"My stack looks like:\n%p\n%p\n%p\n%p\n%p\n% p\n\n"

that is an string you must say to the string what %p is

gcc
No; that format string is there to make printf extract from the stack (without anybody putting there anything) 6 pointers and display them.
Matteo Italia