/dev/random v.s. /dev/urandom

之前在 Openswan Porting 的時候,遇到一個問題:

為甚麼無法順利產生 RSA 所需要的 Key ? 整個程式看起來毫無反應??

其實理由很簡單,因為在產生金鑰的過程,Linux 是透過 /dev/random 去產生所需要的亂數。但是當系統覺得「無法產生夠亂的數」時,應用程式就會被 /dev/random 鎖在那個地方,直到能提供亂數為止。

下面是關於 /dev/random 的介紹:

In Unix-like operating systems, /dev/random is a special file that serves as a true random number generator or as a pseudorandom number generator.

Random number generator from kernel space was first time implemented for Linux[1] in 1994 by Theodore Ts'o. The implementation uses secure hashes rather than ciphers. The implementation was also designed with the assumption that any given hash or cipher might eventually be found to be weak, and so the design is durable in the face of any such weaknesses. Fast recovery from pool compromise is not considered a requirement, because the requirements for pool compromise are sufficient for much easier and more direct attacks on unrelated parts of the operating system.

In this implementation, the generator keeps an estimate of the number of bits of noise in the entropy pool. From this entropy pool random numbers are created. When read, the /dev/random device will only return random bytes within the estimated number of bits of noise in the entropy pool. /dev/random should be suitable for uses that need very high quality randomness such as one-time pad or key generation. When the entropy pool is empty, reads from /dev/random will block until additional environmental noise is gathered. (Source: Linux Programmer's Manual, section 4)

這意味著當 /dev/random 覺得它產生出來的亂數不夠「完美」的話,它會停在那裡等到能夠產生它所滿意的亂數。因為亂數的產生是透過所謂的 entropy pool 來產生,所以接下來我們來看看 Linux 的 entropy pool。

The random number generator gathers environmental noise from device drivers and other sources into an entropy pool. The generator also keeps an estimate of the number of bits of noise in the entropy pool. From this entropy pool random numbers are created. (Source: man 4 random)

其實說穿了,就是透過系統的 interrupt 來收集所需要的 Noise。
至於有哪些設備會產生 interrupt 可以透過 /proc/interrupt 來進行觀看。


time dd if=/dev/random of=1.dmp bs=1024k count=100

上面這個指令,簡單來說,就是從 /dev/random 讀資料,1.dmp 為 Output,這時候你會發現程式不動了,可是一旦你為產生夠多的系統中斷以後,程式就能順利執行結束。

那 urandom 有甚麼不同呢?

A read from the /dev/urandom device will not block waiting for more entropy. As a result, if there is not sufficient entropy in the entropy pool, the returned values are theoretically vulnerable to a cryptographic attack on the algorithms used by the driver. Knowledge of how to do this is not available in the current non-classified literature, but it is theoretically possible that such an attack may exist. If this is a concern in your application, use /dev/random instead. (Source: man 4 random)

FAQ 時間:

為甚麼我在使用 Fedora 的時候,在產生今要得時候都不會碰到被 lock 住的問題??

很簡單,大部分的 Distro 開機的時候都已經生成夠多的 Noise 了(單單一個 Xwindow 可能就夠了吧),如果像我是在處理 embedded Linux 的話,這是很有可能會遇到的。



IPC: Shared Memory Example

如何將Linux打造成OpenFlow Switch:Openvswitch