1 // Copyright 2018 Developers of the Rand project.
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8 use crate::Error;
9 
10 extern crate std;
11 use std::thread_local;
12 
13 use js_sys::Uint8Array;
14 use wasm_bindgen::{prelude::*, JsCast};
15 
16 // Maximum is 65536 bytes see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
17 const BROWSER_CRYPTO_BUFFER_SIZE: usize = 256;
18 
19 enum RngSource {
20     Node(NodeCrypto),
21     Browser(BrowserCrypto, Uint8Array),
22 }
23 
24 // JsValues are always per-thread, so we initialize RngSource for each thread.
25 //   See: https://github.com/rustwasm/wasm-bindgen/pull/955
26 thread_local!(
27     static RNG_SOURCE: Result<RngSource, Error> = getrandom_init();
28 );
29 
getrandom_inner(dest: &mut [u8]) -> Result<(), Error>30 pub(crate) fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
31     RNG_SOURCE.with(|result| {
32         let source = result.as_ref().map_err(|&e| e)?;
33 
34         match source {
35             RngSource::Node(n) => {
36                 if n.random_fill_sync(dest).is_err() {
37                     return Err(Error::NODE_RANDOM_FILL_SYNC);
38                 }
39             }
40             RngSource::Browser(crypto, buf) => {
41                 // getRandomValues does not work with all types of WASM memory,
42                 // so we initially write to browser memory to avoid exceptions.
43                 for chunk in dest.chunks_mut(BROWSER_CRYPTO_BUFFER_SIZE) {
44                     // The chunk can be smaller than buf's length, so we call to
45                     // JS to create a smaller view of buf without allocation.
46                     let sub_buf = buf.subarray(0, chunk.len() as u32);
47 
48                     if crypto.get_random_values(&sub_buf).is_err() {
49                         return Err(Error::WEB_GET_RANDOM_VALUES);
50                     }
51                     sub_buf.copy_to(chunk);
52                 }
53             }
54         };
55         Ok(())
56     })
57 }
58 
getrandom_init() -> Result<RngSource, Error>59 fn getrandom_init() -> Result<RngSource, Error> {
60     let global: Global = js_sys::global().unchecked_into();
61     if is_node(&global) {
62         let crypto = require("crypto").map_err(|_| Error::NODE_CRYPTO)?;
63         return Ok(RngSource::Node(crypto));
64     }
65 
66     // Assume we are in some Web environment (browser or web worker). We get
67     // `self.crypto` (called `msCrypto` on IE), so we can call
68     // `crypto.getRandomValues`. If `crypto` isn't defined, we assume that
69     // we are in an older web browser and the OS RNG isn't available.
70     let crypto = match (global.crypto(), global.ms_crypto()) {
71         (c, _) if c.is_object() => c,
72         (_, c) if c.is_object() => c,
73         _ => return Err(Error::WEB_CRYPTO),
74     };
75 
76     let buf = Uint8Array::new_with_length(BROWSER_CRYPTO_BUFFER_SIZE as u32);
77     Ok(RngSource::Browser(crypto, buf))
78 }
79 
80 // Taken from https://www.npmjs.com/package/browser-or-node
is_node(global: &Global) -> bool81 fn is_node(global: &Global) -> bool {
82     let process = global.process();
83     if process.is_object() {
84         let versions = process.versions();
85         if versions.is_object() {
86             return versions.node().is_string();
87         }
88     }
89     false
90 }
91 
92 #[wasm_bindgen]
93 extern "C" {
94     type Global; // Return type of js_sys::global()
95 
96     // Web Crypto API (https://www.w3.org/TR/WebCryptoAPI/)
97     #[wasm_bindgen(method, getter, js_name = "msCrypto")]
ms_crypto(this: &Global) -> BrowserCrypto98     fn ms_crypto(this: &Global) -> BrowserCrypto;
99     #[wasm_bindgen(method, getter)]
crypto(this: &Global) -> BrowserCrypto100     fn crypto(this: &Global) -> BrowserCrypto;
101     type BrowserCrypto;
102     #[wasm_bindgen(method, js_name = getRandomValues, catch)]
get_random_values(this: &BrowserCrypto, buf: &Uint8Array) -> Result<(), JsValue>103     fn get_random_values(this: &BrowserCrypto, buf: &Uint8Array) -> Result<(), JsValue>;
104 
105     // Node JS crypto module (https://nodejs.org/api/crypto.html)
106     #[wasm_bindgen(catch, js_name = "module.require")]
require(s: &str) -> Result<NodeCrypto, JsValue>107     fn require(s: &str) -> Result<NodeCrypto, JsValue>;
108     type NodeCrypto;
109     #[wasm_bindgen(method, js_name = randomFillSync, catch)]
random_fill_sync(this: &NodeCrypto, buf: &mut [u8]) -> Result<(), JsValue>110     fn random_fill_sync(this: &NodeCrypto, buf: &mut [u8]) -> Result<(), JsValue>;
111 
112     // Node JS process Object (https://nodejs.org/api/process.html)
113     #[wasm_bindgen(method, getter)]
process(this: &Global) -> Process114     fn process(this: &Global) -> Process;
115     type Process;
116     #[wasm_bindgen(method, getter)]
versions(this: &Process) -> Versions117     fn versions(this: &Process) -> Versions;
118     type Versions;
119     #[wasm_bindgen(method, getter)]
node(this: &Versions) -> JsValue120     fn node(this: &Versions) -> JsValue;
121 }
122