Skip to content

Commit 5c59ba8

Browse files
committed
std: sys: random: uefi: Provide rdrand based fallback
Some UEFI systems based on American Megatrends Inc. v3.3 do not provide RNG support [1]. So fallback to rdrand in such cases. [1]: #138252 (comment) Signed-off-by: Ayush Singh <[email protected]>
1 parent 6cab15c commit 5c59ba8

File tree

1 file changed

+148
-19
lines changed

1 file changed

+148
-19
lines changed

library/std/src/sys/random/uefi.rs

Lines changed: 148 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,156 @@
1-
use r_efi::protocols::rng;
1+
pub fn fill_bytes(bytes: &mut [u8]) {
2+
// Try EFI_RNG_PROTOCOL
3+
if rng_protocol::fill_bytes(bytes) {
4+
return;
5+
}
26

3-
use crate::sys::pal::helpers;
7+
// Fallback to rdrand if rng protocol missing.
8+
//
9+
// For real-world example, see [issue-13825](https://github.com/rust-lang/rust/issues/138252#issuecomment-2891270323)
10+
#[cfg(any(target_arch = "x86_64", target_arch = "x86"))]
11+
if rdrand::fill_bytes(bytes) {
12+
return;
13+
}
414

5-
pub fn fill_bytes(bytes: &mut [u8]) {
6-
let handles =
7-
helpers::locate_handles(rng::PROTOCOL_GUID).expect("failed to generate random data");
8-
for handle in handles {
9-
if let Ok(protocol) = helpers::open_protocol::<rng::Protocol>(handle, rng::PROTOCOL_GUID) {
10-
let r = unsafe {
11-
((*protocol.as_ptr()).get_rng)(
12-
protocol.as_ptr(),
13-
crate::ptr::null_mut(),
14-
bytes.len(),
15-
bytes.as_mut_ptr(),
16-
)
15+
panic!("failed to generate random data");
16+
}
17+
18+
mod rng_protocol {
19+
use r_efi::protocols::rng;
20+
21+
use crate::sys::pal::helpers;
22+
23+
pub(crate) fn fill_bytes(bytes: &mut [u8]) -> bool {
24+
if let Ok(handles) = helpers::locate_handles(rng::PROTOCOL_GUID) {
25+
for handle in handles {
26+
if let Ok(protocol) =
27+
helpers::open_protocol::<rng::Protocol>(handle, rng::PROTOCOL_GUID)
28+
{
29+
let r = unsafe {
30+
((*protocol.as_ptr()).get_rng)(
31+
protocol.as_ptr(),
32+
crate::ptr::null_mut(),
33+
bytes.len(),
34+
bytes.as_mut_ptr(),
35+
)
36+
};
37+
if r.is_error() {
38+
continue;
39+
} else {
40+
return true;
41+
}
42+
}
43+
}
44+
}
45+
46+
false
47+
}
48+
}
49+
50+
/// Port from [getrandom](https://github.com/rust-random/getrandom/blob/master/src/backends/rdrand.rs)
51+
#[cfg(any(target_arch = "x86_64", target_arch = "x86"))]
52+
mod rdrand {
53+
cfg_if::cfg_if! {
54+
if #[cfg(target_arch = "x86_64")] {
55+
use crate::arch::x86_64 as arch;
56+
use arch::_rdrand64_step as rdrand_step;
57+
type Word = u64;
58+
} else if #[cfg(target_arch = "x86")] {
59+
use crate::arch::x86 as arch;
60+
use arch::_rdrand32_step as rdrand_step;
61+
type Word = u32;
62+
}
63+
}
64+
65+
static RDRAND_GOOD: crate::sync::LazyLock<bool> = crate::sync::LazyLock::new(is_rdrand_good);
66+
67+
// Recommendation from "Intel® Digital Random Number Generator (DRNG) Software
68+
// Implementation Guide" - Section 5.2.1 and "Intel® 64 and IA-32 Architectures
69+
// Software Developer’s Manual" - Volume 1 - Section 7.3.17.1.
70+
const RETRY_LIMIT: usize = 10;
71+
72+
unsafe fn rdrand() -> Option<Word> {
73+
for _ in 0..RETRY_LIMIT {
74+
let mut val = 0;
75+
if unsafe { rdrand_step(&mut val) } == 1 {
76+
return Some(val);
77+
}
78+
}
79+
None
80+
}
81+
82+
// Run a small self-test to make sure we aren't repeating values
83+
// Adapted from Linux's test in arch/x86/kernel/cpu/rdrand.c
84+
// Fails with probability < 2^(-90) on 32-bit systems
85+
unsafe fn self_test() -> bool {
86+
// On AMD, RDRAND returns 0xFF...FF on failure, count it as a collision.
87+
let mut prev = Word::MAX;
88+
let mut fails = 0;
89+
for _ in 0..8 {
90+
match unsafe { rdrand() } {
91+
Some(val) if val == prev => fails += 1,
92+
Some(val) => prev = val,
93+
None => return false,
1794
};
18-
if r.is_error() {
19-
continue;
20-
} else {
21-
return;
95+
}
96+
fails <= 2
97+
}
98+
99+
fn is_rdrand_good() -> bool {
100+
#[cfg(not(target_feature = "rdrand"))]
101+
{
102+
// SAFETY: All Rust x86 targets are new enough to have CPUID, and we
103+
// check that leaf 1 is supported before using it.
104+
let cpuid0 = unsafe { arch::__cpuid(0) };
105+
if cpuid0.eax < 1 {
106+
return false;
107+
}
108+
let cpuid1 = unsafe { arch::__cpuid(1) };
109+
110+
let vendor_id =
111+
[cpuid0.ebx.to_le_bytes(), cpuid0.edx.to_le_bytes(), cpuid0.ecx.to_le_bytes()];
112+
if vendor_id == [*b"Auth", *b"enti", *b"cAMD"] {
113+
let mut family = (cpuid1.eax >> 8) & 0xF;
114+
if family == 0xF {
115+
family += (cpuid1.eax >> 20) & 0xFF;
116+
}
117+
// AMD CPUs families before 17h (Zen) sometimes fail to set CF when
118+
// RDRAND fails after suspend. Don't use RDRAND on those families.
119+
// See https://bugzilla.redhat.com/show_bug.cgi?id=1150286
120+
if family < 0x17 {
121+
return false;
122+
}
123+
}
124+
125+
const RDRAND_FLAG: u32 = 1 << 30;
126+
if cpuid1.ecx & RDRAND_FLAG == 0 {
127+
return false;
22128
}
23129
}
130+
131+
// SAFETY: We have already checked that rdrand is available.
132+
unsafe { self_test() }
24133
}
25134

26-
panic!("failed to generate random data");
135+
unsafe fn rdrand_exact(dest: &mut [u8]) -> Option<()> {
136+
// We use chunks_exact_mut instead of chunks_mut as it allows almost all
137+
// calls to memcpy to be elided by the compiler.
138+
let mut chunks = dest.chunks_exact_mut(size_of::<Word>());
139+
for chunk in chunks.by_ref() {
140+
let src = unsafe { rdrand() }?.to_ne_bytes();
141+
chunk.copy_from_slice(&src);
142+
}
143+
144+
let tail = chunks.into_remainder();
145+
let n = tail.len();
146+
if n > 0 {
147+
let src = unsafe { rdrand() }?.to_ne_bytes();
148+
tail.copy_from_slice(&src[..n]);
149+
}
150+
Some(())
151+
}
152+
153+
pub(crate) fn fill_bytes(bytes: &mut [u8]) -> bool {
154+
if *RDRAND_GOOD { unsafe { rdrand_exact(bytes).is_some() } } else { false }
155+
}
27156
}

0 commit comments

Comments
 (0)