I am currently practicing buffer overflows, and have recently watched the awesome buffer overflow series by The Cyber Mentor.
Sadly, I am stuck at some basic level regarding how the stack and the ESP work.
Two basic things I found in tutorials to buffer overflows were:
-
The stack grows towards lower addresses, i.e. if I put something on the stack, it is stored at the position, where the ESP points to. Afterwards, the ESP is decremented.
-
The ESP points to the top of the stack, i.e. the last element I put on it.
Now I followed the vulnserver tutorial and observed the following:
Let’s say the offset to the EIP is 2000 and I pass the following input:
2000 * “A” + 4 * “B” + 4 * “C” + 4 * “D”
The EIP will be overwritten with “BBBB” and in the memory directly after the EIP comes “CCCCDDD”.
Now in all examples the ESP points to the beginning of “CCCCDDD”, i.e. to the first C.
I don’t understand why this is so, I would expect it to point to the last D, according to 2), as this was the last thing added to the stack.
Also doesn’t this conflict with 1)? How is data even stored beyond the ESP?
So why does the ESP point there?
Additionally the memory addresses actually increased in the grow direction, specifically the first A of the two thousand had a lower address than the Ds.
According to 1) I would expect it to be the other way round.
How does this make sense?
I would be grateful for someone helping me with these rabbit holes I am stuck in