Elamur Research

Provably-Safe Multilingual Software Sandboxing using WebAssembly

Paper · 2022 · Jay Bosamiya, Wen Shih Lim and Bryan Parno

Summary

A video player may need to run a codec it has little reason to trust. An edge computing service may need to run code supplied by a customer. In both cases, the host wants to give the code enough access to do its job while keeping the rest of the process beyond its reach. The authors study how to enforce that separation using WebAssembly, or Wasm. Since languages including C, C++, Rust, and Go already compile to Wasm, an isolation mechanism at this level can serve programs from many languages. Wasm describes where a program may read, write, and transfer control. The compiler and runtime still have to enforce those rules when the program runs on a real processor.

The paper develops two compilers with different ways of establishing that their output stays inside the sandbox. vWasm uses F*, a programming language and proof assistant, to check a mathematical argument about the x86-64 code it produces. The proof follows execution one machine instruction at a time and shows that the compiled program stays within its assigned memory and control-flow boundaries. Interaction with the host goes through an explicitly supplied interface. The proof covers containment even if the compiler’s early translation stages make a mistake that changes the program’s result.

rWasm translates Wasm into safe Rust and lets the Rust compiler generate native code. Its isolation argument depends on the guarantees of safe Rust and on how the host grants access to memory and services. The authors explain this argument without building a machine-checked proof for rWasm. The design supports the architectures targeted by the Rust compiler, uses resizable memory by default, and makes it possible to add tracing or policy checks to generated programs.

On PolyBench-C, rWasm delivered execution times close to several runtimes optimized for speed and outperformed even the fastest runtime on some individual benchmarks. vWasm consistently beat the interpreters but trailed the other compilers. Disabling its verified sandboxing pass changed mean execution time by only 0.2%, suggesting that its limited code optimization accounted for most of the gap in that evaluation. An image conversion test also showed both sandboxes containing a failure in a vulnerable library and returning control safely to the host. The paper’s guarantees concern protection of the host under a trusted interface. They leave the module’s own bugs, denial of service, and attacks that use speculative execution or side channels outside their scope.

Deep dive: Provably-Safe Multilingual Software Sandboxing using WebAssembly

Two WebAssembly compilers use machine-checked proofs and safe Rust to isolate untrusted code, with different trade-offs in speed and assurance. · about 32 minutes to read

The problem and its context

Isolation within a process

A host application may rely on software it would prefer to run with limited authority. The paper considers plugins, third-party libraries, client-side Web code, services at the network edge, and smart contracts. A video player illustrates why the unit of isolation can be smaller than an application. The player may run several codecs, need to call them frequently, and want each one to work with only the data it has been given. If every codec runs as ordinary native code with the host’s privileges, a memory error in a codec can affect data or execution well beyond it.

An operating system can put code in a separate process. That gives the host an established boundary, with communication mediated through the operating system. The paper points out the cost when a workload has to cross that boundary often. Communication can involve privilege transitions and effects on processor caches, among other overheads. The authors also discuss containers and stronger isolation based on virtual machines or hypervisors. They describe the latter as comparatively heavyweight and often dependent on hardware support. These approaches give context for the paper’s interest in boundaries that can be enforced inside one process.

Software fault isolation, or SFI, puts restrictions into the code itself. The program shares a process with its host, and potentially with other isolated modules. Instructions that might reach beyond the module’s region are constrained before they execute. For a memory operation, the added code might check an address against the permitted bounds. Another approach restricts the computed offset using a bit mask. The particular strategy matters for speed and for what the program does when it requests an invalid access.

For these restrictions to matter, execution has to reach the appropriate checks before it reaches the instructions they protect. A program that could jump into the middle of an instruction sequence could escape the intended checks. SFI therefore also relies on control-flow integrity, a restriction on the destinations at which execution can begin or resume. This makes the memory and control-flow parts of isolation interdependent. A proof for the address check has practical significance only when the code cannot reach the protected access through an unchecked route.

Why start from WebAssembly

Earlier approaches described in the paper include language-specific virtual machines and Web technologies such as Java applets, ActiveX, Flash, and Native Client. A language virtual machine can provide isolation, but the implementation of that virtual machine has to be trusted to enforce the boundary. The intended audience is also tied to the language or environment it supports. JavaScript remained widely available on the Web, but the authors describe its limitations as a general compilation target as part of the motivation for WebAssembly.

Wasm gives source languages a shared format with a small instruction set, a type system, and rules for control flow. It describes computation in terms of a virtual operand stack. An instruction obtains inputs from that stack and can leave a result for subsequent instructions. The format organizes code and data into modules. Each module can contain functions, scalar globals, and a byte array called linear memory. Its memory can grow, and its length is expressed in units of 64 KiB. The bytes in linear memory are separate from the module’s other components.

