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::{global, Uint8Array};
14 use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue};
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 = global().unchecked_into();
61 if is_node(&global) {
62 let crypto = NODE_MODULE
63 .require("crypto")
64 .map_err(|_| Error::NODE_CRYPTO)?;
65 return Ok(RngSource::Node(crypto));
66 }
67
68 // Assume we are in some Web environment (browser or web worker). We get
69 // `self.crypto` (called `msCrypto` on IE), so we can call
70 // `crypto.getRandomValues`. If `crypto` isn't defined, we assume that
71 // we are in an older web browser and the OS RNG isn't available.
72 let crypto = match (global.crypto(), global.ms_crypto()) {
73 (c, _) if c.is_object() => c,
74 (_, c) if c.is_object() => c,
75 _ => return Err(Error::WEB_CRYPTO),
76 };
77
78 let buf = Uint8Array::new_with_length(BROWSER_CRYPTO_BUFFER_SIZE as u32);
79 Ok(RngSource::Browser(crypto, buf))
80 }
81
82 // Taken from https://www.npmjs.com/package/browser-or-node
is_node(global: &Global) -> bool83 fn is_node(global: &Global) -> bool {
84 let process = global.process();
85 if process.is_object() {
86 let versions = process.versions();
87 if versions.is_object() {
88 return versions.node().is_string();
89 }
90 }
91 false
92 }
93
94 #[wasm_bindgen]
95 extern "C" {
96 type Global; // Return type of js_sys::global()
97
98 // Web Crypto API (https://www.w3.org/TR/WebCryptoAPI/)
99 #[wasm_bindgen(method, getter, js_name = "msCrypto")]
ms_crypto(this: &Global) -> BrowserCrypto100 fn ms_crypto(this: &Global) -> BrowserCrypto;
101 #[wasm_bindgen(method, getter)]
crypto(this: &Global) -> BrowserCrypto102 fn crypto(this: &Global) -> BrowserCrypto;
103 type BrowserCrypto;
104 #[wasm_bindgen(method, js_name = getRandomValues, catch)]
get_random_values(this: &BrowserCrypto, buf: &Uint8Array) -> Result<(), JsValue>105 fn get_random_values(this: &BrowserCrypto, buf: &Uint8Array) -> Result<(), JsValue>;
106
107 // We use a "module" object here instead of just annotating require() with
108 // js_name = "module.require", so that Webpack doesn't give a warning. See:
109 // https://github.com/rust-random/getrandom/issues/224
110 type NodeModule;
111 #[wasm_bindgen(js_name = module)]
112 static NODE_MODULE: NodeModule;
113 // Node JS crypto module (https://nodejs.org/api/crypto.html)
114 #[wasm_bindgen(method, catch)]
require(this: &NodeModule, s: &str) -> Result<NodeCrypto, JsValue>115 fn require(this: &NodeModule, s: &str) -> Result<NodeCrypto, JsValue>;
116 type NodeCrypto;
117 #[wasm_bindgen(method, js_name = randomFillSync, catch)]
random_fill_sync(this: &NodeCrypto, buf: &mut [u8]) -> Result<(), JsValue>118 fn random_fill_sync(this: &NodeCrypto, buf: &mut [u8]) -> Result<(), JsValue>;
119
120 // Node JS process Object (https://nodejs.org/api/process.html)
121 #[wasm_bindgen(method, getter)]
process(this: &Global) -> Process122 fn process(this: &Global) -> Process;
123 type Process;
124 #[wasm_bindgen(method, getter)]
versions(this: &Process) -> Versions125 fn versions(this: &Process) -> Versions;
126 type Versions;
127 #[wasm_bindgen(method, getter)]
node(this: &Versions) -> JsValue128 fn node(this: &Versions) -> JsValue;
129 }
130