Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

wasip3: Limit random number generation by default (#12745)

Alex Crichton3f3d65b09ca5
diff --git a/crates/test-programs/src/bin/p3_cli_random_limits.rs b/crates/test-programs/src/bin/p3_cli_random_limits.rs
new file mode 100644
index 0000000000..b4212dceee
--- /dev/null
+++ b/crates/test-programs/src/bin/p3_cli_random_limits.rs
@@ -0,0 +1,26 @@
+use test_programs::p3::wasi::random;
+
+struct Component;
+
+test_programs::p3::export!(Component);
+
+impl test_programs::p3::exports::wasi::cli::run::Guest for Component {
+ async fn run() -> Result<(), ()> {
+ let args = std::env::args().collect::<Vec<_>>();
+ let args = args.iter().map(|s| s.as_str()).collect::<Vec<_>>();
+ match &args[1..] {
+ ["random", n] => {
+ random::random::get_random_bytes(n.parse().unwrap());
+ }
+ ["insecure", n] => {
+ random::insecure::get_insecure_random_bytes(n.parse().unwrap());
+ }
+ other => {
+ panic!("unexpected args: {other:?}");
+ }
+ }
+ Ok(())
+ }
+}
+
+fn main() {}
diff --git a/crates/wasi/src/p3/random/host.rs b/crates/wasi/src/p3/random/host.rs
index 03f106a078..163248fcd5 100644
--- a/crates/wasi/src/p3/random/host.rs
+++ b/crates/wasi/src/p3/random/host.rs
@@ -1,11 +1,14 @@
-use cap_rand::Rng;
-use cap_rand::distributions::Standard;
-
use crate::p3::bindings::random::{insecure, insecure_seed, random};
use crate::random::WasiRandomCtx;
+use cap_rand::Rng;
+use cap_rand::distributions::Standard;
+use wasmtime::bail;
impl random::Host for WasiRandomCtx {
fn get_random_bytes(&mut self, len: u64) -> wasmtime::Result<Vec<u8>> {
+ if len > self.max_size {
+ bail!("requested len {len:?} exceeds limit {}", self.max_size);
+ }
Ok((&mut self.random)
.sample_iter(Standard)
.take(len as usize)
@@ -19,6 +22,9 @@ impl random::Host for WasiRandomCtx {
impl insecure::Host for WasiRandomCtx {
fn get_insecure_random_bytes(&mut self, len: u64) -> wasmtime::Result<Vec<u8>> {
+ if len > self.max_size {
+ bail!("requested len {len:?} exceeds limit {}", self.max_size);
+ }
Ok((&mut self.insecure_random)
.sample_iter(Standard)
.take(len as usize)
diff --git a/tests/all/cli_tests.rs b/tests/all/cli_tests.rs
index 122181e288..4aaa0d692f 100644
--- a/tests/all/cli_tests.rs
+++ b/tests/all/cli_tests.rs
@@ -2757,6 +2757,29 @@ start a print 1234
}
Ok(())
}
+
+ #[test]
+ fn p3_cli_random_limits() -> Result<()> {
+ let c = P3_CLI_RANDOM_LIMITS_COMPONENT;
+
+ for rand in ["random", "insecure"] {
+ run_wasmtime(&["run", "-Sp3", "-Wcomponent-model-async", c, rand, "256"])?;
+ assert!(
+ run_wasmtime(&[
+ "run",
+ "-Sp3",
+ "-Wcomponent-model-async",
+ "-Smax-random-size=255",
+ c,
+ rand,
+ "256"
+ ])
+ .is_err()
+ );
+ }
+
+ Ok(())
+ }
}
#[test]