That separation helps explain what a memory access is supposed to mean. A Wasm load that addresses linear memory asks for bytes within that array. The same address cannot also name a module global or a function table entry. Functions are called directly or through a table of possible indirect targets. Branches inside a function are structured around enclosing blocks and loops. The Wasm rules define these operations before any particular runtime chooses how to represent them on a machine.

The core language leaves the host interface to the embedding application. A module declares what it imports, and the host supplies the corresponding capabilities. A browser and a service outside the browser can therefore expose different operations while using the same core language. The WebAssembly System Interface, or WASI, gives non-browser runtimes a system interface in the style of POSIX. The implementations in the paper can work with WASI, but their approach to isolation does not require the host to choose it.

This common format is what the authors call a narrow waist. Support for a source language can come from an existing compiler that already emits Wasm. The sandboxing implementation then deals with that output format and its execution rules. The security work can serve many frontends, and a source program is covered by the containment argument even when its original language permits errors such as buffer overflows. The paper describes Wasm as considerably smaller than x86-64 and easier to reason about because of its structured operations and largely deterministic behavior. Floating-point operations involving NaNs are its stated exception to determinism.

Where existing execution strategies fit

The boundary at the Wasm level has to survive translation into running code. An interpreter represents operations inside its own execution engine. It can enforce the boundary as each operation is handled, subject to the reliability of that implementation. Interpretation also adds work while the program is running. The paper places interpreters toward the higher-assurance, lower-speed part of its design space and points to a verified interpreter as an example of how assurance can be strengthened. Mechanising and Verifying the WebAssembly Specification

Compilers do more of the work before the resulting instructions execute. An ahead-of-time compiler can spend time on optimization before a workload goes live. A just-in-time compiler has to account for compilation on the path to getting a result, so the balance between preparation and execution is different. Both kinds have to preserve the boundary through their translation and optimization stages. The paper cites failures in existing Wasm runtimes as evidence that a carefully written language specification is insufficient by itself. A defect in the implementation can invalidate the restrictions the compiled program is supposed to obey.

One earlier SFI strategy assigns another program, the validator, the job of checking the machine code before it runs. Native Client and RockSalt use toolchains designed to make their output amenable to such a check. VeriWasm studies how to validate output from an existing compiler. That task can be harder because the validator must recognize the effects of independently chosen machine instructions and optimizations. The paper reports that a signedness error in VeriWasm’s specification caused it to miss a previously identified sandbox defect. The example illustrates the importance of the specification on which a validation proof rests. The authors see validation and safe code generation as complementary ways to check the same boundary. Native Client

The paper also draws a distinction between containment and compiler correctness, using work such as CompCert to explain the latter. Compiler correctness is a statement about the relationship between what a source program means and what its translation does. Containment is a statement about the actions that the resulting program can take in its execution environment. A translation can return the wrong value and still stay inside its allocated memory. Proving safety from preservation of source behavior would require an argument that the source behaviors being preserved are themselves contained. The authors discuss that route for Wasm, then develop techniques that establish a boundary directly for the output.

The method, step by step

What the host grants to a module

In the paper’s threat scenario, the host executes a module whose code may be buggy or deliberately malicious. Calls can start at entry points the module has explicitly exposed. The caller may supply arbitrary argument values and may alter the contents of linear memory between executions. A containment argument must therefore hold even when the input state of the module is unfavorable. An ordinary test with a cooperative caller exercises only a fraction of the cases relevant to that argument.

The host decides what memory to give the module and which operations it may request through imports. The goal is for these choices to govern access throughout execution. A module can act on its own state and invoke the services actually granted to it. The host is trusted to make those grants sensibly and to maintain the execution environment. A host service whose design allows a caller to misuse the host’s authority is a separate issue from whether the module’s machine instructions stay within their boundary.

Both compilers start with Wasm binaries and ultimately produce native code. Their routes differ at the point where restrictions become enforceable. In vWasm, an F* pass transforms an intermediate program and comes with a proof about what the resulting instructions can do. In rWasm, the generated program is expressed in the safe subset of Rust, so the Rust compilation process supplies the relevant memory-safety guarantees. The passes before that point still matter for speed and for faithfully translating the input program.

How vWasm and rWasm turn Wasm into sandboxed native code

The steps in order.

How vWasm and rWasm turn Wasm into sandboxed native codeStep 1: Receive a WebAssembly module1. Receive a WebAssembly moduleStep 2: Parse the module into an intermediate representation2. Parse the module into an intermediate representationStep 3: vWasm rewrites operations with verified containment checks3. vWasm rewrites operations with verified containment checksStep 4: vWasm prints and assembles x86-64 code4. vWasm prints and assembles x86-64 codeStep 5: rWasm analyzes stack use and unreachable code5. rWasm analyzes stack use and unreachable codeStep 6: rWasm emits Rust with unsafe code forbidden6. rWasm emits Rust with unsafe code forbiddenStep 7: The Rust compiler generates native code7. The Rust compiler generates native code

