]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/rand.rs
40885417308b80a2007591f17af0984a44215831
[rust.git] / library / std / src / sys / unix / rand.rs
1 pub fn hashmap_random_keys() -> (u64, u64) {
2     const KEY_LEN: usize = core::mem::size_of::<u64>();
3
4     let mut v = [0u8; KEY_LEN * 2];
5     imp::fill_bytes(&mut v);
6
7     let key1 = v[0..KEY_LEN].try_into().unwrap();
8     let key2 = v[KEY_LEN..].try_into().unwrap();
9
10     (u64::from_ne_bytes(key1), u64::from_ne_bytes(key2))
11 }
12
13 #[cfg(all(
14     unix,
15     not(target_os = "macos"),
16     not(target_os = "ios"),
17     not(target_os = "watchos"),
18     not(target_os = "openbsd"),
19     not(target_os = "freebsd"),
20     not(target_os = "netbsd"),
21     not(target_os = "fuchsia"),
22     not(target_os = "redox"),
23     not(target_os = "vxworks")
24 ))]
25 mod imp {
26     use crate::fs::File;
27     use crate::io::Read;
28
29     #[cfg(any(target_os = "linux", target_os = "android"))]
30     use crate::sys::weak::syscall;
31
32     #[cfg(any(target_os = "linux", target_os = "android"))]
33     fn getrandom(buf: &mut [u8]) -> libc::ssize_t {
34         use crate::sync::atomic::{AtomicBool, Ordering};
35         use crate::sys::os::errno;
36
37         // A weak symbol allows interposition, e.g. for perf measurements that want to
38         // disable randomness for consistency. Otherwise, we'll try a raw syscall.
39         // (`getrandom` was added in glibc 2.25, musl 1.1.20, android API level 28)
40         syscall! {
41             fn getrandom(
42                 buffer: *mut libc::c_void,
43                 length: libc::size_t,
44                 flags: libc::c_uint
45             ) -> libc::ssize_t
46         }
47
48         // This provides the best quality random numbers available at the given moment
49         // without ever blocking, and is preferable to falling back to /dev/urandom.
50         static GRND_INSECURE_AVAILABLE: AtomicBool = AtomicBool::new(true);
51         if GRND_INSECURE_AVAILABLE.load(Ordering::Relaxed) {
52             let ret = unsafe { getrandom(buf.as_mut_ptr().cast(), buf.len(), libc::GRND_INSECURE) };
53             if ret == -1 && errno() as libc::c_int == libc::EINVAL {
54                 GRND_INSECURE_AVAILABLE.store(false, Ordering::Relaxed);
55             } else {
56                 return ret;
57             }
58         }
59
60         unsafe { getrandom(buf.as_mut_ptr().cast(), buf.len(), libc::GRND_NONBLOCK) }
61     }
62
63     #[cfg(any(target_os = "espidf", target_os = "horizon"))]
64     fn getrandom(buf: &mut [u8]) -> libc::ssize_t {
65         unsafe { libc::getrandom(buf.as_mut_ptr().cast(), buf.len(), 0) }
66     }
67
68     #[cfg(not(any(
69         target_os = "linux",
70         target_os = "android",
71         target_os = "espidf",
72         target_os = "horizon"
73     )))]
74     fn getrandom_fill_bytes(_buf: &mut [u8]) -> bool {
75         false
76     }
77
78     #[cfg(any(
79         target_os = "linux",
80         target_os = "android",
81         target_os = "espidf",
82         target_os = "horizon"
83     ))]
84     fn getrandom_fill_bytes(v: &mut [u8]) -> bool {
85         use crate::sync::atomic::{AtomicBool, Ordering};
86         use crate::sys::os::errno;
87
88         static GETRANDOM_UNAVAILABLE: AtomicBool = AtomicBool::new(false);
89         if GETRANDOM_UNAVAILABLE.load(Ordering::Relaxed) {
90             return false;
91         }
92
93         let mut read = 0;
94         while read < v.len() {
95             let result = getrandom(&mut v[read..]);
96             if result == -1 {
97                 let err = errno() as libc::c_int;
98                 if err == libc::EINTR {
99                     continue;
100                 } else if err == libc::ENOSYS || err == libc::EPERM {
101                     // Fall back to reading /dev/urandom if `getrandom` is not
102                     // supported on the current kernel.
103                     //
104                     // Also fall back in case it is disabled by something like
105                     // seccomp or inside of virtual machines.
106                     GETRANDOM_UNAVAILABLE.store(true, Ordering::Relaxed);
107                     return false;
108                 } else if err == libc::EAGAIN {
109                     return false;
110                 } else {
111                     panic!("unexpected getrandom error: {err}");
112                 }
113             } else {
114                 read += result as usize;
115             }
116         }
117         true
118     }
119
120     pub fn fill_bytes(v: &mut [u8]) {
121         // getrandom_fill_bytes here can fail if getrandom() returns EAGAIN,
122         // meaning it would have blocked because the non-blocking pool (urandom)
123         // has not initialized in the kernel yet due to a lack of entropy. The
124         // fallback we do here is to avoid blocking applications which could
125         // depend on this call without ever knowing they do and don't have a
126         // work around. The PRNG of /dev/urandom will still be used but over a
127         // possibly predictable entropy pool.
128         if getrandom_fill_bytes(v) {
129             return;
130         }
131
132         // getrandom failed because it is permanently or temporarily (because
133         // of missing entropy) unavailable. Open /dev/urandom, read from it,
134         // and close it again.
135         let mut file = File::open("/dev/urandom").expect("failed to open /dev/urandom");
136         file.read_exact(v).expect("failed to read /dev/urandom")
137     }
138 }
139
140 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
141 mod imp {
142     use crate::io;
143     use crate::sys::weak::weak;
144     use libc::{c_int, c_void, size_t};
145
146     fn getentropy_fill_bytes(v: &mut [u8]) -> bool {
147         weak!(fn getentropy(*mut c_void, size_t) -> c_int);
148
149         getentropy
150             .get()
151             .map(|f| {
152                 // getentropy(2) permits a maximum buffer size of 256 bytes
153                 for s in v.chunks_mut(256) {
154                     let ret = unsafe { f(s.as_mut_ptr() as *mut c_void, s.len()) };
155                     if ret == -1 {
156                         panic!("unexpected getentropy error: {}", io::Error::last_os_error());
157                     }
158                 }
159                 true
160             })
161             .unwrap_or(false)
162     }
163
164     #[cfg(target_os = "macos")]
165     fn fallback_fill_bytes(v: &mut [u8]) {
166         use crate::fs::File;
167         use crate::io::Read;
168
169         let mut file = File::open("/dev/urandom").expect("failed to open /dev/urandom");
170         file.read_exact(v).expect("failed to read /dev/urandom")
171     }
172
173     // On iOS and MacOS `SecRandomCopyBytes` calls `CCRandomCopyBytes` with
174     // `kCCRandomDefault`. `CCRandomCopyBytes` manages a CSPRNG which is seeded
175     // from `/dev/random` and which runs on its own thread accessed via GCD.
176     //
177     // This is very heavyweight compared to the alternatives, but they may not be usable:
178     // - `getentropy` was added in iOS 10, but we support a minimum of iOS 7
179     // - `/dev/urandom` is not accessible inside the iOS app sandbox.
180     //
181     // Therefore `SecRandomCopyBytes` is only used on older iOS versions where no
182     // better options are present.
183     #[cfg(target_os = "ios")]
184     fn fallback_fill_bytes(v: &mut [u8]) {
185         use crate::ptr;
186
187         enum SecRandom {}
188
189         #[allow(non_upper_case_globals)]
190         const kSecRandomDefault: *const SecRandom = ptr::null();
191
192         extern "C" {
193             fn SecRandomCopyBytes(rnd: *const SecRandom, count: size_t, bytes: *mut u8) -> c_int;
194         }
195
196         let ret = unsafe { SecRandomCopyBytes(kSecRandomDefault, v.len(), v.as_mut_ptr()) };
197         if ret == -1 {
198             panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
199         }
200     }
201
202     // All supported versions of watchOS (>= 5) have support for `getentropy`.
203     #[cfg(target_os = "watchos")]
204     #[cold]
205     fn fallback_fill_bytes(_: &mut [u8]) {
206         unreachable!()
207     }
208
209     pub fn fill_bytes(v: &mut [u8]) {
210         if getentropy_fill_bytes(v) {
211             return;
212         }
213
214         // Older macOS versions (< 10.12) don't support `getentropy`. Fallback to
215         // reading from `/dev/urandom` on these systems.
216         //
217         // Older iOS versions (< 10) don't support it either. Fallback to
218         // `SecRandomCopyBytes` on these systems. On watchOS, this is unreachable
219         // because the minimum supported version is 5 while `getentropy` became accessible
220         // in 3.
221         fallback_fill_bytes(v)
222     }
223 }
224
225 #[cfg(target_os = "openbsd")]
226 mod imp {
227     use crate::sys::os::errno;
228
229     pub fn fill_bytes(v: &mut [u8]) {
230         // getentropy(2) permits a maximum buffer size of 256 bytes
231         for s in v.chunks_mut(256) {
232             let ret = unsafe { libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len()) };
233             if ret == -1 {
234                 panic!("unexpected getentropy error: {}", errno());
235             }
236         }
237     }
238 }
239
240 #[cfg(any(target_os = "freebsd", target_os = "netbsd"))]
241 mod imp {
242     use crate::ptr;
243
244     pub fn fill_bytes(v: &mut [u8]) {
245         let mib = [libc::CTL_KERN, libc::KERN_ARND];
246         // kern.arandom permits a maximum buffer size of 256 bytes
247         for s in v.chunks_mut(256) {
248             let mut s_len = s.len();
249             let ret = unsafe {
250                 libc::sysctl(
251                     mib.as_ptr(),
252                     mib.len() as libc::c_uint,
253                     s.as_mut_ptr() as *mut _,
254                     &mut s_len,
255                     ptr::null(),
256                     0,
257                 )
258             };
259             if ret == -1 || s_len != s.len() {
260                 panic!(
261                     "kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})",
262                     ret,
263                     s.len(),
264                     s_len
265                 );
266             }
267         }
268     }
269 }
270
271 #[cfg(target_os = "fuchsia")]
272 mod imp {
273     #[link(name = "zircon")]
274     extern "C" {
275         fn zx_cprng_draw(buffer: *mut u8, len: usize);
276     }
277
278     pub fn fill_bytes(v: &mut [u8]) {
279         unsafe { zx_cprng_draw(v.as_mut_ptr(), v.len()) }
280     }
281 }
282
283 #[cfg(target_os = "redox")]
284 mod imp {
285     use crate::fs::File;
286     use crate::io::Read;
287
288     pub fn fill_bytes(v: &mut [u8]) {
289         // Open rand:, read from it, and close it again.
290         let mut file = File::open("rand:").expect("failed to open rand:");
291         file.read_exact(v).expect("failed to read rand:")
292     }
293 }
294
295 #[cfg(target_os = "vxworks")]
296 mod imp {
297     use crate::io;
298     use core::sync::atomic::{AtomicBool, Ordering::Relaxed};
299
300     pub fn fill_bytes(v: &mut [u8]) {
301         static RNG_INIT: AtomicBool = AtomicBool::new(false);
302         while !RNG_INIT.load(Relaxed) {
303             let ret = unsafe { libc::randSecure() };
304             if ret < 0 {
305                 panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
306             } else if ret > 0 {
307                 RNG_INIT.store(true, Relaxed);
308                 break;
309             }
310             unsafe { libc::usleep(10) };
311         }
312         let ret = unsafe {
313             libc::randABytes(v.as_mut_ptr() as *mut libc::c_uchar, v.len() as libc::c_int)
314         };
315         if ret < 0 {
316             panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
317         }
318     }
319 }