Skip to content

Truly independent web browser

LibWasm: Cap the operand stack height of a function

Andreas Kling94f098743143
diff --git a/Libraries/LibWasm/Module/src/validator.rs b/Libraries/LibWasm/Module/src/validator.rs
index 1f7279f4331..4724b158395 100644
--- a/Libraries/LibWasm/Module/src/validator.rs
+++ b/Libraries/LibWasm/Module/src/validator.rs
@@ -156,6 +156,11 @@ const MAX_FUNCTION_LOCALS: usize = 50_000;
// The maximum number of fields in a struct is 10,000.
const MAX_STRUCT_FIELDS: usize = 10_000;
+// AD-HOC: A function's operand stack lives in its frame, 8 bytes per slot. Its height is capped so the frame size
+// stays far from wrapping a u32 and validation memory stays bounded. A function that needs more than 8 MiB of
+// operand stack could not be entered on a thread stack anyway.
+const MAX_FUNCTION_STACK_SLOTS: u32 = 1 << 20;
+
fn invalid<T>(message: impl Into<String>) -> Result<T> {
Err(Error::invalid(message))
}
@@ -801,6 +806,11 @@ impl FunctionValidator<'_> {
return Err(Error::malformed("unexpected end of section or function"));
}
self.validate_instruction(reader)?;
+ // NB: One instruction pushes at most a few thousand slots, so checking after each one keeps the height
+ // far from wrapping.
+ if self.slot_height > MAX_FUNCTION_STACK_SLOTS {
+ return invalid("operand stack too deep");
+ }
}
if !reader.is_at_end() {
return Err(Error::malformed("section size mismatch"));
diff --git a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-operand-stack-limit.txt b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-operand-stack-limit.txt
index 18c1098b90b..5f4dba2e58f 100644
--- a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-operand-stack-limit.txt
+++ b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-operand-stack-limit.txt
@@ -1,3 +1,3 @@
1000 slots: true
1048000 slots: true
-1049000 slots: true
+1049000 slots: false