Skip to main content

whisker_dev_protocol/
random.rs

1//! Operating-system randomness for nonces, secrets, and file names.
2
3/// Fill an `N`-byte array from the operating system's CSPRNG
4///
5/// Used for handshake nonces, the per-session secret, and unpredictable
6/// staging-directory names. There is deliberately no fallback generator:
7/// if the operating system cannot supply randomness, the caller fails
8/// closed instead of continuing with a guessable value.
9///
10/// # Example
11///
12/// ```rust
13/// let nonce: [u8; 32] = whisker_dev_protocol::random_bytes()?;
14/// assert_eq!(nonce.len(), 32);
15/// # Ok::<(), std::io::Error>(())
16/// ```
17pub fn random_bytes<const N: usize>() -> std::io::Result<[u8; N]> {
18    let mut bytes = [0; N];
19    fill(&mut bytes)?;
20    Ok(bytes)
21}
22
23/// Generate a fresh per-session secret
24///
25/// The secret is 128 bits of operating-system randomness, hex-encoded into
26/// 32 characters so it survives environment variables and Android system
27/// properties unchanged. `whisker run` generates one per session and hands
28/// it to the app out of band; it is never sent over the WebSocket.
29///
30/// # Example
31///
32/// ```rust
33/// let secret = whisker_dev_protocol::generate_secret()?;
34/// assert_eq!(secret.len(), 32);
35/// assert!(secret.bytes().all(|byte| byte.is_ascii_hexdigit()));
36/// # Ok::<(), std::io::Error>(())
37/// ```
38pub fn generate_secret() -> std::io::Result<String> {
39    Ok(random_bytes::<16>()?
40        .iter()
41        .map(|byte| format!("{byte:02x}"))
42        .collect())
43}
44
45#[cfg(not(windows))]
46fn fill(bytes: &mut [u8]) -> std::io::Result<()> {
47    use std::io::Read;
48    std::fs::File::open("/dev/urandom")?.read_exact(bytes)
49}
50
51#[cfg(windows)]
52fn fill(bytes: &mut [u8]) -> std::io::Result<()> {
53    const BCRYPT_USE_SYSTEM_PREFERRED_RNG: u32 = 2;
54    #[link(name = "bcrypt")]
55    unsafe extern "system" {
56        fn BCryptGenRandom(
57            algorithm: *mut std::ffi::c_void,
58            buffer: *mut u8,
59            length: u32,
60            flags: u32,
61        ) -> i32;
62    }
63    let length =
64        u32::try_from(bytes.len()).map_err(|_| std::io::Error::other("random buffer too large"))?;
65    // SAFETY: a null algorithm handle is valid with
66    // BCRYPT_USE_SYSTEM_PREFERRED_RNG, and the call writes at most `length`
67    // bytes into `bytes`, which is exactly that long.
68    let status = unsafe {
69        BCryptGenRandom(
70            std::ptr::null_mut(),
71            bytes.as_mut_ptr(),
72            length,
73            BCRYPT_USE_SYSTEM_PREFERRED_RNG,
74        )
75    };
76    if status < 0 {
77        return Err(std::io::Error::other("BCryptGenRandom failed"));
78    }
79    Ok(())
80}
81
82#[cfg(test)]
83mod tests {
84    #[test]
85    fn consecutive_values_differ() {
86        assert_ne!(
87            super::random_bytes::<32>().unwrap(),
88            super::random_bytes::<32>().unwrap()
89        );
90        assert_ne!(
91            super::generate_secret().unwrap(),
92            super::generate_secret().unwrap()
93        );
94    }
95}