Skip to content

Commit

Permalink
Add in a RtlGenRandom fallback for non-UWP Windows
Browse files Browse the repository at this point in the history
In some instances BCryptRandom will fail when RtlGenRandom will work.
On UWP, we might be unable to actually use RtlGenRandom.

Thread the needle and use RtlGenRandom when we have to, when we're able.

See also rust-lang/rust#108060

Fixes rust-random#314
  • Loading branch information
chutten committed Feb 17, 2023
1 parent 7c83ea0 commit 16250fd
Showing 1 changed file with 32 additions and 8 deletions.
40 changes: 32 additions & 8 deletions src/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ extern "system" {
) -> u32;
}

extern "system" {
// Forbidden when targetting UWP
#[link_name = "SystemFunction036"]
fn RtlGenRandom(RandomBuffer: *mut u8, RandomBufferLength: u32) -> u8;
}

pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// Prevent overflow of u32
for chunk in dest.chunks_mut(u32::max_value() as usize) {
Expand All @@ -35,15 +41,33 @@ pub fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
};
// NTSTATUS codes use the two highest bits for severity status.
if ret >> 30 == 0b11 {
// We zeroize the highest bit, so the error code will reside
// inside the range designated for OS codes.
let code = ret ^ (1 << 31);
// SAFETY: the second highest bit is always equal to one,
// so it's impossible to get zero. Unfortunately the type
// system does not have a way to express this yet.
let code = unsafe { NonZeroU32::new_unchecked(code) };
return Err(Error::from(code));
// Failed. Try RtlGenRandom as a fallback.
let success = fallback_rng(chunk);
if !success {
// We zeroize the highest bit, so the error code will reside
// inside the range designated for OS codes.
let code = ret ^ (1 << 31);
// SAFETY: the second highest bit is always equal to one,
// so it's impossible to get zero. Unfortunately the type
// system does not have a way to express this yet.
let code = unsafe { NonZeroU32::new_unchecked(code) };
return Err(Error::from(code));
}
}
}
Ok(())
}

#[cfg(not(target_vendor = "uwp"))]
#[inline(never)]
fn fallback_rng(chunk: &mut [MaybeUninit<u8>]) -> bool {
let ret = unsafe { RtlGenRandom(chunk.as_mut_ptr() as *mut u8, chunk.len() as u32) };
// RtlGenRandom returns BOOLEAN TRUE (i.e. 1) on success, FALSE (i.e. 0) on failure.
ret != 0
}

#[cfg(target_vendor = "uwp")]
#[inline(never)]
fn fallback_rng(_chunk: &mut [MaybeUninit<u8>]) -> bool {
return false;
}

0 comments on commit 16250fd

Please sign in to comment.