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