include a getrandom implementation that allows us to use modern randcore

A lot of packages are depending on 0.6 api, which requires a crate
that has OS specific TRNG calls. This patch keeps the 0.5 calls
inside the TRNG crate as direct API calls, and migrates to support
a 0.6 api to a patched version of getrandom that supports Xous.
This commit is contained in:
bunnie 2022-05-29 02:42:14 +08:00 committed by nworbnhoj
parent ea5276700b
commit 47b76a3d5b
14 changed files with 740 additions and 428 deletions

589
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -69,6 +69,7 @@ members = [
"svd2utra",
"xtask",
"imports/com_rs-ref",
"imports/getrandom",
"services/ime-plugin-api",
"services/content-plugin-api",
"services/llio",
@ -149,5 +150,8 @@ branch="main"
#path = "../usb-device"
# for local dev
[patch.crates-io.usbd-human-interface-device]
path = "../usbd-human-interface-device"
#[patch.crates-io.usbd-human-interface-device]
#path = "../usbd-human-interface-device"
[patch.crates-io.getrandom]
path = "imports/getrandom"

View file

@ -11,7 +11,50 @@ categories = ["os", "no-std"]
exclude = [".*"]
[dependencies]
xous-names = {path = "../../../services/xous-names"}
xous-rs = {path = "../../xous-rs"}
cfg-if = "1"
# When built as part of libstd
compiler_builtins = { version = "0.1", optional = true }
core = { version = "1.0", optional = true, package = "rustc-std-workspace-core" }
[target.'cfg(unix)'.dependencies]
libc = { version = "0.2.120", default-features = false }
[target.'cfg(target_os = "wasi")'.dependencies]
wasi = "0.11"
[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
wasm-bindgen = { version = "0.2.62", default-features = false, optional = true }
js-sys = { version = "0.3", optional = true }
[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dev-dependencies]
wasm-bindgen-test = "0.3.18"
[target.'cfg(target_os = "xous")'.dependencies]
xous-names = {path = "../../services/xous-names"}
xous = {path = "../../xous-rs"}
xous-ipc = {path = "../../xous-ipc"}
rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]}
[features]
# Implement std-only traits for getrandom::Error
std = []
# Feature to enable fallback RDRAND-based implementation on x86/x86_64
rdrand = []
# Feature to enable JavaScript bindings on wasm32-unknown-unknown
js = ["wasm-bindgen", "js-sys"]
# Feature to enable custom RNG implementations
custom = []
# Unstable feature to support being a libstd dependency
rustc-dep-of-std = [
"compiler_builtins",
"core",
"libc/rustc-dep-of-std",
"wasi/rustc-dep-of-std",
]
# Unstable/test-only feature to run wasm-bindgen tests in a browser
test-in-browser = []
[package.metadata.docs.rs]
features = ["std", "custom"]
rustdoc-args = ["--cfg", "docsrs"]

View file

