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