1 // Copyright 2013-2014 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(unix, not(target_os = "ios"))]
18 use io::{IoResult, File};
21 use rand::reader::ReaderRng;
22 use result::{Ok, Err};
24 /// A random number generator that retrieves randomness straight from
25 /// the operating system. Platform sources:
27 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
29 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
30 /// service provider with the `PROV_RSA_FULL` type.
31 /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed
32 /// This does not block.
35 inner: ReaderRng<File>
39 /// Create a new `OsRng`.
40 pub fn new() -> IoResult<OsRng> {
41 let reader = try!(File::open(&Path::new("/dev/urandom")));
42 let reader_rng = ReaderRng::new(reader);
44 Ok(OsRng { inner: reader_rng })
49 fn next_u32(&mut self) -> u32 {
52 fn next_u64(&mut self) -> u64 {
55 fn fill_bytes(&mut self, v: &mut [u8]) {
56 self.inner.fill_bytes(v)
61 #[cfg(target_os = "ios")]
65 use collections::Collection;
72 use self::libc::{c_int, size_t};
73 use slice::MutableVector;
75 /// A random number generator that retrieves randomness straight from
76 /// the operating system. Platform sources:
78 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
80 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
81 /// service provider with the `PROV_RSA_FULL` type.
82 /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed
83 /// This does not block.
85 marker: marker::NoCopy
90 static kSecRandomDefault: *SecRandom = 0 as *SecRandom;
92 #[link(name = "Security", kind = "framework")]
94 fn SecRandomCopyBytes(rnd: *SecRandom, count: size_t, bytes: *mut u8) -> c_int;
98 /// Create a new `OsRng`.
99 pub fn new() -> IoResult<OsRng> {
100 Ok(OsRng {marker: marker::NoCopy} )
105 fn next_u32(&mut self) -> u32 {
106 let mut v = [0u8, .. 4];
108 unsafe { mem::transmute(v) }
110 fn next_u64(&mut self) -> u64 {
111 let mut v = [0u8, .. 8];
113 unsafe { mem::transmute(v) }
115 fn fill_bytes(&mut self, v: &mut [u8]) {
117 SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t, v.as_mut_ptr())
120 fail!("couldn't generate random bytes: {}", os::last_os_error());
130 use core_collections::Collection;
131 use io::{IoResult, IoError};
136 use result::{Ok, Err};
138 use self::libc::{c_ulong, DWORD, BYTE, LPCSTR, BOOL};
139 use slice::MutableVector;
141 type HCRYPTPROV = c_ulong;
143 /// A random number generator that retrieves randomness straight from
144 /// the operating system. Platform sources:
146 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
148 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
149 /// service provider with the `PROV_RSA_FULL` type.
151 /// This does not block.
153 hcryptprov: HCRYPTPROV
156 static PROV_RSA_FULL: DWORD = 1;
157 static CRYPT_SILENT: DWORD = 64;
158 static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
159 static NTE_BAD_SIGNATURE: DWORD = 0x80090006;
161 #[allow(non_snake_case_functions)]
163 fn CryptAcquireContextA(phProv: *mut HCRYPTPROV,
164 pszContainer: LPCSTR,
167 dwFlags: DWORD) -> BOOL;
168 fn CryptGenRandom(hProv: HCRYPTPROV,
170 pbBuffer: *mut BYTE) -> BOOL;
171 fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL;
175 /// Create a new `OsRng`.
176 pub fn new() -> IoResult<OsRng> {
178 let mut ret = unsafe {
179 CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
181 CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
185 // It turns out that if we can't acquire a context with the
186 // NTE_BAD_SIGNATURE error code, the documentation states:
188 // The provider DLL signature could not be verified. Either the
189 // DLL or the digital signature has been tampered with.
191 // Sounds fishy, no? As it turns out, our signature can be bad
192 // because our Thread Information Block (TIB) isn't exactly what it
193 // expects. As to why, I have no idea. The only data we store in the
194 // TIB is the stack limit for each thread, but apparently that's
195 // enough to make the signature valid.
197 // Furthermore, this error only happens the *first* time we call
198 // CryptAcquireContext, so we don't have to worry about future
201 // Anyway, the fix employed here is that if we see this error, we
202 // pray that we're not close to the end of the stack, temporarily
203 // set the stack limit to 0 (what the TIB originally was), acquire a
204 // context, and then reset the stack limit.
206 // Again, I'm not sure why this is the fix, nor why we're getting
207 // this error. All I can say is that this seems to allow libnative
208 // to progress where it otherwise would be hindered. Who knew?
209 if ret == 0 && os::errno() as DWORD == NTE_BAD_SIGNATURE {
211 let limit = stack::get_sp_limit();
212 stack::record_sp_limit(0);
213 ret = CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
215 CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
216 stack::record_sp_limit(limit);
221 Err(IoError::last_error())
223 Ok(OsRng { hcryptprov: hcp })
229 fn next_u32(&mut self) -> u32 {
230 let mut v = [0u8, .. 4];
232 unsafe { mem::transmute(v) }
234 fn next_u64(&mut self) -> u64 {
235 let mut v = [0u8, .. 8];
237 unsafe { mem::transmute(v) }
239 fn fill_bytes(&mut self, v: &mut [u8]) {
241 CryptGenRandom(self.hcryptprov, v.len() as DWORD,
245 fail!("couldn't generate random bytes: {}", os::last_os_error());
250 impl Drop for OsRng {
253 CryptReleaseContext(self.hcryptprov, 0)
256 fail!("couldn't release context: {}", os::last_os_error());
272 let mut r = OsRng::new().unwrap();
277 let mut v = [0u8, .. 1000];
282 fn test_os_rng_tasks() {
284 let mut txs = vec!();
285 for _ in range(0, 20) {
286 let (tx, rx) = channel();
289 // wait until all the tasks are ready to go.
292 // deschedule to attempt to interleave things as much
293 // as possible (XXX: is this a good test?)
294 let mut r = OsRng::new().unwrap();
296 let mut v = [0u8, .. 1000];
298 for _ in range(0, 100) {
309 // start all the tasks
310 for tx in txs.iter() {