@ -1,3 +1,250 @@
// Copyright 2019 Developers of the Rand project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Interface to the operating system's random number generator.
//!
//! # Supported targets
//!
//! | Target | Target Triple | Implementation
//! | ----------------- | ------------------ | --------------
//! | Linux, Android | `*‑linux‑*` | [`getrandom`][1] system call if available, otherwise [`/dev/urandom`][2] after successfully polling `/dev/random`
//! | Windows | `*‑windows‑*` | [`BCryptGenRandom`]
//! | macOS | `*‑apple‑darwin` | [`getentropy`][3] if available, otherwise [`/dev/random`][4] (identical to `/dev/urandom`)
//! | iOS | `*‑apple‑ios` | [`SecRandomCopyBytes`]
//! | FreeBSD | `*‑freebsd` | [`getrandom`][5] if available, otherwise [`kern.arandom`][6]
//! | OpenBSD | `*‑openbsd` | [`getentropy`][7]
//! | NetBSD | `*‑netbsd` | [`kern.arandom`][8]
//! | Dragonfly BSD | `*‑dragonfly` | [`getrandom`][9] if available, otherwise [`/dev/random`][10]
//! | Solaris, illumos | `*‑solaris`, `*‑illumos` | [`getrandom`][11] if available, otherwise [`/dev/random`][12]
//! | Fuchsia OS | `*‑fuchsia` | [`cprng_draw`]
//! | Redox | `*‑redox` | `/dev/urandom`
//! | Haiku | `*‑haiku` | `/dev/random` (identical to `/dev/urandom`)
//! | Hermit | `x86_64-*-hermit` | [`RDRAND`]
//! | SGX | `x86_64‑*‑sgx` | [`RDRAND`]
//! | VxWorks | `*‑wrs‑vxworks‑*` | `randABytes` after checking entropy pool initialization with `randSecure`
//! | ESP-IDF | `*‑espidf` | [`esp_fill_random`]
//! | Emscripten | `*‑emscripten` | `/dev/random` (identical to `/dev/urandom`)
//! | WASI | `wasm32‑wasi` | [`random_get`]
//! | Web Browser | `wasm32‑*‑unknown` | [`Crypto.getRandomValues`], see [WebAssembly support]
//! | Node.js | `wasm32‑*‑unknown` | [`crypto.randomBytes`], see [WebAssembly support]
//! | SOLID | `*-kmc-solid_*` | `SOLID_RNG_SampleRandomBytes`
//! | Nintendo 3DS | `armv6k-nintendo-3ds` | [`getrandom`][1]
//! | Xous | `riscv32imac-unknown-xous-elf` | [`trng`]
//!
//! There is no blanket implementation on `unix` targets that reads from
//! `/dev/urandom`. This ensures all supported targets are using the recommended
//! interface and respect maximum buffer sizes.
//!
//! Pull Requests that add support for new targets to `getrandom` are always welcome.
//!
//! ## Unsupported targets
//!
//! By default, `getrandom` will not compile on unsupported targets, but certain
//! features allow a user to select a "fallback" implementation if no supported
//! implementation exists.
//!
//! All of the below mechanisms only affect unsupported
//! targets. Supported targets will _always_ use their supported implementations.
//! This prevents a crate from overriding a secure source of randomness
//! (either accidentally or intentionally).
//!
//! ### RDRAND on x86
//!
//! *If the `rdrand` Cargo feature is enabled*, `getrandom` will fallback to using
//! the [`RDRAND`] instruction to get randomness on `no_std` `x86`/`x86_64`
//! targets. This feature has no effect on other CPU architectures.
//!
//! ### WebAssembly support
//!
//! This crate fully supports the
//! [`wasm32-wasi`](https://github.com/CraneStation/wasi) and
//! [`wasm32-unknown-emscripten`](https://www.hellorust.com/setup/emscripten/)
//! targets. However, the `wasm32-unknown-unknown` target (i.e. the target used
//! by `wasm-pack`) is not automatically
//! supported since, from the target name alone, we cannot deduce which
//! JavaScript interface is in use (or if JavaScript is available at all).
//!
//! Instead, *if the `js` Cargo feature is enabled*, this crate will assume
//! that you are building for an environment containing JavaScript, and will
//! call the appropriate methods. Both web browser (main window and Web Workers)
//! and Node.js environments are supported, invoking the methods
//! [described above](#supported-targets) using the
//! [wasm-bindgen](https://github.com/rust-lang/rust-bindgen) toolchain.
//!
//! This feature has no effect on targets other than `wasm32-unknown-unknown`.
//!
//! ### Custom implementations
//!
//! The [`register_custom_getrandom!`] macro allows a user to mark their own
//! function as the backing implementation for [`getrandom`]. See the macro's
//! documentation for more information about writing and registering your own
//! custom implementations.
//!
//! Note that registering a custom implementation only has an effect on targets
//! that would otherwise not compile. Any supported targets (including those
//! using `rdrand` and `js` Cargo features) continue using their normal
//! implementations even if a function is registered.
//!
//! ### Indirect Dependencies
//!
//! If `getrandom` is not a direct dependency of your crate, you can still
//! enable any of the above fallback behaviors by enabling the relevant
//! feature in your root crate's `Cargo.toml`:
//! ```toml
//! [dependencies]
//! getrandom = { version = "0.2", features = ["js"] }
//! ```
//!
//! ## Early boot
//!
//! Sometimes, early in the boot process, the OS has not collected enough
//! entropy to securely seed its RNG. This is especially common on virtual
//! machines, where standard "random" events are hard to come by.
//!
//! Some operating system interfaces always block until the RNG is securely
//! seeded. This can take anywhere from a few seconds to more than a minute.
//! A few (Linux, NetBSD and Solaris) offer a choice between blocking and
//! getting an error; in these cases, we always choose to block.
//!
//! On Linux (when the `getrandom` system call is not available), reading from
//! `/dev/urandom` never blocks, even when the OS hasn't collected enough
//! entropy yet. To avoid returning low-entropy bytes, we first poll
//! `/dev/random` and only switch to `/dev/urandom` once this has succeeded.
//!
//! ## Error handling
//!
//! We always choose failure over returning insecure "random" bytes. In general,
//! on supported platforms, failure is highly unlikely, though not impossible.
//! If an error does occur, then it is likely that it will occur on every call to
//! `getrandom`, hence after the first successful call one can be reasonably
//! confident that no errors will occur.
//!
//! [1]: http://man7.org/linux/man-pages/man2/getrandom.2.html
//! [2]: http://man7.org/linux/man-pages/man4/urandom.4.html
//! [3]: https://www.unix.com/man-page/mojave/2/getentropy/
//! [4]: https://www.unix.com/man-page/mojave/4/random/
//! [5]: https://www.freebsd.org/cgi/man.cgi?query=getrandom&manpath=FreeBSD+12.0-stable
//! [6]: https://www.freebsd.org/cgi/man.cgi?query=random&sektion=4
//! [7]: https://man.openbsd.org/getentropy.2
//! [8]: https://man.netbsd.org/sysctl.7
//! [9]: https://leaf.dragonflybsd.org/cgi/web-man?command=getrandom
//! [10]: https://leaf.dragonflybsd.org/cgi/web-man?command=random&section=4
//! [11]: https://docs.oracle.com/cd/E88353_01/html/E37841/getrandom-2.html
//! [12]: https://docs.oracle.com/cd/E86824_01/html/E54777/random-7d.html
//!
//! [`BCryptGenRandom`]: https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom
//! [`Crypto.getRandomValues`]: https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues
//! [`RDRAND`]: https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide
//! [`SecRandomCopyBytes`]: https://developer.apple.com/documentation/security/1399291-secrandomcopybytes?language=objc
//! [`cprng_draw`]: https://fuchsia.dev/fuchsia-src/zircon/syscalls/cprng_draw
//! [`crypto.randomBytes`]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback
//! [`esp_fill_random`]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html#_CPPv415esp_fill_randomPv6size_t
//! [`random_get`]: https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---errno
//! [WebAssembly support]: #webassembly-support
#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://docs.rs/getrandom/0.2.6"
)]
#![no_std]
#![warn(rust_2018_idioms, unused_lifetimes, missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#[macro_use]
extern crate cfg_if;
mod error;
mod util;
// To prevent a breaking change when targets are added, we always export the
// register_custom_getrandom macro, so old Custom RNG crates continue to build.
#[cfg(feature = "custom")]
mod custom;
#[cfg(feature = "std")]
mod error_impls;
pub use crate::error::Error;
// System-specific implementations.
//
// These should all provide getrandom_inner with the same signature as getrandom.
cfg_if! {
if #[cfg(any(target_os = "emscripten", target_os = "haiku",
target_os = "redox"))] {
mod util_libc;
#[path = "use_file.rs"] mod imp;
} else if #[cfg(any(target_os = "android", target_os = "linux"))] {
mod util_libc;
mod use_file;
#[path = "linux_android.rs"] mod imp;
} else if #[cfg(any(target_os = "illumos", target_os = "solaris"))] {
mod util_libc;
mod use_file;
#[path = "solaris_illumos.rs"] mod imp;
} else if #[cfg(any(target_os = "freebsd", target_os = "netbsd"))] {
mod util_libc;
#[path = "bsd_arandom.rs"] mod imp;
} else if #[cfg(target_os = "dragonfly")] {
mod util_libc;
mod use_file;
#[path = "dragonfly.rs"] mod imp;
} else if #[cfg(target_os = "fuchsia")] {
#[path = "fuchsia.rs"] mod imp;
} else if #[cfg(target_os = "ios")] {
#[path = "ios.rs"] mod imp;
} else if #[cfg(target_os = "macos")] {
mod util_libc;
mod use_file;
#[path = "macos.rs"] mod imp;
} else if #[cfg(target_os = "openbsd")] {
mod util_libc;
#[path = "openbsd.rs"] mod imp;
} else if #[cfg(target_os = "wasi")] {
#[path = "wasi.rs"] mod imp;
} else if #[cfg(all(target_arch = "x86_64", target_os = "hermit"))] {
#[path = "rdrand.rs"] mod imp;
} else if #[cfg(target_os = "vxworks")] {
mod util_libc;
#[path = "vxworks.rs"] mod imp;
} else if #[cfg(target_os = "solid_asp3")] {
#[path = "solid.rs"] mod imp;
} else if #[cfg(target_os = "espidf")] {
#[path = "espidf.rs"] mod imp;
} else if #[cfg(windows)] {
#[path = "windows.rs"] mod imp;
} else if #[cfg(all(target_arch = "x86_64", target_env = "sgx"))] {
#[path = "rdrand.rs"] mod imp;
} else if #[cfg(all(feature = "rdrand",
any(target_arch = "x86_64", target_arch = "x86")))] {
#[path = "rdrand.rs"] mod imp;
} else if #[cfg(all(feature = "js",
target_arch = "wasm32", target_os = "unknown"))] {
#[path = "js.rs"] mod imp;
} else if #[cfg(all(target_os = "horizon", target_arch = "arm"))] {
// We check for target_arch = "arm" because the Nintendo Switch also
// uses Horizon OS (it is aarch64).
mod util_libc;
#[path = "3ds.rs"] mod imp;
} else if #[cfg(target_os = "xous")] {
#[path = "xous.rs"] mod imp;
} else if #[cfg(feature = "custom")] {
use custom as imp;
} else if #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] {
compile_error!("the wasm32-unknown-unknown target is not supported by \
default, you may need to enable the \"js\" feature. \
For more information see: \
https://docs.rs/getrandom/#webassembly-support");
} else {
compile_error!("target is not supported, for more information see: \
https://docs.rs/getrandom/#unsupported-targets");
}
}
/// Fill `dest` with random bytes from the system's preferred random number
/// source.
///
@ -11,86 +258,9 @@
/// In general, `getrandom` will be fast enough for interactive usage, though
/// significantly slower than a user-space CSPRNG; for the latter consider
/// [`rand::thread_rng`](https://docs.rs/rand/*/rand/fn.thread_rng.html).
use std::atomic::AtomicU32;
use std::atomic::Ordering::*;
use xous_ipc::Buffer;
static TRNG_CONN: AtomicU32 = AtomicU32::new(0);
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
struct TrngBuf {
pub data: [u32; 1024],
pub len: u16,
}
fn ensure_trng_conn() {
if TRNG_CONN.load(Ordering::SeqCst) == 0 {
let xns = xous_names::XousNames::new().unwrap();
TRNG_CONN.store(
xns
.request_connection_blocking("_TRNG manager_")
.expect("Can't connect to TRNG server")
);
}
}
pub fn getrandom(dest: &mut [u8]) -> Result<(), Error> {
if dest.is_empty() {
return Ok(());
}
ensure_trng_conn();
fill_bytes(dest);
Ok(())
}
pub fn fill_buf(data: &mut [u32]) {
let mut tb = TrngBuf {
data: [0; 1024],
len: 0,
};
assert!(data.len() > tb.data.len());
tb.len = data.len() as u16;
let mut buf = Buffer::into_buf(tb).or(Err(xous::Error::InternalError)).unwrap();
buf.lend_mut(TRNG_CONN.load(Ordering::SeqCst), api::Opcode::FillTrng.to_u32().unwrap()).unwrap();
let rtb: TrngBuf = buf.as_flat().unwrap();
assert!(rtb.len as usize == data.len());
data.copy_from_slice(&rtb.data);
}
/// this is less efficient that the implementation in TRNG, but has fewer dependencies
/// In particular, it will always use a memory message to fetch a TRNG value, even if it's just a u32 or u64
fn fill_bytes(dest: &mut [u8]) {
// big chunks handled here, using in-place transformations
for chunk in dest.chunks_exact_mut(4096) {
let chunk_u32 = unsafe {
core::slice::from_raw_parts_mut(dest.as_mut_ptr() as *mut u32, chunk.len() / 4)
};
fill_buf(&chunk);
}
// smaller chunks, we absorb the fill_buf routine above here so we amortize the cost of
// initializing the empty 4k-page...
let remainder = dest.chunks_exact_mut(4096).into_remainder();
if remainder.len() != 0 {
let mut tb = TrngBuf {
data: [0; 1024],
len: 0,
};
tb.len = if remainder.len() % 4 == 0 {
remainder.len() / 4
} else {
1 + (remainder.len() / 4)
};
let mut buf = Buffer::into_buf(tb).unwrap();
buf.lend_mut(TRNG_CONN.load(Ordering::SeqCst), api::Opcode::FillTrng.to_u32().unwrap()).unwrap();
let rtb: TrngBuf = buf.as_flat().unwrap();
// copy the bulk
dest.copy_from_slice(&tb.data[..remainder.len() / 4]);
// handle the trailing odd bytes, if any
if remainder.len() % 4 != 0 {
let last_word = tb.data[remainder.len() / 4 .. 1 + remainder.len() / 4][0].to_le_bytes();
for (&src, dst) in last_word.iter().zip(dest[remainder.len() / 4 .. remainder.len()].iter_mut()) {
*dst = src;
}
}
}
imp::getrandom_inner(dest)
}

