Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would setting a variable to its own address give different results on different program runs?

Yesterday I can across this obfuscated C code implementing Conway's Game of Life. As a pseudorandom generator, it writes code to this effect:

int pseudoRand = (int) &pseudoRand;

According to the author's comments on the program:

This is a big number that should be different on each run, so it works nicely as a seed.

I am fairly confident that the behavior here is either implementation-defined or undefined. However, I'm not sure why this value would vary from run to run. My understanding of how most OS's work is that, due to virtual memory, the stack is initialized to the same virtual address each time the program is run, so the address should be the same each time.

Will this code actually produce different results across different runs on most operating systems? Is it OS-dependent? If so, why would the OS map the same program to different virtual addresses on each run?

Thanks!

like image 674
templatetypedef Avatar asked Nov 30 '13 20:11

templatetypedef


1 Answers

While the assignment of addresses to objects with automatic storage is unspecified (and the conversion of an address to an integer is implementation-defined), what you're doing in your case is simply stealing the entropy the kernel assigned to the initial stack address as part of Address space layout randomization (ASLR). It's a bad idea to use this as a source of entropy which may leak out of your program, especially in applications interacting over a network with untrusted, possibly malicious remote hosts, since you're essentially revealing the random address base the kernel gave you to an attacker who might want to know it and thereby defeating the purpose of ASLR. (Even if you just use this as a seed, as long as the attacker knows the PRNG algorithm, they can reverse it to get the seed.)

like image 185
R.. GitHub STOP HELPING ICE Avatar answered Sep 23 '22 04:09

R.. GitHub STOP HELPING ICE