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