View file

@ -31,7 +31,6 @@ chrono = "0.4.19"
[dev-dependencies]
"chrono" = "0.4.19"
"rand" = "0.8.5"
[features]
debugprint = []

View file

@ -21,7 +21,6 @@ rkyv = {version = "0.4.3", features = ["const_generics"], default-features = fal
trng = {path = "../trng"}
spinor = {path = "../spinor"}
aes = {path="../aes"}
rand_core = "0.5.1"
root-keys = {path="../root-keys"}
cipher = "0.3.0"
bitfield = "0.13.2"

View file

@ -1,6 +1,5 @@
use core::mem::size_of;
use aes_gcm_siv::Nonce;
use rand_core::RngCore;
use std::convert::TryInto;
use core::cell::RefCell;

View file

@ -51,7 +51,6 @@ aes={path="../aes"}
engine-25519 = {path="../engine-25519"}
byteorder = "1.4.3" # used by keywrap
# hardware acceleration adaptations are inserted into a fork of the main branch.
rand_core = "0.5.1"
hex = {version = "0.4.3", default-features = false, features = []}
[dependencies.curve25519-dalek]
version = "3.1.0" # note this is patched to our fork in ./Cargo.toml

View file

@ -24,7 +24,6 @@ use digest::Digest;
use graphics_server::BulkRead;
use core::mem::size_of;
use core::cell::RefCell;
use rand_core::RngCore;
use aes::{Aes256, NewBlockCipher, BlockDecrypt, BlockEncrypt};
use cipher::generic_array::GenericArray;

View file

@ -58,9 +58,12 @@ com_rs-ref = {path = "../../imports/com_rs-ref"}
# for net testing
threadpool = "1.8.1"
# testing rand compatibility - this is chasing the devil, but unfortunately
# a *lot* of useful packages are chasing this devil.
rand = {version = "0.8.5", features = ["getrandom"]}
# for the curve25519 tests
# hardware acceleration adaptations are inserted into a fork of the main branch.
rand_core = "0.5.1"
hex = {version = "0.4.3", default-features = false, features = []}
#sha2 = {version = "0.9.5", default-features = false, features = []}
[dependencies.curve25519-dalek]

View file

@ -67,6 +67,69 @@ impl<'a> ShellCmdApi<'a> for TrngCmd {
}
write!(ret, "Pumped {}x1k values out of the engine", ROUNDS).unwrap();
}
// rand_core API tests - commented out because they only need to be run once, basically.
/*
"api" => {
// the purpose of these tests is to check the edge-case code because
// the trng fetch is u32, but rand_core allows u8
use rand::rngs::OsRng;
use rand::RngCore;
let mut test1 = [0u8; 1];
OsRng.fill_bytes(&mut test1);
log::info!("test 1: {:?}", test1);
let mut test2 = [0u8; 2];
OsRng.fill_bytes(&mut test2);
log::info!("test 2: {:?}", test2);
let mut test3 = [0u8; 3];
OsRng.fill_bytes(&mut test3);
log::info!("test 3: {:?}", test3);
let mut test4 = [0u8; 4];
OsRng.fill_bytes(&mut test4);
log::info!("test 4: {:?}", test4);
let mut test5 = [0u8; 5];
OsRng.fill_bytes(&mut test5);
log::info!("test 5: {:?}", test5);
let mut test6 = [0u8; 6];
OsRng.fill_bytes(&mut test6);
log::info!("test 6: {:?}", test6);
let mut test7 = [0u8; 7];
OsRng.fill_bytes(&mut test7);
log::info!("test 7: {:?}", test7);
let mut test8 = [0u8; 8];
OsRng.fill_bytes(&mut test8);
log::info!("test 8: {:?}", test8);
let mut test4095 = [0u8; 4095];
OsRng.fill_bytes(&mut test4095);
log::info!("test 4095: {:?}", &test4095[4092..]);
let mut test4096 = [0u8; 4096];
OsRng.fill_bytes(&mut test4096);
log::info!("test 4096: {:?}", &test4096[4092..]);
let mut test4097 = [0u8; 4097];
OsRng.fill_bytes(&mut test4097);
log::info!("test 4097: {:?}", &test4097[4092..]);
let mut test4098 = [0u8; 4098];
OsRng.fill_bytes(&mut test4098);
log::info!("test 4098: {:?}", &test4098[4092..]);
let mut test4099 = [0u8; 4099];
OsRng.fill_bytes(&mut test4099);
log::info!("test 4099: {:?}", &test4099[4092..]);
let mut test4100 = [0u8; 4100];
OsRng.fill_bytes(&mut test4100);
log::info!("test 4100: {:?}", &test4100[4092..]);
} */
"errs" => {
write!(ret, "TRNG error stats: {:?}", env.trng.get_error_stats().unwrap()).unwrap();
}

