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