Skip to content
This repository has been archived by the owner on Mar 7, 2021. It is now read-only.

Commit

Permalink
Refs #164 -- expose the kernel's CSPRNG, safely
Browse files Browse the repository at this point in the history
  • Loading branch information
alex committed Dec 24, 2019
1 parent 11ae6d2 commit 666b5e6
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 0 deletions.
4 changes: 4 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,16 @@ const INCLUDED_FUNCTIONS: &[&str] = &[
"_copy_from_user",
"alloc_chrdev_region",
"unregister_chrdev_region",
"wait_for_random_bytes",
"get_random_bytes",
"rng_is_initialized",
];
const INCLUDED_VARS: &[&str] = &[
"EINVAL",
"ENOMEM",
"ESPIPE",
"EFAULT",
"EAGAIN",
"__this_module",
"FS_REQUIRES_DEV",
"FS_BINARY_MOUNTDATA",
Expand Down
1 change: 1 addition & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ impl Error {
pub const ENOMEM: Self = Error(-(bindings::ENOMEM as i32));
pub const EFAULT: Self = Error(-(bindings::EFAULT as i32));
pub const ESPIPE: Self = Error(-(bindings::ESPIPE as i32));
pub const EAGAIN: Self = Error(-(bindings::EAGAIN as i32));

pub fn from_kernel_errno(errno: c_types::c_int) -> Error {
Error(errno)
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ mod error;
pub mod file_operations;
pub mod filesystem;
pub mod printk;
pub mod random;
pub mod sysctl;
mod types;
pub mod user_ptr;
Expand Down
28 changes: 28 additions & 0 deletions src/random.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use core::convert::TryInto;

use crate::{bindings, error};

/// Fills `dest` with random bytes generated from the kernel's CSPRNG. Ensures
/// that the CSPRNG has been seeded before generating any random bytes, and
/// will block until it's ready.
pub fn getrandom(dest: &mut [u8]) -> error::KernelResult<()> {
let res = unsafe { bindings::wait_for_random_bytes() };
if res != 0 {
return Err(error::Error::from_kernel_errno(res));
}

unsafe {
// TODO: convert `unwrap` to proper error handling
bindings::get_random_bytes(dest.as_mut_ptr(), dest.len().try_into().unwrap());
}
Ok(())
}

/// Fills `dest` with random bytes generated from the kernel's CSPRNG. If the
/// CSPRNG is not yet seeded, returns an `Err(EAGAIN)` immediately.
pub fn getrandom_nonblock(dest: &mut [u8]) -> error::KernelResult<()> {
if !unsafe { bindings::rng_is_initialized() } {
return Err(error::Error::EAGAIN);
}
getrandom(dest)
}

0 comments on commit 666b5e6

Please sign in to comment.