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 //! ## `/dev/urandom` fallback on Linux and Android
51 //!
52 //! On Linux targets the fallback is present only if either `target_env` is `musl`,
53 //! or `target_arch` is one of the following: `aarch64`, `arm`, `powerpc`, `powerpc64`,
54 //! `s390x`, `x86`, `x86_64`. Other supported targets [require][platform-support]
55 //! kernel versions which support `getrandom` system call, so fallback is not needed.
56 //!
57 //! On Android targets the fallback is present only for the following `target_arch`es:
58 //! `aarch64`, `arm`, `x86`, `x86_64`. Other `target_arch`es (e.g. RISC-V) require
59 //! sufficiently high API levels.
60 //!
61 //! The fallback can be disabled by enabling the `linux_disable_fallback` crate feature.
62 //! Note that doing so will bump minimum supported Linux kernel version to 3.17 and
63 //! Android API level to 23 (Marshmallow).
64 //!
65 //! ### RDRAND on x86
66 //!
67 //! *If the `rdrand` Cargo feature is enabled*, `getrandom` will fallback to using
68 //! the [`RDRAND`] instruction to get randomness on `no_std` `x86`/`x86_64`
69 //! targets. This feature has no effect on other CPU architectures.
70 //!
71 //! ### WebAssembly support
72 //!
73 //! This crate fully supports the
74 //! [`wasm32-wasi`](https://github.com/CraneStation/wasi) and
75 //! [`wasm32-unknown-emscripten`](https://www.hellorust.com/setup/emscripten/)
76 //! targets. However, the `wasm32-unknown-unknown` target (i.e. the target used
77 //! by `wasm-pack`) is not automatically
78 //! supported since, from the target name alone, we cannot deduce which
79 //! JavaScript interface is in use (or if JavaScript is available at all).
80 //!
81 //! Instead, *if the `js` Cargo feature is enabled*, this crate will assume
82 //! that you are building for an environment containing JavaScript, and will
83 //! call the appropriate methods. Both web browser (main window and Web Workers)
84 //! and Node.js environments are supported, invoking the methods
85 //! [described above](#supported-targets) using the [`wasm-bindgen`] toolchain.
86 //!
87 //! To enable the `js` Cargo feature, add the following to the `dependencies`
88 //! section in your `Cargo.toml` file:
89 //! ```toml
90 //! [dependencies]
91 //! getrandom = { version = "0.2", features = ["js"] }
92 //! ```
93 //!
94 //! This can be done even if `getrandom` is not a direct dependency. Cargo
95 //! allows crates to enable features for indirect dependencies.
96 //!
97 //! This feature should only be enabled for binary, test, or benchmark crates.
98 //! Library crates should generally not enable this feature, leaving such a
99 //! decision to *users* of their library. Also, libraries should not introduce
100 //! their own `js` features *just* to enable `getrandom`'s `js` feature.
101 //!
102 //! This feature has no effect on targets other than `wasm32-unknown-unknown`.
103 //!
104 //! #### Node.js ES module support
105 //!
106 //! Node.js supports both [CommonJS modules] and [ES modules]. Due to
107 //! limitations in wasm-bindgen's [`module`] support, we cannot directly
108 //! support ES Modules running on Node.js. However, on Node v15 and later, the
109 //! module author can add a simple shim to support the Web Cryptography API:
110 //! ```js
111 //! import { webcrypto } from 'node:crypto'
112 //! globalThis.crypto = webcrypto
113 //! ```
114 //! This crate will then use the provided `webcrypto` implementation.
115 //!
116 //! ### Platform Support
117 //! This crate generally supports the same operating system and platform versions
118 //! that the Rust standard library does. Additional targets may be supported using
119 //! pluggable custom implementations.
120 //!
121 //! This means that as Rust drops support for old versions of operating systems
122 //! (such as old Linux kernel versions, Android API levels, etc) in stable releases,
123 //! `getrandom` may create new patch releases (`0.N.x`) that remove support for
124 //! outdated platform versions.
125 //!
126 //! ### Custom implementations
127 //!
128 //! The [`register_custom_getrandom!`] macro allows a user to mark their own
129 //! function as the backing implementation for [`getrandom`]. See the macro's
130 //! documentation for more information about writing and registering your own
131 //! custom implementations.
132 //!
133 //! Note that registering a custom implementation only has an effect on targets
134 //! that would otherwise not compile. Any supported targets (including those
135 //! using `rdrand` and `js` Cargo features) continue using their normal
136 //! implementations even if a function is registered.
137 //!
138 //! ## Early boot
139 //!
140 //! Sometimes, early in the boot process, the OS has not collected enough
141 //! entropy to securely seed its RNG. This is especially common on virtual
142 //! machines, where standard "random" events are hard to come by.
143 //!
144 //! Some operating system interfaces always block until the RNG is securely
145 //! seeded. This can take anywhere from a few seconds to more than a minute.
146 //! A few (Linux, NetBSD and Solaris) offer a choice between blocking and
147 //! getting an error; in these cases, we always choose to block.
148 //!
149 //! On Linux (when the `getrandom` system call is not available), reading from
150 //! `/dev/urandom` never blocks, even when the OS hasn't collected enough
151 //! entropy yet. To avoid returning low-entropy bytes, we first poll
152 //! `/dev/random` and only switch to `/dev/urandom` once this has succeeded.
153 //!
154 //! On OpenBSD, this kind of entropy accounting isn't available, and on
155 //! NetBSD, blocking on it is discouraged. On these platforms, nonblocking
156 //! interfaces are used, even when reliable entropy may not be available.
157 //! On the platforms where it is used, the reliability of entropy accounting
158 //! itself isn't free from controversy. This library provides randomness
159 //! sourced according to the platform's best practices, but each platform has
160 //! its own limits on the grade of randomness it can promise in environments
161 //! with few sources of entropy.
162 //!
163 //! ## Error handling
164 //!
165 //! We always choose failure over returning known insecure "random" bytes. In
166 //! general, on supported platforms, failure is highly unlikely, though not
167 //! impossible. If an error does occur, then it is likely that it will occur
168 //! on every call to `getrandom`, hence after the first successful call one
169 //! can be reasonably confident that no errors will occur.
170 //!
171 //! [1]: https://manned.org/getrandom.2
172 //! [2]: https://manned.org/urandom.4
173 //! [3]: https://www.unix.com/man-page/mojave/2/getentropy/
174 //! [4]: https://www.unix.com/man-page/mojave/4/urandom/
175 //! [5]: https://www.freebsd.org/cgi/man.cgi?query=getrandom&manpath=FreeBSD+12.0-stable
176 //! [6]: https://www.freebsd.org/cgi/man.cgi?query=random&sektion=4
177 //! [7]: https://man.openbsd.org/getentropy.2
178 //! [8]: https://man.netbsd.org/sysctl.7
179 //! [9]: https://leaf.dragonflybsd.org/cgi/web-man?command=getrandom
180 //! [10]: https://leaf.dragonflybsd.org/cgi/web-man?command=random§ion=4
181 //! [11]: https://docs.oracle.com/cd/E88353_01/html/E37841/getrandom-2.html
182 //! [12]: https://docs.oracle.com/cd/E86824_01/html/E54777/random-7d.html
183 //! [13]: https://github.com/emscripten-core/emscripten/pull/12240
184 //! [14]: https://www.qnx.com/developers/docs/7.1/index.html#com.qnx.doc.neutrino.utilities/topic/r/random.html
185 //! [15]: https://www.ibm.com/docs/en/aix/7.3?topic=files-random-urandom-devices
186 //! [16]: https://man.netbsd.org/getrandom.2
187 //! [17]: https://www.gnu.org/software/libc/manual/html_mono/libc.html#index-getrandom
188 //!
189 //! [`BCryptGenRandom`]: https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom
190 //! [`Crypto.getRandomValues`]: https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues
191 //! [`RDRAND`]: https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide
192 //! [`CCRandomGenerateBytes`]: https://opensource.apple.com/source/CommonCrypto/CommonCrypto-60074/include/CommonRandom.h.auto.html
193 //! [`cprng_draw`]: https://fuchsia.dev/fuchsia-src/zircon/syscalls/cprng_draw
194 //! [`crypto.randomFillSync`]: https://nodejs.org/api/crypto.html#cryptorandomfillsyncbuffer-offset-size
195 //! [`esp_fill_random`]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html#_CPPv415esp_fill_randomPv6size_t
196 //! [`random_get`]: https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---errno
197 //! [WebAssembly support]: #webassembly-support
198 //! [`wasm-bindgen`]: https://github.com/rustwasm/wasm-bindgen
199 //! [`module`]: https://rustwasm.github.io/wasm-bindgen/reference/attributes/on-js-imports/module.html
200 //! [CommonJS modules]: https://nodejs.org/api/modules.html
201 //! [ES modules]: https://nodejs.org/api/esm.html
202 //! [`sys_read_entropy`]: https://github.com/hermit-os/kernel/blob/315f58ff5efc81d9bf0618af85a59963ff55f8b1/src/syscalls/entropy.rs#L47-L55
203 //! [platform-support]: https://doc.rust-lang.org/stable/rustc/platform-support.html
204
205 #![doc(
206 html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
207 html_favicon_url = "https://www.rust-lang.org/favicon.ico",
208 html_root_url = "https://docs.rs/getrandom/0.2.14"
209 )]
210 #![no_std]
211 #![warn(rust_2018_idioms, unused_lifetimes, missing_docs)]
212 #![cfg_attr(docsrs, feature(doc_auto_cfg))]
213
214 #[macro_use]
215 extern crate cfg_if;
216
217 use crate::util::{slice_as_uninit_mut, slice_assume_init_mut};
218 use core::mem::MaybeUninit;
219
220 mod error;
221 mod util;
222 // To prevent a breaking change when targets are added, we always export the
223 // register_custom_getrandom macro, so old Custom RNG crates continue to build.
224 #[cfg(feature = "custom")]
225 mod custom;
226 #[cfg(feature = "std")]
227 mod error_impls;
228
229 pub use crate::error::Error;
230
231 // System-specific implementations.
232 //
233 // These should all provide getrandom_inner with the signature
234 // `fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error>`.
235 // The function MUST fully initialize `dest` when `Ok(())` is returned.
236 // The function MUST NOT ever write uninitialized bytes into `dest`,
237 // regardless of what value it returns.
238 cfg_if! {
239 if #[cfg(any(target_os = "haiku", target_os = "redox", target_os = "nto", target_os = "aix"))] {
240 mod util_libc;
241 #[path = "use_file.rs"] mod imp;
242 } else if #[cfg(all(
243 not(feature = "linux_disable_fallback"),
244 any(
245 // Rust supports Android API level 19 (KitKat) [0] and the next upgrade targets
246 // level 21 (Lollipop) [1], while `getrandom(2)` was added only in
247 // level 23 (Marshmallow). Note that it applies only to the "old" `target_arch`es,
248 // RISC-V Android targets sufficiently new API level, same will apply for potential
249 // new Android `target_arch`es.
250 // [0]: https://blog.rust-lang.org/2023/01/09/android-ndk-update-r25.html
251 // [1]: https://github.com/rust-lang/rust/pull/120593
252 all(
253 target_os = "android",
254 any(
255 target_arch = "aarch64",
256 target_arch = "arm",
257 target_arch = "x86",
258 target_arch = "x86_64",
259 ),
260 ),
261 // Only on these `target_arch`es Rust supports Linux kernel versions (3.2+)
262 // that precede the version (3.17) in which `getrandom(2)` was added:
263 // https://doc.rust-lang.org/stable/rustc/platform-support.html
264 all(
265 target_os = "linux",
266 any(
267 target_arch = "aarch64",
268 target_arch = "arm",
269 target_arch = "powerpc",
270 target_arch = "powerpc64",
271 target_arch = "s390x",
272 target_arch = "x86",
273 target_arch = "x86_64",
274 // Minimum supported Linux kernel version for MUSL targets
275 // is not specified explicitly (as of Rust 1.77) and they
276 // are used in practice to target pre-3.17 kernels.
277 target_env = "musl",
278 ),
279 )
280 ),
281 ))] {
282 mod util_libc;
283 mod use_file;
284 mod lazy;
285 #[path = "linux_android_with_fallback.rs"] mod imp;
286 } else if #[cfg(any(target_os = "android", target_os = "linux"))] {
287 mod util_libc;
288 #[path = "linux_android.rs"] mod imp;
289 } else if #[cfg(any(target_os = "illumos", target_os = "solaris"))] {
290 mod util_libc;
291 mod use_file;
292 #[path = "solaris_illumos.rs"] mod imp;
293 } else if #[cfg(any(target_os = "freebsd", target_os = "netbsd"))] {
294 mod util_libc;
295 #[path = "bsd_arandom.rs"] mod imp;
296 } else if #[cfg(target_os = "dragonfly")] {
297 mod util_libc;
298 mod use_file;
299 #[path = "dragonfly.rs"] mod imp;
300 } else if #[cfg(target_os = "fuchsia")] {
301 #[path = "fuchsia.rs"] mod imp;
302 } else if #[cfg(any(target_os = "ios", target_os = "watchos", target_os = "tvos"))] {
303 #[path = "apple-other.rs"] mod imp;
304 } else if #[cfg(target_os = "macos")] {
305 mod util_libc;
306 #[path = "macos.rs"] mod imp;
307 } else if #[cfg(target_os = "openbsd")] {
308 mod util_libc;
309 #[path = "openbsd.rs"] mod imp;
310 } else if #[cfg(all(target_arch = "wasm32", target_os = "wasi"))] {
311 #[path = "wasi.rs"] mod imp;
312 } else if #[cfg(target_os = "hermit")] {
313 #[path = "hermit.rs"] mod imp;
314 } else if #[cfg(target_os = "vxworks")] {
315 mod util_libc;
316 #[path = "vxworks.rs"] mod imp;
317 } else if #[cfg(target_os = "solid_asp3")] {
318 #[path = "solid.rs"] mod imp;
319 } else if #[cfg(target_os = "espidf")] {
320 #[path = "espidf.rs"] mod imp;
321 } else if #[cfg(windows)] {
322 #[path = "windows.rs"] mod imp;
323 } else if #[cfg(all(target_os = "horizon", target_arch = "arm"))] {
324 // We check for target_arch = "arm" because the Nintendo Switch also
325 // uses Horizon OS (it is aarch64).
326 mod util_libc;
327 #[path = "3ds.rs"] mod imp;
328 } else if #[cfg(target_os = "vita")] {
329 mod util_libc;
330 #[path = "vita.rs"] mod imp;
331 } else if #[cfg(target_os = "emscripten")] {
332 mod util_libc;
333 #[path = "emscripten.rs"] mod imp;
334 } else if #[cfg(all(target_arch = "x86_64", target_env = "sgx"))] {
335 mod lazy;
336 #[path = "rdrand.rs"] mod imp;
337 } else if #[cfg(all(feature = "rdrand",
338 any(target_arch = "x86_64", target_arch = "x86")))] {
339 mod lazy;
340 #[path = "rdrand.rs"] mod imp;
341 } else if #[cfg(all(feature = "js",
342 any(target_arch = "wasm32", target_arch = "wasm64"),
343 target_os = "unknown"))] {
344 #[path = "js.rs"] mod imp;
345 } else if #[cfg(target_os = "hurd")] {
346 mod util_libc;
347 #[path = "hurd.rs"] mod imp;
348 } else if #[cfg(feature = "custom")] {
349 use custom as imp;
350 } else if #[cfg(all(any(target_arch = "wasm32", target_arch = "wasm64"),
351 target_os = "unknown"))] {
352 compile_error!("the wasm*-unknown-unknown targets are not supported by \
353 default, you may need to enable the \"js\" feature. \
354 For more information see: \
355 https://docs.rs/getrandom/#webassembly-support");
356 } else {
357 compile_error!("target is not supported, for more information see: \
358 https://docs.rs/getrandom/#unsupported-targets");
359 }
360 }
361
362 /// Fill `dest` with random bytes from the system's preferred random number
363 /// source.
364 ///
365 /// This function returns an error on any failure, including partial reads. We
366 /// make no guarantees regarding the contents of `dest` on error. If `dest` is
367 /// empty, `getrandom` immediately returns success, making no calls to the
368 /// underlying operating system.
369 ///
370 /// Blocking is possible, at least during early boot; see module documentation.
371 ///
372 /// In general, `getrandom` will be fast enough for interactive usage, though
373 /// significantly slower than a user-space CSPRNG; for the latter consider
374 /// [`rand::thread_rng`](https://docs.rs/rand/*/rand/fn.thread_rng.html).
375 #[inline]
getrandom(dest: &mut [u8]) -> Result<(), Error>376 pub fn getrandom(dest: &mut [u8]) -> Result<(), Error> {
377 // SAFETY: The `&mut MaybeUninit<_>` reference doesn't escape, and
378 // `getrandom_uninit` guarantees it will never de-initialize any part of
379 // `dest`.
380 getrandom_uninit(unsafe { slice_as_uninit_mut(dest) })?;
381 Ok(())
382 }
383
384 /// Version of the `getrandom` function which fills `dest` with random bytes
385 /// returns a mutable reference to those bytes.
386 ///
387 /// On successful completion this function is guaranteed to return a slice
388 /// which points to the same memory as `dest` and has the same length.
389 /// In other words, it's safe to assume that `dest` is initialized after
390 /// this function has returned `Ok`.
391 ///
392 /// No part of `dest` will ever be de-initialized at any point, regardless
393 /// of what is returned.
394 ///
395 /// # Examples
396 ///
397 /// ```ignore
398 /// # // We ignore this test since `uninit_array` is unstable.
399 /// #![feature(maybe_uninit_uninit_array)]
400 /// # fn main() -> Result<(), getrandom::Error> {
401 /// let mut buf = core::mem::MaybeUninit::uninit_array::<1024>();
402 /// let buf: &mut [u8] = getrandom::getrandom_uninit(&mut buf)?;
403 /// # Ok(()) }
404 /// ```
405 #[inline]
getrandom_uninit(dest: &mut [MaybeUninit<u8>]) -> Result<&mut [u8], Error>406 pub fn getrandom_uninit(dest: &mut [MaybeUninit<u8>]) -> Result<&mut [u8], Error> {
407 if !dest.is_empty() {
408 imp::getrandom_inner(dest)?;
409 }
410 // SAFETY: `dest` has been fully initialized by `imp::getrandom_inner`
411 // since it returned `Ok`.
412 Ok(unsafe { slice_assume_init_mut(dest) })
413 }
414