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

Commit 59110dc

Browse files
authored
Added an API for contributing randomness to the kernel (#224)
1 parent 7f168a5 commit 59110dc

File tree

4 files changed

+24
-4
lines changed

4 files changed

+24
-4
lines changed

build.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ const INCLUDED_FUNCTIONS: &[&str] = &[
2424
"wait_for_random_bytes",
2525
"get_random_bytes",
2626
"rng_is_initialized",
27+
"add_device_randomness",
2728
];
2829
const INCLUDED_VARS: &[&str] = &[
2930
"EINVAL",

src/random.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,14 @@ pub fn getrandom_nonblock(dest: &mut [u8]) -> error::KernelResult<()> {
3030
}
3131
getrandom(dest)
3232
}
33+
34+
/// Contributes the contents of `data` to the kernel's entropy pool. Does _not_
35+
/// credit the kernel entropy counter though.
36+
pub fn add_randomness(data: &[u8]) {
37+
unsafe {
38+
bindings::add_device_randomness(
39+
data.as_ptr() as *const c_types::c_void,
40+
data.len().try_into().unwrap(),
41+
);
42+
}
43+
}

tests/random/src/lib.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,9 @@ use linux_kernel_module::{self, cstr, random, Mode};
88
struct EntropySource;
99

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

1516
fn read_value(
@@ -35,7 +36,7 @@ impl linux_kernel_module::KernelModule for RandomTestModule {
3536
cstr!("rust/random-tests"),
3637
cstr!("entropy"),
3738
EntropySource,
38-
Mode::from_int(0o444),
39+
Mode::from_int(0o666),
3940
)?,
4041
})
4142
}

tests/random/tests/tests.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::io::Read;
55
use kernel_module_testlib::with_kernel_module;
66

77
#[test]
8-
fn test_random_entropy() {
8+
fn test_random_entropy_read() {
99
with_kernel_module(|| {
1010
let mut keys = HashSet::new();
1111
for _ in 0..1024 {
@@ -17,3 +17,10 @@ fn test_random_entropy() {
1717
assert_eq!(keys.len(), 1024);
1818
});
1919
}
20+
21+
#[test]
22+
fn test_random_entropy_write() {
23+
with_kernel_module(|| {
24+
fs::write("/proc/sys/rust/random-tests/entropy", b"1234567890").unwrap();
25+
});
26+
}

0 commit comments

Comments
 (0)