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.
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:
and when a function is called, e.g.
The current EIP is pushed on the stack (used as the return address), so the stack after the prologue looks like:
So for each
%p, printf uses the next 4 bytes starting from[ebp+0xc](the first%pparameter). 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 fromesp, then the value of eax is moved to [esp], equivalently in code: