tags:

views:

116

answers:

5

I'm on Linux, which has address space layout randomization. Is it necessary to to declare a buffer on the stack, leave it uninitialized, and use it for entropy, or can I just take the address of something already on the stack, cast it to an integer and (knowing that it is somewhat random due to address space layout randomization) use that integer for entropy instead?

The pointer approach has an advantage in that it generates no compiler warnings as the unitialized buffer does when you attempt to manipulate it, but in my tests it seemed only the lower-order part of the address (maybe the last byte or two) would change from invocation to invocation. The entropy buffer seemed to perform even worse, often containing nothing at all.

+6  A: 

If you need weak entropy on Linux, why not read /dev/urandom? It's a non-blocking variant of /dev/random that's less...random (but, again, non-blocking).

T.J. Crowder
+1  A: 

What exactly do you mean by weak? The canonical source of entropy in C (for non-cryptographic purposes) is time from <time.h>.

Accessing an uninitialized variable is undefined behavior and may have unpredictable consequences on some platforms. Don't do it.

avakar
Well, I wanted something else in addition to time() and pid.
Modest
+2  A: 

What's wrong with /dev/random?

Do not use uninitialized memory for entropy. Especially stack. It has tendency to look very similarly in consecutive runs. And it's quite predictable and not very random.

Tomek Szpakowicz
+1  A: 

Why don't you read a few bytes from /dev/random or /dev/urandom?

pmg
+2  A: 

Fundamentally, if you need entropy for anything, you need to take it from some external source, not some quirk of the compiler, or expectations of memory allocation layout. There's no guarantee that the compiler will give you different pointers. You might write code that works okay on one system, but completely fails to give entropy on another.

As others have suggested, using /dev/random is a good idea. If that's not available, you might be able to get away with calling the time() function (time.h) if you just need a little entropy.

However, I get very worried when people ask for just a little entropy because that suggests some kind of reliance on a random value. Having only a little entropy means that it will frequently return the same value, possibly causing the system to fail in unexpected ways. My strong recommendation is to always get good entropy from sources like /dev/random.

Matt Ball