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