Debian Codegraph @

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