]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/rand.rs
Auto merge of #106458 - albertlarsan68:move-tests, r=jyn514
[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(target_os = "macos")]
141 mod imp {
142     use crate::fs::File;
143     use crate::io::Read;
144     use crate::sys::os::errno;
145     use crate::sys::weak::weak;
146     use libc::{c_int, c_void, size_t};
147
148     fn getentropy_fill_bytes(v: &mut [u8]) -> bool {
149         weak!(fn getentropy(*mut c_void, size_t) -> c_int);
150
151         getentropy
152             .get()
153             .map(|f| {
154                 // getentropy(2) permits a maximum buffer size of 256 bytes
155                 for s in v.chunks_mut(256) {
156                     let ret = unsafe { f(s.as_mut_ptr() as *mut c_void, s.len()) };
157                     if ret == -1 {
158                         panic!("unexpected getentropy error: {}", errno());
159                     }
160                 }
161                 true
162             })
163             .unwrap_or(false)
164     }
165
166     pub fn fill_bytes(v: &mut [u8]) {
167         if getentropy_fill_bytes(v) {
168             return;
169         }
170
171         // for older macos which doesn't support getentropy
172         let mut file = File::open("/dev/urandom").expect("failed to open /dev/urandom");
173         file.read_exact(v).expect("failed to read /dev/urandom")
174     }
175 }
176
177 #[cfg(target_os = "openbsd")]
178 mod imp {
179     use crate::sys::os::errno;
180
181     pub fn fill_bytes(v: &mut [u8]) {
182         // getentropy(2) permits a maximum buffer size of 256 bytes
183         for s in v.chunks_mut(256) {
184             let ret = unsafe { libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len()) };
185             if ret == -1 {
186                 panic!("unexpected getentropy error: {}", errno());
187             }
188         }
189     }
190 }
191
192 // On iOS and MacOS `SecRandomCopyBytes` calls `CCRandomCopyBytes` with
193 // `kCCRandomDefault`. `CCRandomCopyBytes` manages a CSPRNG which is seeded
194 // from `/dev/random` and which runs on its own thread accessed via GCD.
195 // This seems needlessly heavyweight for the purposes of generating two u64s
196 // once per thread in `hashmap_random_keys`. Therefore `SecRandomCopyBytes` is
197 // only used on iOS where direct access to `/dev/urandom` is blocked by the
198 // sandbox.
199 #[cfg(any(target_os = "ios", target_os = "watchos"))]
200 mod imp {
201     use crate::io;
202     use crate::ptr;
203     use libc::{c_int, size_t};
204
205     enum SecRandom {}
206
207     #[allow(non_upper_case_globals)]
208     const kSecRandomDefault: *const SecRandom = ptr::null();
209
210     extern "C" {
211         fn SecRandomCopyBytes(rnd: *const SecRandom, count: size_t, bytes: *mut u8) -> c_int;
212     }
213
214     pub fn fill_bytes(v: &mut [u8]) {
215         let ret = unsafe { SecRandomCopyBytes(kSecRandomDefault, v.len(), v.as_mut_ptr()) };
216         if ret == -1 {
217             panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
218         }
219     }
220 }
221
222 #[cfg(any(target_os = "freebsd", target_os = "netbsd"))]
223 mod imp {
224     use crate::ptr;
225
226     pub fn fill_bytes(v: &mut [u8]) {
227         let mib = [libc::CTL_KERN, libc::KERN_ARND];
228         // kern.arandom permits a maximum buffer size of 256 bytes
229         for s in v.chunks_mut(256) {
230             let mut s_len = s.len();
231             let ret = unsafe {
232                 libc::sysctl(
233                     mib.as_ptr(),
234                     mib.len() as libc::c_uint,
235                     s.as_mut_ptr() as *mut _,
236                     &mut s_len,
237                     ptr::null(),
238                     0,
239                 )
240             };
241             if ret == -1 || s_len != s.len() {
242                 panic!(
243                     "kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})",
244                     ret,
245                     s.len(),
246                     s_len
247                 );
248             }
249         }
250     }
251 }
252
253 #[cfg(target_os = "fuchsia")]
254 mod imp {
255     #[link(name = "zircon")]
256     extern "C" {
257         fn zx_cprng_draw(buffer: *mut u8, len: usize);
258     }
259
260     pub fn fill_bytes(v: &mut [u8]) {
261         unsafe { zx_cprng_draw(v.as_mut_ptr(), v.len()) }
262     }
263 }
264
265 #[cfg(target_os = "redox")]
266 mod imp {
267     use crate::fs::File;
268     use crate::io::Read;
269
270     pub fn fill_bytes(v: &mut [u8]) {
271         // Open rand:, read from it, and close it again.
272         let mut file = File::open("rand:").expect("failed to open rand:");
273         file.read_exact(v).expect("failed to read rand:")
274     }
275 }
276
277 #[cfg(target_os = "vxworks")]
278 mod imp {
279     use crate::io;
280     use core::sync::atomic::{AtomicBool, Ordering::Relaxed};
281
282     pub fn fill_bytes(v: &mut [u8]) {
283         static RNG_INIT: AtomicBool = AtomicBool::new(false);
284         while !RNG_INIT.load(Relaxed) {
285             let ret = unsafe { libc::randSecure() };
286             if ret < 0 {
287                 panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
288             } else if ret > 0 {
289                 RNG_INIT.store(true, Relaxed);
290                 break;
291             }
292             unsafe { libc::usleep(10) };
293         }
294         let ret = unsafe {
295             libc::randABytes(v.as_mut_ptr() as *mut libc::c_uchar, v.len() as libc::c_int)
296         };
297         if ret < 0 {
298             panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
299         }
300     }
301 }