View file

@ -17,13 +17,12 @@ num-traits = {version = "0.2.14", default-features = false}
susres = {path = "../susres"}
rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]}
xous-ipc = {path = "../../xous-ipc"}
rand_core = "0.5.1"
[target.'cfg(not(any(windows,unix)))'.dependencies]
utralib = { path = "../../utralib"}
[target.'cfg(any(windows,unix))'.dependencies]
rand = "0.7.3"
rand = "0.8.5"
rand_chacha = "0.3.1"
[features]

View file

@ -48,30 +48,33 @@ pub struct TrngBuf {
pub len: u16,
}
/// These opcode numbers are partially baked into the `getrandom` library --
/// which kind of acts as a `std`-lib-ish style interface for the trng, so,
/// by design it can't have a dependency on this crate :-/
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
pub(crate) enum Opcode {
/// Get one or two 32-bit words of TRNG data
GetTrng,
GetTrng = 0,
/// Fill a buffer with random data
FillTrng,
FillTrng = 1,
/// Suspend/resume callback
SuspendResume,
SuspendResume = 2,
/// Notification of an error from the interrupt handler
ErrorNotification,
ErrorNotification = 3,
/// Subscribe to error notifications
ErrorSubscribe,
ErrorSubscribe = 4,
/// Get TRNG health stats
HealthStats,
HealthStats = 5,
/// Get Error stats
ErrorStats,
ErrorStats = 6,
Quit,
Quit = 7,
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]

