|
| 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 Windows UWP targets. After deprecation of Windows XP |
| 10 | +//! and Vista, this can superseed the `RtlGenRandom`-based implementation. |
| 11 | +use crate::Error; |
| 12 | +use core::{ffi::c_void, num::NonZeroU32, ptr}; |
| 13 | + |
| 14 | +const BCRYPT_USE_SYSTEM_PREFERRED_RNG: u32 = 0x00000002; |
| 15 | + |
| 16 | +extern "system" { |
| 17 | + fn BCryptGenRandom( |
| 18 | + hAlgorithm: *mut c_void, |
| 19 | + pBuffer: *mut u8, |
| 20 | + cbBuffer: u32, |
| 21 | + dwFlags: u32, |
| 22 | + ) -> u32; |
| 23 | +} |
| 24 | + |
| 25 | +pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> { |
| 26 | + // Prevent overflow of u32 |
| 27 | + for chunk in dest.chunks_mut(u32::max_value() as usize) { |
| 28 | + let ret = unsafe { |
| 29 | + BCryptGenRandom( |
| 30 | + ptr::null_mut(), |
| 31 | + chunk.as_mut_ptr(), |
| 32 | + chunk.len() as u32, |
| 33 | + BCRYPT_USE_SYSTEM_PREFERRED_RNG, |
| 34 | + ) |
| 35 | + }; |
| 36 | + // NTSTATUS codes use two highest bits for severity status |
| 37 | + match ret >> 30 { |
| 38 | + 0b01 => { |
| 39 | + info!("BCryptGenRandom: information code 0x{:08X}", ret); |
| 40 | + } |
| 41 | + 0b10 => { |
| 42 | + warn!("BCryptGenRandom: warning code 0x{:08X}", ret); |
| 43 | + } |
| 44 | + 0b11 => { |
| 45 | + error!("BCryptGenRandom: failed with 0x{:08X}", ret); |
| 46 | + // We zeroize the highest bit, so the error code will reside |
| 47 | + // inside the range of designated for OS codes. |
| 48 | + let code = ret ^ (1 << 31); |
| 49 | + // SAFETY: the second highest bit is always equal to one, |
| 50 | + // so it's impossible to get zero. Unfortunately compiler |
| 51 | + // is not smart enough to figure out it yet. |
| 52 | + let code = unsafe { NonZeroU32::new_unchecked(code) }; |
| 53 | + return Err(Error::from(code)); |
| 54 | + } |
| 55 | + _ => (), |
| 56 | + } |
| 57 | + } |
| 58 | + Ok(()) |
| 59 | +} |
0 commit comments