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/urandom`][4] (identical to `/dev/random`) |
18 | //! | iOS, tvOS, watchOS | `*‑apple‑ios`, `*-apple-tvos`, `*-apple-watchos` | [`SecRandomCopyBytes`] |
19 | //! | FreeBSD | `*‑freebsd` | [`getrandom`][5] if available, otherwise [`kern.arandom`][6] |
20 | //! | OpenBSD | `*‑openbsd` | [`getentropy`][7] |
21 | //! | NetBSD | `*‑netbsd` | [`getrandom`][16] if available, otherwise [`kern.arandom`][8] |
22 | //! | Dragonfly BSD | `*‑dragonfly` | [`getrandom`][9] if available, otherwise [`/dev/urandom`][10] (identical to `/dev/random`) |
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/urandom` (identical to `/dev/random`) |
27 | //! | Hermit | `*-hermit` | [`sys_read_entropy`] |
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` | [`getentropy`][13] |
32 | //! | WASI | `wasm32‑wasi` | [`random_get`] |
33 | //! | Web Browser and Node.js | `wasm*‑*‑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 | //! | PS Vita | `armv7-sony-vita-newlibeabihf` | [`getentropy`][13] |
37 | //! | QNX Neutrino | `*‑nto-qnx*` | [`/dev/urandom`][14] (identical to `/dev/random`) |
38 | //! | AIX | `*-ibm-aix` | [`/dev/urandom`][15] |
39 | //! |
40 | //! There is no blanket implementation on `unix` targets that reads from |
41 | //! `/dev/urandom`. This ensures all supported targets are using the recommended |
42 | //! interface and respect maximum buffer sizes. |
43 | //! |
44 | //! Pull Requests that add support for new targets to `getrandom` are always welcome. |
45 | //! |
46 | //! ## Unsupported targets |
47 | //! |
48 | //! By default, `getrandom` will not compile on unsupported targets, but certain |
49 | //! features allow a user to select a "fallback" implementation if no supported |
50 | //! implementation exists. |
51 | //! |
52 | //! All of the below mechanisms only affect unsupported |
53 | //! targets. Supported targets will _always_ use their supported implementations. |
54 | //! This prevents a crate from overriding a secure source of randomness |
55 | //! (either accidentally or intentionally). |
56 | //! |
57 | //! ### RDRAND on x86 |
58 | //! |
59 | //! *If the `rdrand` Cargo feature is enabled*, `getrandom` will fallback to using |
60 | //! the [`RDRAND`] instruction to get randomness on `no_std` `x86`/`x86_64` |
61 | //! targets. This feature has no effect on other CPU architectures. |
62 | //! |
63 | //! ### WebAssembly support |
64 | //! |
65 | //! This crate fully supports the |
66 | //! [`wasm32-wasi`](https://github.com/CraneStation/wasi) and |
67 | //! [`wasm32-unknown-emscripten`](https://www.hellorust.com/setup/emscripten/) |
68 | //! targets. However, the `wasm32-unknown-unknown` target (i.e. the target used |
69 | //! by `wasm-pack`) is not automatically |
70 | //! supported since, from the target name alone, we cannot deduce which |
71 | //! JavaScript interface is in use (or if JavaScript is available at all). |
72 | //! |
73 | //! Instead, *if the `js` Cargo feature is enabled*, this crate will assume |
74 | //! that you are building for an environment containing JavaScript, and will |
75 | //! call the appropriate methods. Both web browser (main window and Web Workers) |
76 | //! and Node.js environments are supported, invoking the methods |
77 | //! [described above](#supported-targets) using the [`wasm-bindgen`] toolchain. |
78 | //! |
79 | //! To enable the `js` Cargo feature, add the following to the `dependencies` |
80 | //! section in your `Cargo.toml` file: |
81 | //! ```toml |
82 | //! [dependencies] |
83 | //! getrandom = { version = "0.2", features = ["js"] } |
84 | //! ``` |
85 | //! |
86 | //! This can be done even if `getrandom` is not a direct dependency. Cargo |
87 | //! allows crates to enable features for indirect dependencies. |
88 | //! |
89 | //! This feature should only be enabled for binary, test, or benchmark crates. |
90 | //! Library crates should generally not enable this feature, leaving such a |
91 | //! decision to *users* of their library. Also, libraries should not introduce |
92 | //! their own `js` features *just* to enable `getrandom`'s `js` feature. |
93 | //! |
94 | //! This feature has no effect on targets other than `wasm32-unknown-unknown`. |
95 | //! |
96 | //! #### Node.js ES module support |
97 | //! |
98 | //! Node.js supports both [CommonJS modules] and [ES modules]. Due to |
99 | //! limitations in wasm-bindgen's [`module`] support, we cannot directly |
100 | //! support ES Modules running on Node.js. However, on Node v15 and later, the |
101 | //! module author can add a simple shim to support the Web Cryptography API: |
102 | //! ```js |
103 | //! import { webcrypto } from 'node:crypto' |
104 | //! globalThis.crypto = webcrypto |
105 | //! ``` |
106 | //! This crate will then use the provided `webcrypto` implementation. |
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§ion=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 | //! |
170 | //! [`BCryptGenRandom`]: https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom |
171 | //! [`Crypto.getRandomValues`]: https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues |
172 | //! [`RDRAND`]: https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide |
173 | //! [`SecRandomCopyBytes`]: https://developer.apple.com/documentation/security/1399291-secrandomcopybytes?language=objc |
174 | //! [`cprng_draw`]: https://fuchsia.dev/fuchsia-src/zircon/syscalls/cprng_draw |
175 | //! [`crypto.randomFillSync`]: https://nodejs.org/api/crypto.html#cryptorandomfillsyncbuffer-offset-size |
176 | //! [`esp_fill_random`]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html#_CPPv415esp_fill_randomPv6size_t |
177 | //! [`random_get`]: https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---errno |
178 | //! [WebAssembly support]: #webassembly-support |
179 | //! [`wasm-bindgen`]: https://github.com/rustwasm/wasm-bindgen |
180 | //! [`module`]: https://rustwasm.github.io/wasm-bindgen/reference/attributes/on-js-imports/module.html |
181 | //! [CommonJS modules]: https://nodejs.org/api/modules.html |
182 | //! [ES modules]: https://nodejs.org/api/esm.html |
183 | //! [`sys_read_entropy`]: https://hermitcore.github.io/libhermit-rs/hermit/fn.sys_read_entropy.html |
184 | |
185 | #![doc ( |
186 | html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png" , |
187 | html_favicon_url = "https://www.rust-lang.org/favicon.ico" , |
188 | html_root_url = "https://docs.rs/getrandom/0.2.10" |
189 | )] |
190 | #![no_std ] |
191 | #![warn (rust_2018_idioms, unused_lifetimes, missing_docs)] |
192 | #![cfg_attr (docsrs, feature(doc_cfg))] |
193 | |
194 | #[macro_use ] |
195 | extern crate cfg_if; |
196 | |
197 | use crate::util::{slice_as_uninit_mut, slice_assume_init_mut}; |
198 | use core::mem::MaybeUninit; |
199 | |
200 | mod error; |
201 | mod util; |
202 | // To prevent a breaking change when targets are added, we always export the |
203 | // register_custom_getrandom macro, so old Custom RNG crates continue to build. |
204 | #[cfg (feature = "custom" )] |
205 | mod custom; |
206 | #[cfg (feature = "std" )] |
207 | mod error_impls; |
208 | |
209 | pub use crate::error::Error; |
210 | |
211 | // System-specific implementations. |
212 | // |
213 | // These should all provide getrandom_inner with the signature |
214 | // `fn getrandom_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error>`. |
215 | // The function MUST fully initialize `dest` when `Ok(())` is returned. |
216 | // The function MUST NOT ever write uninitialized bytes into `dest`, |
217 | // regardless of what value it returns. |
218 | cfg_if! { |
219 | if #[cfg(any(target_os = "haiku" , target_os = "redox" , target_os = "nto" , target_os = "aix" ))] { |
220 | mod util_libc; |
221 | #[path = "use_file.rs" ] mod imp; |
222 | } else if #[cfg(any(target_os = "android" , target_os = "linux" ))] { |
223 | mod util_libc; |
224 | mod use_file; |
225 | #[path = "linux_android.rs" ] mod imp; |
226 | } else if #[cfg(any(target_os = "illumos" , target_os = "solaris" ))] { |
227 | mod util_libc; |
228 | mod use_file; |
229 | #[path = "solaris_illumos.rs" ] mod imp; |
230 | } else if #[cfg(any(target_os = "freebsd" , target_os = "netbsd" ))] { |
231 | mod util_libc; |
232 | #[path = "bsd_arandom.rs" ] mod imp; |
233 | } else if #[cfg(target_os = "dragonfly" )] { |
234 | mod util_libc; |
235 | mod use_file; |
236 | #[path = "dragonfly.rs" ] mod imp; |
237 | } else if #[cfg(target_os = "fuchsia" )] { |
238 | #[path = "fuchsia.rs" ] mod imp; |
239 | } else if #[cfg(any(target_os = "ios" , target_os = "watchos" , target_os = "tvos" ))] { |
240 | #[path = "apple-other.rs" ] mod imp; |
241 | } else if #[cfg(target_os = "macos" )] { |
242 | mod util_libc; |
243 | mod use_file; |
244 | #[path = "macos.rs" ] mod imp; |
245 | } else if #[cfg(target_os = "openbsd" )] { |
246 | mod util_libc; |
247 | #[path = "openbsd.rs" ] mod imp; |
248 | } else if #[cfg(all(target_arch = "wasm32" , target_os = "wasi" ))] { |
249 | #[path = "wasi.rs" ] mod imp; |
250 | } else if #[cfg(target_os = "hermit" )] { |
251 | #[path = "hermit.rs" ] mod imp; |
252 | } else if #[cfg(target_os = "vxworks" )] { |
253 | mod util_libc; |
254 | #[path = "vxworks.rs" ] mod imp; |
255 | } else if #[cfg(target_os = "solid_asp3" )] { |
256 | #[path = "solid.rs" ] mod imp; |
257 | } else if #[cfg(target_os = "espidf" )] { |
258 | #[path = "espidf.rs" ] mod imp; |
259 | } else if #[cfg(windows)] { |
260 | #[path = "windows.rs" ] mod imp; |
261 | } else if #[cfg(all(target_os = "horizon" , target_arch = "arm" ))] { |
262 | // We check for target_arch = "arm" because the Nintendo Switch also |
263 | // uses Horizon OS (it is aarch64). |
264 | mod util_libc; |
265 | #[path = "3ds.rs" ] mod imp; |
266 | } else if #[cfg(target_os = "vita" )] { |
267 | mod util_libc; |
268 | #[path = "vita.rs" ] mod imp; |
269 | } else if #[cfg(target_os = "emscripten" )] { |
270 | mod util_libc; |
271 | #[path = "emscripten.rs" ] mod imp; |
272 | } else if #[cfg(all(target_arch = "x86_64" , target_env = "sgx" ))] { |
273 | #[path = "rdrand.rs" ] mod imp; |
274 | } else if #[cfg(all(feature = "rdrand" , |
275 | any(target_arch = "x86_64" , target_arch = "x86" )))] { |
276 | #[path = "rdrand.rs" ] mod imp; |
277 | } else if #[cfg(all(feature = "js" , |
278 | any(target_arch = "wasm32" , target_arch = "wasm64" ), |
279 | target_os = "unknown" ))] { |
280 | #[path = "js.rs" ] mod imp; |
281 | } else if #[cfg(feature = "custom" )] { |
282 | use custom as imp; |
283 | } else if #[cfg(all(any(target_arch = "wasm32" , target_arch = "wasm64" ), |
284 | target_os = "unknown" ))] { |
285 | compile_error!("the wasm*-unknown-unknown targets are not supported by \ |
286 | default, you may need to enable the \"js \" feature. \ |
287 | For more information see: \ |
288 | https://docs.rs/getrandom/#webassembly-support" ); |
289 | } else { |
290 | compile_error!("target is not supported, for more information see: \ |
291 | https://docs.rs/getrandom/#unsupported-targets" ); |
292 | } |
293 | } |
294 | |
295 | /// Fill `dest` with random bytes from the system's preferred random number |
296 | /// source. |
297 | /// |
298 | /// This function returns an error on any failure, including partial reads. We |
299 | /// make no guarantees regarding the contents of `dest` on error. If `dest` is |
300 | /// empty, `getrandom` immediately returns success, making no calls to the |
301 | /// underlying operating system. |
302 | /// |
303 | /// Blocking is possible, at least during early boot; see module documentation. |
304 | /// |
305 | /// In general, `getrandom` will be fast enough for interactive usage, though |
306 | /// significantly slower than a user-space CSPRNG; for the latter consider |
307 | /// [`rand::thread_rng`](https://docs.rs/rand/*/rand/fn.thread_rng.html). |
308 | #[inline ] |
309 | pub fn getrandom(dest: &mut [u8]) -> Result<(), Error> { |
310 | // SAFETY: The `&mut MaybeUninit<_>` reference doesn't escape, and |
311 | // `getrandom_uninit` guarantees it will never de-initialize any part of |
312 | // `dest`. |
313 | getrandom_uninit(dest:unsafe { slice_as_uninit_mut(slice:dest) })?; |
314 | Ok(()) |
315 | } |
316 | |
317 | /// Version of the `getrandom` function which fills `dest` with random bytes |
318 | /// returns a mutable reference to those bytes. |
319 | /// |
320 | /// On successful completion this function is guaranteed to return a slice |
321 | /// which points to the same memory as `dest` and has the same length. |
322 | /// In other words, it's safe to assume that `dest` is initialized after |
323 | /// this function has returned `Ok`. |
324 | /// |
325 | /// No part of `dest` will ever be de-initialized at any point, regardless |
326 | /// of what is returned. |
327 | /// |
328 | /// # Examples |
329 | /// |
330 | /// ```ignore |
331 | /// # // We ignore this test since `uninit_array` is unstable. |
332 | /// #![feature(maybe_uninit_uninit_array)] |
333 | /// # fn main() -> Result<(), getrandom::Error> { |
334 | /// let mut buf = core::mem::MaybeUninit::uninit_array::<1024>(); |
335 | /// let buf: &mut [u8] = getrandom::getrandom_uninit(&mut buf)?; |
336 | /// # Ok(()) } |
337 | /// ``` |
338 | #[inline ] |
339 | pub fn getrandom_uninit(dest: &mut [MaybeUninit<u8>]) -> Result<&mut [u8], Error> { |
340 | if !dest.is_empty() { |
341 | imp::getrandom_inner(dest)?; |
342 | } |
343 | // SAFETY: `dest` has been fully initialized by `imp::getrandom_inner` |
344 | // since it returned `Ok`. |
345 | Ok(unsafe { slice_assume_init_mut(slice:dest) }) |
346 | } |
347 | |