vWasm separates translation from containment

vWasm begins by translating the module into an intermediate representation, or IR. An IR gives the compiler its own vocabulary for instructions, operands, and transfers of control. Here that vocabulary is parameterized by the target architecture. The frontend is free to use ordinary compiler techniques to produce an IR program, and the implementation includes a simple register allocator and a basic optimizer that works on short instruction sequences. The sandboxing proof does not require those transformations to preserve the behavior of the original module.

This choice changes the tasks the proof has to cover. A register allocator tries to decide which values can be kept in machine registers and where the remaining values should go. Getting those decisions wrong can make a translated program compute an incorrect result. The later sandboxing pass must still confine the program it receives. The frontend therefore has substantial freedom to optimize within the IR even though its implementation has no correctness proof. Improving an optimization’s performance still calls for checking its behavior on programs, but its accuracy is outside the theorem used to establish containment.

After the frontend comes the pass that imposes the boundary. It deals with linear memory, the indirect function call table, imports, and globals, among other parts of module execution. Some operations can be justified from the representation of these regions and the ways that code reaches them. Direct accesses into linear memory are the main place where checks still have to run. The authors prove that the omitted checks are unnecessary under the machine semantics and the established control-flow restrictions.

When possible, the pass constrains a linear-memory offset with a bitwise AND operation. The mask makes the resulting offset stay in the permitted region. Other cases use an explicit check followed by a branch. The paper allows a semantic difference between a masked operation and the behavior specified by Wasm. Under Wasm’s rules, an out-of-bounds linear-memory access is supposed to trap. A masked invalid access can land inside the module and let the program continue, potentially altering its own state. In-bounds executions are unaffected by that difference. The proof concerns the reach of the operation, even when its effect within the module diverges from Wasm’s specified behavior.

vWasm fixes the maximum sandbox size at compile time. It can then emulate changes to the amount of memory currently available to the program up to that reserved limit. The paper describes this in the context of Wasm’s 32-bit addresses, with 4GiB as the maximum the implementation can be configured to support. The location of the reserved memory is chosen at run time. The distinction between size and location means the host can still apply address-space layout randomization. The proof confines writes to data regions designated for that purpose, so it does not rely on a separate assumption that executable memory must be unwritable.

The final compiler stage prints the transformed instructions as x86-64 assembly. An assembler turns that assembly into machine code. The assembly printer is trusted to carry the verified instructions across to the assembly text faithfully. According to the paper, this stage is largely a direct translation from the IR’s instructions to their printed form, which makes it comparatively straightforward to inspect. The assembler is also among the components the authors trust.

What vWasm proves about a run

The proof is written in F*, which combines a functional programming language with facilities for stating properties and proving them. Some properties can appear as conditions attached to functions. Others are established by separate lemmas or encoded in the types of values. F* uses the Z3 solver for automated reasoning, and the authors extract the executable parts of vWasm to OCaml. The compiler can thus run without carrying around the initial states and other proof-only information used to establish its theorem.

The authors give rules for the part of x86-64 that vWasm emits. Each rule describes the effect of one step of execution. A machine state includes the instruction location, register contents, memory, stack, and a status field. That field records whether execution is still valid. AllOk means no invalid action has occurred up to that point, including a memory operation outside the module’s allowed region. An error in the mathematical account of the processor could compromise the connection from the proof to actual execution. Restricting the instruction set to the portion the compiler needs keeps the description smaller.

The paper presents the theorem as a contract for the sandboxing pass. Its displayed preconditions include the following conjunction.

s.ok = AllOk ∧ reasonable_size(a.sb_size, s.mem) ∧ in_code(s.ip, c) ∧ …

Here s is the initial machine state used in the proof. A dot selects a field from a state or record, so s.ok is that state’s status, s.mem its memory, and s.ip its instruction location. The equals sign tests whether the status is AllOk. The symbol ∧ means all the conditions joined by it must hold. The argument a supplies auxiliary information and a.sb_size is the sandbox size in that information. reasonable_size expresses the paper’s size requirement in relation to the starting memory. in_code checks that the starting location belongs to the input code c. Parentheses enclose the arguments to each check, commas separate them, and … stands for the additional requirements left implicit in the paper’s simplified presentation.

The pass can report an error rather than returning code. The paper gives a call to a nonexistent function as an example of an input it can reject. For successful output, the postcondition in the simplified theorem is as follows.

