1// Copyright 2019 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//! Interface to the operating system's random number generator.
10//!
11//! # Supported targets
12//!
13//! | Target | Target Triple | Implementation
14//! | ----------------- | ------------------ | --------------
15//! | Linux, Android | `*‑linux‑*` | [`getrandom`][1] system call if available, otherwise [`/dev/urandom`][2] after successfully polling `/dev/random`
16//! | Windows | `*‑windows‑*` | [`BCryptGenRandom`]
17//! | macOS | `*‑apple‑darwin` | [`getentropy`][3] if available, otherwise [`/dev/urandom`][4] (identical to `/dev/random`)
18//! | iOS, tvOS, watchOS | `*‑apple‑ios`, `*-apple-tvos`, `*-apple-watchos` | [`SecRandomCopyBytes`]
19//! | FreeBSD | `*‑freebsd` | [`getrandom`][5] if available, otherwise [`kern.arandom`][6]
20//! | OpenBSD | `*‑openbsd` | [`getentropy`][7]
21//! | NetBSD | `*‑netbsd` | [`getrandom`][16] if available, otherwise [`kern.arandom`][8]
22//! | Dragonfly BSD | `*‑dragonfly` | [`getrandom`][9] if available, otherwise [`/dev/urandom`][10] (identical to `/dev/random`)
23//! | Solaris, illumos | `*‑solaris`, `*‑illumos` | [`getrandom`][11] if available, otherwise [`/dev/random`][12]
24//! | Fuchsia OS | `*‑fuchsia` | [`cprng_draw`]
25//! | Redox | `*‑redox` | `/dev/urandom`
26//! | Haiku | `*‑haiku` | `/dev/urandom` (identical to `/dev/random`)
27//! | Hermit | `*-hermit` | [`sys_read_entropy`]
28//! | Hurd | `*-hurd-*` | [`getrandom`][17]
29//! | SGX | `x86_64‑*‑sgx` | [`RDRAND`]
30//! | VxWorks | `*‑wrs‑vxworks‑*` | `randABytes` after checking entropy pool initialization with `randSecure`
31//! | ESP-IDF | `*‑espidf` | [`esp_fill_random`]
32//! | Emscripten | `*‑emscripten` | [`getentropy`][13]
33//! | WASI | `wasm32‑wasi` | [`random_get`]
34//! | Web Browser and Node.js | `wasm*‑*‑unknown` | [`Crypto.getRandomValues`] if available, then [`crypto.randomFillSync`] if on Node.js, see [WebAssembly support]
35//! | SOLID | `*-kmc-solid_*` | `SOLID_RNG_SampleRandomBytes`
36//! | Nintendo 3DS | `armv6k-nintendo-3ds` | [`getrandom`][1]
37//! | PS Vita | `armv7-sony-vita-newlibeabihf` | [`getentropy`][13]
38//! | QNX Neutrino | `*‑nto-qnx*` | [`/dev/urandom`][14] (identical to `/dev/random`)
39//! | AIX | `*-ibm-aix` | [`/dev/urandom`][15]
40//!
41//! There is no blanket implementation on `unix` targets that reads from
42//! `/dev/urandom`. This ensures all supported targets are using the recommended
43//! interface and respect maximum buffer sizes.
44//!
45//! Pull Requests that add support for new targets to `getrandom` are always welcome.
46//!
47//! ## Unsupported targets
48//!
49//! By default, `getrandom` will not compile on unsupported targets, but certain
50//! features allow a user to select a "fallback" implementation if no supported
51//! implementation exists.
52//!
53//! All of the below mechanisms only affect unsupported
54//! targets. Supported targets will _always_ use their supported implementations.
55//! This prevents a crate from overriding a secure source of randomness
56//! (either accidentally or intentionally).
57//!
58//! ### RDRAND on x86
59//!
60//! *If the `rdrand` Cargo feature is enabled*, `getrandom` will fallback to using
61//! the [`RDRAND`] instruction to get randomness on `no_std` `x86`/`x86_64`
62//! targets. This feature has no effect on other CPU architectures.
63//!
64//! ### WebAssembly support
65//!
66//! This crate fully supports the
67//! [`wasm32-wasi`](https://github.com/CraneStation/wasi) and
68//! [`wasm32-unknown-emscripten`](https://www.hellorust.com/setup/emscripten/)
69//! targets. However, the `wasm32-unknown-unknown` target (i.e. the target used
70//! by `wasm-pack`) is not automatically
71//! supported since, from the target name alone, we cannot deduce which
72//! JavaScript interface is in use (or if JavaScript is available at all).
73//!
74//! Instead, *if the `js` Cargo feature is enabled*, this crate will assume
75//! that you are building for an environment containing JavaScript, and will
76//! call the appropriate methods. Both web browser (main window and Web Workers)
77//! and Node.js environments are supported, invoking the methods
78//! [described above](#supported-targets) using the [`wasm-bindgen`] toolchain.
79//!
80//! To enable the `js` Cargo feature, add the following to the `dependencies`
81//! section in your `Cargo.toml` file:
82//! ```toml
83//! [dependencies]
84//! getrandom = { version = "0.2", features = ["js"] }
85//! ```
86//!
87//! This can be done even if `getrandom` is not a direct dependency. Cargo
88//! allows crates to enable features for indirect dependencies.
89//!
90//! This feature should only be enabled for binary, test, or benchmark crates.
91//! Library crates should generally not enable this feature, leaving such a
92//! decision to *users* of their library. Also, libraries should not introduce
93//! their own `js` features *just* to enable `getrandom`'s `js` feature.
94//!
95//! This feature has no effect on targets other than `wasm32-unknown-unknown`.
96//!
97//! #### Node.js ES module support
98//!
99//! Node.js supports both [CommonJS modules] and [ES modules]. Due to
100//! limitations in wasm-bindgen's [`module`] support, we cannot directly
101//! support ES Modules running on Node.js. However, on Node v15 and later, the
102//! module author can add a simple shim to support the Web Cryptography API:
103//! ```js
104//! import { webcrypto } from 'node:crypto'
105//! globalThis.crypto = webcrypto
106//! ```
107//! This crate will then use the provided `webcrypto` implementation.
108//!
109//! ### Custom implementations
110//!
111//! The [`register_custom_getrandom!`] macro allows a user to mark their own
112//! function as the backing implementation for [`getrandom`]. See the macro's
113//! documentation for more information about writing and registering your own
114//! custom implementations.
115//!
116//! Note that registering a custom implementation only has an effect on targets
117//! that would otherwise not compile. Any supported targets (including those
118//! using `rdrand` and `js` Cargo features) continue using their normal
119//! implementations even if a function is registered.
120//!
121//! ## Early boot
122//!
123//! Sometimes, early in the boot process, the OS has not collected enough
124//! entropy to securely seed its RNG. This is especially common on virtual
125//! machines, where standard "random" events are hard to come by.
126//!
127//! Some operating system interfaces always block until the RNG is securely
128//! seeded. This can take anywhere from a few seconds to more than a minute.
129//! A few (Linux, NetBSD and Solaris) offer a choice between blocking and
130//! getting an error; in these cases, we always choose to block.
131//!
132//! On Linux (when the `getrandom` system call is not available), reading from
133//! `/dev/urandom` never blocks, even when the OS hasn't collected enough
134//! entropy yet. To avoid returning low-entropy bytes, we first poll
135//! `/dev/random` and only switch to `/dev/urandom` once this has succeeded.
136//!
137//! On OpenBSD, this kind of entropy accounting isn't available, and on
138//! NetBSD, blocking on it is discouraged. On these platforms, nonblocking
139//! interfaces are used, even when reliable entropy may not be available.
140//! On the platforms where it is used, the reliability of entropy accounting
141//! itself isn't free from controversy. This library provides randomness
142//! sourced according to the platform's best practices, but each platform has
143//! its own limits on the grade of randomness it can promise in environments
144//! with few sources of entropy.
145//!
146//! ## Error handling
147//!
148//! We always choose failure over returning known insecure "random" bytes. In
149//! general, on supported platforms, failure is highly unlikely, though not
150//! impossible. If an error does occur, then it is likely that it will occur
151//! on every call to `getrandom`, hence after the first successful call one
152//! can be reasonably confident that no errors will occur.
153//!
154//! [1]: http://man7.org/linux/man-pages/man2/getrandom.2.html
155//! [2]: http://man7.org/linux/man-pages/man4/urandom.4.html
156//! [3]: https://www.unix.com/man-page/mojave/2/getentropy/
157//! [4]: https://www.unix.com/man-page/mojave/4/urandom/
158//! [5]: https://www.freebsd.org/cgi/man.cgi?query=getrandom&manpath=FreeBSD+12.0-stable
159//! [6]: https://www.freebsd.org/cgi/man.cgi?query=random&sektion=4
160//! [7]: https://man.openbsd.org/getentropy.2
161//! [8]: https://man.netbsd.org/sysctl.7
162//! [9]: https://leaf.dragonflybsd.org/cgi/web-man?command=getrandom
163//! [10]: https://leaf.dragonflybsd.org/cgi/web-man?command=random§ion=4
164//! [11]: https://docs.oracle.com/cd/E88353_01/html/E37841/getrandom-2.html
165//! [12]: https://docs.oracle.com/cd/E86824_01/html/E54777/random-7d.html
166//! [13]: https://github.com/emscripten-core/emscripten/pull/12240
167//! [14]: https://www.qnx.com/developers/docs/7.1/index.html#com.qnx.doc.neutrino.utilities/topic/r/random.html
168//! [15]: https://www.ibm.com/docs/en/aix/7.3?topic=files-random-urandom-devices
169//! [16]: https://man.netbsd.org/getrandom.2
170//! [17]: https://www.gnu.org/software/libc/manual/html_mono/libc.html#index-getrandom
171//!
172//! [`BCryptGenRandom`]: https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom
173//! [`Crypto.getRandomValues`]: https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues
174//! [`RDRAND`]: https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide
175//! [`SecRandomCopyBytes`]: https://developer.apple.com/documentation/security/1399291-secrandomcopybytes?language=objc
176//! [`cprng_draw`]: https://fuchsia.dev/fuchsia-src/zircon/syscalls/cprng_draw
177//! [`crypto.randomFillSync`]: https://nodejs.org/api/crypto.html#cryptorandomfillsyncbuffer-offset-size
178//! [`esp_fill_random`]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html#_CPPv415esp_fill_randomPv6size_t
179//! [`random_get`]: https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---errno
180//! [WebAssembly support]: #webassembly-support
181//! [`wasm-bindgen`]: https://github.com/rustwasm/wasm-bindgen
182//! [`module`]: https://rustwasm.github.io/wasm-bindgen/reference/attributes/on-js-imports/module.html
183//! [CommonJS modules]: https://nodejs.org/api/modules.html
184//! [ES modules]: https://nodejs.org/api/esm.html
185//! [`sys_read_entropy`]: https://github.com/hermit-os/kernel/blob/315f58ff5efc81d9bf0618af85a59963ff55f8b1/src/syscalls/entropy.rs#L47-L55
186
187#![doc(
188 html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
189 html_favicon_url = "https://www.rust-lang.org/favicon.ico",
190 html_root_url = "https://docs.rs/getrandom/0.2.11"
191)]
192#![no_std]
193#![warn(rust_2018_idioms, unused_lifetimes, missing_docs)]
194#![cfg_attr(docsrs, feature(doc_cfg))]
195
196#[macro_use]
197extern crate cfg_if;
198
199use crate::util::{slice_as_uninit_mut, slice_assume_init_mut};
200use core::mem::MaybeUninit;
201
202mod error;
203mod util;
204// To prevent a breaking change when targets are added, we always export the
205// register_custom_getrandom macro, so old Custom RNG crates continue to build.
206#[cfg(feature = "custom")]
207mod custom;
208#[cfg(feature = "std")]
209mod error_impls;
210
211pub use crate::error::Error;
212
213// System-specific implementations.
214//
215// These should all provide getrandom_inner with the signature
216// `fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error>`.
217// The function MUST fully initialize `dest` when `Ok(())` is returned.
218// The function MUST NOT ever write uninitialized bytes into `dest`,
219// regardless of what value it returns.
220cfg_if! {
221 if #[cfg(any(target_os = "haiku", target_os = "redox", target_os = "nto", target_os = "aix"))] {
222 mod util_libc;
223 #[path = "use_file.rs"] mod imp;
224 } else if #[cfg(any(target_os = "android", target_os = "linux"))] {
225 mod util_libc;
226 mod use_file;
227 #[path = "linux_android.rs"] mod imp;
228 } else if #[cfg(any(target_os = "illumos", target_os = "solaris"))] {
229 mod util_libc;
230 mod use_file;
231 #[path = "solaris_illumos.rs"] mod imp;
232 } else if #[cfg(any(target_os = "freebsd", target_os = "netbsd"))] {
233 mod util_libc;
234 #[path = "bsd_arandom.rs"] mod imp;
235 } else if #[cfg(target_os = "dragonfly")] {
236 mod util_libc;
237 mod use_file;
238 #[path = "dragonfly.rs"] mod imp;
239 } else if #[cfg(target_os = "fuchsia")] {
240 #[path = "fuchsia.rs"] mod imp;
241 } else if #[cfg(any(target_os = "ios", target_os = "watchos", target_os = "tvos"))] {
242 #[path = "apple-other.rs"] mod imp;
243 } else if #[cfg(target_os = "macos")] {
244 mod util_libc;
245 mod use_file;
246 #[path = "macos.rs"] mod imp;
247 } else if #[cfg(target_os = "openbsd")] {
248 mod util_libc;
249 #[path = "openbsd.rs"] mod imp;
250 } else if #[cfg(all(target_arch = "wasm32", target_os = "wasi"))] {
251 #[path = "wasi.rs"] mod imp;
252 } else if #[cfg(target_os = "hermit")] {
253 #[path = "hermit.rs"] mod imp;
254 } else if #[cfg(target_os = "vxworks")] {
255 mod util_libc;
256 #[path = "vxworks.rs"] mod imp;
257 } else if #[cfg(target_os = "solid_asp3")] {
258 #[path = "solid.rs"] mod imp;
259 } else if #[cfg(target_os = "espidf")] {
260 #[path = "espidf.rs"] mod imp;
261 } else if #[cfg(windows)] {
262 #[path = "windows.rs"] mod imp;
263 } else if #[cfg(all(target_os = "horizon", target_arch = "arm"))] {
264 // We check for target_arch = "arm" because the Nintendo Switch also
265 // uses Horizon OS (it is aarch64).
266 mod util_libc;
267 #[path = "3ds.rs"] mod imp;
268 } else if #[cfg(target_os = "vita")] {
269 mod util_libc;
270 #[path = "vita.rs"] mod imp;
271 } else if #[cfg(target_os = "emscripten")] {
272 mod util_libc;
273 #[path = "emscripten.rs"] mod imp;
274 } else if #[cfg(all(target_arch = "x86_64", target_env = "sgx"))] {
275 #[path = "rdrand.rs"] mod imp;
276 } else if #[cfg(all(feature = "rdrand",
277 any(target_arch = "x86_64", target_arch = "x86")))] {
278 #[path = "rdrand.rs"] mod imp;
279 } else if #[cfg(all(feature = "js",
280 any(target_arch = "wasm32", target_arch = "wasm64"),
281 target_os = "unknown"))] {
282 #[path = "js.rs"] mod imp;
283 } else if #[cfg(target_os = "hurd")] {
284 mod util_libc;
285 #[path = "hurd.rs"] mod imp;
286 } else if #[cfg(feature = "custom")] {
287 use custom as imp;
288 } else if #[cfg(all(any(target_arch = "wasm32", target_arch = "wasm64"),
289 target_os = "unknown"))] {
290 compile_error!("the wasm*-unknown-unknown targets are not supported by \
291 default, you may need to enable the \"js\" feature. \
292 For more information see: \
293 https://docs.rs/getrandom/#webassembly-support");
294 } else {
295 compile_error!("target is not supported, for more information see: \
296 https://docs.rs/getrandom/#unsupported-targets");
297 }
298}
299
300/// Fill `dest` with random bytes from the system's preferred random number
301/// source.
302///
303/// This function returns an error on any failure, including partial reads. We
304/// make no guarantees regarding the contents of `dest` on error. If `dest` is
305/// empty, `getrandom` immediately returns success, making no calls to the
306/// underlying operating system.
307///
308/// Blocking is possible, at least during early boot; see module documentation.
309///
310/// In general, `getrandom` will be fast enough for interactive usage, though
311/// significantly slower than a user-space CSPRNG; for the latter consider
312/// [`rand::thread_rng`](https://docs.rs/rand/*/rand/fn.thread_rng.html).
313#[inline]
314pub fn getrandom(dest: &mut [u8]) -> Result<(), Error> {
315 // SAFETY: The `&mut MaybeUninit<_>` reference doesn't escape, and
316 // `getrandom_uninit` guarantees it will never de-initialize any part of
317 // `dest`.
318 getrandom_uninit(unsafe { slice_as_uninit_mut(dest) })?;
319 Ok(())
320}
321
322/// Version of the `getrandom` function which fills `dest` with random bytes
323/// returns a mutable reference to those bytes.
324///
325/// On successful completion this function is guaranteed to return a slice
326/// which points to the same memory as `dest` and has the same length.
327/// In other words, it's safe to assume that `dest` is initialized after
328/// this function has returned `Ok`.
329///
330/// No part of `dest` will ever be de-initialized at any point, regardless
331/// of what is returned.
332///
333/// # Examples
334///
335/// ```ignore
336/// # // We ignore this test since `uninit_array` is unstable.
337/// #![feature(maybe_uninit_uninit_array)]
338/// # fn main() -> Result<(), getrandom::Error> {
339/// let mut buf = core::mem::MaybeUninit::uninit_array::<1024>();
340/// let buf: &mut [u8] = getrandom::getrandom_uninit(&mut buf)?;
341/// # Ok(()) }
342/// ```
343#[inline]
344pub fn getrandom_uninit(dest: &mut [MaybeUninit<u8>]) -> Result<&mut [u8], Error> {
345 if !dest.is_empty() {
346 imp::getrandom_inner(dest)?;
347 }
348 // SAFETY: `dest` has been fully initialized by `imp::getrandom_inner`
349 // since it returned `Ok`.
350 Ok(unsafe { slice_assume_init_mut(dest) })
351}
352