CVE-2022-24791: Use After Free (CWE-416)
value: Wasmtime is a standalone JIT-style runtime for WebAssembly, using Cranelift. There is a use after free vulnerability in Wasmtime when both running Wasm that uses externrefs and enabling epoch interruption in Wasmtime. If you are not explicitly enabling epoch interruption (it is disabled by default) then you are not affected. If you are explicitly disabling the Wasm reference types proposal (it is enabled by default) then you are also not affected. The use after free is caused by Cranelift failing to emit stack maps when there are safepoints inside cold blocks. Cold blocks occur when epoch interruption is enabled. Cold blocks are emitted at the end of compiled functions, and change the order blocks are emitted versus defined. This reordering accidentally caused Cranelift to skip emitting some stack maps because it expected to emit the stack maps in block definition order, rather than block emission order. When Wasmtime would eventually collect garbage, it would fail to find live references on the stack because of the missing stack maps, think that they were unreferenced garbage, and therefore reclaim them. Then after the collection ended, the Wasm code could use the reclaimed-too-early references, which is a use after free. Patches have been released in versions 0.34.2 and 0.35.2, which fix the vulnerability. All Wasmtime users are recommended to upgrade to these patched versions. If upgrading is not an option for you at this time, you can avoid the vulnerability by either: disabling the Wasm reference types proposal, config.wasm_reference_types(false); or by disabling epoch interruption if you were previously enabling it. config.epoch_interruption(false).
CWE description: The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer.
CVSS v3 base score: 9.8
Published: 2022-03-31T23:15Z
Repository: https://github.com/bytecodealliance/wasmtime
Language: Rust
Files changed: cranelift/codegen/src/machinst/vcode.rs, tests/all/funcref.rs, tests/all/gc.rs, tests/all/main.rs
Commit date: 2022-03-31 14:26:01 -0700
Commit message: Merge pull request from GHSA-gwc9-348x-qwv2

* Run the GC smoketest with epoch support enabled as well.

* Handle safepoints in cold blocks properly.

Currently, the way that we find safepoint slots for a given instruction
relies on the instruction index order in the safepoint list matching the
order of instruction emission.

Previous to the introduction of cold-block support, this was trivially
satisfied by sorting the safepoint list: we emit instructions 0, 1, 2,
3, 4, ..., and so if we have safepoints at instructions 1 and 4, we will
encounter them in that order.

However, cold blocks are supported by swizzling the emission order at
the last moment (to avoid having to renumber instructions partway
through the compilation pipeline), so we actually emit instructions out
of index order when cold blocks are present.

Reference-type support in Wasm in particular uses cold blocks for
slowpaths, and has live refs and safepoints in these slowpaths, so we
can reliably "skip" a safepoint (not emit any metadata for it) in the
presence of reftype usage.

This PR fixes the emission code by building a map from instruction index
to safepoint index first, then doing lookups through this map, rather
than following along in-order as it emits instructions.
Diff: diff --git a/cranelift/codegen/src/machinst/vcode.rs b/cranelift/codegen/src/machinst/vcode.rs
index e31c1d8ec1..d1e585c609 100644
--- a/cranelift/codegen/src/machinst/vcode.rs
+++ b/cranelift/codegen/src/machinst/vcode.rs
@@ -15,10 +15,11 @@
 //! play with layout prior to final binary emission, as well, if we want.
 //!
 //! See the main module comment in `mod.rs` for more details on the VCode-based
 //! backend pipeline.
 
+use crate::fx::FxHashMap;
 use crate::ir::{self, types, Constant, ConstantData, SourceLoc};
 use crate::machinst::*;
 use crate::settings;
 use crate::timing;
 use regalloc::Function as RegallocFunction;
