0

When I mmap a block of memory, the returned pointer might be something like 2607194112 or 3614339072 (both actual values I've gotten).

Why are these values seemingly so random? It's all virtual anyway, so why not just give me address 4096 to start us off?

I suppose this question extends also to something like malloc, but that will use one of these under the hood anyways.

doliphin
  • 752
  • 6
  • 22
  • 1
    https://en.wikipedia.org/wiki/Address_space_layout_randomization – erik258 May 01 '23 at 15:24
  • @erik258 thank you! That's an acceptable answer if it's summarised into a sentence or two. Otherwise, I'll answer my own question. It would be very helpful to note at what level this is implemented -- is it inside of the `mmap` implementation, or somewhere else? – doliphin May 01 '23 at 15:25

3 Answers3

3

You're observing Address Space Layout Randomization.

In order to prevent an attacker from reliably jumping to, for example, a particular exploited function in memory, ASLR randomly arranges the address space positions of key data areas of a process

erik258
  • 14,701
  • 2
  • 25
  • 31
1

Like @erik258 mentioned, it's because of Address space layout randomization (ASLR). Without that feature, it would be pretty easier for attackers to predict addresses of your code and libc functions and execute return-to-libc attacks. It implemented under the kernel - so far all this functions get such random values (malloc, mmap, etc).

LightVillet
  • 119
  • 3
0

Why are these values seemingly so random? It's all virtual anyway, so why not just give me address 4096 to start us off?

without specifying the operating system and architecture of your system, it's not possible to say. But as somebody has pointed out, the malloc library tries to take advantage (and for security reasons too) by acquiring memory segments spread enough in the full 64bit virtual address space of your computer (that is, indeed, huge) This will allow a malicious process that, for some reason has access to your virtual space, to have almost no probability of guessing where in memory your data is. But as a side effect, you get all those big numbers. You don't tell if you are in such a 64bit cpu, but it's common in linux, to have this spread of memory segments to allow for big holes of unused memory in its virtual address space, interspersed with small used segments. Also, the probability of a stack collision with a memory segment is low (while this is checked anyway by other means) or the grow of a data segment to overlap another segment to be impossible.

Luis Colorado
  • 10,974
  • 1
  • 16
  • 31