∀ n, (eval_steps(n, c′, s)).ok = AllOk

The symbol ∀ means “for every,” and n is the number of execution steps. c′ is the transformed code and s is the admissible initial state. eval_steps advances the state by the indicated number of steps using the rules for the target instructions. The parentheses group that evaluation, and the commas separate its inputs. The dot selects the resulting status field. The equality requires the state after those steps to remain AllOk. A run that continues indefinitely must satisfy the same property at every finite prefix. The theorem therefore applies without a bound on how long the code will run.

The proof divides instructions into straight-line groups. A group can include the operations that check or constrain an address along with the memory access that uses it. First the authors establish a control-flow property for these groups. A legal transfer enters a group at its beginning and leaves at its end. This prevents another instruction from transferring execution around a required check. The authors explain that indirect jumps, calls through tables, and function returns need more work in this part of the argument than sequential execution or direct branches whose destinations are explicit.

Next the proof shows that the instructions in a group keep execution valid. If a group starts from an acceptable state, its constraints suffice to keep a protected access within the region it is allowed to reach. Combining this local reasoning with the legal transfers between groups gives the global result for an arbitrary number of steps. It accounts for execution inside the groups as well as the transitions from one group to the next. The grouping lets the authors reason about related instructions together without changing the machine’s instruction-at-a-time rules.

The implementation evolved around this proof structure. The authors initially represented a whole execution with a trace. They found the reasoning simpler once the semantics described individual steps and they could work with finite groups of them. They also moved early from Wasm’s structured blocks to a control-flow graph, in which the flow of execution is described by locations and connections. Wasm has several distinct constructs for organizing branches and loops. The graph gives the containment argument a common way to reason about where control can go.

The graph representation led to a practical compilation problem. Using ordinary immutable lists for instructions gives convenient proof definitions, but some changes to the list require considerable copying or traversal. The authors implemented an Append Optimized List, which arranges list operations around a tree and can defer some work. Appending can build a node that refers to the constituent lists, avoiding a traversal of the first list for that operation. The authors proved that the new operations implement the same abstract list operations. Existing arguments stated in terms of lists could then carry over while the compiler used the more efficient representation.

Taken together, the proof and implementation define a trusted computing base, or TCB. This is the collection of components whose reliability the guarantee assumes. For vWasm it includes the machine semantics and the actual theorem, the assembly printer and assembler, and the F* toolchain components identified by the authors, including Z3 and OCaml. The Wasm source semantics and the correctness of the frontend are unnecessary for the theorem about instructions emitted by the sandboxing pass. They would matter to a separate proof that the translation faithfully implements Wasm.

rWasm lifts the same operations into safe Rust

rWasm starts with a parser that reads the Wasm binary into an IR. A subsequent stage analyzes how the module uses its operand stack and identifies unreachable code. A printer then expresses the program as Rust source, and rustc compiles that source to native code. The authors implement the translator itself in safe Rust. Their argument about the native output relies on the generated program being accepted under Rust’s safety rules, so the correctness of the translator’s own analysis is a separate matter.

Rust uses a discipline of ownership and borrowing to govern how code obtains and uses access to objects. The safe subset prevents code from treating arbitrary memory as an accessible object. Rust also has an explicitly marked unsafe facility for operations that require additional obligations of the programmer. rWasm forbids this facility in the generated program through a Rust source declaration. It also dispenses with the Rust standard library and uses allocation-related support for the resizable byte array. The paper emphasizes these choices because the safety of a generated program depends on the code and facilities it can call as well as its own source.

The sandboxing argument starts from that restriction. The generated program has access to the module state and whatever facilities the host makes available through its interface. Safe Rust provides object integrity and prevents out-of-bounds accesses to the underlying objects. An erroneous translation can try the wrong operation or calculate the wrong index, but the compiler’s safety guarantees still govern what the accepted Rust program can access. The authors describe this as an informal argument for sandboxing. The trust placed in rustc and its guarantees does essential work. They cite RustBelt as an effort toward formalizing the relevant foundations. RustBelt

A practical lifting strategy also has to express Wasm computation in a form rustc can optimize. rWasm represents the locations on the Wasm operand stack as Rust variables. This gives it a way to express the virtual computation without deciding which actual machine registers hold which values. The Rust compiler makes those decisions when it generates native code. Wasm parameters and ordinary function locals become scalar Rust variables. Stack slots can be represented with a tagged enumeration, a value that carries both its data and an indication of which Wasm type the data belongs to.

The tag lets the same Rust variable represent different kinds of values at different points in the program. Consider a stack slot that first holds an integer. After the integer is discarded, a subsequent instruction can use the slot for a floating-point value. The translator has to know how many slots are occupied, while the generated operations can check which kind of value is present when they extract it. Operations that work across several Wasm types, such as discarding a value, also have a common representation. The authors report that rustc can eliminate much of the wrapping and unwrapping involved in this design.

