* Validate faulting addresses are valid to fault on This commit adds a defense-in-depth measure to Wasmtime which is intended to mitigate the impact of CVEs such as GHSA-ff4p-7xrq-q5r8. Currently Wasmtime will catch `SIGSEGV` signals for WebAssembly code so long as the instruction which faulted is an allow-listed instruction (aka has a trap code listed for it). With the recent security issue, however, the problem was that a wasm guest could exploit a compiler bug to access memory outside of its sandbox. If the access was successful there's no real way to detect that, but if the access was unsuccessful then Wasmtime would happily swallow the `SIGSEGV` and report a nominal trap. To embedders, this might look like nothing is going awry. The new strategy implemented here in this commit is to attempt to be more robust towards these sorts of failures. When a `SIGSEGV` is raised the faulting pc is recorded but additionally the address of the inaccessible location is also record. After the WebAssembly stack is unwound and control returns to Wasmtime which has access to a `Store` Wasmtime will now use this inaccessible faulting address to translate it to a wasm address. This process should be guaranteed to succeed as WebAssembly should only be able to access a well-defined region of memory for all linear memories in a `Store`. If no linear memory in a `Store` could contain the faulting address, then Wasmtime now prints a scary message and aborts the process. The purpose of this is to catch these sorts of bugs, make them very loud errors, and hopefully mitigate impact. This would continue to not mitigate the impact of a guest successfully loading data outside of its sandbox, but if a guest was doing a sort of probing strategy trying to find valid addresses then any invalid access would turn into a process crash which would immediately be noticed by embedders. While I was here I went ahead and additionally took a stab at #3120. Traps due to `SIGSEGV` will now report the size of linear memory and the address that was being accessed in addition to the bland "access out of bounds" error. While this is still somewhat bland in the context of a high level source language it's hopefully at least a little bit more actionable for some. I'll note though that this isn't a guaranteed contextual message since only the default configuration for Wasmtime generates `SIGSEGV` on out-of-bounds memory accesses. Dynamically bounds-checked configurations, for example, don't do this. Testing-wise I unfortunately am not aware of a great way to test this. The closet equivalent would be something like an `unsafe` method `Config::allow_wasm_sandbox_escape`. In lieu of adding tests, though, I can confirm that during development the crashing messages works just fine as it took awhile on macOS to figure out where the faulting address was recorded in the exception information which meant I had lots of instances of recording an address of a trap not accessible from wasm. * Fix tests * Review comments * Fix compile after refactor * Fix compile on macOS * Fix trap test for s390x s390x rounds faulting addresses to 4k boundaries.
192 lines
5.8 KiB
Rust
192 lines
5.8 KiB
Rust
#[cfg(not(target_os = "windows"))]
|
|
mod not_for_windows {
|
|
use wasmtime::*;
|
|
use wasmtime_environ::{WASM32_MAX_PAGES, WASM_PAGE_SIZE};
|
|
|
|
use rustix::mm::{mmap_anonymous, mprotect, munmap, MapFlags, MprotectFlags, ProtFlags};
|
|
|
|
use std::convert::TryFrom;
|
|
use std::ops::Range;
|
|
use std::ptr::null_mut;
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
struct CustomMemory {
|
|
mem: usize,
|
|
size: usize,
|
|
guard_size: usize,
|
|
used_wasm_bytes: usize,
|
|
glob_bytes_counter: Arc<Mutex<usize>>,
|
|
}
|
|
|
|
impl CustomMemory {
|
|
unsafe fn new(minimum: usize, maximum: usize, glob_counter: Arc<Mutex<usize>>) -> Self {
|
|
let page_size = rustix::param::page_size();
|
|
let guard_size = page_size;
|
|
let size = maximum + guard_size;
|
|
assert_eq!(size % page_size, 0); // we rely on WASM_PAGE_SIZE being multiple of host page size
|
|
|
|
let mem = mmap_anonymous(null_mut(), size, ProtFlags::empty(), MapFlags::PRIVATE)
|
|
.expect("mmap failed");
|
|
|
|
mprotect(mem, minimum, MprotectFlags::READ | MprotectFlags::WRITE)
|
|
.expect("mprotect failed");
|
|
*glob_counter.lock().unwrap() += minimum;
|
|
|
|
Self {
|
|
mem: mem as usize,
|
|
size,
|
|
guard_size,
|
|
used_wasm_bytes: minimum,
|
|
glob_bytes_counter: glob_counter,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Drop for CustomMemory {
|
|
fn drop(&mut self) {
|
|
*self.glob_bytes_counter.lock().unwrap() -= self.used_wasm_bytes;
|
|
unsafe { munmap(self.mem as *mut _, self.size).expect("munmap failed") };
|
|
}
|
|
}
|
|
|
|
unsafe impl LinearMemory for CustomMemory {
|
|
fn byte_size(&self) -> usize {
|
|
self.used_wasm_bytes
|
|
}
|
|
|
|
fn maximum_byte_size(&self) -> Option<usize> {
|
|
Some(self.size - self.guard_size)
|
|
}
|
|
|
|
fn grow_to(&mut self, new_size: usize) -> wasmtime::Result<()> {
|
|
println!("grow to {:x}", new_size);
|
|
let delta = new_size - self.used_wasm_bytes;
|
|
unsafe {
|
|
let start = (self.mem as *mut u8).add(self.used_wasm_bytes) as _;
|
|
mprotect(start, delta, MprotectFlags::READ | MprotectFlags::WRITE)
|
|
.expect("mprotect failed");
|
|
}
|
|
|
|
*self.glob_bytes_counter.lock().unwrap() += delta;
|
|
self.used_wasm_bytes = new_size;
|
|
Ok(())
|
|
}
|
|
|
|
fn as_ptr(&self) -> *mut u8 {
|
|
self.mem as *mut u8
|
|
}
|
|
|
|
fn wasm_accessible(&self) -> Range<usize> {
|
|
let base = self.mem as usize;
|
|
let end = base + self.size;
|
|
base..end
|
|
}
|
|
}
|
|
|
|
struct CustomMemoryCreator {
|
|
pub num_created_memories: Mutex<usize>,
|
|
pub num_total_bytes: Arc<Mutex<usize>>,
|
|
}
|
|
|
|
impl CustomMemoryCreator {
|
|
pub fn new() -> Self {
|
|
Self {
|
|
num_created_memories: Mutex::new(0),
|
|
num_total_bytes: Arc::new(Mutex::new(0)),
|
|
}
|
|
}
|
|
}
|
|
|
|
unsafe impl MemoryCreator for CustomMemoryCreator {
|
|
fn new_memory(
|
|
&self,
|
|
ty: MemoryType,
|
|
minimum: usize,
|
|
maximum: Option<usize>,
|
|
reserved_size: Option<usize>,
|
|
guard_size: usize,
|
|
) -> Result<Box<dyn LinearMemory>, String> {
|
|
assert_eq!(guard_size, 0);
|
|
assert!(reserved_size.is_none());
|
|
assert!(!ty.is_64());
|
|
unsafe {
|
|
let mem = Box::new(CustomMemory::new(
|
|
minimum,
|
|
maximum.unwrap_or(
|
|
usize::try_from(WASM32_MAX_PAGES * u64::from(WASM_PAGE_SIZE)).unwrap(),
|
|
),
|
|
self.num_total_bytes.clone(),
|
|
));
|
|
*self.num_created_memories.lock().unwrap() += 1;
|
|
Ok(mem)
|
|
}
|
|
}
|
|
}
|
|
|
|
fn config() -> (Store<()>, Arc<CustomMemoryCreator>) {
|
|
let mem_creator = Arc::new(CustomMemoryCreator::new());
|
|
let mut config = Config::new();
|
|
config
|
|
.with_host_memory(mem_creator.clone())
|
|
.static_memory_maximum_size(0)
|
|
.dynamic_memory_guard_size(0);
|
|
(Store::new(&Engine::new(&config).unwrap(), ()), mem_creator)
|
|
}
|
|
|
|
#[test]
|
|
fn host_memory() -> anyhow::Result<()> {
|
|
let (mut store, mem_creator) = config();
|
|
let module = Module::new(
|
|
store.engine(),
|
|
r#"
|
|
(module
|
|
(memory (export "memory") 1)
|
|
)
|
|
"#,
|
|
)?;
|
|
Instance::new(&mut store, &module, &[])?;
|
|
|
|
assert_eq!(*mem_creator.num_created_memories.lock().unwrap(), 1);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn host_memory_grow() -> anyhow::Result<()> {
|
|
let (mut store, mem_creator) = config();
|
|
let module = Module::new(
|
|
store.engine(),
|
|
r#"
|
|
(module
|
|
(func $f (drop (memory.grow (i32.const 1))))
|
|
(memory (export "memory") 1 2)
|
|
(start $f)
|
|
)
|
|
"#,
|
|
)?;
|
|
|
|
Instance::new(&mut store, &module, &[])?;
|
|
let instance2 = Instance::new(&mut store, &module, &[])?;
|
|
|
|
assert_eq!(*mem_creator.num_created_memories.lock().unwrap(), 2);
|
|
|
|
assert_eq!(
|
|
instance2
|
|
.get_memory(&mut store, "memory")
|
|
.unwrap()
|
|
.size(&store),
|
|
2
|
|
);
|
|
|
|
// we take the lock outside the assert, so it won't get poisoned on assert failure
|
|
let tot_pages = *mem_creator.num_total_bytes.lock().unwrap();
|
|
assert_eq!(tot_pages, (4 * WASM_PAGE_SIZE) as usize);
|
|
|
|
drop(store);
|
|
let tot_pages = *mem_creator.num_total_bytes.lock().unwrap();
|
|
assert_eq!(tot_pages, 0);
|
|
|
|
Ok(())
|
|
}
|
|
}
|