Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address Space Layout Randomization( ALSR ) and mmap

I expect that due to Address Space Layout Randomization (ALSR) a process forked from another process will have different addresses returned when calling mmap. But as I found out, that was not the case. I made the following test program for that purpose. All the addresses returned by malloc are exactly the same for the parent and the child. Note that the malloc for cl1, cl2, pl1, pl2 internally uses mmap because they are large blocks.

So, my question is, why mmap is not returning different addresses even in the presence of ALSR. Maybe its because the seed for randomization here is the same for the original and forked process. Or is there any other reason?

int main()
{
  pid = fork();

  if (pid == 0)                // child
  {
    void * c1 = malloc( 4096 );
    void * c2 = malloc( 4096 );

    void * cl1 = malloc( (long)512e3 ); // internally uses mmap
    void * cl2 = malloc( (long)512e3 ); // internally uses mmap

    printf( "c1 = %p, c2 = %p, cl1 = %p, cl2 = %p!\n", c1, c2, cl1, cl2 );
  }
  else
  {
    void * p1 = malloc( 4096 );
    void * p2 = malloc( 4096 );

    void * pl1 = malloc( (long)512e3 ); // internally uses mmap
    void * pl2 = malloc( (long)512e3 ); // internally uses mmap

    printf( "p1 = %p, p2 = %p, pl1 = %p, pl2 = %p!\n", p1, p2, pl1, pl2 );
  }

  return 0;
}
like image 877
MetallicPriest Avatar asked Feb 28 '12 15:02

MetallicPriest


1 Answers

ASLR mainly randomizes the distance from the top of user-space address space down to the stack, and the distance from the bottom of stack-reserved space to the first mmap (which is probably the mapping of the dynamic linker). Any further randomization would have serious fragmenting effects on the virtual memory space, and thus would break programs that need to make large mmaps (e.g. a 1-2 GB mapping on a 32-bit machine).

I have seen some Linux distros ship patched kernels that perform much more randomization on the addresses returned by mmap. Some of them even give you mappings overlapping with the space reserved for the stack to expand into, and then when the stack grows it clobbers your mapping (resulting a huge gaping security hole, much bigger than anything non-random address assignments could have caused). Stay away from these hacks.

like image 137
R.. GitHub STOP HELPING ICE Avatar answered Oct 20 '22 10:10

R.. GitHub STOP HELPING ICE