diff --git a/Cargo.toml b/Cargo.toml index 3be9c8bc03..acb92d152f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -298,6 +298,10 @@ libc = { version = "0.2.45" } [target.'cfg(any(target_os = "redox", all(unix, not(any(target_os = "macos", target_os = "ios")))))'.dependencies] lazy_static = "1.2" +[target.'cfg(target_env = "sgx")'.dependencies] +rand_core = "0.3.0" +rdrand = "0.4.0" + # Keep this in sync with `[dependencies]` in pregenerate_asm/Cargo.toml. [build-dependencies] cc = "1.0.26" diff --git a/src/rand.rs b/src/rand.rs index 8baf521a2c..c8f7578572 100644 --- a/src/rand.rs +++ b/src/rand.rs @@ -60,6 +60,8 @@ pub trait SecureRandom: sealed::Sealed { /// On Windows, `fill` is implemented using the platform's API for secure /// random number generation. /// +/// On SGX, `fill()` is implemented using the `RDRAND` instruction. +/// /// Otherwise, `fill()` is implemented by reading from `/dev/urandom`. (This is /// something that should be improved for any platform that adds something /// better.) @@ -93,7 +95,7 @@ impl SecureRandom for SystemRandom { impl sealed::Sealed for SystemRandom {} -#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "ios", windows)))] +#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "ios", windows, target_env = "sgx")))] use self::urandom::fill as fill_impl; #[cfg(any( @@ -107,6 +109,10 @@ use self::sysrand_or_urandom::fill as fill_impl; #[cfg(any(target_os = "macos", target_os = "ios"))] use self::darwin::fill as fill_impl; + +#[cfg(target_env = "sgx")] +use self::rdrandom::fill as fill_impl; + use crate::sealed; #[cfg(target_os = "linux")] @@ -275,6 +281,19 @@ mod darwin { } } +#[cfg(target_env = "sgx")] +mod rdrandom { + use crate::error; + use rdrand::RdRand; + use rand_core::RngCore; + + pub fn fill(dest: &mut [u8]) -> Result<(), error::Unspecified> { + let mut rng = RdRand::new().map_err(|_| error::Unspecified)?; + rng.try_fill_bytes(dest).map_err(|_| error::Unspecified)?; + Ok(()) + } +} + #[cfg(test)] mod tests { use crate::rand::{self, SecureRandom};