• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1From 5bce943cdb8fc81525257413f174844d644d63c8 Mon Sep 17 00:00:00 2001
2From: Eric Biggers <ebiggers@google.com>
3Date: Tue, 20 Apr 2021 16:48:07 -0700
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: Ie81a1f3a893d578348db11aee114d1a8f2d9fac5
18---
19diff --git a/src/random_state.rs b/src/random_state.rs
20index c3628bf..835467c 100644
21--- a/src/random_state.rs
22+++ b/src/random_state.rs
23@@ -48,6 +48,15 @@ use crate::fallback_hash::*;
24 #[cfg(not(all(target_arch = "arm", target_os = "none")))]
25 static RAND_SOURCE: OnceBox<Box<dyn RandomSource + Send + Sync>> = OnceBox::new();
26
27+#[cfg(all(feature = "runtime-rng", not(all(feature = "compile-time-rng", test))))]
28+fn read_urandom(dest: &mut [u8]) -> Result<(), std::io::Error> {
29+    use std::fs::File;
30+    use std::io::Read;
31+
32+    let mut f = File::open("/dev/urandom")?;
33+    f.read_exact(dest)
34+}
35+
36 /// A supplier of Randomness used for different hashers.
37 /// See [RandomState.set_random_source].
38 pub trait RandomSource {
39@@ -98,7 +107,9 @@ impl RandomSource for DefaultRandomSource {
40
41         SEEDS.get_or_init(|| {
42             let mut result: [u8; 64] = [0; 64];
43-            getrandom::getrandom(&mut result).expect("getrandom::getrandom() failed.");
44+            if read_urandom(&mut result).is_err() {
45+                getrandom::getrandom(&mut result).expect("getrandom::getrandom() failed.");
46+            }
47             Box::new(result.convert())
48         })
49     }
50