]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/rand.rs
use SecRandomCopyBytes on macOS in Miri
[rust.git] / src / libstd / sys / unix / rand.rs
1 use crate::mem;
2 use crate::slice;
3
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,
8                                              mem::size_of_val(&v));
9         imp::fill_bytes(view);
10     }
11     return v
12 }
13
14 #[cfg(all(unix,
15           not(target_os = "ios"),
16           not(all(target_os = "macos", miri)),
17           not(target_os = "openbsd"),
18           not(target_os = "freebsd"),
19           not(target_os = "fuchsia")))]
20 mod imp {
21     use crate::fs::File;
22     use crate::io::Read;
23
24     #[cfg(any(target_os = "linux", target_os = "android"))]
25     fn getrandom(buf: &mut [u8]) -> libc::c_long {
26         unsafe {
27             libc::syscall(libc::SYS_getrandom, buf.as_mut_ptr(), buf.len(), libc::GRND_NONBLOCK)
28         }
29     }
30
31     #[cfg(not(any(target_os = "linux", target_os = "android")))]
32     fn getrandom_fill_bytes(_buf: &mut [u8]) -> bool { false }
33
34     #[cfg(any(target_os = "linux", target_os = "android"))]
35     fn getrandom_fill_bytes(v: &mut [u8]) -> bool {
36         use crate::sync::atomic::{AtomicBool, Ordering};
37         use crate::sys::os::errno;
38
39         static GETRANDOM_UNAVAILABLE: AtomicBool = AtomicBool::new(false);
40         if GETRANDOM_UNAVAILABLE.load(Ordering::Relaxed) {
41             return false;
42         }
43
44         let mut read = 0;
45         while read < v.len() {
46             let result = getrandom(&mut v[read..]);
47             if result == -1 {
48                 let err = errno() as libc::c_int;
49                 if err == libc::EINTR {
50                     continue;
51                 } else if err == libc::ENOSYS {
52                     GETRANDOM_UNAVAILABLE.store(true, Ordering::Relaxed);
53                     return false;
54                 } else if err == libc::EAGAIN {
55                     return false;
56                 } else {
57                     panic!("unexpected getrandom error: {}", err);
58                 }
59             } else {
60                 read += result as usize;
61             }
62         }
63         true
64     }
65
66     pub fn fill_bytes(v: &mut [u8]) {
67         // getrandom_fill_bytes here can fail if getrandom() returns EAGAIN,
68         // meaning it would have blocked because the non-blocking pool (urandom)
69         // has not initialized in the kernel yet due to a lack of entropy. The
70         // fallback we do here is to avoid blocking applications which could
71         // depend on this call without ever knowing they do and don't have a
72         // work around. The PRNG of /dev/urandom will still be used but over a
73         // possibly predictable entropy pool.
74         if getrandom_fill_bytes(v) {
75             return;
76         }
77
78         // getrandom failed because it is permanently or temporarily (because
79         // of missing entropy) unavailable. Open /dev/urandom, read from it,
80         // and close it again.
81         let mut file = File::open("/dev/urandom").expect("failed to open /dev/urandom");
82         file.read_exact(v).expect("failed to read /dev/urandom")
83     }
84 }
85
86 #[cfg(target_os = "openbsd")]
87 mod imp {
88     use crate::sys::os::errno;
89
90     pub fn fill_bytes(v: &mut [u8]) {
91         // getentropy(2) permits a maximum buffer size of 256 bytes
92         for s in v.chunks_mut(256) {
93             let ret = unsafe {
94                 libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len())
95             };
96             if ret == -1 {
97                 panic!("unexpected getentropy error: {}", errno());
98             }
99         }
100     }
101 }
102
103 // On iOS and MacOS `SecRandomCopyBytes` calls `CCRandomCopyBytes` with
104 // `kCCRandomDefault`. `CCRandomCopyBytes` manages a CSPRNG which is seeded
105 // from `/dev/random` and which runs on its own thread accessed via GCD.
106 // This seems needlessly heavyweight for the purposes of generating two u64s
107 // once per thread in `hashmap_random_keys`. Therefore `SecRandomCopyBytes` is
108 // only used on iOS where direct access to `/dev/urandom` is blocked by the
109 // sandbox.
110 // HACK: However, we do use this when running in Miri on macOS; intercepting this is much
111 // easier than intercepting accesses to /dev/urandom.
112 #[cfg(any(target_os = "ios", all(target_os = "macos", miri)))]
113 mod imp {
114     use crate::io;
115     use crate::ptr;
116     use libc::{c_int, size_t};
117
118     enum SecRandom {}
119
120     #[allow(non_upper_case_globals)]
121     const kSecRandomDefault: *const SecRandom = ptr::null();
122
123     extern {
124         fn SecRandomCopyBytes(rnd: *const SecRandom,
125                               count: size_t,
126                               bytes: *mut u8) -> c_int;
127     }
128
129     pub fn fill_bytes(v: &mut [u8]) {
130         let ret = unsafe {
131             SecRandomCopyBytes(kSecRandomDefault,
132                                v.len(),
133                                v.as_mut_ptr())
134         };
135         if ret == -1 {
136             panic!("couldn't generate random bytes: {}",
137                    io::Error::last_os_error());
138         }
139     }
140 }
141
142 #[cfg(target_os = "freebsd")]
143 mod imp {
144     use crate::ptr;
145
146     pub fn fill_bytes(v: &mut [u8]) {
147         let mib = [libc::CTL_KERN, libc::KERN_ARND];
148         // kern.arandom permits a maximum buffer size of 256 bytes
149         for s in v.chunks_mut(256) {
150             let mut s_len = s.len();
151             let ret = unsafe {
152                 libc::sysctl(mib.as_ptr(), mib.len() as libc::c_uint,
153                              s.as_mut_ptr() as *mut _, &mut s_len,
154                              ptr::null(), 0)
155             };
156             if ret == -1 || s_len != s.len() {
157                 panic!("kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})",
158                        ret, s.len(), s_len);
159             }
160         }
161     }
162 }
163
164 #[cfg(target_os = "fuchsia")]
165 mod imp {
166     #[link(name = "zircon")]
167     extern {
168         fn zx_cprng_draw(buffer: *mut u8, len: usize);
169     }
170
171     pub fn fill_bytes(v: &mut [u8]) {
172         unsafe { zx_cprng_draw(v.as_mut_ptr(), v.len()) }
173     }
174 }