Debian Codegraph @

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