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