Skip to main content

keep_core/
entropy.rs

1//! Multi-source entropy mixing for defense-in-depth randomness.
2// SAFETY: CPUID and RDRAND intrinsics require unsafe for hardware entropy.
3#![allow(unsafe_code)]
4
5use blake2::{Blake2b512, Digest};
6use rand::Rng;
7use std::sync::atomic::{AtomicU64, Ordering};
8use std::sync::OnceLock;
9
10const POOL_SIZE: usize = 128;
11
12static PROCESS_CONTEXT_COUNTER: AtomicU64 = AtomicU64::new(0);
13
14fn hash_to_32(hasher: Blake2b512) -> [u8; 32] {
15    let mut output = [0u8; 32];
16    output.copy_from_slice(&hasher.finalize()[..32]);
17    output
18}
19
20fn gather_os_entropy(pool: &mut [u8]) {
21    rand::rng().fill_bytes(pool);
22}
23
24#[cfg(target_arch = "x86_64")]
25fn is_rdrand_available() -> bool {
26    static AVAILABLE: OnceLock<bool> = OnceLock::new();
27    *AVAILABLE.get_or_init(|| {
28        // SAFETY: __cpuid with leaf 1 is safe on all x86_64 processors.
29        // This instruction queries CPU feature flags and does not modify state.
30        let result = unsafe { core::arch::x86_64::__cpuid(1) };
31        (result.ecx & (1 << 30)) != 0
32    })
33}
34
35#[cfg(target_arch = "x86_64")]
36fn is_rdrand_validated() -> bool {
37    static VALIDATED: OnceLock<bool> = OnceLock::new();
38    *VALIDATED.get_or_init(|| {
39        if !is_rdrand_available() {
40            return false;
41        }
42        let mut buf1 = [0u8; 16];
43        let mut buf2 = [0u8; 16];
44        if !fill_rdrand(&mut buf1) || !fill_rdrand(&mut buf2) {
45            return false;
46        }
47        buf1 != buf2
48    })
49}
50
51#[cfg(target_arch = "x86_64")]
52fn rdrand64_with_retry() -> Option<u64> {
53    const MAX_RETRIES: u32 = 10;
54    let mut val: u64 = 0;
55    for _ in 0..MAX_RETRIES {
56        // SAFETY: _rdrand64_step is safe to call when RDRAND is available (checked by caller).
57        // It writes a random value to `val` and returns 1 on success, 0 on underflow.
58        // The instruction does not have side effects beyond writing to the output parameter.
59        if unsafe { core::arch::x86_64::_rdrand64_step(&mut val) } == 1 {
60            return Some(val);
61        }
62    }
63    None
64}
65
66#[cfg(target_arch = "x86_64")]
67fn fill_rdrand(pool: &mut [u8; 16]) -> bool {
68    for chunk in pool.chunks_exact_mut(8) {
69        let Some(val) = rdrand64_with_retry() else {
70            return false;
71        };
72        chunk.copy_from_slice(&val.to_le_bytes());
73    }
74    true
75}
76
77#[cfg(target_arch = "x86_64")]
78fn gather_rdrand(pool: &mut [u8; 16]) -> bool {
79    is_rdrand_validated() && fill_rdrand(pool)
80}
81
82#[cfg(not(target_arch = "x86_64"))]
83fn gather_rdrand(_pool: &mut [u8; 16]) -> bool {
84    false
85}
86
87fn gather_timing_jitter() -> [u8; 32] {
88    let mut hasher = Blake2b512::new();
89    let mut work_buffer = [0u8; 64];
90
91    for i in 0..64 {
92        let t1 = std::time::Instant::now();
93
94        for (j, byte) in work_buffer.iter_mut().enumerate() {
95            *byte = byte.wrapping_add((i ^ j) as u8);
96        }
97        std::hint::spin_loop();
98        std::sync::atomic::compiler_fence(Ordering::SeqCst);
99
100        let jitter = t1.elapsed().as_nanos() as u64;
101        hasher.update(jitter.to_le_bytes());
102
103        let sys_time = std::time::SystemTime::now()
104            .duration_since(std::time::UNIX_EPOCH)
105            .map(|d| d.as_nanos() as u64)
106            .unwrap_or(0);
107        hasher.update(sys_time.to_le_bytes());
108    }
109
110    hasher.update(work_buffer);
111    hash_to_32(hasher)
112}
113
114fn gather_process_context() -> [u8; 32] {
115    let mut hasher = Blake2b512::new();
116    hasher.update(std::process::id().to_le_bytes());
117    hasher.update(format!("{:?}", std::thread::current().id()).as_bytes());
118
119    let counter = PROCESS_CONTEXT_COUNTER.fetch_add(1, Ordering::Relaxed);
120    hasher.update(counter.to_le_bytes());
121
122    let stack_var: u8 = 0;
123    hasher.update((&stack_var as *const u8 as usize).to_le_bytes());
124
125    let heap_box = Box::new(0u8);
126    hasher.update((&*heap_box as *const u8 as usize).to_le_bytes());
127
128    hash_to_32(hasher)
129}
130
131fn mix_entropy(sources: &[&[u8]]) -> [u8; 32] {
132    let mut hasher = Blake2b512::new();
133    hasher.update(b"keep-entropy-v1");
134
135    for (i, source) in sources.iter().enumerate() {
136        hasher.update([i as u8]);
137        hasher.update((source.len() as u64).to_le_bytes());
138        hasher.update(*source);
139    }
140
141    hash_to_32(hasher)
142}
143
144fn ensure_entropy_health() -> Result<(), EntropyHealthError> {
145    static HEALTH_RESULT: OnceLock<Result<(), EntropyHealthError>> = OnceLock::new();
146    *HEALTH_RESULT.get_or_init(check_entropy_health_internal)
147}
148
149/// Generates 32 bytes of mixed entropy from multiple sources.
150///
151/// Sources:
152/// - OS randomness (getrandom/urandom via rand crate)
153/// - CPU randomness (RDRAND on x86_64 if available)
154/// - Timing jitter (high-resolution timestamps with spin loops)
155/// - Process context (PID, thread ID, memory addresses)
156///
157/// All sources are mixed through BLAKE2b-512, truncated to 32 bytes.
158///
159/// Returns an error if the RNG health check fails.
160pub fn random_bytes_mixed() -> Result<[u8; 32], EntropyHealthError> {
161    ensure_entropy_health()?;
162    Ok(random_bytes_mixed_internal())
163}
164
165fn random_bytes_mixed_internal() -> [u8; 32] {
166    let mut os_pool = [0u8; POOL_SIZE];
167    gather_os_entropy(&mut os_pool);
168
169    let mut rdrand_pool = [0u8; 16];
170    let has_rdrand = gather_rdrand(&mut rdrand_pool);
171
172    let timing = gather_timing_jitter();
173    let context = gather_process_context();
174
175    if has_rdrand {
176        mix_entropy(&[&os_pool, &timing, &context, &rdrand_pool])
177    } else {
178        mix_entropy(&[&os_pool, &timing, &context])
179    }
180}
181
182/// Generates N bytes of mixed entropy.
183///
184/// For requests <= 32 bytes, returns a truncated output from `random_bytes_mixed()`.
185/// For larger requests, generates multiple 32-byte blocks with unique counters.
186///
187/// Returns an error if the RNG health check fails.
188pub fn try_random_bytes<const N: usize>() -> Result<[u8; N], EntropyHealthError> {
189    ensure_entropy_health()?;
190
191    let mut output = [0u8; N];
192
193    if N <= 32 {
194        output.copy_from_slice(&random_bytes_mixed_internal()[..N]);
195        return Ok(output);
196    }
197
198    for (counter, chunk) in output.chunks_mut(32).enumerate() {
199        let block = random_bytes_mixed_internal();
200        let mut hasher = Blake2b512::new();
201        hasher.update(block);
202        hasher.update((counter as u64).to_le_bytes());
203        chunk.copy_from_slice(&hasher.finalize()[..chunk.len()]);
204    }
205
206    Ok(output)
207}
208
209/// Generates N bytes of mixed entropy.
210///
211/// For requests <= 32 bytes, returns a truncated output from `random_bytes_mixed()`.
212/// For larger requests, generates multiple 32-byte blocks with unique counters.
213///
214/// # Panics
215/// Panics if the RNG health check fails. **Production code MUST use
216/// [`try_random_bytes`] and propagate the error instead** — a CSPRNG failure is a
217/// fail-closed condition, not a crash. This panicking convenience is for tests,
218/// benchmarks, and non-fallible contexts only (#jrec: all production callers were
219/// migrated to `try_random_bytes`).
220pub fn random_bytes<const N: usize>() -> [u8; N] {
221    try_random_bytes().expect("RNG health check failed: constant or zero output detected")
222}
223
224/// Error returned when RNG health check fails.
225#[derive(Debug, Clone, Copy)]
226pub struct EntropyHealthError;
227
228impl std::fmt::Display for EntropyHealthError {
229    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
230        write!(
231            f,
232            "RNG health check failed: constant or zero output detected"
233        )
234    }
235}
236
237impl std::error::Error for EntropyHealthError {}
238
239fn hamming_distance(a: &[u8; 32], b: &[u8; 32]) -> u32 {
240    a.iter().zip(b).map(|(x, y)| (x ^ y).count_ones()).sum()
241}
242
243fn check_bit_distribution(samples: &[[u8; 32]]) -> bool {
244    (0..32).all(|pos| {
245        let all_zeros = samples.iter().all(|s| s[pos] == 0x00);
246        let all_ones = samples.iter().all(|s| s[pos] == 0xff);
247        !all_zeros && !all_ones
248    })
249}
250
251fn check_entropy_health_internal() -> Result<(), EntropyHealthError> {
252    let samples: [[u8; 32]; 3] = std::array::from_fn(|_| random_bytes_mixed_internal());
253
254    let all_nonzero = samples.iter().all(|s| s.iter().any(|&b| b != 0));
255    let all_unique =
256        samples[0] != samples[1] && samples[1] != samples[2] && samples[0] != samples[2];
257
258    if !all_nonzero || !all_unique || !check_bit_distribution(&samples) {
259        return Err(EntropyHealthError);
260    }
261
262    const MIN_HAMMING: u32 = 64;
263    let sufficient_distance = [(0, 1), (1, 2), (0, 2)]
264        .iter()
265        .all(|&(i, j)| hamming_distance(&samples[i], &samples[j]) >= MIN_HAMMING);
266
267    if !sufficient_distance {
268        return Err(EntropyHealthError);
269    }
270
271    Ok(())
272}
273
274/// Verifies the RNG produces non-constant, non-zero output.
275///
276/// Generates multiple samples and checks:
277/// - Output is not all zeros
278/// - Different calls produce different output
279/// - Byte positions are not all 0x00 or 0xff across samples
280/// - Hamming distance between samples is at least 64 bits
281pub fn check_entropy_health() -> Result<(), EntropyHealthError> {
282    check_entropy_health_internal()
283}
284
285/// Returns whether RDRAND is available on this system.
286pub fn has_rdrand() -> bool {
287    #[cfg(target_arch = "x86_64")]
288    {
289        is_rdrand_available()
290    }
291    #[cfg(not(target_arch = "x86_64"))]
292    {
293        false
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300
301    #[test]
302    fn test_random_bytes_mixed_produces_output() {
303        let bytes = random_bytes_mixed().unwrap();
304        assert!(!bytes.iter().all(|&b| b == 0));
305    }
306
307    #[test]
308    fn test_random_bytes_mixed_different_each_call() {
309        let b1 = random_bytes_mixed().unwrap();
310        let b2 = random_bytes_mixed().unwrap();
311        let b3 = random_bytes_mixed().unwrap();
312        assert_ne!(b1, b2);
313        assert_ne!(b2, b3);
314        assert_ne!(b1, b3);
315    }
316
317    #[test]
318    fn test_entropy_health_check_passes() {
319        assert!(check_entropy_health().is_ok());
320    }
321
322    #[test]
323    fn test_timing_jitter_produces_output() {
324        let t1 = gather_timing_jitter();
325        let t2 = gather_timing_jitter();
326        assert!(!t1.iter().all(|&b| b == 0));
327        assert_ne!(t1, t2);
328    }
329
330    #[test]
331    fn test_process_context_produces_output() {
332        let ctx = gather_process_context();
333        assert!(!ctx.iter().all(|&b| b == 0));
334    }
335
336    #[test]
337    fn test_mix_entropy_domain_separation() {
338        let data = [1u8; 32];
339        let m1 = mix_entropy(&[&data]);
340        let m2 = mix_entropy(&[&data, &data]);
341        assert_ne!(m1, m2);
342    }
343
344    #[test]
345    fn test_random_bytes_large_buffer() {
346        let bytes: [u8; 128] = random_bytes();
347        assert!(!bytes.iter().all(|&b| b == 0));
348        assert_ne!(&bytes[..32], &bytes[32..64]);
349    }
350}