Debian Codegraph @

.cargo/vendor/getrandom/README.md

raw
1 # getrandom: system's random number generator
2
3 [![Build Status]][GitHub Actions]
4 [![Crate]][crates.io]
5 [![Documentation]][docs.rs]
6 [![Dependency Status]][deps.rs]
7 [![Downloads]][crates.io]
8 [![License]][LICENSE-MIT]
9
10 `getrandom` is a Rust library for retrieving random data from (operating) system sources.
11
12 It is assumed that the system always provides high-quality, cryptographically secure random
13 data, ideally backed by hardware entropy sources. This crate derives its name from
14 the Linux `getrandom` syscall but is cross-platform, roughly supporting the same set
15 of platforms as Rust's `std` library.
16
17 This is a low-level API. Most users should prefer using a higher-level random-number
18 library like [`rand`].
19
20 [`rand`]: https://crates.io/crates/rand
21
22 ## Usage
23
24 Add the `getrandom` dependency to your `Cargo.toml` file:
25
26 ```toml
27 [dependencies]
28 getrandom = "0.3"
29 ```
30
31 Then invoke the `fill` function on a byte buffer to fill it with random data:
32
33 ```rust
34 fn get_random_u128() -> Result<u128, getrandom::Error> {
35 let mut buf = [0u8; 16];
36 getrandom::fill(&mut buf)?;
37 Ok(u128::from_ne_bytes(buf))
38 }
39 ```
40
41 ## Supported targets
42
43 | Target | Target Triple | Implementation
44 | ------------------ | ------------------ | --------------
45 | Linux, Android | `*‑linux‑*` | [`getrandom`][1] system call if available, otherwise [`/dev/urandom`][2] after successfully polling `/dev/random`
46 | Windows 10+ | `*‑windows‑*` | [`ProcessPrng`] on Rust 1.78+, [`RtlGenRandom`] otherwise
47 | Windows 7, 8 | `*-win7‑windows‑*` | [`RtlGenRandom`]
48 | macOS | `*‑apple‑darwin` | [`getentropy`][3]
49 | iOS, tvOS, watchOS | `*‑apple‑{ios,tvos,watchos}` | [`CCRandomGenerateBytes`]
50 | FreeBSD | `*‑freebsd` | [`getrandom`][5]
51 | OpenBSD | `*‑openbsd` | [`getentropy`][7]
52 | NetBSD | `*‑netbsd` | [`getrandom`][16] if available, otherwise [`kern.arandom`][8]
53 | Dragonfly BSD | `*‑dragonfly` | [`getrandom`][9]
54 | Solaris | `*‑solaris` | [`getrandom`][11] with `GRND_RANDOM`
55 | illumos | `*‑illumos` | [`getrandom`][12]
56 | Fuchsia OS | `*‑fuchsia` | [`cprng_draw`]
57 | Redox | `*‑redox` | `/dev/urandom`
58 | Haiku | `*‑haiku` | `/dev/urandom` (identical to `/dev/random`)
59 | Hermit | `*-hermit` | [`sys_read_entropy`]
60 | Hurd | `*-hurd-*` | [`getrandom`][17]
61 | SGX | `x86_64‑*‑sgx` | [`RDRAND`]
62 | VxWorks | `*‑wrs‑vxworks‑*` | `randABytes` after checking entropy pool initialization with `randSecure`
63 | Emscripten | `*‑emscripten` | [`getentropy`][13]
64 | WASI 0.1 | `wasm32‑wasip1` | [`random_get`]
65 | WASI 0.2 | `wasm32‑wasip2` | [`get-random-u64`]
66 | SOLID | `*-kmc-solid_*` | `SOLID_RNG_SampleRandomBytes`
67 | Nintendo 3DS | `*-nintendo-3ds` | [`getrandom`][18]
68 | ESP-IDF | `*‑espidf` | [`esp_fill_random`] WARNING: see "Early Boot" section below
69 | PS Vita | `*-vita-*` | [`getentropy`][19]
70 | QNX Neutrino | `*‑nto-qnx*` | [`/dev/urandom`][14] (identical to `/dev/random`)
71 | AIX | `*-ibm-aix` | [`/dev/urandom`][15]
72 | Cygwin | `*-cygwin` | [`getrandom`][20] (based on [`RtlGenRandom`])
73
74 Pull Requests that add support for new targets to `getrandom` are always welcome.
75
76 ### Opt-in backends
77
78 `getrandom` also provides optional (opt-in) backends, which allow users to customize the source
79 of randomness based on their specific needs:
80
81 | Backend name | Target | Target Triple | Implementation
82 | ----------------- | -------------------- | ------------------------ | --------------
83 | `linux_getrandom` | Linux, Android | `*‑linux‑*` | [`getrandom`][1] system call (without `/dev/urandom` fallback). Bumps minimum supported Linux kernel version to 3.17 and Android API level to 23 (Marshmallow).
84 | `linux_raw` | Linux, Android | `*‑linux‑*` | Same as `linux_getrandom`, but uses raw `asm!`-based syscalls instead of `libc`.
85 | `rdrand` | x86, x86-64 | `x86_64-*`, `i686-*` | [`RDRAND`] instruction
86 | `rndr` | AArch64 | `aarch64-*` | [`RNDR`] register
87 | `wasm_js` | Web Browser, Node.js | `wasm32‑unknown‑unknown`, `wasm32v1-none` | [`Crypto.getRandomValues`]. Enabled by the `wasm_js` feature ([see below](#webassembly-support)).
88 | `efi_rng` | UEFI | `*-unknown‑uefi` | [`EFI_RNG_PROTOCOL`] with `EFI_RNG_ALGORITHM_RAW` (requires `std` and Nightly compiler)
89 | `windows_legacy` | Windows | `*-windows-*` | [`RtlGenRandom`]
90 | `custom` | All targets | `*` | User-provided custom implementation (see [custom backend])
91 | `unsupported` | All targets | `*` | Always returns `Err(Error::UNSUPPORTED)` (see [unsupported backend])
92
93 Opt-in backends can be enabled using the `getrandom_backend` configuration flag.
94 The flag can be set either by specifying the `rustflags` field in [`.cargo/config.toml`]:
95 ```toml
96 # It's recommended to set the flag on a per-target basis:
97 [target.wasm32-unknown-unknown]
98 rustflags = ['--cfg', 'getrandom_backend="wasm_js"']
99 ```
100
101 Or by using the `RUSTFLAGS` environment variable:
102
103 ```sh
104 RUSTFLAGS='--cfg getrandom_backend="linux_getrandom"' cargo build
105 ```
106
107 Enabling an opt-in backend will replace the backend used by default. Doing this for
108 an incorrect target (e.g. using `linux_getrandom` while compiling for a Windows target)
109 will result in a compilation error. Be extremely careful while using opt-in backends,
110 as incorrect configuration may result in vulnerable applications or applications
111 that always panic.
112
113 Note that using an opt-in backend in a library (e.g. for tests or benchmarks)
114 WILL NOT have any effect on its downstream users.
115
116 [`.cargo/config.toml`]: https://doc.rust-lang.org/cargo/reference/config.html
117
118 ### Raw Linux syscall support
119
120 Currently the `linux_raw` backend supports only targets with stabilized `asm!` macro,
121 i.e. `arm`, `aarch64`, `loongarch64`, `riscv32`, `riscv64`, `s390x`, `x86`, and `x86_64`.
122
123 Note that the raw syscall backend may be slower than backends based on `libc::getrandom`,
124 e.g. it does not implement vDSO optimizations and on `x86` it uses the infamously slow
125 `int 0x80` instruction to perform syscall.
126
127 ### WebAssembly support
128
129 This crate fully supports the [WASI] and [Emscripten] targets. However,
130 the `wasm32-unknown-unknown` target (i.e. the target used by `wasm-pack`)
131 is not automatically supported since, from the target name alone, we cannot deduce
132 which JavaScript interface should be used (or if JavaScript is available at all).
133
134 We do not include support for this target in the default configuration because
135 our JS backend (supporting web browsers, web workers and Node.js v19 or later)
136 requires [`wasm-bindgen`], **bloating `Cargo.lock`** and
137 **potentially breaking builds** on non-web WASM platforms.
138
139 To enable `getrandom`'s functionality on `wasm32-unknown-unknown` using the Web
140 Crypto methods [described above][opt-in] via [`wasm-bindgen`], enable the
141 `wasm_js` feature flag. Setting `RUSTFLAGS='--cfg getrandom_backend="wasm_js"'`
142 is allowed but is no longer required and does nothing (it was required in a
143 prior version of this crate).
144
145 WARNING: enabling the `wasm_js` feature will bloat `Cargo.lock` on all platforms
146 (where [`wasm-bindgen`] is not an existing dependency) and is known to cause
147 build issues on some non-web WASM platforms, even when a different backend is
148 selected via `getrandom_backend`.
149
150 ### Custom backend
151
152 If this crate does not support your target out of the box or you have to use
153 a non-default entropy source, then you can provide a custom implementation.
154 You need to enable the custom backend as described in the
155 [opt-in backends][opt-in] section.
156
157 Next, you need to define an `extern` function with the following signature:
158
159 ```rust
160 use getrandom::Error;
161
162 #[no_mangle]
163 unsafe extern "Rust" fn __getrandom_v03_custom(
164 dest: *mut u8,
165 len: usize,
166 ) -> Result<(), Error> {
167 todo!()
168 }
169 ```
170
171 This function should, ideally, be defined in the root crate of your project,
172 e.g. in your `main.rs`. This function MUST be defined only once for your
173 project, i.e. upstream library crates SHOULD NOT define it outside of
174 tests and benchmarks. Improper configuration of this backend may result
175 in linking errors.
176
177 The function accepts a pointer to a buffer that should be filled with random
178 data and its length in bytes. Note that the buffer MAY be uninitialized.
179 On success, the function should return `Ok(())` and fully fill the input buffer;
180 otherwise, it should return an error value.
181
182 While wrapping functions which work with byte slices you should fully initialize
183 the buffer before passing it to the function:
184 ```rust
185 use getrandom::Error;
186
187 fn my_entropy_source(buf: &mut [u8]) -> Result<(), getrandom::Error> {
188 // ...
189 Ok(())
190 }
191
192 #[no_mangle]
193 unsafe extern "Rust" fn __getrandom_v03_custom(
194 dest: *mut u8,
195 len: usize,
196 ) -> Result<(), Error> {
197 let buf = unsafe {
198 // fill the buffer with zeros
199 core::ptr::write_bytes(dest, 0, len);
200 // create mutable byte slice
201 core::slice::from_raw_parts_mut(dest, len)
202 };
203 my_entropy_source(buf)
204 }
205 ```
206
207 ### Unsupported backend
208
209 In some rare scenarios, you might be compiling this crate for an unsupported
210 target (e.g. `wasm32-unknown-unknown`), but this crate's functionality
211 is not actually used by your code. If you are confident that `getrandom` is
212 not used in your project, but it gets pulled nevertheless by one of your
213 dependencies, then you can enable the `unsupported` backend, which always
214 returns `Err(Error::UNSUPPORTED)`.
215
216 ### Platform Support
217
218 This crate generally supports the same operating system and platform versions
219 that the Rust standard library does. Additional targets may be supported using
220 the opt-in custom backend.
221
222 This means that as Rust drops support for old versions of operating systems
223 (such as old Linux kernel versions, Android API levels, etc.) in stable releases,
224 `getrandom` may create new patch releases that remove support for
225 outdated platform versions.
226
227 ### `/dev/urandom` fallback on Linux and Android
228
229 On Linux targets, the `/dev/urandom` fallback is present only if either `target_env`
230 is `musl`, or `target_arch` is one of the following: `aarch64`, `arm`, `powerpc`,
231 `powerpc64`, `s390x`, `x86`, `x86_64`. Other supported targets [require][platform-support]
232 kernel versions that support the `getrandom` system call, so the fallback is not needed.
233
234 On Android targets the fallback is present only for the following `target_arch`es:
235 `aarch64`, `arm`, `x86`, `x86_64`. Other `target_arch`es (e.g. RISC-V) require
236 sufficiently high API levels.
237
238 The fallback can be disabled by enabling the `linux_getrandom` opt-in backend.
239 Note that doing so will bump minimum supported Linux kernel version to 3.17
240 and Android API level to 23 (Marshmallow).
241
242 ### Early boot
243
244 Sometimes, early in the boot process, the OS has not collected enough
245 entropy to securely seed its RNG. This is especially common on virtual
246 machines, where standard "random" events are hard to come by.
247
248 Some operating system interfaces always block until the RNG is securely
249 seeded. This can take anywhere from a few seconds to more than a minute.
250 A few (Linux, NetBSD and Solaris) offer a choice between blocking and
251 getting an error; in these cases, we always choose to block.
252
253 On Linux (when the `getrandom` system call is not available), reading from
254 `/dev/urandom` never blocks, even when the OS hasn't collected enough
255 entropy yet. To avoid returning low-entropy bytes, we first poll
256 `/dev/random` and only switch to `/dev/urandom` once this has succeeded.
257
258 On OpenBSD, this kind of entropy accounting isn't available, and on
259 NetBSD, blocking on it is discouraged. On these platforms, nonblocking
260 interfaces are used, even when reliable entropy may not be available.
261 On the platforms where it is used, the reliability of entropy accounting
262 itself isn't free from controversy. This library provides randomness
263 sourced according to the platform's best practices, but each platform has
264 its own limits on the grade of randomness it can promise in environments
265 with few sources of entropy.
266
267 On ESP-IDF, if `esp_fill_random` is used before enabling WiFi, BT, or the
268 voltage noise entropy source (SAR ADC), the Hardware RNG will only be seeded
269 via RC_FAST_CLK. This can occur during early boot unless
270 `bootloader_random_enable()` is called. For more information see the
271 [ESP-IDF RNG Docs][esp-idf-rng] or the
272 [RNG section of the ESP32 Technical Reference Manual][esp-trng-docs].
273
274 ## Error handling
275
276 We always prioritize failure over returning known insecure "random" bytes.
277 Generally, on supported platforms, failure is highly unlikely, though not
278 impossible. If an error does occur, it is likely that it will occur
279 on every call to `getrandom`. Therefore, after the first successful call,
280 one can be reasonably confident that no errors will occur.
281
282 ## Panic handling
283
284 We strive to eliminate all potential panics from our backend implementations.
285 In other words, when compiled with optimizations enabled, the generated
286 binary code for `getrandom` functions should not contain any panic branches.
287 Even if the platform misbehaves and returns an unexpected result,
288 our code should correctly handle it and return an error, e.g.
289 [`Error::UNEXPECTED`].
290
291 ## Sanitizer support
292
293 If your code uses [`fill_uninit`] and you enable
294 [MemorySanitizer](https://doc.rust-lang.org/beta/unstable-book/compiler-flags/sanitizer.html#memorysanitizer)
295 (i.e. `-Zsanitizer=memory`), we will automatically handle unpoisoning
296 of the destination buffer filled by `fill_uninit`.
297
298 You can run sanitizer tests for your crate dependent on `getrandom` like this:
299 ```sh
300 RUSTFLAGS="-Zsanitizer=memory" cargo test -Zbuild-std --target=x86_64-unknown-linux-gnu
301 ```
302
303 ## Minimum Supported Rust Version
304
305 This crate requires Rust 1.63 or later.
306
307 ## License
308
309 The `getrandom` library is distributed under either of
310
311 * [Apache License, Version 2.0][LICENSE-APACHE]
312 * [MIT license][LICENSE-MIT]
313
314 at your option.
315
316 ### Contribution
317
318 Unless you explicitly state otherwise, any contribution intentionally submitted
319 for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
320 dual licensed as above, without any additional terms or conditions.
321
322 [//]: # (badges)
323
324 [GitHub Actions]: https://github.com/rust-random/getrandom/actions?query=branch:master
325 [Build Status]: https://github.com/rust-random/getrandom/actions/workflows/tests.yml/badge.svg?branch=master
326 [crates.io]: https://crates.io/crates/getrandom
327 [Crate]: https://img.shields.io/crates/v/getrandom
328 [docs.rs]: https://docs.rs/getrandom
329 [Documentation]: https://docs.rs/getrandom/badge.svg
330 [deps.rs]: https://deps.rs/repo/github/rust-random/getrandom
331 [Dependency Status]: https://deps.rs/repo/github/rust-random/getrandom/status.svg
332 [Downloads]: https://img.shields.io/crates/d/getrandom
333 [License]: https://img.shields.io/crates/l/getrandom
334
335 [//]: # (supported targets)
336
337 [1]: https://manned.org/getrandom.2
338 [2]: https://manned.org/urandom.4
339 [3]: https://www.unix.com/man-page/mojave/2/getentropy/
340 [4]: https://www.unix.com/man-page/mojave/4/urandom/
341 [5]: https://www.freebsd.org/cgi/man.cgi?query=getrandom&manpath=FreeBSD+12.0-stable
342 [7]: https://man.openbsd.org/getentropy.2
343 [8]: https://man.netbsd.org/sysctl.7
344 [9]: https://leaf.dragonflybsd.org/cgi/web-man?command=getrandom
345 [11]: https://docs.oracle.com/cd/E88353_01/html/E37841/getrandom-2.html
346 [12]: https://illumos.org/man/2/getrandom
347 [13]: https://github.com/emscripten-core/emscripten/pull/12240
348 [14]: https://www.qnx.com/developers/docs/7.1/index.html#com.qnx.doc.neutrino.utilities/topic/r/random.html
349 [15]: https://www.ibm.com/docs/en/aix/7.3?topic=files-random-urandom-devices
350 [16]: https://man.netbsd.org/getrandom.2
351 [17]: https://www.gnu.org/software/libc/manual/html_mono/libc.html#index-getrandom
352 [18]: https://github.com/rust3ds/shim-3ds/commit/b01d2568836dea2a65d05d662f8e5f805c64389d
353 [19]: https://github.com/vitasdk/newlib/blob/2d869fe47aaf02b8e52d04e9a2b79d5b210fd016/newlib/libc/sys/vita/getentropy.c
354 [20]: https://github.com/cygwin/cygwin/blob/main/winsup/cygwin/libc/getentropy.cc
355
356 [`ProcessPrng`]: https://learn.microsoft.com/en-us/windows/win32/seccng/processprng
357 [`RtlGenRandom`]: https://learn.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom
358 [`Crypto.getRandomValues`]: https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues
359 [`RDRAND`]: https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide
360 [`RNDR`]: https://developer.arm.com/documentation/ddi0601/2024-06/AArch64-Registers/RNDR--Random-Number
361 [`CCRandomGenerateBytes`]: https://opensource.apple.com/source/CommonCrypto/CommonCrypto-60074/include/CommonRandom.h.auto.html
362 [`cprng_draw`]: https://fuchsia.dev/fuchsia-src/zircon/syscalls/cprng_draw
363 [`esp_fill_random`]: https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/random.html#functions
364 [esp-idf-rng]: https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/random.html
365 [esp-trng-docs]: https://www.espressif.com/sites/default/files/documentation/esp32_technical_reference_manual_en.pdf#rng
366 [`EFI_RNG_PROTOCOL`]: https://uefi.org/specs/UEFI/2.10/37_Secure_Technologies.html#efi-rng-protocol
367 [`random_get`]: https://github.com/WebAssembly/WASI/blob/snapshot-01/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---errno
368 [`get-random-u64`]: https://github.com/WebAssembly/WASI/blob/v0.2.1/wasip2/random/random.wit#L23-L28
369 [configuration flags]: #configuration-flags
370 [custom backend]: #custom-backend
371 [unsupported backend]: #unsupported-backend
372 [`wasm-bindgen`]: https://github.com/rustwasm/wasm-bindgen
373 [`module`]: https://rustwasm.github.io/wasm-bindgen/reference/attributes/on-js-imports/module.html
374 [`sys_read_entropy`]: https://github.com/hermit-os/kernel/blob/315f58ff5efc81d9bf0618af85a59963ff55f8b1/src/syscalls/entropy.rs#L47-L55
375 [platform-support]: https://doc.rust-lang.org/stable/rustc/platform-support.html
376 [WASI]: https://github.com/WebAssembly/WASI
377 [Emscripten]: https://emscripten.org
378 [opt-in]: #opt-in-backends
379
380 [//]: # (licenses)
381
382 [LICENSE-APACHE]: https://github.com/rust-random/getrandom/blob/master/LICENSE-APACHE
383 [LICENSE-MIT]: https://github.com/rust-random/getrandom/blob/master/LICENSE-MIT
384
385 [`Error::UNEXPECTED`]: https://docs.rs/getrandom/latest/getrandom/struct.Error.html#associatedconstant.UNEXPECTED
386 [`fill_uninit`]: https://docs.rs/getrandom/latest/getrandom/fn.fill_uninit.html