[PATCH 3/9] rust: random: add a safe get_random_bytes wrapper
Mike Lothian <[email protected]>
| Newsgroups | org.kernel.vger.rust-for-linux,org.kernel.vger.linux-kernel |
|---|---|
| Message-ID | <[email protected]> |
Expose a slice-based wrapper around get_random_bytes() so Rust callers can fill key, nonce, and other random buffers without touching raw pointers. Assisted-by: Claude:claude-opus-5 Signed-off-by: Mike Lothian <[email protected]> --- rust/kernel/lib.rs | 1 + rust/kernel/random.rs | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 rust/kernel/random.rs diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 08e5730753eb..f39648246271 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -116,6 +116,7 @@ pub mod ptr; #[cfg(CONFIG_RUST_PWM_ABSTRACTIONS)] pub mod pwm; +pub mod random; pub mod rbtree; pub mod regulator; pub mod revocable; diff --git a/rust/kernel/random.rs b/rust/kernel/random.rs new file mode 100644 index 000000000000..5f2288969dbf --- /dev/null +++ b/rust/kernel/random.rs @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Random number generation. +//! +//! C header: [`include/linux/random.h`](srctree/include/linux/random.h) + +use crate::bindings; + +/// Fills `buf` with cryptographically secure random bytes from the kernel's CSPRNG. +/// +/// This is the in-kernel equivalent of reading from `/dev/urandom`, and is suitable for generating +/// keys, nonces and other secrets. It never blocks: once the CSPRNG has been seeded during boot it +/// stays seeded, and callers running that early should use +/// [`wait_for_random_bytes()`] instead of assuming otherwise. +/// +/// [`wait_for_random_bytes()`]: srctree/include/linux/random.h +/// +/// # Examples +/// +/// ``` +/// use kernel::random; +/// +/// let mut key = [0u8; 16]; +/// random::fill_bytes(&mut key); +/// +/// // A zero-length request is valid and does nothing. +/// random::fill_bytes(&mut []); +/// ``` +#[inline] +pub fn fill_bytes(buf: &mut [u8]) { + // SAFETY: `buf` is a valid slice, so its pointer is valid for writes of `buf.len()` bytes, and + // `get_random_bytes()` writes exactly that many. + unsafe { bindings::get_random_bytes(buf.as_mut_ptr().cast(), buf.len()) }; +}