• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1From fff15380539c659ccdb03fcc192eb95578b1feb5 Mon Sep 17 00:00:00 2001
2From: Jeff Vander Stoep <jeffv@google.com>
3Date: Thu, 1 Dec 2022 11:29:41 +0100
4Subject: [PATCH] Use /dev/urandom instead of getrandom()
5
6To generate the ahash crate's default hash keys, use /dev/urandom
7instead of getrandom() to avoid blocking boot on systems where the
8entropy pool isn't initialized in time and where the use case of this
9crate doesn't actually require cryptographic randomness.
10
11If opening or reading from /dev/urandom fails, fall back to getrandom().
12
13Note that std::collections::HashMap doesn't block for randomness either,
14for the same reason.  So this change just makes ahash work like HashMap.
15
16Bug: 185934601
17Change-Id: Ieaf4bcfde5664d0b5d845234d0c2139d89c4153c
18---
19 src/random_state.rs | 13 ++++++++++++-
20 1 file changed, 12 insertions(+), 1 deletion(-)
21
22diff --git a/src/random_state.rs b/src/random_state.rs
23index e885fa4..5b85726 100644
24--- a/src/random_state.rs
25+++ b/src/random_state.rs
26@@ -48,6 +48,15 @@ pub(crate) const PI2: [u64; 4] = [
27     0x3f84_d5b5_b547_0917,
28 ];
29
30+#[cfg(all(feature = "runtime-rng", not(all(feature = "compile-time-rng", test))))]
31+fn read_urandom(dest: &mut [u8]) -> Result<(), std::io::Error> {
32+    use std::fs::File;
33+    use std::io::Read;
34+
35+    let mut f = File::open("/dev/urandom")?;
36+    f.read_exact(dest)
37+}
38+
39 cfg_if::cfg_if! {
40     if #[cfg(all(feature = "compile-time-rng", any(test, fuzzing)))] {
41         #[inline]
42@@ -78,7 +87,9 @@ cfg_if::cfg_if! {
43
44             SEEDS.get_or_init(|| {
45                 let mut result: [u8; 64] = [0; 64];
46-                getrandom::getrandom(&mut result).expect("getrandom::getrandom() failed.");
47+                if read_urandom(&mut result).is_err() {
48+                    getrandom::getrandom(&mut result).expect("getrandom::getrandom() failed.");
49+                }
50                 Box::new(result.convert())
51             })
52         }
53--
542.38.1.584.g0f3c55d4c2-goog
55
56