1use std::fmt;
33use std::io::Read;
34use std::time::Duration;
35
36use hmac::{Hmac, KeyInit, Mac};
37use sha2::Sha256;
38
39type HmacSha256 = Hmac<Sha256>;
40
41const HKDF_SALT: &[u8] = b"envvault/entropy/v1";
44
45#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum Source {
48 Os,
51 File { path: std::path::PathBuf },
56}
57
58impl Source {
59 pub fn parse(spec: &str) -> Result<Self, String> {
61 let spec = spec.trim();
62 match spec {
63 "os" | "" => Ok(Source::Os),
64 other => match other.split_once(':') {
65 Some(("file", p)) if !p.is_empty() => Ok(Source::File {
66 path: std::path::PathBuf::from(p),
67 }),
68 Some(("file", _)) => Err("file: needs a path, e.g. file:/dev/random".into()),
69 Some(("pkcs11", _)) | Some(("tpm", _)) => Err(format!(
73 "Entropy source '{other}' is not available in this build. \
74 Available: os, file:PATH"
75 )),
76 _ => Err(format!(
77 "Unknown entropy source '{other}'. Available: os, file:PATH"
78 )),
79 },
80 }
81 }
82
83 pub fn is_external(&self) -> bool {
85 !matches!(self, Source::Os)
86 }
87
88 pub fn label(&self) -> String {
91 match self {
92 Source::Os => "os".into(),
93 Source::File { path } => format!("file:{}", path.display()),
94 }
95 }
96
97 pub fn availability(&self) -> Availability {
99 match self {
100 Source::Os => Availability::Ready,
101 Source::File { path } => {
102 if !path.exists() {
103 Availability::Missing(format!("{} does not exist", path.display()))
104 } else if std::fs::File::open(path).is_err() {
105 Availability::Missing(format!("{} is not readable", path.display()))
106 } else {
107 Availability::Ready
108 }
109 }
110 }
111 }
112}
113
114impl fmt::Display for Source {
115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116 write!(f, "{}", self.label())
117 }
118}
119
120#[derive(Debug, Clone, PartialEq, Eq)]
122pub enum Availability {
123 Ready,
124 Missing(String),
125}
126
127fn read_external(source: &Source, buf: &mut [u8], timeout: Duration) -> Result<(), String> {
129 match source {
130 Source::Os => unreachable!("Os is never read as an external source"),
131 Source::File { path } => {
132 let (tx, rx) = std::sync::mpsc::channel();
137 let p = path.clone();
138 let n = buf.len();
139 std::thread::spawn(move || {
140 let mut out = vec![0u8; n];
141 let r = std::fs::File::open(&p).and_then(|mut f| f.read_exact(&mut out));
142 let _ = tx.send(r.map(|_| out).map_err(|e| e.to_string()));
143 });
144 match rx.recv_timeout(timeout) {
145 Ok(Ok(bytes)) => {
146 buf.copy_from_slice(&bytes);
147 Ok(())
148 }
149 Ok(Err(e)) => Err(format!("Cannot read {}: {e}", path.display())),
150 Err(_) => Err(format!(
151 "{} produced no bytes within {:?}. A blocking source such as \
152 /dev/random may be waiting for the entropy pool to refill.",
153 path.display(),
154 timeout
155 )),
156 }
157 }
158 }
159}
160
161fn repetition_count_ok(bytes: &[u8]) -> bool {
169 const CUTOFF: usize = 32;
172 let mut run = 1usize;
173 for w in bytes.windows(2) {
174 if w[0] == w[1] {
175 run += 1;
176 if run >= CUTOFF {
177 return false;
178 }
179 } else {
180 run = 1;
181 }
182 }
183 true
184}
185
186fn adaptive_proportion_ok(bytes: &[u8]) -> bool {
191 const WINDOW: usize = 512;
192 const CUTOFF: usize = 410; if bytes.len() < WINDOW {
194 return true; }
196 for chunk in bytes.chunks(WINDOW) {
197 if chunk.len() < WINDOW {
198 break;
199 }
200 let mut counts = [0usize; 256];
201 for &b in chunk {
202 counts[b as usize] += 1;
203 if counts[b as usize] >= CUTOFF {
204 return false;
205 }
206 }
207 }
208 true
209}
210
211pub fn health_check(bytes: &[u8]) -> Result<(), String> {
213 if !repetition_count_ok(bytes) {
214 return Err(
215 "Entropy source failed the repetition-count test — it is returning the same \
216 byte repeatedly, which is what a stopped or disconnected device looks like."
217 .into(),
218 );
219 }
220 if !adaptive_proportion_ok(bytes) {
221 return Err(
222 "Entropy source failed the adaptive-proportion test — its output is heavily \
223 biased toward one value."
224 .into(),
225 );
226 }
227 Ok(())
228}
229
230fn hkdf_sha256(ikm: &[u8], info: &[u8], out: &mut [u8]) -> Result<(), String> {
231 let mut mac = HmacSha256::new_from_slice(HKDF_SALT).map_err(|e| e.to_string())?;
233 mac.update(ikm);
234 let prk = mac.finalize().into_bytes();
235
236 let mut t: Vec<u8> = Vec::new();
238 let mut counter: u8 = 1;
239 let mut written = 0;
240 while written < out.len() {
241 let mut mac = HmacSha256::new_from_slice(&prk).map_err(|e| e.to_string())?;
242 mac.update(&t);
243 mac.update(info);
244 mac.update(&[counter]);
245 t = mac.finalize().into_bytes().to_vec();
246 let take = (out.len() - written).min(t.len());
247 out[written..written + take].copy_from_slice(&t[..take]);
248 written += take;
249 counter = counter
250 .checked_add(1)
251 .ok_or_else(|| "HKDF output length exceeds one round".to_string())?;
252 }
253 Ok(())
254}
255
256pub fn fill(source: &Source, purpose: &str, buf: &mut [u8]) -> Result<(), String> {
262 use rand::Rng;
263
264 let mut os_bytes = vec![0u8; buf.len().max(32)];
267 rand::rng().fill_bytes(&mut os_bytes);
268
269 if !source.is_external() {
270 buf.copy_from_slice(&os_bytes[..buf.len()]);
271 return Ok(());
272 }
273
274 if let Availability::Missing(why) = source.availability() {
275 return Err(format!("Entropy source {source} is unavailable: {why}"));
276 }
277
278 let probe_len = buf.len().max(1024);
281 let mut dev_bytes = vec![0u8; probe_len];
282 read_external(source, &mut dev_bytes, Duration::from_secs(10))?;
283 health_check(&dev_bytes)?;
284
285 let mut ikm = Vec::with_capacity(os_bytes.len() + dev_bytes.len());
286 ikm.extend_from_slice(&os_bytes);
287 ikm.extend_from_slice(&dev_bytes);
288 hkdf_sha256(&ikm, purpose.as_bytes(), buf)
289}
290
291pub struct EntropyRng {
296 source: Source,
297 purpose: &'static str,
298}
299
300impl EntropyRng {
301 pub fn new(source: Source, purpose: &'static str) -> Self {
302 Self { source, purpose }
303 }
304}
305
306impl ssh_key::rand_core::RngCore for EntropyRng {
307 fn next_u32(&mut self) -> u32 {
308 let mut b = [0u8; 4];
309 self.fill_bytes(&mut b);
310 u32::from_le_bytes(b)
311 }
312 fn next_u64(&mut self) -> u64 {
313 let mut b = [0u8; 8];
314 self.fill_bytes(&mut b);
315 u64::from_le_bytes(b)
316 }
317 fn fill_bytes(&mut self, dest: &mut [u8]) {
318 if let Err(e) = self.try_fill_bytes(dest) {
324 panic!("entropy source failed during key generation: {e}");
325 }
326 }
327 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), ssh_key::rand_core::Error> {
328 fill(&self.source, self.purpose, dest)
329 .map_err(|e| ssh_key::rand_core::Error::new(std::io::Error::other(e)))
330 }
331}
332
333impl ssh_key::rand_core::CryptoRng for EntropyRng {}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338
339 #[test]
340 fn os_is_the_default_and_parses_from_nothing() {
341 assert_eq!(Source::parse("").unwrap(), Source::Os);
342 assert_eq!(Source::parse("os").unwrap(), Source::Os);
343 assert!(!Source::Os.is_external());
344 }
345
346 #[test]
347 fn unbuilt_backends_say_so_rather_than_being_unknown() {
348 let err = Source::parse("pkcs11:0").unwrap_err();
350 assert!(err.contains("not available in this build"), "{err}");
351 let err = Source::parse("banana").unwrap_err();
352 assert!(err.contains("Unknown entropy source"), "{err}");
353 }
354
355 #[test]
356 fn a_missing_device_fails_closed_and_produces_nothing() {
357 let src = Source::File {
360 path: "/nonexistent/entropy/device".into(),
361 };
362 let mut buf = [0u8; 32];
363 let err = fill(&src, "test", &mut buf).unwrap_err();
364 assert!(err.contains("unavailable"), "{err}");
365 assert_eq!(buf, [0u8; 32], "no bytes may be written on failure");
366 }
367
368 #[test]
369 fn a_stuck_device_is_caught_before_mixing_hides_it() {
370 assert!(health_check(&[0x41; 4096]).is_err());
373 assert!(health_check(&[7u8; 64]).is_err());
374 }
375
376 #[test]
377 fn a_biased_but_unstuck_device_is_caught_too() {
378 let mut bytes = vec![0xAAu8; 512];
379 for (i, b) in bytes.iter_mut().enumerate() {
380 if i % 7 == 0 {
381 *b = i as u8; }
383 }
384 assert!(health_check(&bytes).is_err());
385 }
386
387 #[test]
388 fn real_random_bytes_pass_the_health_tests() {
389 use rand::Rng;
390 let mut bytes = vec![0u8; 4096];
391 rand::rng().fill_bytes(&mut bytes);
392 assert!(health_check(&bytes).is_ok());
393 }
394
395 #[test]
396 fn mixing_changes_when_either_input_changes() {
397 let mut a = [0u8; 32];
400 let mut b = [0u8; 32];
401 hkdf_sha256(b"os-part-1device-part", b"secret", &mut a).unwrap();
402 hkdf_sha256(b"os-part-2device-part", b"secret", &mut b).unwrap();
403 assert_ne!(a, b, "changing the OS half must change the output");
404
405 hkdf_sha256(b"os-part-1device-part", b"secret", &mut a).unwrap();
406 hkdf_sha256(b"os-part-1device-XXXX", b"secret", &mut b).unwrap();
407 assert_ne!(a, b, "changing the device half must change the output");
408 }
409
410 #[test]
411 fn purpose_separates_streams() {
412 let mut a = [0u8; 32];
413 let mut b = [0u8; 32];
414 hkdf_sha256(b"identical-input", b"secret", &mut a).unwrap();
415 hkdf_sha256(b"identical-input", b"ssh-ed25519", &mut b).unwrap();
416 assert_ne!(a, b);
417 }
418
419 #[test]
420 fn a_file_source_produces_usable_bytes() {
421 let src = Source::File {
422 path: "/dev/urandom".into(),
423 };
424 if src.availability() != Availability::Ready {
425 return; }
427 let mut buf = [0u8; 32];
428 fill(&src, "test", &mut buf).expect("read /dev/urandom");
429 assert_ne!(buf, [0u8; 32]);
430 }
431
432 #[test]
433 fn hkdf_fills_more_than_one_block() {
434 let mut long = [0u8; 100];
435 hkdf_sha256(b"input", b"info", &mut long).unwrap();
436 assert!(long.iter().any(|&b| b != 0));
437 assert_ne!(long[0..32], long[32..64]);
440 }
441}