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;
31 // NOTE: for old macros; remove after the next snapshot
32 #[cfg(stage0)] use result::Result::Err;
34 #[cfg(all(target_os = "linux",
35 any(target_arch = "x86_64",
38 target_arch = "aarch64")))]
39 fn getrandom(buf: &mut [u8]) -> libc::c_long {
41 fn syscall(number: libc::c_long, ...) -> libc::c_long;
44 #[cfg(target_arch = "x86_64")]
45 const NR_GETRANDOM: libc::c_long = 318;
46 #[cfg(target_arch = "x86")]
47 const NR_GETRANDOM: libc::c_long = 355;
48 #[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
49 const NR_GETRANDOM: libc::c_long = 384;
52 syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), 0u)
56 #[cfg(not(all(target_os = "linux",
57 any(target_arch = "x86_64",
60 target_arch = "aarch64"))))]
61 fn getrandom(_buf: &mut [u8]) -> libc::c_long { -1 }
63 fn getrandom_fill_bytes(v: &mut [u8]) {
67 let result = getrandom(v.slice_from_mut(read));
69 let err = errno() as libc::c_int;
70 if err == libc::EINTR {
73 panic!("unexpected getrandom error: {}", err);
76 read += result as uint;
81 fn getrandom_next_u32() -> u32 {
82 let mut buf: [u8; 4] = [0u8; 4];
83 getrandom_fill_bytes(&mut buf);
84 unsafe { mem::transmute::<[u8; 4], u32>(buf) }
87 fn getrandom_next_u64() -> u64 {
88 let mut buf: [u8; 8] = [0u8; 8];
89 getrandom_fill_bytes(&mut buf);
90 unsafe { mem::transmute::<[u8; 8], u64>(buf) }
93 #[cfg(all(target_os = "linux",
94 any(target_arch = "x86_64",
97 target_arch = "aarch64")))]
98 fn is_getrandom_available() -> bool {
99 use sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
101 static GETRANDOM_CHECKED: AtomicBool = ATOMIC_BOOL_INIT;
102 static GETRANDOM_AVAILABLE: AtomicBool = ATOMIC_BOOL_INIT;
104 if !GETRANDOM_CHECKED.load(Ordering::Relaxed) {
105 let mut buf: [u8; 0] = [];
106 let result = getrandom(&mut buf);
107 let available = if result == -1 {
108 let err = errno() as libc::c_int;
113 GETRANDOM_AVAILABLE.store(available, Ordering::Relaxed);
114 GETRANDOM_CHECKED.store(true, Ordering::Relaxed);
117 GETRANDOM_AVAILABLE.load(Ordering::Relaxed)
121 #[cfg(not(all(target_os = "linux",
122 any(target_arch = "x86_64",
125 target_arch = "aarch64"))))]
126 fn is_getrandom_available() -> bool { false }
128 /// A random number generator that retrieves randomness straight from
129 /// the operating system. Platform sources:
131 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
132 /// `/dev/urandom`, or from `getrandom(2)` system call if available.
133 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
134 /// service provider with the `PROV_RSA_FULL` type.
135 /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
137 /// This does not block.
144 OsReaderRng(ReaderRng<File>),
148 /// Create a new `OsRng`.
149 pub fn new() -> IoResult<OsRng> {
150 if is_getrandom_available() {
151 return Ok(OsRng { inner: OsGetrandomRng });
154 let reader = try!(File::open(&Path::new("/dev/urandom")));
155 let reader_rng = ReaderRng::new(reader);
157 Ok(OsRng { inner: OsReaderRng(reader_rng) })
162 fn next_u32(&mut self) -> u32 {
164 OsGetrandomRng => getrandom_next_u32(),
165 OsReaderRng(ref mut rng) => rng.next_u32(),
168 fn next_u64(&mut self) -> u64 {
170 OsGetrandomRng => getrandom_next_u64(),
171 OsReaderRng(ref mut rng) => rng.next_u64(),
174 fn fill_bytes(&mut self, v: &mut [u8]) {
176 OsGetrandomRng => getrandom_fill_bytes(v),
177 OsReaderRng(ref mut rng) => rng.fill_bytes(v)
183 #[cfg(target_os = "ios")]
192 use result::Result::{Ok};
193 use self::libc::{c_int, size_t};
196 /// A random number generator that retrieves randomness straight from
197 /// the operating system. Platform sources:
199 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
200 /// `/dev/urandom`, or from `getrandom(2)` system call if available.
201 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
202 /// service provider with the `PROV_RSA_FULL` type.
203 /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
205 /// This does not block.
206 #[allow(missing_copy_implementations)]
208 // dummy field to ensure that this struct cannot be constructed outside of this module
215 unsafe impl Sync for *const SecRandom {}
217 #[allow(non_upper_case_globals)]
218 static kSecRandomDefault: *const SecRandom = 0 as *const SecRandom;
220 #[link(name = "Security", kind = "framework")]
222 fn SecRandomCopyBytes(rnd: *const SecRandom,
223 count: size_t, bytes: *mut u8) -> c_int;
227 /// Create a new `OsRng`.
228 pub fn new() -> IoResult<OsRng> {
229 Ok(OsRng { _dummy: () })
234 fn next_u32(&mut self) -> u32 {
235 let mut v = [0u8; 4];
236 self.fill_bytes(&mut v);
237 unsafe { mem::transmute(v) }
239 fn next_u64(&mut self) -> u64 {
240 let mut v = [0u8; 8];
241 self.fill_bytes(&mut v);
242 unsafe { mem::transmute(v) }
244 fn fill_bytes(&mut self, v: &mut [u8]) {
246 SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t, v.as_mut_ptr())
249 panic!("couldn't generate random bytes: {}", os::last_os_error());
259 use io::{IoResult, IoError};
264 use result::Result::{Ok, Err};
265 use self::libc::{DWORD, BYTE, LPCSTR, BOOL};
266 use self::libc::types::os::arch::extra::{LONG_PTR};
269 type HCRYPTPROV = LONG_PTR;
271 /// A random number generator that retrieves randomness straight from
272 /// the operating system. Platform sources:
274 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
275 /// `/dev/urandom`, or from `getrandom(2)` system call if available.
276 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
277 /// service provider with the `PROV_RSA_FULL` type.
278 /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
280 /// This does not block.
282 hcryptprov: HCRYPTPROV
285 static PROV_RSA_FULL: DWORD = 1;
286 static CRYPT_SILENT: DWORD = 64;
287 static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
289 #[allow(non_snake_case)]
291 fn CryptAcquireContextA(phProv: *mut HCRYPTPROV,
292 pszContainer: LPCSTR,
295 dwFlags: DWORD) -> BOOL;
296 fn CryptGenRandom(hProv: HCRYPTPROV,
298 pbBuffer: *mut BYTE) -> BOOL;
299 fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL;
303 /// Create a new `OsRng`.
304 pub fn new() -> IoResult<OsRng> {
307 CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
309 CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
313 Err(IoError::last_error())
315 Ok(OsRng { hcryptprov: hcp })
321 fn next_u32(&mut self) -> u32 {
322 let mut v = [0u8; 4];
323 self.fill_bytes(&mut v);
324 unsafe { mem::transmute(v) }
326 fn next_u64(&mut self) -> u64 {
327 let mut v = [0u8; 8];
328 self.fill_bytes(&mut v);
329 unsafe { mem::transmute(v) }
331 fn fill_bytes(&mut self, v: &mut [u8]) {
333 CryptGenRandom(self.hcryptprov, v.len() as DWORD,
337 panic!("couldn't generate random bytes: {}", os::last_os_error());
342 impl Drop for OsRng {
345 CryptReleaseContext(self.hcryptprov, 0)
348 panic!("couldn't release context: {}", os::last_os_error());
358 use sync::mpsc::channel;
365 let mut r = OsRng::new().unwrap();
370 let mut v = [0u8; 1000];
371 r.fill_bytes(&mut v);
375 fn test_os_rng_tasks() {
377 let mut txs = vec!();
378 for _ in range(0u, 20) {
379 let (tx, rx) = channel();
382 Thread::spawn(move|| {
383 // wait until all the tasks are ready to go.
386 // deschedule to attempt to interleave things as much
387 // as possible (XXX: is this a good test?)
388 let mut r = OsRng::new().unwrap();
390 let mut v = [0u8; 1000];
392 for _ in range(0u, 100) {
397 r.fill_bytes(&mut v);
403 // start all the tasks
404 for tx in txs.iter() {
405 tx.send(()).unwrap();