6

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!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • It's only different on certain OS architectures. At best it's a very unreliable seed. (But I suppose more obfuscated than sampling the clock.) – Hot Licks Nov 30 '13 at 20:16
  • 1
    Most IOCCC winners contain undefined behavior here and there. No surprise at all. – n. m. could be an AI Nov 30 '13 at 20:19
  • @n.m.- Although I understand that this might be UB, my question is why the value would be different each time. This depends on what the compilers and OSes are actually doing, which I currently don't understand. – templatetypedef Nov 30 '13 at 20:22
  • 5
    Without Address Space Layout Randomization (ASLR), it's likely to be the same address for every run of the same binary. Especially for a stack variable. – Medinoc Nov 30 '13 at 20:23
  • 1
    You beat me by 45 secs ... @Medinoc At least here's the link: http://en.wikipedia.org/wiki/Address_space_layout_randomization – alk Nov 30 '13 at 20:25

1 Answers1

3

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.)

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711