|
| 1 | +// Copyright 2018 Developers of the Rand project. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 4 | +// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 5 | +// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your |
| 6 | +// option. This file may not be copied, modified, or distributed |
| 7 | +// except according to those terms. |
| 8 | + |
| 9 | +//! Implementation for SGX using RDRAND instruction |
| 10 | +use crate::Error; |
| 11 | +use core::mem; |
| 12 | +use core::arch::x86_64::_rdrand64_step; |
| 13 | +use core::num::NonZeroU32; |
| 14 | + |
| 15 | +#[cfg(not(target_feature = "rdrand"))] |
| 16 | +compile_error!("enable rdrand target feature!"); |
| 17 | + |
| 18 | +// Recommendation from "Intel® Digital Random Number Generator (DRNG) Software |
| 19 | +// Implementation Guide" - Section 5.2.1 and "Intel® 64 and IA-32 Architectures |
| 20 | +// Software Developer’s Manual" - Volume 1 - Section 7.3.17.1. |
| 21 | +const RETRY_LIMIT: usize = 10; |
| 22 | +const WORD_SIZE: usize = mem::size_of::<u64>(); |
| 23 | + |
| 24 | +fn rdrand() -> Result<[u8; WORD_SIZE], Error> { |
| 25 | + for _ in 0..RETRY_LIMIT { |
| 26 | + unsafe { |
| 27 | + // SAFETY: we've checked RDRAND support, and u64 can have any value. |
| 28 | + let mut el = mem::uninitialized(); |
| 29 | + if _rdrand64_step(&mut el) == 1 { |
| 30 | + return Ok(el.to_ne_bytes()); |
| 31 | + } |
| 32 | + }; |
| 33 | + } |
| 34 | + error!("RDRAND failed, CPU issue likely"); |
| 35 | + Err(Error::UNKNOWN) |
| 36 | +} |
| 37 | + |
| 38 | +pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { |
| 39 | + // We use chunks_exact_mut instead of chunks_mut as it allows almost all |
| 40 | + // calls to memcpy to be elided by the compiler. |
| 41 | + let mut chunks = dest.chunks_exact_mut(WORD_SIZE); |
| 42 | + for chunk in chunks.by_ref() { |
| 43 | + chunk.copy_from_slice(&rdrand()?); |
| 44 | + } |
| 45 | + |
| 46 | + let tail = chunks.into_remainder(); |
| 47 | + let n = tail.len(); |
| 48 | + if n > 0 { |
| 49 | + tail.copy_from_slice(&rdrand()?[..n]); |
| 50 | + } |
| 51 | + Ok(()) |
| 52 | +} |
| 53 | + |
| 54 | +#[inline(always)] |
| 55 | +pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None } |
0 commit comments