23 / 08 / 07

Deploying Wasm Securely

WebAssembly, or Wasm for short, provides revolutionary new ways to develop for the web. But like any technology, it has its own security challenges.

Security with WebAssembly: Overview

  • Wasm runs in a sandbox. It is hence isolated from the system it runs on, thereby decreasing possible risk.

  • The WebAssembly execution model is by design strict, keeping behavior well-defined and consistent—something essential for security.

Security challenges with Wasm

  • It is difficult to read and can serve as a potential place to hide malicious code since Wasm is a low-level binary format.

  • High-performance tasks in Wasm can clog CPU resources and create potential DoS attack vectors.

  • Some browser optimizations for Wasm could have vulnerabilities to attacks like Spectre.

Practical Session

Environment Setup

Be sure to check that your Wasm environment is updated.

$ cargo install was time

Compile with Limited Permissions

Define your Wasm functions with minimal permissions. Avoid importing or exporting unnecessarily.

// Rust code targeting Wasm #[no_mangle] pub fn add(a: i32, b: i32) -> i32 { a + b }

Validate and Sanitize Inputs

Guard against hostile or unexpected inputs.

// Loading Wasm in JavaScript WebAssembly.instantiate(wasmModule).then(results => { let add = results.instance.exports.add; let input1 = sanitizeInput(userInput1); let input2 = sanitizeInput(userInput2); console.log(add(input1, input2)); }); function sanitizeInput(input) { // For this example, ensure input is a number and within a safe range let num = parseInt(input); return (isNaN(num) || num > 1000000) ? 0 : num; }

Memory Safety with Wasm

WebAssembly does have a linear memory model; nevertheless, it can still be a security risk without good memory handling. Use language features and tools that prevent buffer overflows and memory access violations.

A real-life example would be how, by working in Rust with Wasm, the ownership model helps to prevent some memory security problems. Always be careful of raw pointers and unsafe blocks.

What is a Safe Third-party

Care must be taken to ensure that third-party modules come from trusted sources. Look for known vulnerabilities; make sure you always use the latest, patched version.

# Using `wasm-pack` to build Rust code to Wasm, and then audit for vulnerabilities $ wasm-pack build $ cargo audit