Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NewSeeded: use JitterRng fallback #54

Merged
merged 5 commits into from
Nov 21, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/jitter_rng.rs
Original file line number Diff line number Diff line change
Expand Up @@ -611,7 +611,7 @@ impl JitterRng {
/// times. This measures the absolute worst-case, and gives a lower bound
/// for the available entropy.
///
/// ```no_run
/// ```rust,no_run
/// use rand::JitterRng;
///
/// # use std::error::Error;
Expand Down Expand Up @@ -670,7 +670,7 @@ impl JitterRng {
}
}

#[cfg(feature="std")]
#[cfg(all(feature="std", not(any(target_os = "macos", target_os = "ios"))))]
fn get_nstime() -> u64 {
use std::time::{SystemTime, UNIX_EPOCH};

Expand All @@ -682,6 +682,18 @@ fn get_nstime() -> u64 {
dur.as_secs() << 30 | dur.subsec_nanos() as u64
}

#[cfg(all(feature="std", any(target_os = "macos", target_os = "ios")))]
fn get_nstime() -> u64 {
extern crate libc;
// On Mac OS and iOS std::time::SystemTime only has 1000ns resolution.
// We use `mach_absolute_time` instead. This provides a CPU dependent unit,
// to get real nanoseconds the result should by multiplied by numer/denom
// from `mach_timebase_info`.
// But we are not interested in the exact nanoseconds, just entropy. So we
// use the raw result.
unsafe { libc::mach_absolute_time() }
}

// A function that is opaque to the optimizer to assist in avoiding dead-code
// elimination. Taken from `bencher`.
fn black_box<T>(dummy: T) -> T {
Expand Down
51 changes: 41 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,24 +286,55 @@ mod read;
#[cfg(feature="std")]
mod thread_local;

/// Support mechanism for creating securely seeded objects
/// using the OS generator.
/// Intended for use by RNGs, but not restricted to these.
/// Seeding mechanism for PRNGs, providing a `new` function.
/// This is the recommended way to create (pseudo) random number generators,
/// unless a deterministic seed is desired (in which case the `SeedableRng`
/// trait should be used directly).
///
/// This is implemented automatically for any PRNG implementing `SeedFromRng`,
/// and for normal types shouldn't be implemented directly. For mock generators
/// it may be useful to implement this instead of `SeedFromRng`.
/// Note: this trait is automatically implemented for any PRNG implementing
/// `SeedFromRng` and is not intended to be implemented by users.
///
/// ## Example
///
/// ```
/// use rand::{StdRng, Sample, NewSeeded};
///
/// let mut rng = StdRng::new().unwrap();
/// println!("Random die roll: {}", rng.gen_range(1, 7));
/// ```
#[cfg(feature="std")]
pub trait NewSeeded: Sized {
/// Creates a new instance, automatically seeded via `OsRng`.
pub trait NewSeeded: SeedFromRng {
/// Creates a new instance, automatically seeded with fresh entropy.
///
/// Normally this will use `OsRng`, but if that fails `JitterRng` will be
/// used instead. Both should be suitable for cryptography. It is possible
/// that both entropy sources will fail though unlikely.
fn new() -> Result<Self, Error>;
}

#[cfg(feature="std")]
impl<R: SeedFromRng> NewSeeded for R {
fn new() -> Result<Self, Error> {
let mut r = OsRng::new()?;
Self::from_rng(&mut r)
// Note: error handling would be easier with try/catch blocks
fn new_os<T: SeedFromRng>() -> Result<T, Error> {
let mut r = OsRng::new()?;
T::from_rng(&mut r)
}
fn new_jitter<T: SeedFromRng>() -> Result<T, Error> {
let mut r = JitterRng::new()?;
T::from_rng(&mut r)
}

new_os().or_else(|e1| {
new_jitter().map_err(|_e2| {
// TODO: log
// TODO: can we somehow return both error sources?
Error::new_with_cause(
ErrorKind::Unavailable,
"seeding a new RNG failed: both OS and Jitter entropy sources failed",
e1)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does error handling seem to be to most difficult part again and again ;-)?

Good idea to report e1 from OsRng as the error. That seems to be the most important one.

But not reporting the error cause from JitterRng is not great...

One option is to implement a struct TwoCauses and implement a custom stdError::description and other machinery for that. Maybe overkill though.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If Error::cause returned an iterator instead of an Option it would be easier :(

A custom description implementation doesn't cover it very well either, because (a) it requires formatting two messages into one (long) string somehow and (b) if both causes have sub-causes there are even more problems.

Easier to log/print something directly.

})
})
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/os.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ mod imp {

use {Error, ErrorKind};

use std::{io, ptr};
use std::ptr;

#[derive(Debug)]
pub struct OsRng;
Expand Down