The Wasm control-flow constructs have counterparts in Rust’s structured control flow. A block or loop can be represented using labelled constructs that permit leaving or continuing an enclosing loop. Conditionals and selection among alternatives cover other transfers within a function. A direct Wasm call can become a direct Rust call. For an indirect call the translator must account for the target chosen from a table and its expected type. The implementation uses one shared dispatch routine. Values are passed in a common representation, checked against the expected type, and recovered for the chosen call. The paper reports that this choice worked best among the designs the authors explored for both compilation and execution time.

An instance of a Wasm module becomes a Rust structure holding the module’s mutable state. Its globals and its linear memory are fields on that structure. The generated functions are methods that can receive mutable access to the instance. A Wasm global therefore persists across calls as a field of the module instance. Its representation needs no unrestricted Rust global variable. This also gives the generated code a single explicit place to locate the module’s linear memory.

The default memory is a resizable vector of bytes. On an invalid request, the default policy checks the access and panics, stopping normal execution of the module. The paper compares this with a design that reserves a region in advance and emulates the active size, and with an approach that wraps addresses into the allocated region. The authors choose the resizable allocation and explicit checks based on their measurements. The Rust optimizer can also remove checks when it can establish that an access is already within bounds or a prior check suffices.

Some semantics have to be specified explicitly in the generated Rust. Wasm integer arithmetic wraps when the result exceeds the integer range. The paper explains that Rust’s default overflow behavior differs between debug and release builds. The translator therefore uses operations that explicitly request wrapping arithmetic. This makes the intended integer behavior consistent across build modes. It is an example of work needed for faithful emulation even after the choice of safe Rust has supplied the basis for containment.

What the generated Rust lets the compiler and host see

The paper illustrates rWasm’s output with a Wasm function that sums the positive integers up to its argument. The Rust translation has visible machinery for the operand stack and Wasm control flow. The authors use this example to show that such machinery can disappear during optimization. In this case, the compiler recognizes that the loop can be replaced by a closed-form computation.

Σᵃᵢ₌₀ i = a(a + 1) / 2

The symbol Σ denotes a sum. Its lower annotation starts the index i at 0, and the upper annotation ends it at a, the given upper bound. The i to the right of the summation sign is the value added at each index. The equals sign relates the sum to the expression on its right. There, + 1 gives the successor of a, parentheses group that addition, the adjacent terms mean multiplication, and / 2 divides the product by 2. The zero term adds nothing. The example demonstrates an optimization of this program, while the broader evaluation measures the effects of the translation choices across a benchmark suite.

The generated representation also makes it possible to insert an inline reference monitor, meaning checks or observations that run as part of the translated program. The authors implemented tracers for functions, instructions, and memory accesses. The tracers inspect relevant state through the generated Rust representation. Since the tracing logic and the translated computation are compiled together, rustc has an opportunity to optimize across them. Function, instruction, and memory-access tracing took 75, 10, and 70 lines of code respectively in the implementations reported by the authors.

The method involves program translation, proof, and analysis of the resulting executables. There is no training stage. For testing translation behavior, the authors created a semantics fuzzer that generates valid Wasm programs with built-in checks on their results. For performance comparisons they used a common benchmark input pipeline, compiling C programs to WASI-compatible Wasm before giving them to the various runtimes. The paper’s open-source release contains vWasm, rWasm, and the semantics fuzzer in the repository secure-foundations/provably-safe-sandboxing-wasm-usenix22.

Experiments and results

How execution time was measured

The main execution benchmark is PolyBench-C. The paper uses 30 programs from the suite and compiles the C source in two ways. For the shared Wasm input, Clang targets WASI with the -O3 optimization setting. For the native comparison, Clang produces x86-64 code directly from C with the same optimization setting. The native program serves as the reference time for each benchmark. An AMD Ryzen 3700x powers the main system, which has 64 GB of memory.

The interpreted baselines are wasm3 and WAMR in interpreter mode. The just-in-time compilers are Wasmer and Wasmtime. The ahead-of-time baselines include WAVM, wasm2c, and WAMR in its ahead-of-time mode. The authors selected popular systems that supported WASI so they could compare executions of the same programs through a common system interface. They also tried Lucet with multiple versions. None ran the suite successfully in their attempts, so Lucet is absent from the reported performance comparison.

A benchmark runs between 10 and 1,000 times per measured setting, depending on its running time. The authors use timing reported from inside the benchmark, rather than relying on a timer that measures the entire enclosing process. They first take the mean timing for each program, then normalize it against the mean for that same program compiled directly to native code. In symbols, the measurement can be written as follows.

