Skip to main content

vault_core/
entropy.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Entropy sources for secret generation.
4//!
5//! The point of this module is a rule that is easy to state and easy to get
6//! wrong: **hardware entropy is mixed in, never consumed raw.**
7//!
8//! A physical source can be absent, unplugged mid-read, wedged returning
9//! constant bytes, counterfeit, or deliberately backdoored. If its output were
10//! used directly, anyone who controlled the device would control every key
11//! generated on that machine — strictly worse than the OS RNG the feature was
12//! meant to improve on. Mixing means the result is at least as good as
13//! `getrandom` no matter what the device does:
14//!
15//! ```text
16//! output = HKDF-SHA256(ikm = os_bytes ‖ device_bytes, salt = domain, info = purpose)
17//! ```
18//!
19//! Three consequences, all deliberate:
20//!
21//! * **The default never changes.** [`Source::Os`] is what every generator uses
22//!   unless a caller asks for something else.
23//! * **Absence fails closed.** A selected device that cannot be read is an
24//!   error, not a quiet fallback — otherwise the user believes they used the
25//!   token and did not, which is the one outcome worse than not having the
26//!   feature.
27//! * **Generation only.** The vault salt, the Argon2 salt and backup IVs stay on
28//!   the OS RNG. A salt that depends on a device turns a lost device into a lost
29//!   vault, and this module exists to reduce risk, not to add a new way to lose
30//!   everything.
31
32use 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
41/// Domain separator, so bytes produced here can never collide with bytes some
42/// other part of the program derives from the same inputs.
43const HKDF_SALT: &[u8] = b"envvault/entropy/v1";
44
45/// Where the extra entropy comes from.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum Source {
48    /// The operating system CSPRNG (`getrandom`). The default, and the floor
49    /// that mixing guarantees every other variant stays above.
50    Os,
51    /// A character device or file — `/dev/random`, an rng-tools device, a
52    /// hardware RNG exposed as a node. Read with a timeout, because
53    /// `/dev/random` can block and a generator pane that hangs forever is a bug
54    /// report, not a security feature.
55    File { path: std::path::PathBuf },
56}
57
58impl Source {
59    /// Parse the `--entropy-source` argument.
60    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                // Named rather than ignored. "pkcs11 is not built in" is a
70                // different problem from "pkcs11 is not a thing", and a user who
71                // typed it deserves to know which.
72                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    /// True when this source contributes bytes from outside the OS CSPRNG.
84    pub fn is_external(&self) -> bool {
85        !matches!(self, Source::Os)
86    }
87
88    /// Human label, also what the CLI reports in its output metadata so a caller
89    /// can tell how a secret was produced.
90    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    /// Whether this machine can actually use the source right now.
98    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/// Result of probing a source without using it.
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub enum Availability {
123    Ready,
124    Missing(String),
125}
126
127/// Read `buf.len()` bytes from the source itself, before mixing.
128fn 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            // A blocking source must fail loudly rather than hang. The thread is
133            // detached deliberately: it may be parked in a blocking read on
134            // /dev/random that no timeout can interrupt, and leaking one thread
135            // beats wedging the caller.
136            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
161/// NIST SP 800-90B repetition-count test.
162///
163/// Catches the realistic hardware failure: a device that has stopped and is
164/// returning the same byte forever. Cheap, and necessary *because* of the
165/// mixing — HKDF would turn a constant input into perfectly random-looking
166/// output, so without this check a dead device is indistinguishable from a
167/// working one and the user keeps believing they have hardware entropy.
168fn repetition_count_ok(bytes: &[u8]) -> bool {
169    // Cutoff for 8-bit samples at the usual α = 2^-30 with a conservative
170    // 1 bit/byte min-entropy assumption.
171    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
186/// NIST SP 800-90B adaptive-proportion test, single window.
187///
188/// Catches a source that is not stuck but is badly biased — one value dominating
189/// the window.
190fn adaptive_proportion_ok(bytes: &[u8]) -> bool {
191    const WINDOW: usize = 512;
192    const CUTOFF: usize = 410; // ~80% of the window
193    if bytes.len() < WINDOW {
194        return true; // too little data to judge; the repetition test still applies
195    }
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
211/// Run both health tests, naming which one failed.
212pub 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    // Extract
232    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    // Expand
237    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
256/// Fill `buf` with random bytes from `source`, mixed with OS entropy.
257///
258/// `purpose` is HKDF `info` — a label such as `"secret"` or `"ssh-ed25519"`, so
259/// two generators asking for bytes in the same instant cannot receive the same
260/// stream.
261pub fn fill(source: &Source, purpose: &str, buf: &mut [u8]) -> Result<(), String> {
262    use rand::Rng;
263
264    // OS bytes always, and always first. Even in the external case they are the
265    // floor under the result.
266    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    // Read enough to health-test meaningfully even for a short request. A 16-byte
279    // secret is not enough data to judge a device on.
280    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
291/// A `RngCore` view over a [`Source`], for crates that generate keys themselves.
292///
293/// `ssh-key` and the certificate path take an RNG rather than bytes, so the
294/// mixing has to reach them through this rather than being applied afterwards.
295pub 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        // `RngCore::fill_bytes` cannot fail, and a key generator that silently
319        // produced weak bytes on a device error would be indefensible. Panicking
320        // is wrong too — so the fallible path is `try_fill_bytes`, and this one
321        // falls back to the OS RNG only for `Source::Os`, where there is nothing
322        // to fall back *from*.
323        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        // "not available in this build" and "not a thing" are different problems.
349        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        // The whole feature turns on this test. A user who selected a device and
358        // got OS bytes anyway believes something false about their key.
359        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        // HKDF turns constant input into random-looking output, so without the
371        // health check a dead device is indistinguishable from a working one.
372        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; // breaks runs, keeps the bias
382            }
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        // Both directions. If only one is tested, a mix that ignores the device
398        // still passes — and that is precisely the bug worth catching.
399        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; // not every CI box has it; the failure path is tested above
426        }
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        // Second 32-byte block must differ from the first, or the counter is
438        // not being fed into the expand step.
439        assert_ne!(long[0..32], long[32..64]);
440    }
441}