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