R(b, r) = T̄(b, r) / T̄(b, native)

R is the normalized execution time. b identifies the benchmark program and r identifies the Wasm runtime or compiler setting. T̄ is mean execution time across repeated runs, with the bar marking the mean. The word native designates the direct Clang-to-x86-64 comparison. The equals sign defines the normalized time and the slash denotes division. The parentheses group the arguments to each quantity and the commas separate them. A smaller result means less execution time relative to the native run for that program.

The paper summarizes the distribution across benchmarks using a mean and the 25% and 75% quartiles. Each program has its own comparison with native execution before those summaries are made. The appendix also presents runtimes benchmark by benchmark. That breakdown matters because a program whose native run is especially fast or slow can have a very different normalized result from another program on the same Wasm runtime. The summary gives a picture of the suite, while the individual points show where that picture changes from workload to workload.

Execution across the suite

The compiled settings ran faster than the interpreters in the main comparison. vWasm consistently outperformed the interpreters on the individual benchmarks. The authors report an average speed advantage of 2× to 3× over the interpreters, with gains varying across programs. Compared with the other compilers, vWasm was slower by factors of 3.5× to 7.5×. These comparisons place it in between the two groups. The formal assurance of the sandboxing pass accompanies a compiler that does comparatively little optimization in its frontend.

rWasm was closer to the faster compiled systems. The paper reports a range of 3% to 26% for how much slower rWasm was on average than wasm2c, ahead-of-time WAMR, and Wasmtime. WAVM had the fastest average result. The relative order changed on some individual programs. For longer-running benchmarks including 2mm, 3mm, and gemm, the authors report that rWasm was more than twice as fast as WAVM. The aggregate and the individual cases therefore answer different questions about how a runtime performs.

The native reference also has to be read as a measurement. On lu, every Wasm setting in the appendix was slower than the direct native build. On symm, all were faster. Both compilation routes begin with the same C program, but the route through Wasm gives the compilers a different representation to optimize. The authors suggest that the quality of compilation to Wasm and the programs’ memory access patterns may help explain the differences. They cite earlier work on performance bottlenecks in browser Wasm runtimes as another way to understand why a Wasm translation can differ from direct native execution. Not So Fast

Compilation time is a separate cost

The ahead-of-time comparison also measures how long it takes to produce executable code from the Wasm input. That cost can be important when a user has to wait for a program to be prepared. If compilation takes place before a module is installed on a service, execution may dominate the ongoing cost. The paper separates compilation and execution to make both cases visible.

Mean PolyBench-C compilation time for vWasm and rWasm

vWasm completes compilation sooner than rWasm in this comparison.

Mean PolyBench-C compilation time for vWasm and rWasmvWasm (this paper): 16vWasm (this paper)16rWasm: 137rWasm137
The numbers
System or settingseconds
vWasm (this paper)16
rWasm137

For vWasm, the paper attributes approximately 17% of the 16 seconds to the compiler itself. The assembler accounts for the rest. In the rWasm measurement, the translator takes 1.5% of the 137 seconds, and rustc accounts for the rest. The measured time therefore includes the downstream tools needed to turn each compiler’s output into executable code. A faster translation to Rust alone would affect only the smaller portion of the measured rWasm pipeline. Improvements to rustc’s compilation speed could affect the larger portion without a change to the translator.

The image conversion test

The authors also test a workload with a host and multiple library modules. A trusted driver converts GIFs to JPEGs using netpbm 10.26 and libjpeg-turbo 2.1.1. For each sandboxed version, the libraries run in separate modules inside the driver’s process. The comparison uses an equivalent native program without the Wasm compilation route or its isolation. On an example input, the paper measures mean slowdown across 100 executions.

Mean image conversion slowdown on the example GIF input

The rWasm build stays closer to native execution time than the vWasm build.

Mean image conversion slowdown on the example GIF inputvWasm: 3.825vWasm3.825rWasm (this paper): 1.301rWasm (this paper)1.301
The numbers
System or setting× native execution time
vWasm3.825
rWasm (this paper)1.301

The netpbm version in the test contains the vulnerability identified as CVE-2008-0554. The researchers exercised its existing proof of concept against the native and sandboxed builds. The native application crashed with attacker-controlled state. Both sandboxed applications stopped the affected module’s execution after the overflow and returned safely to the driver. The test exercises the boundary as used by an actual application, with the host and libraries interacting through their integration. The broader containment claims derive from the proof and the Rust safety argument rather than from the outcome of this one security test.

Implementation and verification effort

