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

Add RNG for Fortanix SGX #883

Closed
wants to merge 1 commit into from
Closed
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
34 changes: 34 additions & 0 deletions src/rand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,9 @@ use self::darwin::fill as fill_impl;
#[cfg(any(target_os = "fuchsia"))]
use self::fuchsia::fill as fill_impl;

#[cfg(any(target_env = "sgx"))]
use self::sgx::fill as fill_impl;

#[cfg(any(target_os = "android", target_os = "linux"))]
mod sysrand_chunk {
use crate::{c, error};
Expand Down Expand Up @@ -432,3 +435,34 @@ mod fuchsia {
fn zx_cprng_draw(buffer: *mut u8, length: usize);
}
}

#[cfg(any(target_env = "sgx"))]
mod sgx {
use core::arch::x86_64::_rdrand64_step;
use crate::error;

#[inline]
Copy link
Contributor

Choose a reason for hiding this comment

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

#[inline] does nothing on a private function, the attribute is only useful for pub functions/methods.

fn rdrand() -> Result<u64, error::Unspecified> {
Copy link
Contributor

Choose a reason for hiding this comment

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

If you end up having multiple call-sites for this function (i.e. if you make the chunks_exact_mut changes), it might be worth having this function return a [u8; 8] instead of a u64.

// See https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide
// Section 5.2.1
for _ in 0..10 {
let mut r = 0;
if unsafe { _rdrand64_step(&mut r) } == 1 {
Copy link
Contributor

Choose a reason for hiding this comment

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

Explain why this is safe (i.e. that SGX always supports RDRAND).

return Ok(r);
}
}

Err(error::Unspecified)
}

pub fn fill(mut dest: &mut [u8]) -> Result<(), error::Unspecified> {
while dest.len() > 0 {
Copy link
Contributor

Choose a reason for hiding this comment

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

This can me made more clear (and more efficient by eliding memcpy calls) by using chunks_exact_mut, like the getrandom implementation does.

See the comparison here: https://rust.godbolt.org/z/gwprxd

let rand = rdrand()?.to_ne_bytes();
let len = core::cmp::min(dest.len(), rand.len());
dest[..len].copy_from_slice(&rand[..len]);
dest = &mut dest[len..];
}

Ok(())
}
}