This repository has been archived by the owner on Mar 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 120
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refs #164 -- expose the kernel's CSPRNG, safely
- Loading branch information
Showing
5 changed files
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |