Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
73 changes: 49 additions & 24 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ name = "ring"

[dependencies]
cfg-if = { version = "1.0.0", default-features = false }
getrandom = { version = "0.2.10" }
getrandom = { version = "0.3" }
untrusted = { version = "0.9" }

[target.'cfg(all(any(all(target_arch = "aarch64", target_endian = "little"), all(target_arch = "arm", target_endian = "little")), any(target_os = "android", target_os = "linux")))'.dependencies]
Expand All @@ -165,6 +165,9 @@ libc = { version = "0.2.172", default-features = false }
[target.'cfg(all(all(target_arch = "aarch64", target_endian = "little"), target_os = "windows"))'.dependencies]
windows-sys = { version = "0.60", features = ["Win32_Foundation", "Win32_System_Threading"] }

[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
wasm-bindgen = { version = "0.2.101" }

[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dev-dependencies]
wasm-bindgen-test = { version = "0.3.37", default-features = false, features = ["std"] }

Expand All @@ -186,7 +189,7 @@ std = ["alloc"]
unstable-testing-arm-no-hw = []
unstable-testing-arm-no-neon = []
test_logging = []
wasm32_unknown_unknown_js = ["getrandom/js"]
wasm32_unknown_unknown_js = ["getrandom/wasm_js"]

[package.metadata.cargo-semver-checks.lints]
trait_marked_deprecated = { level = "warn" }
Expand Down
11 changes: 10 additions & 1 deletion src/rand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@

use crate::error;

#[cfg(all(
target_arch = "wasm32",
any(
target_os = "wasi",
all(target_os = "unknown", feature = "wasm32_unknown_unknown_js")
)
))]
mod getrandom;

/// A secure random number generator.
pub trait SecureRandom: sealed::SecureRandom {
/// Fills `dest` with random bytes.
Expand Down Expand Up @@ -165,6 +174,6 @@ impl SystemRandom {
impl sealed::SecureRandom for SystemRandom {
#[inline(always)]
fn fill_impl(&self, dest: &mut [u8], _: crate::sealed::Arg) -> Result<(), error::Unspecified> {
getrandom::getrandom(dest).map_err(|_| error::Unspecified)
getrandom::fill(dest).map_err(|_| error::Unspecified)
}
}
129 changes: 129 additions & 0 deletions src/rand/getrandom.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// This file, and all code in `rand/getrandom`, are vendored from
// the `getrandom` project:
// https://github.com/rust-random/getrandom/tree/78ef61a0e7a5dc876da0b496998464630a4c0bf0
//
// Copyright (c) 2018-2025 The rust-random Project Developers
// Copyright (c) 2014 The Rust Project Developers
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

// Overwrite links to crate items with intra-crate links
//! [`Error::UNEXPECTED`]: Error::UNEXPECTED
//! [`fill_uninit`]: fill_uninit

#![warn(rust_2018_idioms, unused_lifetimes, missing_docs)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![cfg_attr(getrandom_backend = "efi_rng", feature(uefi_std))]
#![deny(
clippy::cast_lossless,
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_precision_loss,
clippy::cast_ptr_alignment,
clippy::cast_sign_loss,
clippy::char_lit_as_u8,
clippy::checked_conversions,
clippy::fn_to_numeric_cast,
clippy::fn_to_numeric_cast_with_truncation,
clippy::ptr_as_ptr,
clippy::unnecessary_cast,
clippy::useless_conversion
)]

use core::mem::MaybeUninit;

mod backends;
mod error;
mod util;

pub use error::Error;

/// Fill `dest` with random bytes from the system's preferred random number source.
///
/// This function returns an error on any failure, including partial reads. We
/// make no guarantees regarding the contents of `dest` on error. If `dest` is
/// empty, `getrandom` immediately returns success, making no calls to the
/// underlying operating system.
///
/// Blocking is possible, at least during early boot; see module documentation.
///
/// In general, `getrandom` will be fast enough for interactive usage, though
/// significantly slower than a user-space CSPRNG; for the latter consider
/// [`rand::thread_rng`](https://docs.rs/rand/*/rand/fn.thread_rng.html).
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), getrandom::Error> {
/// let mut buf = [0u8; 32];
/// getrandom::fill(&mut buf)?;
/// # Ok(()) }
/// ```
#[inline]
pub fn fill(dest: &mut [u8]) -> Result<(), Error> {
// SAFETY: The `&mut MaybeUninit<_>` reference doesn't escape,
// and `fill_uninit` guarantees it will never de-initialize
// any part of `dest`.
let _ = fill_uninit(unsafe { util::slice_as_uninit_mut(dest) })?;
Ok(())
}

/// Fill potentially uninitialized buffer `dest` with random bytes from
/// the system's preferred random number source and return a mutable
/// reference to those bytes.
///
/// On successful completion this function is guaranteed to return a slice
/// which points to the same memory as `dest` and has the same length.
/// In other words, it's safe to assume that `dest` is initialized after
/// this function has returned `Ok`.
///
/// No part of `dest` will ever be de-initialized at any point, regardless
/// of what is returned.
///
/// # Examples
///
/// ```ignore
/// # // We ignore this test since `uninit_array` is unstable.
/// #![feature(maybe_uninit_uninit_array)]
/// # fn main() -> Result<(), getrandom::Error> {
/// let mut buf = core::mem::MaybeUninit::uninit_array::<1024>();
/// let buf: &mut [u8] = getrandom::fill_uninit(&mut buf)?;
/// # Ok(()) }
/// ```
#[inline]
pub fn fill_uninit(dest: &mut [MaybeUninit<u8>]) -> Result<&mut [u8], Error> {
if !dest.is_empty() {
backends::fill_inner(dest)?;
}

#[cfg(getrandom_msan)]
extern "C" {
fn __msan_unpoison(a: *mut core::ffi::c_void, size: usize);
}

// SAFETY: `dest` has been fully initialized by `imp::fill_inner`
// since it returned `Ok`.
Ok(unsafe { util::slice_assume_init_mut(dest) })
}
11 changes: 11 additions & 0 deletions src/rand/getrandom/backends.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
//! System-specific implementations.
//!
//! This module should provide `fill_inner` with the signature
//! `fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error>`.
//! The function MUST fully initialize `dest` when `Ok(())` is returned;
//! the function may need to use `sanitizer::unpoison` as well.
//! The function MUST NOT ever write uninitialized bytes into `dest`,
//! regardless of what value it returns.

mod wasm_js;
pub use wasm_js::*;
Loading