1 //! Support for maintaining the usefulness of a corpus over time. 2 //! 3 //! Wasmtime's fuzzing strategy in general is to use `wasm-smith` to generate 4 //! modules which interprets fuzz input from libFuzzer as a sort of "DNA". This 5 //! works to generate pretty interesting modules but falls down over time 6 //! because the DNA to generate the same module over time can change. This 7 //! means that maintaining a corpus for Wasmtime is not the most useful thing 8 //! in the world unfortunately and any historical discoveries of coverage need 9 //! to be rediscovered every time the DNA changes. 10 //! 11 //! To help with this the module here implements a scheme where Wasmtime's fuzz 12 //! inputs are highly likely to be of the form: 13 //! 14 //! ```text 15 //! [ ... wasm module ... ][ .. fuzz custom section .. ] 16 //! ``` 17 //! 18 //! The `fuzz custom section` here contains the original fuzz input used to 19 //! generate the `wasm module`, and if the DNA hasn't changed then it should 20 //! still be possible to do that as well. The benefit of this format, though, 21 //! is that if the DNA is changed then the interpretation of the `fuzz custom 22 //! section` will change but the original `wasm module` will not. This enables 23 //! us to populate the corpus, ideally, with a set of interesting `wasm module` 24 //! entries. 25 //! 26 //! Over time the `fuzz custom section` will "bitrot" and will be no longer able 27 //! to generate the original `wasm module`. The main consequence of this is that 28 //! when the original test case is mutated the generated wasm module from the 29 //! mutation will be nothing alike from the original test case's wasm module. 30 //! This means libFuzzer will have to rediscover ways to mutate into 31 //! interesting modules, but we're no worse off than before hopefully. 32 //! Additionally this more easily opens the door to integrate `wasm-mutate` one 33 //! day into mutation here as well. 34 //! 35 //! Currently this is all supported via two methods: 36 //! 37 //! 1. A custom mutator is registered with libfuzzer. This means that all 38 //! inputs generated by the mutator, so long as they fit, will be the 39 //! "envelope" format of this module. This means that the corpus will 40 //! hopefully naturally get populated with wasm files rather than random 41 //! inputs. Note that this is not guaranteed to succeed since sometimes the 42 //! buffer to store the fuzz input in the mutator is not big enough to store 43 //! the final wasm module, in which case a non-enveloped wasm module is 44 //! stored. 45 //! 46 //! 2. If the environment variable `WRITE_FUZZ_INPUT_TO is set then the fuzz 47 //! input, in its envelope format, will be written to the specified file. 48 //! This can be useful in case an input is in its binary form or if a 49 //! preexisting corpus is being rewritten. 50 51 use arbitrary::{Arbitrary, Result, Unstructured}; 52 use wasm_encoder::Section; 53 54 /// Helper macro for fuzz targets that are single-module fuzzers. 55 /// 56 /// This combines the features of this module into one macro invocation to 57 /// generate the fuzz entry point and mutator in tandem. 58 #[macro_export] 59 macro_rules! single_module_fuzzer { 60 ($execute:ident $generate:ident) => { 61 libfuzzer_sys::fuzz_target!(|data: &[u8]| { 62 $crate::init_fuzzing(); 63 drop($crate::single_module_fuzzer::execute( 64 data, $execute, $generate, 65 )); 66 }); 67 68 libfuzzer_sys::fuzz_mutator!(|data: &mut [u8], size: usize, max_size: usize, seed: u32| { 69 $crate::single_module_fuzzer::mutate( 70 data, 71 size, 72 max_size, 73 $generate, 74 libfuzzer_sys::fuzzer_mutate, 75 ) 76 }); 77 }; 78 } 79 80 /// Executes a "single module fuzzer" given the raw `input` from libfuzzer. 81 /// 82 /// This will use the `input` to generate `T`, some configuration, which is 83 /// then used by `gen_module` to generate a WebAssembly module. The module is 84 /// then passed to `run` along with the configuration and remaining data that 85 /// can be used as fuzz input. 86 /// 87 /// The main purpose of this function is to handle when `input` is actually a 88 /// WebAssembly module "envelope". If the `input` is a valid wasm module and 89 /// ends with a specific trailing custom section then the module generated by 90 /// `gen_module` is actually discarded. The purpose of this is to handle the 91 /// case where the input used to generate a module may change over time but 92 /// we're still interested in the historical coverage of the original wasm 93 /// module. 94 pub fn execute<'a, T, U>( 95 input: &'a [u8], 96 run: fn(&[u8], bool, T, &mut Unstructured<'a>) -> Result<U>, 97 gen_module: fn(&mut T, &mut Unstructured<'a>) -> Result<Vec<u8>>, 98 ) -> Result<U> 99 where 100 T: Arbitrary<'a>, 101 { 102 let (fuzz_data, module_in_input) = match extract_fuzz_input(input) { 103 Ok(input) => { 104 log::debug!("fuzz input was a valid module with trailing custom section"); 105 (input.fuzz_data, Some(input.module)) 106 } 107 Err(e) => { 108 log::debug!("fuzz input not a valid module: {e:?}"); 109 (input, None) 110 } 111 }; 112 let mut u = Unstructured::new(fuzz_data); 113 let mut config = u.arbitrary()?; 114 let generated = gen_module(&mut config, &mut u)?; 115 let module = module_in_input.unwrap_or(&generated); 116 if let Ok(file) = std::env::var("WRITE_FUZZ_INPUT_TO") { 117 std::fs::write(file, encode_module(&module, &fuzz_data)).unwrap(); 118 } 119 run(module, module_in_input.is_none(), config, &mut u) 120 } 121 122 const SECTION_NAME: &str = "wasmtime-fuzz-input"; 123 124 /// Implementation of a libfuzzer custom mutator for a single-module-fuzzer. 125 /// 126 /// This mutator will take the seed specified in `data` and attempt to mutate 127 /// it with the provided `mutate` function. The `mutate` function may not 128 /// receive the `data` as-specified, but instead may receive only the seed 129 /// that was used to generate `data`. 130 pub fn mutate<T>( 131 data: &mut [u8], 132 mut size: usize, 133 max_size: usize, 134 gen_module: fn(&mut T, &mut Unstructured<'_>) -> Result<Vec<u8>>, 135 mutate: fn(&mut [u8], usize, usize) -> usize, 136 ) -> usize 137 where 138 T: for<'a> Arbitrary<'a>, 139 { 140 // If `data` is a valid wasm module with the fuzz seed at the end, then 141 // discard the wasm module portion and instead shuffle the seed into the 142 // beginning of the `data` slice. This is the "de-envelope" part of the 143 // seed management here. 144 // 145 // After this the `data` array should contain the raw contents used to 146 // produce the module and is ripe for mutation/minimization/etc. 147 if let Ok(input) = extract_fuzz_input(&data[..size]) { 148 let start = input.fuzz_data.as_ptr() as usize - data.as_ptr() as usize; 149 size = input.fuzz_data.len(); 150 data.copy_within(start..start + input.fuzz_data.len(), 0); 151 } 152 153 // Delegate to the provided mutation function for standard mutations to 154 // apply. 155 let new_size = mutate(data, size, max_size); 156 157 // Next the goal of this function is to produce a test case which is an 158 // actual wasm module. To that end this will run module generation over the 159 // input provided. If this is all successful then the custom section 160 // representing the seed is appended to the module, making it a sort of 161 // self-referential module. 162 // 163 // After all this it's copied into `data` if the it fits. If the module 164 // doesn't fit then the seed is left un-perturbed since there's not much 165 // that we can do about that. 166 let mut u = Unstructured::new(&data[..new_size]); 167 match u 168 .arbitrary() 169 .and_then(|mut config| gen_module(&mut config, &mut u)) 170 { 171 Ok(module) => { 172 let module = encode_module(&module, &data[..new_size]); 173 174 if module.len() < max_size { 175 log::debug!( 176 "successfully generated mutated module with \ 177 appended input section" 178 ); 179 data[..module.len()].copy_from_slice(&module); 180 return module.len(); 181 } else { 182 log::debug!("mutated module doesn't fit in original slice"); 183 } 184 } 185 186 // If our new seed can't generate a new module then that's something 187 // for the fuzzer to figure out later when it "officially" executes 188 // this fuzz input. For the purposes of this function it's not too 189 // useful to try to put it in an envelope otherwise so ignore it. 190 Err(e) => { 191 log::debug!("failed to generate module from mutated seed {e:?}"); 192 } 193 } 194 195 new_size 196 } 197 198 fn encode_module(module: &[u8], fuzz_data: &[u8]) -> Vec<u8> { 199 let mut module = module.to_vec(); 200 wasm_encoder::CustomSection { 201 name: SECTION_NAME, 202 data: &fuzz_data, 203 } 204 .append_to(&mut module); 205 module 206 } 207 208 struct FuzzInput<'a> { 209 /// The module extracted from the input, without the fuzz input custom 210 /// section. 211 module: &'a [u8], 212 213 /// The contents of the fuzz input custom section. 214 fuzz_data: &'a [u8], 215 } 216 217 /// Attempts to extract a fuzz input from the `data` provided. 218 /// 219 /// This will attempt to read `data` as a WebAssembly binary. If successful 220 /// and the module ends with a custom section indicating it's a fuzz input 221 /// then the contents of the custom section are returned along with the 222 /// contents of the original module. 223 fn extract_fuzz_input(data: &[u8]) -> anyhow::Result<FuzzInput<'_>> { 224 use wasmparser::{Parser, Payload}; 225 let mut prev_end = 8; 226 for section in Parser::new(0).parse_all(data) { 227 let section = section?; 228 229 // If this is a custom section, the end of the section is the end of 230 // the entire module, and it's got the expected name, then this section 231 // is assumed to be the input seed to the fuzzer. 232 // 233 // The section's contents are returned through `fuzz_data` and the wasm 234 // binary format means that we can simply chop off the last custom 235 // section and still have a valid module. 236 if let Payload::CustomSection(s) = §ion { 237 if s.name() == SECTION_NAME && s.range().end == data.len() { 238 return Ok(FuzzInput { 239 module: &data[..prev_end], 240 fuzz_data: s.data(), 241 }); 242 } 243 } 244 245 // Record each section's end to record what the end of the module is 246 // up to this point. 247 if let Some((_, range)) = section.as_section() { 248 prev_end = range.end; 249 } 250 } 251 anyhow::bail!("no input found") 252 } 253 254 #[cfg(test)] 255 mod tests { 256 use super::*; 257 use rand::rngs::SmallRng; 258 use rand::{RngCore, SeedableRng}; 259 260 #[test] 261 fn changing_configuration_does_not_change_module() { 262 drop(env_logger::try_init()); 263 264 // This test asserts that if the static configuration associated with a 265 // module changes then the generated module, as sourced from the 266 // original fuzz input, does not change. That's the whole purpose of 267 // this module, to enable our fuzz inputs to be in a format that's 268 // resilient to changes in configuration over time (or at least the 269 // module part of the input). 270 // 271 // This test will execute N=200 iterations where each iteration will 272 // attempt to, with some fresh random data, generate a module. This 273 // module is then "mutated" with a noop mutation to effectively 274 // serialize it into the envelope where the module is preserved. The 275 // now-mutated input, which should be a wasm module, is then passed 276 // as the seed to a second execution which has a different static input. 277 // 278 // This simulates having a fuzzer one day produce an interesting test 279 // case through mutation, and then the next day the configuration of 280 // the fuzzer changes. On both days the module input to the function 281 // should have been the same. 282 283 let mut rng = SmallRng::seed_from_u64(0); 284 let max_size = 2048; 285 let seed_size = 128; 286 let mut buf = vec![0; max_size]; 287 let mut compares = 0; 288 for _ in 0..200 { 289 rng.fill_bytes(&mut buf[..seed_size]); 290 291 let run1 = run_config::<u32>; 292 let mutate = mutate::<u32>; 293 let run2 = run_config::<(u32, u32)>; 294 295 if let Ok((module, known_valid)) = execute(&buf[..seed_size], run1, gen) { 296 assert!(known_valid); 297 let new_size = mutate(&mut buf, seed_size, max_size, gen, noop_mutate); 298 if let Ok((module2, known_valid)) = execute(&buf[..new_size], run2, gen) { 299 assert!(!known_valid); 300 compares += 1; 301 if module != module2 { 302 panic!("modules differ"); 303 } 304 } 305 } 306 } 307 308 // At least one iteration should have succeeded in the fuzz generation 309 // above. 310 assert!(compares > 0); 311 312 fn run_config<T>( 313 data: &[u8], 314 known_valid: bool, 315 _: T, 316 _: &mut Unstructured<'_>, 317 ) -> Result<(Vec<u8>, bool)> 318 where 319 T: for<'a> Arbitrary<'a>, 320 { 321 Ok((data.to_vec(), known_valid)) 322 } 323 324 fn gen<T>(_: &mut T, u: &mut Unstructured<'_>) -> Result<Vec<u8>> 325 where 326 T: for<'a> Arbitrary<'a>, 327 { 328 Ok(u.arbitrary::<wasm_smith::Module>()?.to_bytes()) 329 } 330 331 fn noop_mutate(_buf: &mut [u8], size: usize, _new_size: usize) -> usize { 332 size 333 } 334 } 335 } 336