Skip to content

Commit b4a2bad

Browse files
committed
Add support for Custom RNGS
1 parent 9fd99d8 commit b4a2bad

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,7 @@ wasi = "0.7"
3030

3131
[features]
3232
std = []
33+
# Feature to enable custom RNG implementations
34+
custom = []
3335
# Unstable feature to support being a libstd dependency
3436
rustc-dep-of-std = ["compiler_builtins", "core"]

src/custom.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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+
9+
//! An implementation which calls out to an externally defined function.
10+
use crate::Error;
11+
12+
pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
13+
extern "Rust" {
14+
#[allow(improper_ctypes)] // See rust-lang/rust#64593
15+
fn __getrandom_custom(dest: &mut [u8]) -> Result<(), Error>;
16+
}
17+
unsafe { __getrandom_custom(dest) }
18+
}

src/lib.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,8 @@ cfg_if! {
230230
target_env = "sgx",
231231
)))] {
232232
#[path = "rdrand.rs"] mod imp;
233+
} else if #[cfg(feature = "custom")] {
234+
#[path = "custom.rs"] mod imp;
233235
} else {
234236
compile_error!("\
235237
target is not supported, for more information see: \
@@ -238,6 +240,23 @@ cfg_if! {
238240
}
239241
}
240242

243+
/// Reister a function to be invoked by `getrandom` on custom targets. This
244+
/// function will only be invoked on targets not supported by `getrandom`. This
245+
/// prevents crate dependancies from either inadvertantly or maliciously
246+
/// overriding the secure RNG implementations in `getrandom`.
247+
///
248+
/// *This API requires the following crate features to be activated: `custom`*
249+
#[macro_export]
250+
#[cfg(feature = "custom")]
251+
macro_rules! register_custom_getrandom {
252+
($path:path) => {
253+
#[no_mangle]
254+
fn __getrandom_custom(dest: &mut [u8]) -> Result<(), Error> {
255+
$path(dest)
256+
}
257+
};
258+
}
259+
241260
/// Fill `dest` with random bytes from the system's preferred random number
242261
/// source.
243262
///

0 commit comments

Comments
 (0)