rand/rngs/thread.rs
1// Copyright 2018 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//! Thread-local random number generator
10
11use core::{cell::UnsafeCell, convert::Infallible};
12use std::fmt;
13use std::rc::Rc;
14use std::thread_local;
15
16use super::{SysError, SysRng};
17use rand_core::SeedableRng;
18use rand_core::block::{BlockRng, Generator};
19use rand_core::{TryCryptoRng, TryRng};
20
21// Rationale for using `UnsafeCell` in `ThreadRng`:
22//
23// Previously we used a `RefCell`, with an overhead of ~15%. There will only
24// ever be one mutable reference to the interior of the `UnsafeCell`, because
25// we only have such a reference inside `next_u32`, `next_u64`, etc. Within a
26// single thread (which is the definition of `ThreadRng`), there will only ever
27// be one of these methods active at a time.
28//
29// A possible scenario where there could be multiple mutable references is if
30// `ThreadRng` is used inside `next_u32` and co. But the implementation is
31// completely under our control. We just have to ensure none of them use
32// `ThreadRng` internally, which is nonsensical anyway. We should also never run
33// `ThreadRng` in destructors of its implementation, which is also nonsensical.
34
35// Number of generated bytes after which to reseed `ThreadRng`.
36// According to benchmarks, reseeding has a noticeable impact with thresholds
37// of 32 kB and less. We choose 64 kiB output to avoid significant overhead;
38// since a block consists of 16 4-byte words this equals 1024 blocks.
39const RESEED_BLOCK_THRESHOLD: u64 = 1024;
40
41type Core = chacha20::ChaChaCore<chacha20::R12, chacha20::variants::Legacy>;
42type Results = <Core as Generator>::Output;
43
44struct ReseedingCore {
45 inner: Core,
46}
47
48impl Generator for ReseedingCore {
49 type Output = Results;
50
51 #[inline(always)]
52 fn generate(&mut self, results: &mut Results) {
53 if self.inner.get_block_pos() >= RESEED_BLOCK_THRESHOLD {
54 self.try_to_reseed();
55 }
56 self.inner.generate(results);
57 }
58}
59
60impl ReseedingCore {
61 /// Reseed the internal PRNG.
62 fn reseed(&mut self) -> Result<(), SysError> {
63 Core::try_from_rng(&mut SysRng).map(|result| self.inner = result)
64 }
65
66 #[cold]
67 #[inline(never)]
68 fn try_to_reseed(&mut self) {
69 if let Err(e) = self.reseed() {
70 panic!("could not reseed ThreadRng: {e}");
71 }
72 }
73}
74
75/// A reference to the thread-local generator
76///
77/// This type is a reference to a lazily-initialized thread-local generator.
78/// An instance can be obtained via [`rand::rng()`][crate::rng()] or via
79/// [`ThreadRng::default()`].
80/// The handle cannot be passed between threads (is not `Send` or `Sync`).
81///
82/// # Security
83///
84/// Security must be considered relative to a threat model and validation
85/// requirements. The Rand project can provide no guarantee of fitness for
86/// purpose. The design criteria for `ThreadRng` are as follows:
87///
88/// - Automatic seeding via [`SysRng`] and after every 64 kB of output.
89/// Limitation: there is no automatic reseeding on process fork or virtual
90/// machine snapshot/restore (see [below](#special-cases)).
91/// - A rigorously analyzed, unpredictable (cryptographic) pseudo-random generator
92/// (see [the book on security](https://rust-random.github.io/book/guide-rngs.html#security)).
93/// The currently selected algorithm is ChaCha (12-rounds).
94/// See also [`StdRng`] documentation.
95/// - Not to leak internal state through [`Debug`] or serialization
96/// implementations.
97/// - No further protections exist to in-memory state. In particular, the
98/// implementation is not required to zero memory on exit (of the process or
99/// thread). (This may change in the future.)
100/// - Be fast enough for general-purpose usage. Note in particular that
101/// `ThreadRng` is designed to be a "fast, reasonably secure generator"
102/// (where "reasonably secure" implies the above criteria).
103///
104/// We leave it to the user to determine whether this generator meets their
105/// security requirements. For an alternative, see [`SysRng`].
106///
107/// # Special cases
108///
109/// ## Fork
110///
111/// `ThreadRng` is not automatically reseeded on fork. It is recommended to
112/// explicitly call [`ThreadRng::reseed`] immediately after a fork, for example:
113/// ```ignore
114/// fn do_fork() {
115/// let pid = unsafe { libc::fork() };
116/// if pid == 0 {
117/// // Reseed ThreadRng in child processes:
118/// rand::rng().reseed();
119/// }
120/// }
121/// ```
122///
123/// (Note that this relies on the assumption that the new process only has a
124/// single thread; see also [`ThreadRng::reseed`] documentation.)
125///
126/// ## Interrupt
127///
128/// Methods on `ThreadRng` are not reentrant-safe and thus should not be called
129/// from an interrupt (e.g. a fork handler) unless it can be guaranteed that no
130/// other method on the same `ThreadRng` is currently executing.
131///
132/// ## Snapshot and restore
133///
134/// Checkpoint-and-restore of a process (e.g. via CRIU) or a virtual machine
135/// allows duplication of an process. [`ThreadRng`] state is not automatically
136/// reseeded in this case.
137///
138/// Since it is not safe to assume that a snapshotted process has only a single
139/// thread, it may be difficult to reseed all [`ThreadRng`] instances using
140/// [`ThreadRng::reseed`]. We therefore recommend usage of [`SysRng`] instead
141/// for all secret generation where VM snapshots may be used.
142///
143/// # Panics
144///
145/// Implementations of [`TryRng`] and [`Rng`] panic in case of [`SysRng`]
146/// failure during reseeding (highly unlikely).
147///
148/// [`StdRng`]: crate::rngs::StdRng
149/// [`Rng`]: rand_core::Rng
150#[derive(Clone)]
151pub struct ThreadRng {
152 // Rc is explicitly !Send and !Sync
153 rng: Rc<UnsafeCell<BlockRng<ReseedingCore>>>,
154}
155
156impl ThreadRng {
157 /// Immediately reseed the generator on the current thread
158 ///
159 /// This discards any remaining random data in the cache.
160 ///
161 /// Note that [`ThreadRng`] has one instance per thread and this method only
162 /// affects the instance on the current thread.
163 pub fn reseed(&mut self) -> Result<(), SysError> {
164 // SAFETY: We must make sure to stop using `rng` before anyone else
165 // creates another mutable reference
166 let rng = unsafe { &mut *self.rng.get() };
167 rng.reset_and_skip(0);
168 rng.core.reseed()
169 }
170}
171
172/// Debug implementation does not leak internal state
173impl fmt::Debug for ThreadRng {
174 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
175 write!(fmt, "ThreadRng {{ .. }}")
176 }
177}
178
179thread_local!(
180 // We require Rc<..> to avoid premature freeing when ThreadRng is used
181 // within thread-local destructors. See #968.
182 static THREAD_RNG_KEY: Rc<UnsafeCell<BlockRng<ReseedingCore>>> = {
183 Rc::new(UnsafeCell::new(BlockRng::new(ReseedingCore {
184 inner: Core::try_from_rng(&mut SysRng).unwrap_or_else(|err| {
185 panic!("could not initialize ThreadRng: {}", err)
186 }),
187 })))
188 }
189);
190
191/// Access a fast, pre-initialized generator
192///
193/// This is a handle to the local [`ThreadRng`].
194///
195/// See also [`crate::rngs`] for alternatives.
196///
197/// # Example
198///
199/// ```
200/// use rand::prelude::*;
201///
202/// # fn main() {
203///
204/// let mut numbers = [1, 2, 3, 4, 5];
205/// numbers.shuffle(&mut rand::rng());
206/// println!("Numbers: {numbers:?}");
207///
208/// // Using a local binding avoids an initialization-check on each usage:
209/// let mut rng = rand::rng();
210///
211/// println!("True or false: {}", rng.random::<bool>());
212/// println!("A simulated die roll: {}", rng.random_range(1..=6));
213/// # }
214/// ```
215///
216/// # Security
217///
218/// Refer to [`ThreadRng#Security`].
219///
220/// # Panics
221///
222/// This method panics in case of [`SysRng`] failure during initial seeding.
223pub fn rng() -> ThreadRng {
224 let rng = THREAD_RNG_KEY.with(|t| t.clone());
225 ThreadRng { rng }
226}
227
228impl Default for ThreadRng {
229 fn default() -> ThreadRng {
230 rng()
231 }
232}
233
234impl TryRng for ThreadRng {
235 type Error = Infallible;
236
237 #[inline(always)]
238 fn try_next_u32(&mut self) -> Result<u32, Infallible> {
239 // SAFETY: We must make sure to stop using `rng` before anyone else
240 // creates another mutable reference
241 let rng = unsafe { &mut *self.rng.get() };
242 Ok(rng.next_word())
243 }
244
245 #[inline(always)]
246 fn try_next_u64(&mut self) -> Result<u64, Infallible> {
247 // SAFETY: We must make sure to stop using `rng` before anyone else
248 // creates another mutable reference
249 let rng = unsafe { &mut *self.rng.get() };
250 Ok(rng.next_u64_from_u32())
251 }
252
253 #[inline(always)]
254 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Infallible> {
255 // SAFETY: We must make sure to stop using `rng` before anyone else
256 // creates another mutable reference
257 let rng = unsafe { &mut *self.rng.get() };
258 rng.fill_bytes(dest);
259 Ok(())
260 }
261}
262
263impl TryCryptoRng for ThreadRng {}
264
265#[cfg(test)]
266mod test {
267 #[test]
268 fn test_thread_rng() {
269 use crate::RngExt;
270 let mut r = crate::rng();
271 r.random::<i32>();
272 assert_eq!(r.random_range(0..1), 0);
273 }
274
275 #[test]
276 fn test_debug_output() {
277 // We don't care about the exact output here, but it must not include
278 // private CSPRNG state or the cache stored by BlockRng!
279 assert_eq!(std::format!("{:?}", crate::rng()), "ThreadRng { .. }");
280 }
281}