1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Interfaces to the operating system provided random number
14 pub use self::imp::OsRng;
16 #[cfg(all(unix, not(target_os = "ios")))]
20 use self::OsRngInner::*;
22 use io::{IoResult, File};
25 use rand::reader::ReaderRng;
26 use result::Result::{Ok, Err};
31 #[cfg(all(target_os = "linux",
32 any(target_arch = "x86_64",
35 target_arch = "aarch64")))]
36 fn getrandom(buf: &mut [u8]) -> libc::c_long {
38 fn syscall(number: libc::c_long, ...) -> libc::c_long;
41 #[cfg(target_arch = "x86_64")]
42 const NR_GETRANDOM: libc::c_long = 318;
43 #[cfg(target_arch = "x86")]
44 const NR_GETRANDOM: libc::c_long = 355;
45 #[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
46 const NR_GETRANDOM: libc::c_long = 384;
49 syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), 0u)
53 #[cfg(not(all(target_os = "linux",
54 any(target_arch = "x86_64",
57 target_arch = "aarch64"))))]
58 fn getrandom(_buf: &mut [u8]) -> libc::c_long { -1 }
60 fn getrandom_fill_bytes(v: &mut [u8]) {
64 let result = getrandom(v.slice_from_mut(read));
66 let err = errno() as libc::c_int;
67 if err == libc::EINTR {
70 panic!("unexpected getrandom error: {}", err);
73 read += result as uint;
78 fn getrandom_next_u32() -> u32 {
79 let mut buf: [u8; 4] = [0u8; 4];
80 getrandom_fill_bytes(&mut buf);
81 unsafe { mem::transmute::<[u8; 4], u32>(buf) }
84 fn getrandom_next_u64() -> u64 {
85 let mut buf: [u8; 8] = [0u8; 8];
86 getrandom_fill_bytes(&mut buf);
87 unsafe { mem::transmute::<[u8; 8], u64>(buf) }
90 #[cfg(all(target_os = "linux",
91 any(target_arch = "x86_64",
94 target_arch = "aarch64")))]
95 fn is_getrandom_available() -> bool {
96 use sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
98 static GETRANDOM_CHECKED: AtomicBool = ATOMIC_BOOL_INIT;
99 static GETRANDOM_AVAILABLE: AtomicBool = ATOMIC_BOOL_INIT;
101 if !GETRANDOM_CHECKED.load(Ordering::Relaxed) {
102 let mut buf: [u8; 0] = [];
103 let result = getrandom(&mut buf);
104 let available = if result == -1 {
105 let err = errno() as libc::c_int;
110 GETRANDOM_AVAILABLE.store(available, Ordering::Relaxed);
111 GETRANDOM_CHECKED.store(true, Ordering::Relaxed);
114 GETRANDOM_AVAILABLE.load(Ordering::Relaxed)
118 #[cfg(not(all(target_os = "linux",
119 any(target_arch = "x86_64",
122 target_arch = "aarch64"))))]
123 fn is_getrandom_available() -> bool { false }
125 /// A random number generator that retrieves randomness straight from
126 /// the operating system. Platform sources:
128 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
129 /// `/dev/urandom`, or from `getrandom(2)` system call if available.
130 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
131 /// service provider with the `PROV_RSA_FULL` type.
132 /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
134 /// This does not block.
141 OsReaderRng(ReaderRng<File>),
145 /// Create a new `OsRng`.
146 pub fn new() -> IoResult<OsRng> {
147 if is_getrandom_available() {
148 return Ok(OsRng { inner: OsGetrandomRng });
151 let reader = try!(File::open(&Path::new("/dev/urandom")));
152 let reader_rng = ReaderRng::new(reader);
154 Ok(OsRng { inner: OsReaderRng(reader_rng) })
159 fn next_u32(&mut self) -> u32 {
161 OsGetrandomRng => getrandom_next_u32(),
162 OsReaderRng(ref mut rng) => rng.next_u32(),
165 fn next_u64(&mut self) -> u64 {
167 OsGetrandomRng => getrandom_next_u64(),
168 OsReaderRng(ref mut rng) => rng.next_u64(),
171 fn fill_bytes(&mut self, v: &mut [u8]) {
173 OsGetrandomRng => getrandom_fill_bytes(v),
174 OsReaderRng(ref mut rng) => rng.fill_bytes(v)
180 #[cfg(target_os = "ios")]
189 use result::Result::{Ok};
190 use self::libc::{c_int, size_t};
193 /// A random number generator that retrieves randomness straight from
194 /// the operating system. Platform sources:
196 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
197 /// `/dev/urandom`, or from `getrandom(2)` system call if available.
198 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
199 /// service provider with the `PROV_RSA_FULL` type.
200 /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
202 /// This does not block.
203 #[allow(missing_copy_implementations)]
205 // dummy field to ensure that this struct cannot be constructed outside of this module
212 unsafe impl Sync for *const SecRandom {}
214 #[allow(non_upper_case_globals)]
215 static kSecRandomDefault: *const SecRandom = 0 as *const SecRandom;
217 #[link(name = "Security", kind = "framework")]
219 fn SecRandomCopyBytes(rnd: *const SecRandom,
220 count: size_t, bytes: *mut u8) -> c_int;
224 /// Create a new `OsRng`.
225 pub fn new() -> IoResult<OsRng> {
226 Ok(OsRng { _dummy: () })
231 fn next_u32(&mut self) -> u32 {
232 let mut v = [0u8; 4];
233 self.fill_bytes(&mut v);
234 unsafe { mem::transmute(v) }
236 fn next_u64(&mut self) -> u64 {
237 let mut v = [0u8; 8];
238 self.fill_bytes(&mut v);
239 unsafe { mem::transmute(v) }
241 fn fill_bytes(&mut self, v: &mut [u8]) {
243 SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t, v.as_mut_ptr())
246 panic!("couldn't generate random bytes: {}", os::last_os_error());
256 use io::{IoResult, IoError};
261 use result::Result::{Ok, Err};
262 use self::libc::{DWORD, BYTE, LPCSTR, BOOL};
263 use self::libc::types::os::arch::extra::{LONG_PTR};
266 type HCRYPTPROV = LONG_PTR;
268 /// A random number generator that retrieves randomness straight from
269 /// the operating system. Platform sources:
271 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
272 /// `/dev/urandom`, or from `getrandom(2)` system call if available.
273 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
274 /// service provider with the `PROV_RSA_FULL` type.
275 /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
277 /// This does not block.
279 hcryptprov: HCRYPTPROV
282 static PROV_RSA_FULL: DWORD = 1;
283 static CRYPT_SILENT: DWORD = 64;
284 static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
286 #[allow(non_snake_case)]
288 fn CryptAcquireContextA(phProv: *mut HCRYPTPROV,
289 pszContainer: LPCSTR,
292 dwFlags: DWORD) -> BOOL;
293 fn CryptGenRandom(hProv: HCRYPTPROV,
295 pbBuffer: *mut BYTE) -> BOOL;
296 fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL;
300 /// Create a new `OsRng`.
301 pub fn new() -> IoResult<OsRng> {
304 CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
306 CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
310 Err(IoError::last_error())
312 Ok(OsRng { hcryptprov: hcp })
318 fn next_u32(&mut self) -> u32 {
319 let mut v = [0u8; 4];
320 self.fill_bytes(&mut v);
321 unsafe { mem::transmute(v) }
323 fn next_u64(&mut self) -> u64 {
324 let mut v = [0u8; 8];
325 self.fill_bytes(&mut v);
326 unsafe { mem::transmute(v) }
328 fn fill_bytes(&mut self, v: &mut [u8]) {
330 CryptGenRandom(self.hcryptprov, v.len() as DWORD,
334 panic!("couldn't generate random bytes: {}", os::last_os_error());
339 impl Drop for OsRng {
342 CryptReleaseContext(self.hcryptprov, 0)
345 panic!("couldn't release context: {}", os::last_os_error());
355 use sync::mpsc::channel;
362 let mut r = OsRng::new().unwrap();
367 let mut v = [0u8; 1000];
368 r.fill_bytes(&mut v);
372 fn test_os_rng_tasks() {
374 let mut txs = vec!();
375 for _ in range(0u, 20) {
376 let (tx, rx) = channel();
379 Thread::spawn(move|| {
380 // wait until all the tasks are ready to go.
383 // deschedule to attempt to interleave things as much
384 // as possible (XXX: is this a good test?)
385 let mut r = OsRng::new().unwrap();
387 let mut v = [0u8; 1000];
389 for _ in range(0u, 100) {
394 r.fill_bytes(&mut v);
400 // start all the tasks
401 for tx in txs.iter() {
402 tx.send(()).unwrap();