garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /kernel/src/drivers/random.rs

raw

//! Randomness for keys: entropy from a virtio-rng device (QEMU's, from the
//! host; the SoC's own generator on hardware) mixed with timer jitter by
//! SHA-256 into a seed, which keys a ChaCha20 generator that rekeys itself
//! from its own output after every request, so what it gave before cannot
//! be worked out from its state later.

use super::virtio::{self, Buffer, Queue};
use crate::mm::pages;
use crate::sync::SpinLock;
use pinnacle_crypto::{aead, sha2::Sha256};

static KEY: SpinLock<Option<[u8; 32]>> = SpinLock::new(None);

/// The device's transport, for its interrupt, and the interrupts taken:
/// the boot's proof that a device's interrupt arrives (by INTx on ARM's
/// PCI, by MSI-X on a PC's).
static TRANSPORT: SpinLock<Option<virtio::Transport>> = SpinLock::new(None);
pub static INTERRUPTS: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);

/// The device's interrupt: acknowledged and counted. False if not its.
pub fn interrupt(intid: u32) -> bool {
    let transport = *TRANSPORT.lock();
    match transport {
        Some(t) if t.intid == intid => {
            t.acknowledge();
            INTERRUPTS.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
            true
        }
        _ => false,
    }
}

/// Timer jitter: the low bits of the counter across busy loops of
/// uncertain length, which is all there is without a hardware source.
fn jitter(hash: &mut Sha256) {
    for _ in 0..256 {
        let count = crate::arch::counter();
        hash.update(&count.to_le_bytes());
        for _ in 0..(count & 0xff) {
            core::hint::spin_loop();
        }
    }
}

/// Gathers entropy and keys the generator. Returns the hardware sources
/// there were: a virtio-rng, and on a PC the core's own generator
/// (RDSEED or RDRAND), which every laptop's has.
pub fn init() -> Sources {
    let mut hash = Sha256::new();
    let mut hardware = false;
    if let Some(transport) = virtio::find(virtio::device::RNG).next()
        && transport.begin(0).is_some()
    {
        let mut queue = Queue::new(transport, 0);
        *TRANSPORT.lock() = Some(transport);
        crate::gic::enable_shared(transport.intid);
        transport.ready();
        if let Some(page) = pages::alloc(0) {
            queue.submit_and_wait(&[Buffer {
                address: page,
                len: 64,
                device_writes: true,
            }]);
            // SAFETY: the device filled 64 bytes of our page.
            hash.update(unsafe { core::slice::from_raw_parts(page as *const u8, 64) });
            pages::free(page, 0);
            hardware = true;
        }
    }
    #[cfg(target_arch = "x86_64")]
    let core = (0..32)
        .filter_map(|_| crate::arch::hardware_random())
        .fold(false, |_, word| {
            hash.update(&word.to_le_bytes());
            true
        });
    #[cfg(not(target_arch = "x86_64"))]
    let core = false;
    jitter(&mut hash);
    hash.update(&crate::board::clock().to_le_bytes());
    *KEY.lock() = Some(hash.finish());
    Sources {
        virtio: hardware,
        core,
    }
}

/// Where the seed's entropy came from, beside the timer's jitter.
#[derive(Clone, Copy)]
pub struct Sources {
    pub virtio: bool,
    pub core: bool,
}

impl Sources {
    /// For the boot log: "seeded from ...".
    pub fn describe(self) -> &'static str {
        match (self.virtio, self.core) {
            (true, true) => " from virtio-rng and the core's generator",
            (true, false) => " from virtio-rng",
            (false, true) => " from the core's generator",
            (false, false) => " from timer jitter only",
        }
    }
}

/// Fills `out` with random bytes.
pub fn fill(out: &mut [u8]) {
    let mut key = KEY.lock();
    let k = key.get_or_insert_with(|| {
        let mut hash = Sha256::new();
        jitter(&mut hash);
        hash.finish()
    });
    let mut stream = alloc::vec![0u8; 32 + out.len()];
    aead::chacha20(k, 0, &[0; 12], &mut stream);
    k.copy_from_slice(&stream[..32]);
    out.copy_from_slice(&stream[32..]);
}