The authors report roughly two person-years to implement vWasm, including its proofs, and one person-month for rWasm. Part of the difference comes from verification work. The implementations also have different responsibilities beyond validation of safety. vWasm generates assembly directly and must account for architectural details. rWasm generates a high-level program and delegates native code generation to rustc. The authors found that the ability to instrument generated Rust also helped during debugging.

The component inventory in the paper separates code volume from time spent running the proof checker. vWasm’s sandboxing component has 3607 lines of code and takes 450 seconds to verify as a whole in the reported breakdown. Its x64 semantics and printer have 2068 and 1458 lines of code respectively. rWasm’s combined stack analysis and printer has 2157 lines. These figures describe different kinds of work. The effort to write and revise a proof includes interactive attempts and decisions that do not appear in the eventual checker time. The authors say most individual proofs check in under ten seconds and even the slowest take under two minutes. The distinction explains how a sizable total can coexist with a more manageable feedback loop for particular proof edits.

What the ablations show

Disabling vWasm’s sandboxing pass

The most direct control in the paper is a vWasm build with its sandboxing pass disabled. The authors then measure the generated code on the same PolyBench-C workloads. Mean execution time changes by only 0.2%. This comparison isolates the contribution of the pass within the implementation and workloads tested. It supports the interpretation that vWasm’s gap from the faster compilers comes mostly from the code it generates before sandboxing, including its basic register allocation and limited optimization.

That interpretation matters because the proof is designed to accept IR from an unverified frontend. A more capable frontend could improve register allocation or eliminate repeated computation while leaving the containment proof in place. The paper proposes such changes as future optimization opportunities. The pass-disabled measurement quantifies what happened when the checks were removed. The performance of a future frontend remains an open question.

Changing how a memory access is checked

The memory microbenchmark narrows the performance question to a single 64-bit load. It compares an unchecked reference, an explicit bounds check, and wrapping the address with a bitwise AND. Each method is measured with both a fixed-size array and a resizable byte vector. The main AMD test machine is joined by a system with an Intel i9-9900K and 128GB of RAM. The paper plots timing distributions for the individual loads so that the comparison shows where the observed times are concentrated.

With a fixed-size array, the two protected methods perform similarly on both processors. In resizable memory on the AMD machine, the explicit bounds check is three times faster than wrapping, according to the paper. On the Intel machine, wrapping is marginally faster for that same kind of memory. The choice of array representation and processor both affect the result. A technique that looks advantageous for one combination may have little advantage or a different ordering for another.

The unchecked load supplies a reference for timing only. The protected choices also have different semantics when an address is invalid. An explicit check can stop the access, while the mask can confine it to the permitted region and let execution continue. The comparison helps explain the authors’ use of a checked resizable vector by default in rWasm. It measures a load in isolation, while a full program can give the compiler opportunities to eliminate checks or combine work across accesses.

Changing the compiler’s internal list representation

Another comparison replaces ordinary functional lists with Append Optimized Lists inside vWasm. The paper reports a reduction in PolyBench-C compilation time from 25+ seconds to 2.5s for this change. It also reports negligible additional verification time and effort once the equivalence of the data structure’s operations had been established. This is a separate comparison from the end-to-end compilation chart, which includes the assembler.

The control is informative because the improvement concerns the compiler’s own operations, such as assembling and modifying instruction sequences. The substitute storage structure supports the same abstract operations, so the existing proof can use the same account of what a list operation does. This explains how an implementation decision made partly for convenient reasoning can later be improved without requiring a corresponding change throughout the proof.

Checking translation behavior with generated programs

The semantics fuzzer creates valid Wasm programs that can report when a calculation yields an unexpected result. A program can perform a computation with a known result and explicitly signal failure if its execution disagrees. This lets the authors search for errors in the way compiler output implements Wasm operations. It complements the containment argument, which permits a wrong calculation as long as the resulting machine operations stay within the boundary.

With the fuzzer, the authors identified and corrected more than 15 separate issues affecting semantic correctness in vWasm. They report that the issues could give incorrect computation results while leaving the sandbox guarantee intact. The same fuzzer found no issues in rWasm. The authors also report that both tools pass the correctness and consistency checks for the benchmarks. These observations give evidence about the programs that were exercised. The difference in findings also shows a practical reason to evaluate translation accuracy separately from the scope of the proof.

Limitations

Limits stated by the authors

The authors define the protected party as the host. A guest program can still corrupt its own state, return the wrong value, or misuse data within its authority. The difference is particularly visible when vWasm masks an access that Wasm specifies should trap. The address is constrained to the module’s own region, and the program may continue after changing bytes there. The paper discusses termination as an alternative for applications that require the specified trap behavior.

