]> git.lizzy.rs Git - rust.git/blob - src/libstd/rand/os.rs
ffe8e539ffba13b9b07516eb393fce74d3354a0a
[rust.git] / src / libstd / rand / os.rs
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.
4 //
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.
10
11 //! Interfaces to the operating system provided random number
12 //! generators.
13
14 pub use self::imp::OsRng;
15
16 #[cfg(unix, not(target_os = "ios"))]
17 mod imp {
18     use io::{IoResult, File};
19     use path::Path;
20     use rand::Rng;
21     use rand::reader::ReaderRng;
22     use result::{Ok, Err};
23
24     /// A random number generator that retrieves randomness straight from
25     /// the operating system. Platform sources:
26     ///
27     /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
28     ///   `/dev/urandom`.
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.
33     #[cfg(unix)]
34     pub struct OsRng {
35         inner: ReaderRng<File>
36     }
37
38     impl OsRng {
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);
43
44             Ok(OsRng { inner: reader_rng })
45         }
46     }
47
48     impl Rng for OsRng {
49         fn next_u32(&mut self) -> u32 {
50             self.inner.next_u32()
51         }
52         fn next_u64(&mut self) -> u64 {
53             self.inner.next_u64()
54         }
55         fn fill_bytes(&mut self, v: &mut [u8]) {
56             self.inner.fill_bytes(v)
57         }
58     }
59 }
60
61 #[cfg(target_os = "ios")]
62 mod imp {
63     extern crate libc;
64
65     use collections::Collection;
66     use io::{IoResult};
67     use kinds::marker;
68     use mem;
69     use os;
70     use rand::Rng;
71     use result::{Ok};
72     use self::libc::{c_int, size_t};
73     use slice::MutableVector;
74
75     /// A random number generator that retrieves randomness straight from
76     /// the operating system. Platform sources:
77     ///
78     /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
79     ///   `/dev/urandom`.
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.
84     pub struct OsRng {
85         marker: marker::NoCopy
86     }
87
88     struct SecRandom;
89
90     static kSecRandomDefault: *const SecRandom = 0 as *const SecRandom;
91
92     #[link(name = "Security", kind = "framework")]
93     extern "C" {
94         fn SecRandomCopyBytes(rnd: *const SecRandom,
95                               count: size_t, bytes: *mut u8) -> c_int;
96     }
97
98     impl OsRng {
99         /// Create a new `OsRng`.
100         pub fn new() -> IoResult<OsRng> {
101             Ok(OsRng {marker: marker::NoCopy} )
102         }
103     }
104
105     impl Rng for OsRng {
106         fn next_u32(&mut self) -> u32 {
107             let mut v = [0u8, .. 4];
108             self.fill_bytes(v);
109             unsafe { mem::transmute(v) }
110         }
111         fn next_u64(&mut self) -> u64 {
112             let mut v = [0u8, .. 8];
113             self.fill_bytes(v);
114             unsafe { mem::transmute(v) }
115         }
116         fn fill_bytes(&mut self, v: &mut [u8]) {
117             let ret = unsafe {
118                 SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t, v.as_mut_ptr())
119             };
120             if ret == -1 {
121                 fail!("couldn't generate random bytes: {}", os::last_os_error());
122             }
123         }
124     }
125 }
126
127 #[cfg(windows)]
128 mod imp {
129     extern crate libc;
130
131     use core_collections::Collection;
132     use io::{IoResult, IoError};
133     use mem;
134     use ops::Drop;
135     use os;
136     use rand::Rng;
137     use result::{Ok, Err};
138     use rt::stack;
139     use self::libc::{DWORD, BYTE, LPCSTR, BOOL};
140     use self::libc::types::os::arch::extra::{LONG_PTR};
141     use slice::MutableVector;
142
143     type HCRYPTPROV = LONG_PTR;
144
145     /// A random number generator that retrieves randomness straight from
146     /// the operating system. Platform sources:
147     ///
148     /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
149     ///   `/dev/urandom`.
150     /// - Windows: calls `CryptGenRandom`, using the default cryptographic
151     ///   service provider with the `PROV_RSA_FULL` type.
152     ///
153     /// This does not block.
154     pub struct OsRng {
155         hcryptprov: HCRYPTPROV
156     }
157
158     static PROV_RSA_FULL: DWORD = 1;
159     static CRYPT_SILENT: DWORD = 64;
160     static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
161     static NTE_BAD_SIGNATURE: DWORD = 0x80090006;
162
163     #[allow(non_snake_case_functions)]
164     extern "system" {
165         fn CryptAcquireContextA(phProv: *mut HCRYPTPROV,
166                                 pszContainer: LPCSTR,
167                                 pszProvider: LPCSTR,
168                                 dwProvType: DWORD,
169                                 dwFlags: DWORD) -> BOOL;
170         fn CryptGenRandom(hProv: HCRYPTPROV,
171                           dwLen: DWORD,
172                           pbBuffer: *mut BYTE) -> BOOL;
173         fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL;
174     }
175
176     impl OsRng {
177         /// Create a new `OsRng`.
178         pub fn new() -> IoResult<OsRng> {
179             let mut hcp = 0;
180             let mut ret = unsafe {
181                 CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
182                                      PROV_RSA_FULL,
183                                      CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
184             };
185
186             // FIXME #13259:
187             // It turns out that if we can't acquire a context with the
188             // NTE_BAD_SIGNATURE error code, the documentation states:
189             //
190             //     The provider DLL signature could not be verified. Either the
191             //     DLL or the digital signature has been tampered with.
192             //
193             // Sounds fishy, no? As it turns out, our signature can be bad
194             // because our Thread Information Block (TIB) isn't exactly what it
195             // expects. As to why, I have no idea. The only data we store in the
196             // TIB is the stack limit for each thread, but apparently that's
197             // enough to make the signature valid.
198             //
199             // Furthermore, this error only happens the *first* time we call
200             // CryptAcquireContext, so we don't have to worry about future
201             // calls.
202             //
203             // Anyway, the fix employed here is that if we see this error, we
204             // pray that we're not close to the end of the stack, temporarily
205             // set the stack limit to 0 (what the TIB originally was), acquire a
206             // context, and then reset the stack limit.
207             //
208             // Again, I'm not sure why this is the fix, nor why we're getting
209             // this error. All I can say is that this seems to allow libnative
210             // to progress where it otherwise would be hindered. Who knew?
211             if ret == 0 && os::errno() as DWORD == NTE_BAD_SIGNATURE {
212                 unsafe {
213                     let limit = stack::get_sp_limit();
214                     stack::record_sp_limit(0);
215                     ret = CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
216                                                PROV_RSA_FULL,
217                                                CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
218                     stack::record_sp_limit(limit);
219                 }
220             }
221
222             if ret == 0 {
223                 Err(IoError::last_error())
224             } else {
225                 Ok(OsRng { hcryptprov: hcp })
226             }
227         }
228     }
229
230     impl Rng for OsRng {
231         fn next_u32(&mut self) -> u32 {
232             let mut v = [0u8, .. 4];
233             self.fill_bytes(v);
234             unsafe { mem::transmute(v) }
235         }
236         fn next_u64(&mut self) -> u64 {
237             let mut v = [0u8, .. 8];
238             self.fill_bytes(v);
239             unsafe { mem::transmute(v) }
240         }
241         fn fill_bytes(&mut self, v: &mut [u8]) {
242             let ret = unsafe {
243                 CryptGenRandom(self.hcryptprov, v.len() as DWORD,
244                                v.as_mut_ptr())
245             };
246             if ret == 0 {
247                 fail!("couldn't generate random bytes: {}", os::last_os_error());
248             }
249         }
250     }
251
252     impl Drop for OsRng {
253         fn drop(&mut self) {
254             let ret = unsafe {
255                 CryptReleaseContext(self.hcryptprov, 0)
256             };
257             if ret == 0 {
258                 fail!("couldn't release context: {}", os::last_os_error());
259             }
260         }
261     }
262 }
263
264 #[cfg(test)]
265 mod test {
266     use prelude::*;
267
268     use super::OsRng;
269     use rand::Rng;
270     use task;
271
272     #[test]
273     fn test_os_rng() {
274         let mut r = OsRng::new().unwrap();
275
276         r.next_u32();
277         r.next_u64();
278
279         let mut v = [0u8, .. 1000];
280         r.fill_bytes(v);
281     }
282
283     #[test]
284     fn test_os_rng_tasks() {
285
286         let mut txs = vec!();
287         for _ in range(0u, 20) {
288             let (tx, rx) = channel();
289             txs.push(tx);
290             task::spawn(proc() {
291                 // wait until all the tasks are ready to go.
292                 rx.recv();
293
294                 // deschedule to attempt to interleave things as much
295                 // as possible (XXX: is this a good test?)
296                 let mut r = OsRng::new().unwrap();
297                 task::deschedule();
298                 let mut v = [0u8, .. 1000];
299
300                 for _ in range(0u, 100) {
301                     r.next_u32();
302                     task::deschedule();
303                     r.next_u64();
304                     task::deschedule();
305                     r.fill_bytes(v);
306                     task::deschedule();
307                 }
308             })
309         }
310
311         // start all the tasks
312         for tx in txs.iter() {
313             tx.send(())
314         }
315     }
316 }