Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
12 changes: 11 additions & 1 deletion src/rand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,16 @@

use crate::error;

#[cfg(all(
target_arch = "wasm32",
any(
target_os = "wasi",
all(target_os = "unknown", feature = "wasm32_unknown_unknown_js")
)
))]
#[path = "rand/getrandom/lib.rs"]
mod getrandom;

/// A secure random number generator.
pub trait SecureRandom: sealed::SecureRandom {
/// Fills `dest` with random bytes.
Expand Down Expand Up @@ -165,6 +175,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)
}
}
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::*;
70 changes: 70 additions & 0 deletions src/rand/getrandom/backends/wasm_js.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
//! Implementation for WASM based on Web and Node.js
use crate::rand::getrandom::Error;
use core::mem::MaybeUninit;

#[cfg(not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none"))))]
compile_error!("`wasm_js` backend can be enabled only for OS-less WASM targets!");

use wasm_bindgen::{prelude::wasm_bindgen, JsValue};

// Maximum buffer size allowed in `Crypto.getRandomValuesSize` is 65536 bytes.
// See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
const MAX_BUFFER_SIZE: usize = 65536;

#[cfg(not(target_feature = "atomics"))]
#[inline]
pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
for chunk in dest.chunks_mut(MAX_BUFFER_SIZE) {
if get_random_values(chunk).is_err() {
return Err(Error::WEB_CRYPTO);
}
}
Ok(())
}

#[cfg(target_feature = "atomics")]
pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> {
// getRandomValues does not work with all types of WASM memory,
// so we initially write to browser memory to avoid exceptions.
let buf_len = usize::min(dest.len(), MAX_BUFFER_SIZE);
let buf_len_u32 = buf_len
.try_into()
.expect("buffer length is bounded by MAX_BUFFER_SIZE");
let buf = js_sys::Uint8Array::new_with_length(buf_len_u32);
for chunk in dest.chunks_mut(buf_len) {
let chunk_len = chunk
.len()
.try_into()
.expect("chunk length is bounded by MAX_BUFFER_SIZE");
// The chunk can be smaller than buf's length, so we call to
// JS to create a smaller view of buf without allocation.
let sub_buf = if chunk_len == buf_len_u32 {
&buf
} else {
&buf.subarray(0, chunk_len)
};

if get_random_values(sub_buf).is_err() {
return Err(Error::WEB_CRYPTO);
}

sub_buf.copy_to_uninit(chunk);
}
Ok(())
}

#[wasm_bindgen]
extern "C" {
// Crypto.getRandomValues()
#[cfg(not(target_feature = "atomics"))]
#[wasm_bindgen(js_namespace = ["globalThis", "crypto"], js_name = getRandomValues, catch)]
fn get_random_values(buf: &mut [MaybeUninit<u8>]) -> Result<(), JsValue>;
#[cfg(target_feature = "atomics")]
#[wasm_bindgen(js_namespace = ["globalThis", "crypto"], js_name = getRandomValues, catch)]
fn get_random_values(buf: &js_sys::Uint8Array) -> Result<(), JsValue>;
}

impl Error {
/// The environment does not support the Web Crypto API.
pub(crate) const WEB_CRYPTO: Error = Self::new_internal(10);
}
45 changes: 45 additions & 0 deletions src/rand/getrandom/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use core::fmt;

// This private alias mirrors `std::io::RawOsError`:
// https://doc.rust-lang.org/std/io/type.RawOsError.html)
cfg_if::cfg_if!(
if #[cfg(target_os = "uefi")] {
// See the UEFI spec for more information:
// https://uefi.org/specs/UEFI/2.10/Apx_D_Status_Codes.html
type RawOsError = usize;
type NonZeroRawOsError = core::num::NonZeroUsize;
const UEFI_ERROR_FLAG: RawOsError = 1 << (RawOsError::BITS - 1);
} else {
type RawOsError = i32;
type NonZeroRawOsError = core::num::NonZeroI32;
}
);

/// A small and `no_std` compatible error type
///
/// The [`Error::raw_os_error()`] will indicate if the error is from the OS, and
/// if so, which error code the OS gave the application. If such an error is
/// encountered, please consult with your system documentation.
///
/// *If this crate's `"std"` Cargo feature is enabled*, then:
/// - [`getrandom::Error`][Error] implements
/// [`std::error::Error`](https://doc.rust-lang.org/std/error/trait.Error.html)
/// - [`std::io::Error`](https://doc.rust-lang.org/std/io/struct.Error.html) implements
/// [`From<getrandom::Error>`](https://doc.rust-lang.org/std/convert/trait.From.html).

// note: on non-UEFI targets OS errors are represented as negative integers,
// while on UEFI targets OS errors have the highest bit set to 1.
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Error(NonZeroRawOsError);

impl Error {
/// Internal errors can be in the range of 2^16..2^17
const INTERNAL_START: RawOsError = 1 << 16;

/// Creates a new instance of an `Error` from a particular internal error code.
pub(crate) const fn new_internal(n: u16) -> Error {
// SAFETY: code > 0 as INTERNAL_START > 0 and adding `n` won't overflow `RawOsError`.
let code = Error::INTERNAL_START + (n as RawOsError);
Error(unsafe { NonZeroRawOsError::new_unchecked(code) })
}
}
Loading