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 25, 2019
1 parent 11ae6d2 commit b532cce
Show file tree
Hide file tree
Showing 8 changed files with 125 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/bindings_helper.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/module.h>
#include <linux/random.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/version.h>
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
32 changes: 32 additions & 0 deletions src/random.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use core::convert::TryInto;

use crate::{bindings, c_types, 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 {
bindings::get_random_bytes(
dest.as_mut_ptr() as *mut c_types::c_void,
dest.len().try_into()?,
);
}
Ok(())
}

/// Fills `dest` with random bytes generated from the kernel's CSPRNG. If the
/// CSPRNG is not yet seeded, returns an `Err(EAGAIN)` immediately. Only
/// available on 4.19 and later kernels.
#[cfg(kernel_4_19_0_or_greater)]
pub fn getrandom_nonblock(dest: &mut [u8]) -> error::KernelResult<()> {
if !unsafe { bindings::rng_is_initialized() } {
return Err(error::Error::EAGAIN);
}
getrandom(dest)
}
18 changes: 18 additions & 0 deletions tests/random/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "random-tests"
version = "0.1.0"
authors = ["Alex Gaynor <[email protected]>", "Geoffrey Thomas <[email protected]>"]
edition = "2018"

[lib]
crate-type = ["staticlib"]
test = false

[features]
default = ["linux-kernel-module"]

[dependencies]
linux-kernel-module = { path = "../..", optional = true }

[dev-dependencies]
kernel-module-testlib = { path = "../../testlib" }
49 changes: 49 additions & 0 deletions tests/random/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#![no_std]

use alloc::vec;

use linux_kernel_module::sysctl::{Sysctl, SysctlStorage};
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 read_value(
&self,
data: &mut linux_kernel_module::user_ptr::UserSlicePtrWriter,
) -> (usize, linux_kernel_module::KernelResult<()>) {
let mut storage = vec![0; data.len()];
if let Err(e) = random::getrandom(&mut storage) {
return (0, Err(e));
}
(storage.len(), data.write(&storage))
}
}

struct RandomTestModule {
_sysctl_entropy: Sysctl<EntropySource>,
}

impl linux_kernel_module::KernelModule for RandomTestModule {
fn init() -> linux_kernel_module::KernelResult<Self> {
Ok(RandomTestModule {
_sysctl_entropy: Sysctl::register(
cstr!("rust/random-tests"),
cstr!("entropy"),
EntropySource,
Mode::from_int(0o444),
)?,
})
}
}

linux_kernel_module::kernel_module!(
RandomTestModule,
author: "Fish in a Barrel Contributors",
description: "A module for testing the CSPRNG",
license: "GPL"
);
19 changes: 19 additions & 0 deletions tests/random/tests/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use std::collections::HashSet;
use std::fs;
use std::io::Read;

use kernel_module_testlib::{assert_dmesg_contains, with_kernel_module};

#[test]
fn test_random_entropy() {
with_kernel_module(|| {
let mut keys = HashSet::new();
for _ in 0..1024 {
let mut key = [0; 16];
let mut f = fs::File::open("/proc/sys/rust/random-tests/entropy").unwrap();
f.read_exact(&mut key).unwrap();
keys.insert(key);
}
assert_eq!(keys.len(), 1024);
});
}

0 comments on commit b532cce

Please sign in to comment.