Often when writing exploits under ASLR you’ll need to calculate an address based on some leak. Usually, you’ll just calculate the base address of that section and then compute any desired address relative to the base. I’ve often noticed that this doesn’t work with stack addresses. Leaked stack addresses are constant offsets relative to each other but not constant relative to the base of the stack — even in cases where the stack is not explicitly grown downwards.
Some brief gdb investigation shows that the initial stack pointer is randomized within a page from the very first userspace instruction.
So, why is that?
randomize_stack_top will randomize the base of the stack — specifically randomizing the 22 least significant bits, shifted upwards by a page. We saw earlier that the initial stack pointer isn’t page aligned, though? Where does that come from?
Turns out Linux ASLR will randomize the initial stack pointer within a page as well! This adds an additional 8 bits of entropy for a total of 2^30 initial stack pointer values.