@@ -476,10 +477,23 @@ impl<I: VCodeInst> VCode<I> {
         buffer.reserve_labels_for_constants(&self.constants);
 
         let mut inst_end_offsets = vec![0; self.insts.len()];
         let mut label_inst_indices = vec![0; self.num_blocks()];
 
+        // Map from instruction index to index in
+        // `safepoint_slots`. We need this because we emit
+        // instructions out-of-order, while the safepoint_insns /
+        // safepoint_slots data structures are sorted in instruction
+        // order.
+        let mut safepoint_indices: FxHashMap<u32, usize> = FxHashMap::default();
+        for (safepoint_idx, iix) in self.safepoint_insns.iter().enumerate() {
+            // Disregard safepoints that ended up having no live refs.
+            if self.safepoint_slots[safepoint_idx].len() > 0 {
+                safepoint_indices.insert(*iix, safepoint_idx);
+            }
+        }
+
         // Construct the final order we emit code in: cold blocks at the end.
         let mut final_order: SmallVec<[BlockIndex; 16]> = smallvec![];
         let mut cold_blocks: SmallVec<[BlockIndex; 16]> = smallvec![];
         for block in 0..self.num_blocks() {
             let block = block as BlockIndex;
@@ -491,11 +505,10 @@ impl<I: VCodeInst> VCode<I> {
         }
         let first_cold_block = cold_blocks.first().cloned();
         final_order.extend(cold_blocks.clone());
 
         // Emit blocks.
-        let mut safepoint_idx = 0;
         let mut cur_srcloc = None;
         let mut last_offset = None;
         let mut start_of_cold_code = None;
         for block in final_order {
             let new_offset = I::align_basic_block(buffer.cur_offset());
@@ -539,21 +552,15 @@ impl<I: VCodeInst> VCode<I> {
                     buffer.start_srcloc(srcloc);
                     cur_srcloc = Some(srcloc);
                 }
                 state.pre_sourceloc(cur_srcloc.unwrap_or(SourceLoc::default()));
 
-                if safepoint_idx < self.safepoint_insns.len()
-                    && self.safepoint_insns[safepoint_idx] == iix
-                {
-                    if self.safepoint_slots[safepoint_idx].len() > 0 {
-                        let stack_map = self.abi.spillslots_to_stack_map(
-                            &self.safepoint_slots[safepoint_idx][..],
-                            &state,
-                        );
-                        state.pre_safepoint(stack_map);
-                    }
-                    safepoint_idx += 1;
+                if let Some(safepoint_idx) = safepoint_indices.get(&iix) {
+                    let stack_map = self
+                        .abi
+                        .spillslots_to_stack_map(&self.safepoint_slots[*safepoint_idx][..], &state);
+                    state.pre_safepoint(stack_map);
                 }
 
                 self.insts[iix as usize].emit(&mut buffer, &self.emit_info, &mut state);
 
                 if self.generate_debug_info {
diff --git a/tests/all/funcref.rs b/tests/all/funcref.rs
index 73dd21319d..74980bb21c 100644
--- a/tests/all/funcref.rs
+++ b/tests/all/funcref.rs
@@ -4,10 +4,11 @@ use std::sync::Arc;
 use wasmtime::*;
 
 #[test]
 fn pass_funcref_in_and_out_of_wasm() -> anyhow::Result<()> {
     let (mut store, module) = ref_types_module(
+        false,
         r#"
             (module
                 (func (export "func") (param funcref) (result funcref)
                     local.get 0
                 )
@@ -58,11 +59,12 @@ fn pass_funcref_in_and_out_of_wasm() -> anyhow::Result<()> {
         assert_eq!(other_instance_func.ty(&store), result_func.ty(&store));
     }
 
     // Passing in a `funcref` from another store fails.
     {
-        let (mut other_store, other_module) = ref_types_module(r#"(module (func (export "f")))"#)?;
+        let (mut other_store, other_module) =
+            ref_types_module(false, r#"(module (func (export "f")))"#)?;
         let other_store_instance = Instance::new(&mut other_store, &other_module, &[])?;
         let f = other_store_instance
             .get_func(&mut other_store, "f")
             .unwrap();
 
@@ -75,10 +77,11 @@ fn pass_funcref_in_and_out_of_wasm() -> anyhow::Result<()> {
 }
 
 #[test]
 fn receive_null_funcref_from_wasm() -> anyhow::Result<()> {
     let (mut store, module) = ref_types_module(
+        false,
         r#"
             (module
                 (func (export "get-null") (result funcref)
                     ref.null func
                 )
diff --git a/tests/all/gc.rs b/tests/all/gc.rs
index 6de09f1c53..4730f79418 100644
--- a/tests/all/gc.rs
+++ b/tests/all/gc.rs
@@ -12,11 +12,21 @@ impl Drop for SetFlagOnDrop {
     }
 }
 
 #[test]
 fn smoke_test_gc() -> anyhow::Result<()> {
+    smoke_test_gc_impl(false)
+}
+
+#[test]
+fn smoke_test_gc_epochs() -> anyhow::Result<()> {
+    smoke_test_gc_impl(true)
+}
+
+fn smoke_test_gc_impl(use_epochs: bool) -> anyhow::Result<()> {
     let (mut store, module) = ref_types_module(
+        use_epochs,
         r#"
             (module
                 (import "" "" (func $do_gc))
                 (func $recursive (export "func") (param i32 externref) (result externref)
                     local.get 0
@@ -67,10 +77,11 @@ fn smoke_test_gc() -> anyhow::Result<()> {
 }
 
 #[test]
 fn wasm_dropping_refs() -> anyhow::Result<()> {
     let (mut store, module) = ref_types_module(
+        false,
         r#"
             (module
                 (func (export "drop_ref") (param externref)
                     nop
                 )
@@ -143,11 +154,11 @@ fn many_live_refs() -> anyhow::Result<()> {
             ) ;; func
         ) ;; module
         ",
     );
 
-    let (mut store, module) = ref_types_module(&wat)?;
+    let (mut store, module) = ref_types_module(false, &wat)?;
 
     let live_refs = Arc::new(AtomicUsize::new(0));
 
     let make_ref = Func::wrap(&mut store, {
         let live_refs = live_refs.clone();
@@ -189,10 +200,11 @@ fn many_live_refs() -> anyhow::Result<()> {
 }
 
 #[test]
 fn drop_externref_via_table_set() -> anyhow::Result<()> {
     let (mut store, module) = ref_types_module(
+        false,
         r#"
             (module
                 (table $t 1 externref)
 
                 (func (export "table-set") (param externref)
@@ -398,10 +410,11 @@ fn gee_i_sure_hope_refcounting_is_atomic() -> anyhow::Result<()> {
 }
 
 #[test]
 fn global_init_no_leak() -> anyhow::Result<()> {
     let (mut store, module) = ref_types_module(
+        false,
         r#"
             (module
                 (import "" "" (global externref))
                 (global externref (global.get 0))
             )
@@ -422,10 +435,11 @@ fn global_init_no_leak() -> anyhow::Result<()> {
 }
 
 #[test]
 fn no_gc_middle_of_args() -> anyhow::Result<()> {
     let (mut store, module) = ref_types_module(
+        false,
         r#"
             (module
                 (import "" "return_some" (func $return (result externref externref externref)))
                 (import "" "take_some" (func $take (param externref externref externref)))
                 (func (export "run")
diff --git a/tests/all/main.rs b/tests/all/main.rs
index 461bf8d84f..a04ced711e 100644
--- a/tests/all/main.rs
+++ b/tests/all/main.rs
@@ -31,21 +31,28 @@ mod table;
 mod traps;
 mod wast;
 
 /// A helper to compile a module in a new store with reference types enabled.
 pub(crate) fn ref_types_module(
+    use_epochs: bool,
     source: &str,
 ) -> anyhow::Result<(wasmtime::Store<()>, wasmtime::Module)> {
     use wasmtime::*;
 
     let _ = env_logger::try_init();
 
     let mut config = Config::new();
     config.wasm_reference_types(true);
+    if use_epochs {
+        config.epoch_interruption(true);
+    }
 
     let engine = Engine::new(&config)?;
-    let store = Store::new(&engine, ());
+    let mut store = Store::new(&engine, ());
+    if use_epochs {
+        store.set_epoch_deadline(1);
+    }
 
     let module = Module::new(&engine, source)?;
 
     Ok((store, module))
 }

Vulnerable code:         let mut safepoint_idx = 0;
                if safepoint_idx < self.safepoint_insns.len()
                    && self.safepoint_insns[safepoint_idx] == iix
                {
                    if self.safepoint_slots[safepoint_idx].len() > 0 {
                        let stack_map = self.abi.spillslots_to_stack_map(
                            &self.safepoint_slots[safepoint_idx][..],
                            &state,
                        );
                        state.pre_safepoint(stack_map);
                    }
                    safepoint_idx += 1;
        let (mut other_store, other_module) = ref_types_module(r#"(module (func (export "f")))"#)?;
    let (mut store, module) = ref_types_module(&wat)?;
    let store = Store::new(&engine, ());
Fixed code: use crate::fx::FxHashMap;
        // Map from instruction index to index in
        // `safepoint_slots`. We need this because we emit
        // instructions out-of-order, while the safepoint_insns /
        // safepoint_slots data structures are sorted in instruction
        // order.
        let mut safepoint_indices: FxHashMap<u32, usize> = FxHashMap::default();
        for (safepoint_idx, iix) in self.safepoint_insns.iter().enumerate() {
            // Disregard safepoints that ended up having no live refs.
            if self.safepoint_slots[safepoint_idx].len() > 0 {
                safepoint_indices.insert(*iix, safepoint_idx);
            }
        }

                if let Some(safepoint_idx) = safepoint_indices.get(&iix) {
                    let stack_map = self
                        .abi
                        .spillslots_to_stack_map(&self.safepoint_slots[*safepoint_idx][..], &state);
                    state.pre_safepoint(stack_map);
        false,
        let (mut other_store, other_module) =
            ref_types_module(false, r#"(module (func (export "f")))"#)?;
        false,
    smoke_test_gc_impl(false)
}

#[test]
fn smoke_test_gc_epochs() -> anyhow::Result<()> {
    smoke_test_gc_impl(true)
}

fn smoke_test_gc_impl(use_epochs: bool) -> anyhow::Result<()> {
        use_epochs,
        false,
    let (mut store, module) = ref_types_module(false, &wat)?;
        false,
        false,
        false,
    use_epochs: bool,
    if use_epochs {
        config.epoch_interruption(true);
    }
    let mut store = Store::new(&engine, ());
    if use_epochs {
        store.set_epoch_deadline(1);
    }