rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
98.69k stars 12.75k forks source link

wasip2 uses wasi:random/random to generate hashmap_random_keys #129402

Open juntyr opened 2 months ago

juntyr commented 2 months ago

wasip2 currently still uses (all?) wasip1 implementations internally. The generation of hashmap_random_keys for wasip1 is implemented here: https://github.com/rust-lang/rust/blob/a32d4a0e822a29a6682e08b75a8df4c29c7fa9f1/library/std/src/sys/pal/wasi/helpers.rs#L109-L117 using the wasi::random_get (https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md#-random_getbuf-pointeru8-buf_len-size---result-errno) general-purpose function. With the popular wasi-preview1-component adapter crate (https://github.com/bytecodealliance/wasmtime/tree/main/crates/wasi-preview1-component-adapter), this call is mapped to the wasi:random/random wasip2 interface, which must be backed by a secure random source. This is unfortunate as wasip2 Rust code which only uses randomness in hashmaps now required a secure random source when an insecure one would suffice.

In wasip2, there is the separate wasi:random/insecure-seed interface, which is specifically designed to provide DoS protection when initialising a hash map. When the wasip2 implementation is fleshed out, perhaps the hashmap_random_keys function could be implemented with a pseudo-RNG that is seeded with one call to wasi:random/insecure-seed's insecure-seed()?

cc @alexcrichton

alexcrichton commented 2 months ago

Yes hashmap_random_keys would be a good use case for insecure-random in WASIp2, and there's no blocking reason that hasn't been done yet other than the work just hasn't been prioritized. I think such work shouldn't be too too hard with the wasi crate which libstd already depends on, but most of the work of implementing this would be integrating the wasi crate at the latest version in the standard library as opposed to implementing this function (but getting that work done would pave the way for future updates too)