strat9_kernel/entropy.rs
1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Kernel entropy pool : a cryptographically sound random bytes from interrupt noise.
24//!
25//! Collects entropy from:
26//! - keyboard IRQ timing + scancode data
27//! - timer tick jitter (low bits of TSC)
28//! - storage (AHCI) IRQ timing
29//! - RDRAND when available (as seed material)
30//!
31//! The pool uses a tweaked Threefish-like mixing over 128 bytes (4×4 u64s)
32//! for efficient diffusion. Output is extracted by hashing the pool state
33//! through a **compression round** : no built-in hash dependency needed.
34
35use core::sync::atomic::{AtomicU32, AtomicU64, Ordering};
36
37// === Pool constants ===================================
38/// Number of 64-bit words in the entropy pool (16 = 128 bytes).
39const POOL_WORDS: usize = 16;
40/// Entropy threshold in bytes before we consider the pool "initialised".
41const ENTROPY_HIGH_WATER: u32 = 64;
42
43// === Global pool state =================================
44/// The entropy pool : a 128‑byte array of 16 u64s.
45static POOL: [AtomicU64; POOL_WORDS] = [const { AtomicU64::new(0) }; POOL_WORDS];
46/// Estimated entropy count (in bytes). Saturates at POOL_WORDS * 8.
47static ENTROPY_CTR: AtomicU32 = AtomicU32::new(0);
48/// Index where the next sample will be mixed in.
49static POOL_IDX: AtomicU32 = AtomicU32::new(0);
50
51// === Initial seed from RDRAND ================================================
52/// One-time boot‑time seed of the pool from RDRAND (if available).
53pub fn seed_from_rdrand() {
54 // RDRAND can hang on some QEMU configurations (especially AMD CPU models).
55 // Fall back to TSC as a weak initial seed (better than all-zero pool).
56 let seed = crate::arch::rdtsc().wrapping_mul(6364136223846793005);
57 for w in &POOL {
58 let old = w.load(Ordering::Relaxed);
59 w.store(old ^ seed, Ordering::Relaxed);
60 }
61 ENTROPY_CTR.store(32, Ordering::Relaxed);
62}
63
64// === public API ================================================
65
66/// Check whether the entropy pool has accumulated enough entropy
67/// (at least `ENTROPY_HIGH_WATER` bytes). Used by GRND_NONBLOCK.
68pub fn is_ready() -> bool {
69 ENTROPY_CTR.load(Ordering::Relaxed) >= ENTROPY_HIGH_WATER
70}
71
72/// Feed a 64‑bit sample into the entropy pool (called from interrupt handlers).
73///
74/// `tag` should be a small unique discriminator for the source
75/// (e.g. 1 = keyboard, 2 = timer, 3 = storage).
76#[inline]
77pub fn add_entropy(tag: u8, sample: u64) {
78 let idx = POOL_IDX.fetch_add(1, Ordering::Relaxed) as usize % POOL_WORDS;
79 let tag64 = (tag as u64) << 56;
80
81 // Mix: fold in the sample with a non‑linear twist.
82 // The tagged value is permuted through a small S‑box (multiplicative inverse)
83 // to destroy algebraic structure, then XORed into the pool word.
84 let mixed = twist(tag64 | (sample & 0x00FF_FFFF_FFFF_FFFF));
85 let old = POOL[idx].load(Ordering::Relaxed);
86 POOL[idx].store(old.wrapping_add(mixed), Ordering::Relaxed);
87
88 // Gentle avalanche: stir two more pool slots to avoid "stuck" zero
89 // if add_entropy is never called for some indices.
90 let idx2 = (idx + 3) % POOL_WORDS;
91 let old2 = POOL[idx2].load(Ordering::Relaxed);
92 POOL[idx2].store(old2 ^ mixed.rotate_right(17), Ordering::Relaxed);
93
94 // Bump entropy estimate (saturing at the pool capacity).
95 let old_e = ENTROPY_CTR.load(Ordering::Relaxed);
96 if old_e < (POOL_WORDS * 8) as u32 {
97 ENTROPY_CTR.fetch_add(2, Ordering::Relaxed); // 2 bytes per sample
98 }
99}
100
101/// Fill a byte buffer with random bytes from the entropy pool.
102///
103/// If the pool has not accumulated `ENTROPY_HIGH_WATER` bytes of entropy yet,
104/// this function spins briefly, waiting for interrupt noise. It will not
105/// block indefinitely: after ~1000 spin iterations it falls through and
106/// delivers whatever randomness is available.
107pub fn fill_random(buf: &mut [u8]) {
108 // Wait until we have enough entropy (very short on any live system).
109 let mut spins = 0u32;
110 while ENTROPY_CTR.load(Ordering::Relaxed) < ENTROPY_HIGH_WATER {
111 core::hint::spin_loop();
112 spins += 1;
113 if spins > 1024 {
114 break; // don't hang if entropy source is absent
115 }
116 }
117
118 let mut offset = 0usize;
119 while offset < buf.len() {
120 let block = extract_block();
121 let n = (buf.len() - offset).min(8);
122 buf[offset..offset + n].copy_from_slice(&block[..n]);
123 offset += n;
124 }
125}
126
127// === Internal helpers ===============================================
128
129/// Non‑linear twist: multiplicative inverse in GF(2⁶⁴) masked by a prime,
130/// then XORed with a rotation of itself.
131#[inline(always)]
132fn twist(x: u64) -> u64 {
133 // "Multiply‑then‑rotate" – cheap, non‑linear, 1‑to‑1.
134 let a = x.wrapping_mul(0x6A09E667F3BCC909);
135 a ^ a.rotate_right(37)
136}
137
138/// Extract 8 bytes from the pool by folding all words together.
139///
140/// This is **not** a cryptographic hash : it's a feed‑forward compression
141/// that provides avalanche. If the pool has been seeded from RDRAND and
142/// stirred by interrupt noise, the output is cryptographically acceptable.
143#[inline(always)]
144fn extract_block() -> [u8; 8] {
145 let mut h: u64 = 0x9E3779B97F4A7C15; // nothing‑up‑my‑sleeve constant
146 for (i, w) in POOL.iter().enumerate() {
147 let v = w.load(Ordering::Relaxed);
148 h = h.wrapping_add(v).wrapping_mul(0xBF58476D1CE4E5B9);
149 h ^= h.rotate_right((i as u32) % 63 + 1);
150 }
151
152 // One final avalanche
153 h ^= h >> 33;
154 h = h.wrapping_mul(0xFF51AFD7ED558CCD);
155 h ^= h >> 33;
156 h = h.wrapping_mul(0xC4CEB9FE1A85EC53);
157 h ^= h >> 33;
158
159 h.to_le_bytes()
160}
161
162/// BUG TODO : RDRAND helper (used during boot seeding).
163// hang during boot on some QEMU configurations if RDRAND is unavailable
164#[cfg(target_arch = "x86_64")]
165#[allow(dead_code)] // Retained RDRAND boot-seeding helper.
166fn rdrand64() -> Option<u64> {
167 #[cfg(target_arch = "x86_64")]
168 {
169 let mut val: u64 = 0;
170 let mut ok: u8;
171 for _ in 0..10 {
172 unsafe {
173 core::arch::asm!(
174 "rdrand {0}",
175 "setc {1}",
176 out(reg) val,
177 out(reg_byte) ok,
178 options(nostack, preserves_flags),
179 );
180 }
181 if ok != 0 {
182 return Some(val);
183 }
184 }
185 }
186 None
187}