| From 5bce943cdb8fc81525257413f174844d644d63c8 Mon Sep 17 00:00:00 2001 |
| From: Eric Biggers <ebiggers@google.com> |
| Date: Tue, 20 Apr 2021 16:48:07 -0700 |
| Subject: [PATCH] Use /dev/urandom instead of getrandom() |
| |
| To generate the ahash crate's default hash keys, use /dev/urandom |
| instead of getrandom() to avoid blocking boot on systems where the |
| entropy pool isn't initialized in time and where the use case of this |
| crate doesn't actually require cryptographic randomness. |
| |
| If opening or reading from /dev/urandom fails, fall back to getrandom(). |
| |
| Note that std::collections::HashMap doesn't block for randomness either, |
| for the same reason. So this change just makes ahash work like HashMap. |
| |
| Bug: 185934601 |
| Change-Id: Ie81a1f3a893d578348db11aee114d1a8f2d9fac5 |
| --- |
| diff --git a/src/random_state.rs b/src/random_state.rs |
| index f394cd0..d8280b7 100644 |
| --- a/src/random_state.rs |
| +++ b/src/random_state.rs |
| @@ -34,6 +34,15 @@ use crate::aes_hash::*; |
| #[cfg(not(all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "aes", not(miri))))] |
| use crate::fallback_hash::*; |
| |
| +#[cfg(all(feature = "runtime-rng", not(all(feature = "compile-time-rng", test))))] |
| +fn read_urandom(dest: &mut [u8]) -> Result<(), std::io::Error> { |
| + use std::fs::File; |
| + use std::io::Read; |
| + |
| + let mut f = File::open("/dev/urandom")?; |
| + f.read_exact(dest) |
| +} |
| + |
| #[cfg(all(feature = "runtime-rng", not(all(feature = "compile-time-rng", test))))] |
| static SEEDS: OnceBox<[[u64; 4]; 2]> = OnceBox::new(); |
| |
| @@ -59,7 +68,9 @@ pub(crate) fn seeds() -> [u64; 4] { |
| { |
| SEEDS.get_or_init(|| { |
| let mut result: [u8; 64] = [0; 64]; |
| - getrandom::getrandom(&mut result).expect("getrandom::getrandom() failed."); |
| + if read_urandom(&mut result).is_err() { |
| + getrandom::getrandom(&mut result).expect("getrandom::getrandom() failed.") |
| + } |
| Box::new(result.convert()) |
| })[1] |
| } |
| @@ -107,7 +118,9 @@ impl RandomState { |
| { |
| let seeds = SEEDS.get_or_init(|| { |
| let mut result: [u8; 64] = [0; 64]; |
| - getrandom::getrandom(&mut result).expect("getrandom::getrandom() failed."); |
| + if read_urandom(&mut result).is_err() { |
| + getrandom::getrandom(&mut result).expect("getrandom::getrandom() failed.") |
| + } |
| Box::new(result.convert()) |
| }); |
| RandomState::from_keys(seeds[0], seeds[1]) |