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

Commit

Permalink
Added an API for contributing randomness to the kernel (#224)
Browse files Browse the repository at this point in the history
  • Loading branch information
alex authored Jul 16, 2020
1 parent 7f168a5 commit 59110dc
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 4 deletions.
1 change: 1 addition & 0 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const INCLUDED_FUNCTIONS: &[&str] = &[
"wait_for_random_bytes",
"get_random_bytes",
"rng_is_initialized",
"add_device_randomness",
];
const INCLUDED_VARS: &[&str] = &[
"EINVAL",
Expand Down
11 changes: 11 additions & 0 deletions src/random.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,14 @@ pub fn getrandom_nonblock(dest: &mut [u8]) -> error::KernelResult<()> {
}
getrandom(dest)
}

/// Contributes the contents of `data` to the kernel's entropy pool. Does _not_
/// credit the kernel entropy counter though.
pub fn add_randomness(data: &[u8]) {
unsafe {
bindings::add_device_randomness(
data.as_ptr() as *const c_types::c_void,
data.len().try_into().unwrap(),
);
}
}
7 changes: 4 additions & 3 deletions tests/random/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ use linux_kernel_module::{self, cstr, random, Mode};
struct EntropySource;

impl SysctlStorage for EntropySource {
fn store_value(&self, _data: &[u8]) -> (usize, linux_kernel_module::KernelResult<()>) {
(0, Err(linux_kernel_module::Error::EINVAL))
fn store_value(&self, data: &[u8]) -> (usize, linux_kernel_module::KernelResult<()>) {
random::add_randomness(data);
(data.len(), Ok(()))
}

fn read_value(
Expand All @@ -35,7 +36,7 @@ impl linux_kernel_module::KernelModule for RandomTestModule {
cstr!("rust/random-tests"),
cstr!("entropy"),
EntropySource,
Mode::from_int(0o444),
Mode::from_int(0o666),
)?,
})
}
Expand Down
9 changes: 8 additions & 1 deletion tests/random/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::io::Read;
use kernel_module_testlib::with_kernel_module;

#[test]
fn test_random_entropy() {
fn test_random_entropy_read() {
with_kernel_module(|| {
let mut keys = HashSet::new();
for _ in 0..1024 {
Expand All @@ -17,3 +17,10 @@ fn test_random_entropy() {
assert_eq!(keys.len(), 1024);
});
}

#[test]
fn test_random_entropy_write() {
with_kernel_module(|| {
fs::write("/proc/sys/rust/random-tests/entropy", b"1234567890").unwrap();
});
}

0 comments on commit 59110dc

Please sign in to comment.