The execution environment and the interfaces it exposes remain trusted. The host has to choose what it grants. If it offers a service that performs privileged actions on behalf of a guest, the safety of that service depends on its own policy and implementation. The authors expressly exclude confused-deputy attacks, in which the guest induces a more privileged component to misuse its authority. The threat scope likewise excludes denial of service, excessive resource consumption, speculative-execution attacks, side channels, and hardware attacks. In particular, preserving the boundary through every step says nothing about how many steps a guest will take or how promptly the host can reclaim its resources.

The assurances also depend on different trusted computing bases. vWasm’s proof is checked against the authors’ account of the x86-64 instructions it emits. Its applicability to the executable depends on the theorem stating the intended property, those instruction rules describing the relevant processor behavior, and the printer and assembler carrying the instructions into the binary faithfully. rWasm depends on the safety guarantees supplied by rustc and the facilities it uses. The authors describe rWasm’s argument as informal and discuss the different bases of trust as a reason that the two assurances are difficult to rank directly.

The implemented vWasm backend targets x86-64. The authors report that much of its proof uses general reasoning about permitted memory accesses, but they describe adapting the code and proof to an architecture such as ARM as real work still to be done. rWasm inherits architectures supported by rustc. That gives it wider reach as a design, while the regular benchmark setup and the additional memory microbenchmark cover the particular processors reported. The authors also describe how extensions to Wasm might affect the implementations. A new memory access mechanism could require changes to vWasm’s sandboxing pass and proof, whereas the scale of future maintenance is an assessment based on the current designs.

Limits visible in the evaluation

The execution and compilation measurements establish concrete results for PolyBench-C and the named baseline configurations. They cannot supply a single expected overhead for every host application. The paper’s own per-program results show changes in relative ranking, even within the same suite. The choice of direct native compilation as a reference is also part of the interpretation. A normalized time reflects the code produced by both compilation routes and the behavior of the benchmark on the test system. It is not a standalone measure of the cost of enforcing the sandbox. The disabled-pass comparison addresses that cost more directly for vWasm.

The image conversion scenario extends the evaluation to an application that calls libraries inside the host process. Its timings still characterize one example input, and its security demonstration exercises one known vulnerability in a particular integration. The result shows safe return to the driver in that case. It cannot establish that every error in a guest will be detected, because some errors affect guest state without crossing the boundary. The fuzzer has a parallel limit. A generated program can reveal a semantic mistake when its self-check fails, while passing the generated programs leaves other input programs and behaviors untested.

The memory experiment also supports a narrower inference than the overall runtime comparison. A single indexed read exposes how array representation and bounds enforcement interact on the two processors. In an application, surrounding operations affect which checks the compiler can remove and how frequently memory is accessed. This is one reason to read the microbenchmark and the whole-program results together. The former supports a specific implementation choice in rWasm. The latter shows the performance that emerged when that choice was combined with the rest of the translation strategy.

The reported engineering effort reflects the implementations as built by the authors. It includes the consequences of targeting assembly in one system and delegating native code generation in the other, as well as the difference between writing a proof and using a language’s existing safety guarantees. It does not isolate the productivity effect of F* or Rust by itself. Similarly, the tracing implementations demonstrate that several forms of instrumentation are easy to express in the generated Rust. More elaborate reference monitors, including the analyses and sanitizers suggested by the authors, remain proposals whose precision and overhead were not evaluated in the paper.

What came after

No later citing work can be identified for this account. The paper itself closes with several directions whose status is prospective. The authors suggest improving vWasm’s frontend so that better register allocation and standard optimizations can raise execution speed while retaining the existing sandboxing proof. They also describe the remaining proof work for additional target architectures. On the rWasm side, they propose using the generated Rust representation for more detailed runtime monitoring.

The authors also discuss combining their compilers with systems that already use Wasm to isolate libraries, run code on embedded devices, or execute workloads at the edge. In those settings, the embedding system would still decide what an isolated module may do through its host interface. The compiler would provide the containment mechanism for the generated program. These are proposed integrations. The paper’s evaluated contributions are the two compilers, their respective safety arguments, and the measurements of how those designs behave in the reported workloads.

Cite

Cite as Jay Bosamiya, Wen Shih Lim and Bryan Parno. 2022. Provably-Safe Multilingual Software Sandboxing using WebAssembly. USENIX Security 2022.

The paper itself, not this page. BibTeX from the library's record of the work.

@inproceedings{bosamiya2022provably,
  title = {{Provably-Safe Multilingual Software Sandboxing using WebAssembly}},
  author = {Jay Bosamiya, Wen Shih Lim and Bryan Parno},
  booktitle = {USENIX Security 2022},
  year = {2022},
  url = {https://www.usenix.org/system/files/sec22-bosamiya.pdf}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/bosamiya-2022-provably-safe-multilingual-software-sandboxing/