View file

@ -117,52 +117,18 @@ impl Trng {
.or(Err(xous::Error::InternalError))?;
Ok(buf.to_original().unwrap())
}
}
use core::sync::atomic::{AtomicU32, Ordering};
static REFCOUNT: AtomicU32 = AtomicU32::new(0);
impl Drop for Trng {
fn drop(&mut self) {
// de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection.
if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
unsafe {
xous::disconnect(self.conn).unwrap();
}
}
}
}
fn error_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
let sid = xous::SID::from_u32(sid0 as u32, sid1 as u32, sid2 as u32, sid3 as u32);
loop {
let msg = xous::receive_message(sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(api::EventCallback::Event) => xous::msg_scalar_unpack!(msg, cid, id, _, _, {
// directly pass the scalar message onto the CID with the ID memorized in the original hook
send_message(cid as u32, xous::Message::new_scalar(id, 0, 0, 0, 0)).unwrap();
}),
Some(api::EventCallback::Drop) => {
break; // this exits the loop and kills the thread
}
None => (),
}
}
xous::destroy_server(sid).unwrap();
}
use rand_core::{impls, CryptoRng, RngCore};
impl CryptoRng for Trng {}
impl RngCore for Trng {
fn next_u32(&mut self) -> u32 {
// legacy (0.5) trng apis
pub fn next_u32(&mut self) -> u32 {
self.get_u32().expect("couldn't get random u32 from server")
}
fn next_u64(&mut self) -> u64 {
pub fn next_u64(&mut self) -> u64 {
self.get_u64().expect("couldn't get random u64 from server")
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
pub fn fill_bytes(&mut self, dest: &mut [u8]) {
// smaller than 64 bytes (512 bits), just use 8x next_u64 calls to fill.
if dest.len() < 64 {
return impls::fill_bytes_via_next(self, dest);
return self.fill_bytes_via_next(dest);
}
// one page is the max size we can do with the fill_buf() API
let chunks_page = dest.chunks_exact_mut(4096);
@ -216,9 +182,62 @@ impl RngCore for Trng {
.into_remainder()
.chunks_exact_mut(64)
.into_remainder();
impls::fill_bytes_via_next(self, leftovers);
self.fill_bytes_via_next(leftovers);
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
Ok(self.fill_bytes(dest))
/// This is copied out of the 0.5 API for rand_core
fn fill_bytes_via_next(&mut self, dest: &mut [u8]) {
use core::mem::transmute;
let mut left = dest;
while left.len() >= 8 {
let (l, r) = {left}.split_at_mut(8);
left = r;
let chunk: [u8; 8] = unsafe {
transmute(self.next_u64().to_le())
};
l.copy_from_slice(&chunk);
}
let n = left.len();
if n > 4 {
let chunk: [u8; 8] = unsafe {
transmute(self.next_u64().to_le())
};
left.copy_from_slice(&chunk[..n]);
} else if n > 0 {
let chunk: [u8; 4] = unsafe {
transmute(self.next_u32().to_le())
};
left.copy_from_slice(&chunk[..n]);
}
}
}
use core::sync::atomic::{AtomicU32, Ordering};
static REFCOUNT: AtomicU32 = AtomicU32::new(0);
impl Drop for Trng {
fn drop(&mut self) {
// de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection.
if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
unsafe {
xous::disconnect(self.conn).unwrap();
}
}
}
}
fn error_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
let sid = xous::SID::from_u32(sid0 as u32, sid1 as u32, sid2 as u32, sid3 as u32);
loop {
let msg = xous::receive_message(sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(api::EventCallback::Event) => xous::msg_scalar_unpack!(msg, cid, id, _, _, {
// directly pass the scalar message onto the CID with the ID memorized in the original hook
send_message(cid as u32, xous::Message::new_scalar(id, 0, 0, 0, 0)).unwrap();
}),
Some(api::EventCallback::Drop) => {
break; // this exits the loop and kills the thread
}
None => (),
}
}
xous::destroy_server(sid).unwrap();
}