synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-wire / src / fuzz.rs
| 1 | //! In-repository coverage-guided fuzzer for the untrusted frame decoder (step G1). |
| 2 | //! |
| 3 | //! What it is, plainly: a deterministic mutation loop with edge-coverage feedback. The |
| 4 | //! decoder in `frame.rs` is compiled with an [`EdgeProbe`] at every branch (AFL-style edge |
| 5 | //! map over source-line sites); an input that reaches a new edge, or an edge a new number of |
| 6 | //! times (hit-count bucket), joins the corpus and is mutated further. It is not libFuzzer or |
| 7 | //! AFL: there is no compiler instrumentation, so coverage is exactly the instrumented |
| 8 | //! decoder states of `frame.rs` (the capability chain decoder of `synapse-auth` and the |
| 9 | //! envelope decoder of `synapse-store::codec` run, and are checked, but are not |
| 10 | //! instrumented). The budget (executions or seconds) and the seed are fixed before a run. |
| 11 | //! |
| 12 | //! The target is what a server does with untrusted bytes: [`decode_frame`] on the input, |
| 13 | //! then, for a `Submit` frame, `decode_envelope` on its payload. Every execution checks: |
| 14 | //! * no panic (`catch_unwind`); |
| 15 | //! * no read past the frame: the probe's high-water mark never exceeds the declared frame |
| 16 | //! end, and decoding the input followed by different trailing bytes gives the same answer |
| 17 | //! whenever the input already held the whole declared frame; |
| 18 | //! * no allocation above the cap: the largest single allocation during the decode is at |
| 19 | //! most `max_frame_body` (needs [`CountingAlloc`] as the global allocator); |
| 20 | //! * a frame that decodes re-encodes to exactly the bytes it was decoded from, and a |
| 21 | //! payload that decodes as an envelope re-encodes to exactly the payload; |
| 22 | //! * everything else is a typed [`WireRefusal`] (or a typed `CodecRefusal` for a payload). |
| 23 | |
| 24 | use crate::frame::{ |
| 25 | decode_frame, decode_frame_probed, encode_frame, Frame, FrameBody, WireLimits, WireRefusal, |
| 26 | FRAME_HEADER_LEN, |
| 27 | }; |
| 28 | use crate::probe::{bucket, EdgeProbe, EDGE_MAP_LEN}; |
| 29 | use std::alloc::{GlobalAlloc, Layout, System}; |
| 30 | use std::cell::Cell; |
| 31 | use std::collections::BTreeMap; |
| 32 | use std::panic::{catch_unwind, AssertUnwindSafe}; |
| 33 | use std::time::Instant; |
| 34 | use synapse_store::codec::{decode_envelope, encode_envelope}; |
| 35 | use synapse_store::CodecRefusal; |
| 36 | |
| 37 | // --------------------------------------------------------------------------------------- |
| 38 | // Allocation accounting |
| 39 | // --------------------------------------------------------------------------------------- |
| 40 | |
| 41 | thread_local! { |
| 42 | static TRACK: Cell<bool> = const { Cell::new(false) }; |
| 43 | static PEAK: Cell<usize> = const { Cell::new(0) }; |
| 44 | static TOTAL: Cell<usize> = const { Cell::new(0) }; |
| 45 | } |
| 46 | |
| 47 | fn note(size: usize) { |
| 48 | let _ = TRACK.try_with(|t| { |
| 49 | if t.get() { |
| 50 | let _ = PEAK.try_with(|p| p.set(p.get().max(size))); |
| 51 | let _ = TOTAL.try_with(|p| p.set(p.get().saturating_add(size))); |
| 52 | } |
| 53 | }); |
| 54 | } |
| 55 | |
| 56 | /// Global allocator that records, per thread and only while a measurement is open, the |
| 57 | /// largest single allocation and the total bytes allocated. Install it in the binary or |
| 58 | /// test that runs the fuzzer: `#[global_allocator] static A: CountingAlloc = CountingAlloc;` |
| 59 | pub struct CountingAlloc; |
| 60 | |
| 61 | // SAFETY: every method forwards to `System` with the same arguments; the bookkeeping only |
| 62 | // touches thread-local `Cell`s through `try_with`, which never allocates. |
| 63 | unsafe impl GlobalAlloc for CountingAlloc { |
| 64 | unsafe fn alloc(&self, layout: Layout) -> *mut u8 { |
| 65 | note(layout.size()); |
| 66 | System.alloc(layout) |
| 67 | } |
| 68 | unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { |
| 69 | note(layout.size()); |
| 70 | System.alloc_zeroed(layout) |
| 71 | } |
| 72 | unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { |
| 73 | note(new_size); |
| 74 | System.realloc(ptr, layout, new_size) |
| 75 | } |
| 76 | unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { |
| 77 | System.dealloc(ptr, layout) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | thread_local! { |
| 82 | static QUIET_PANICS: Cell<bool> = const { Cell::new(false) }; |
| 83 | } |
| 84 | |
| 85 | /// Silence the panic message of expected (caught) panics on this thread only, leaving the |
| 86 | /// process panic hook in place for every other thread (test harness threads included). |
| 87 | fn quiet_panics_on_this_thread() { |
| 88 | static INSTALL: std::sync::Once = std::sync::Once::new(); |
| 89 | INSTALL.call_once(|| { |
| 90 | let previous = std::panic::take_hook(); |
| 91 | std::panic::set_hook(Box::new(move |info| { |
| 92 | if !QUIET_PANICS.try_with(|q| q.get()).unwrap_or(false) { |
| 93 | previous(info); |
| 94 | } |
| 95 | })); |
| 96 | }); |
| 97 | QUIET_PANICS.with(|q| q.set(true)); |
| 98 | } |
| 99 | /// Run `f`, returning its result (or panic) with (largest single allocation, total bytes). |
| 100 | pub fn measured<T>(f: impl FnOnce() -> T) -> (std::thread::Result<T>, usize, usize) { |
| 101 | PEAK.with(|p| p.set(0)); |
| 102 | TOTAL.with(|p| p.set(0)); |
| 103 | TRACK.with(|t| t.set(true)); |
| 104 | let r = catch_unwind(AssertUnwindSafe(f)); |
| 105 | TRACK.with(|t| t.set(false)); |
| 106 | (r, PEAK.with(|p| p.get()), TOTAL.with(|p| p.get())) |
| 107 | } |
| 108 | |
| 109 | /// True when [`CountingAlloc`] is the global allocator (a probe allocation is seen). |
| 110 | pub fn alloc_tracking_installed() -> bool { |
| 111 | let (_, peak, _) = measured(|| std::hint::black_box(vec![0u8; 4321])); |
| 112 | peak >= 4321 |
| 113 | } |
| 114 | |
| 115 | // --------------------------------------------------------------------------------------- |
| 116 | // Target |
| 117 | // --------------------------------------------------------------------------------------- |
| 118 | |
| 119 | /// What the server-side decode of one input produced. |
| 120 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 121 | #[allow(clippy::large_enum_variant)] // built once per execution; boxing buys nothing here |
| 122 | pub enum TargetOutcome { |
| 123 | /// A frame of `consumed` bytes; for a `Submit`, the payload's envelope decode result. |
| 124 | Accepted { |
| 125 | frame: Frame, |
| 126 | consumed: usize, |
| 127 | payload: Option<Result<synapse_core::ChangesetEnvelope, CodecRefusal>>, |
| 128 | }, |
| 129 | Refused(WireRefusal), |
| 130 | } |
| 131 | |
| 132 | fn target_with<P: crate::probe::Probe>( |
| 133 | input: &[u8], |
| 134 | limits: &WireLimits, |
| 135 | probe: &mut P, |
| 136 | ) -> TargetOutcome { |
| 137 | match decode_frame_probed(input, limits, probe) { |
| 138 | Ok((frame, consumed)) => { |
| 139 | let payload = match &frame.body { |
| 140 | FrameBody::Submit(req) => Some(decode_envelope( |
| 141 | &req.payload, |
| 142 | u64::from(limits.max_frame_body), |
| 143 | )), |
| 144 | _ => None, |
| 145 | }; |
| 146 | TargetOutcome::Accepted { |
| 147 | frame, |
| 148 | consumed, |
| 149 | payload, |
| 150 | } |
| 151 | } |
| 152 | Err(r) => TargetOutcome::Refused(r), |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | /// A fuzz target: decode untrusted `input` under `limits`, reporting to the probe. |
| 157 | pub type Target = fn(&[u8], &WireLimits, &mut EdgeProbe) -> TargetOutcome; |
| 158 | |
| 159 | /// The real target: [`decode_frame_probed`], then `decode_envelope` on a `Submit` payload. |
| 160 | pub fn server_decode(input: &[u8], limits: &WireLimits, probe: &mut EdgeProbe) -> TargetOutcome { |
| 161 | target_with(input, limits, probe) |
| 162 | } |
| 163 | |
| 164 | /// The real target without instrumentation. |
| 165 | pub fn target(input: &[u8], limits: &WireLimits) -> TargetOutcome { |
| 166 | target_with(input, limits, &mut crate::probe::NoProbe) |
| 167 | } |
| 168 | |
| 169 | /// Declared end of the frame at the start of `input` (header length plus `body_len`), or |
| 170 | /// the header length when the header is incomplete. |
| 171 | fn declared_end(input: &[u8]) -> usize { |
| 172 | if input.len() < FRAME_HEADER_LEN { |
| 173 | return FRAME_HEADER_LEN; |
| 174 | } |
| 175 | let n = u32::from_le_bytes(input[12..16].try_into().expect("4 bytes")); |
| 176 | FRAME_HEADER_LEN + n as usize |
| 177 | } |
| 178 | |
| 179 | // --------------------------------------------------------------------------------------- |
| 180 | // Engine |
| 181 | // --------------------------------------------------------------------------------------- |
| 182 | |
| 183 | /// Deterministic PRNG (SplitMix64). |
| 184 | #[derive(Debug, Clone)] |
| 185 | pub struct SplitMix64(pub u64); |
| 186 | |
| 187 | impl SplitMix64 { |
| 188 | pub fn next_u64(&mut self) -> u64 { |
| 189 | self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); |
| 190 | let mut z = self.0; |
| 191 | z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); |
| 192 | z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); |
| 193 | z ^ (z >> 31) |
| 194 | } |
| 195 | pub fn below(&mut self, n: usize) -> usize { |
| 196 | if n == 0 { |
| 197 | 0 |
| 198 | } else { |
| 199 | (self.next_u64() % n as u64) as usize |
| 200 | } |
| 201 | } |
| 202 | fn chance(&mut self, num: usize, den: usize) -> bool { |
| 203 | self.below(den) < num |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | /// When the run stops; fixed before the run. |
| 208 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 209 | pub enum Budget { |
| 210 | Execs(u64), |
| 211 | Seconds(f64), |
| 212 | } |
| 213 | |
| 214 | #[derive(Debug, Clone)] |
| 215 | pub struct FuzzConfig { |
| 216 | pub seed: u64, |
| 217 | pub budget: Budget, |
| 218 | pub limits: WireLimits, |
| 219 | /// Corpus size limit (new-coverage inputs beyond it are counted, not kept). |
| 220 | pub max_corpus: usize, |
| 221 | } |
| 222 | |
| 223 | /// One broken invariant, with the input that broke it. |
| 224 | #[derive(Debug, Clone)] |
| 225 | pub struct Violation { |
| 226 | pub kind: &'static str, |
| 227 | pub detail: String, |
| 228 | pub input: Vec<u8>, |
| 229 | } |
| 230 | |
| 231 | #[derive(Debug, Clone, Default)] |
| 232 | pub struct FuzzReport { |
| 233 | pub execs: u64, |
| 234 | pub elapsed_s: f64, |
| 235 | pub seeds: usize, |
| 236 | /// Distinct edges reached. |
| 237 | pub edges: usize, |
| 238 | /// Inputs that reached new coverage (seeds first), in discovery order. |
| 239 | pub corpus: Vec<Vec<u8>>, |
| 240 | /// Executions at which each non-seed corpus entry was found. |
| 241 | pub corpus_found_at: Vec<u64>, |
| 242 | /// Count per outcome class: `accepted:<kind>`, `refused:<kind>`, |
| 243 | /// `payload_accepted`, `payload_refused:<kind>`. |
| 244 | pub outcomes: BTreeMap<String, u64>, |
| 245 | pub violation_counts: BTreeMap<&'static str, u64>, |
| 246 | /// First violations of each kind (at most 4 each). |
| 247 | pub violations: Vec<Violation>, |
| 248 | /// Largest single allocation in any decode, bytes. |
| 249 | pub peak_alloc: usize, |
| 250 | /// Largest total bytes allocated by one decode. |
| 251 | pub peak_alloc_total: usize, |
| 252 | pub alloc_tracking: bool, |
| 253 | pub largest_input: usize, |
| 254 | /// Instrumented decoder sites (source lines of `frame.rs`) in total, and those never |
| 255 | /// reached during the run. |
| 256 | pub sites_total: usize, |
| 257 | pub sites_unreached: Vec<u32>, |
| 258 | } |
| 259 | |
| 260 | impl FuzzReport { |
| 261 | pub fn violation_total(&self) -> u64 { |
| 262 | self.violation_counts.values().sum() |
| 263 | } |
| 264 | |
| 265 | fn violate(&mut self, kind: &'static str, detail: String, input: &[u8]) { |
| 266 | let n = self.violation_counts.entry(kind).or_insert(0); |
| 267 | *n += 1; |
| 268 | if *n <= 4 { |
| 269 | self.violations.push(Violation { |
| 270 | kind, |
| 271 | detail, |
| 272 | input: input.to_vec(), |
| 273 | }); |
| 274 | } |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | fn classify(out: &TargetOutcome, outcomes: &mut BTreeMap<String, u64>) { |
| 279 | let mut add = |k: String| *outcomes.entry(k).or_insert(0) += 1; |
| 280 | match out { |
| 281 | TargetOutcome::Accepted { frame, payload, .. } => { |
| 282 | add(format!("accepted:{}", frame.body.kind().name())); |
| 283 | match payload { |
| 284 | Some(Ok(_)) => add("payload_accepted".into()), |
| 285 | Some(Err(r)) => add(format!("payload_refused:{}", r.kind())), |
| 286 | None => {} |
| 287 | } |
| 288 | } |
| 289 | TargetOutcome::Refused(r) => add(format!("refused:{}", r.kind())), |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | /// Invariant checks on one execution's outcome. Returns the violations found. |
| 294 | fn check_outcome( |
| 295 | input: &[u8], |
| 296 | out: &TargetOutcome, |
| 297 | limits: &WireLimits, |
| 298 | ) -> Vec<(&'static str, String)> { |
| 299 | let mut v = Vec::new(); |
| 300 | if let TargetOutcome::Accepted { |
| 301 | frame, |
| 302 | consumed, |
| 303 | payload, |
| 304 | } = out |
| 305 | { |
| 306 | match encode_frame(frame) { |
| 307 | Ok(bytes) if bytes.as_slice() == &input[..*consumed] => {} |
| 308 | Ok(bytes) => v.push(( |
| 309 | "non_canonical_accept", |
| 310 | format!("re-encoded {} bytes differ from {consumed}", bytes.len()), |
| 311 | )), |
| 312 | Err(e) => v.push(("non_canonical_accept", format!("re-encode refused: {e}"))), |
| 313 | } |
| 314 | if let (Some(Ok(env)), FrameBody::Submit(req)) = (payload, &frame.body) { |
| 315 | match encode_envelope(env) { |
| 316 | Ok(b) if b == req.payload => {} |
| 317 | _ => v.push(( |
| 318 | "payload_non_canonical", |
| 319 | "payload envelope does not re-encode to its bytes".into(), |
| 320 | )), |
| 321 | } |
| 322 | } |
| 323 | if *consumed > input.len() || *consumed != declared_end(input) { |
| 324 | v.push(( |
| 325 | "read_past_frame", |
| 326 | format!("consumed {consumed} of declared {}", declared_end(input)), |
| 327 | )); |
| 328 | } |
| 329 | } |
| 330 | let _ = limits; |
| 331 | v |
| 332 | } |
| 333 | |
| 334 | struct Engine { |
| 335 | target: Target, |
| 336 | scratch: EdgeProbe, |
| 337 | cfg: FuzzConfig, |
| 338 | rng: SplitMix64, |
| 339 | virgin: Vec<u8>, |
| 340 | probe: EdgeProbe, |
| 341 | report: FuzzReport, |
| 342 | } |
| 343 | |
| 344 | const INTERESTING_U8: [u8; 12] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 0x7F, 0x80, 0xFF]; |
| 345 | |
| 346 | impl Engine { |
| 347 | fn interesting_u32(&mut self, v: &[u8], off: usize) -> u32 { |
| 348 | let cap = self.cfg.limits.max_frame_body; |
| 349 | let remaining = v.len().saturating_sub(off + 4) as u32; |
| 350 | let choices = [ |
| 351 | 0, |
| 352 | 1, |
| 353 | 2, |
| 354 | 3, |
| 355 | 4, |
| 356 | 16, |
| 357 | 32, |
| 358 | 33, |
| 359 | 64, |
| 360 | cap.saturating_sub(1), |
| 361 | cap, |
| 362 | cap.saturating_add(1), |
| 363 | remaining, |
| 364 | remaining.saturating_add(1), |
| 365 | remaining.saturating_sub(1), |
| 366 | remaining / 32, |
| 367 | remaining / 32 + 1, |
| 368 | v.len() as u32, |
| 369 | 0x7FFF_FFFF, |
| 370 | u32::MAX, |
| 371 | ]; |
| 372 | choices[self.rng.below(choices.len())] |
| 373 | } |
| 374 | |
| 375 | fn mutate(&mut self, base: &[u8]) -> Vec<u8> { |
| 376 | let mut v = base.to_vec(); |
| 377 | let rounds = 1 + self.rng.below(4); |
| 378 | for _ in 0..rounds { |
| 379 | let len = v.len(); |
| 380 | match self.rng.below(12) { |
| 381 | 0 if len > 0 => { |
| 382 | let i = self.rng.below(len); |
| 383 | v[i] ^= 1 << self.rng.below(8); |
| 384 | } |
| 385 | 1 if len > 0 => { |
| 386 | let i = self.rng.below(len); |
| 387 | v[i] = self.rng.next_u64() as u8; |
| 388 | } |
| 389 | 2 if len > 0 => { |
| 390 | let i = self.rng.below(len); |
| 391 | v[i] = INTERESTING_U8[self.rng.below(INTERESTING_U8.len())]; |
| 392 | } |
| 393 | 3 if len >= 4 => { |
| 394 | let off = self.rng.below(len - 3); |
| 395 | let x = self.interesting_u32(&v, off); |
| 396 | v[off..off + 4].copy_from_slice(&x.to_le_bytes()); |
| 397 | } |
| 398 | 4 => { |
| 399 | let n = self.rng.below(len + 1); |
| 400 | v.truncate(n); |
| 401 | } |
| 402 | 5 => { |
| 403 | let at = self.rng.below(len + 1); |
| 404 | let n = 1 + self.rng.below(16); |
| 405 | let ins: Vec<u8> = (0..n).map(|_| self.rng.next_u64() as u8).collect(); |
| 406 | v.splice(at..at, ins); |
| 407 | } |
| 408 | 6 if len > 0 => { |
| 409 | let a = self.rng.below(len); |
| 410 | let b = (a + 1 + self.rng.below(32)).min(len); |
| 411 | v.drain(a..b); |
| 412 | } |
| 413 | 7 if len > 0 => { |
| 414 | let a = self.rng.below(len); |
| 415 | let b = (a + 1 + self.rng.below(64)).min(len); |
| 416 | let piece = v[a..b].to_vec(); |
| 417 | let at = self.rng.below(len + 1); |
| 418 | v.splice(at..at, piece); |
| 419 | } |
| 420 | 8 if !self.report.corpus.is_empty() => { |
| 421 | let other = |
| 422 | self.report.corpus[self.rng.below(self.report.corpus.len())].clone(); |
| 423 | let cut = self.rng.below(len + 1); |
| 424 | let from = self.rng.below(other.len() + 1); |
| 425 | v.truncate(cut); |
| 426 | v.extend_from_slice(&other[from..]); |
| 427 | } |
| 428 | 9 if len >= 64 => { |
| 429 | // Swap two 32-byte runs (reorders digests and keys). |
| 430 | let a = self.rng.below(len - 31); |
| 431 | let b = self.rng.below(len - 31); |
| 432 | let (x, y) = (v[a..a + 32].to_vec(), v[b..b + 32].to_vec()); |
| 433 | v[a..a + 32].copy_from_slice(&y); |
| 434 | v[b..b + 32].copy_from_slice(&x); |
| 435 | } |
| 436 | 10 if len >= 6 => { |
| 437 | v[5] = self.rng.below(9) as u8; |
| 438 | } |
| 439 | 11 if len >= 4 => { |
| 440 | // Rewrite an aligned u32 near a random position to the bytes left. |
| 441 | let off = self.rng.below(len - 3); |
| 442 | let rem = (len - off - 4) as u32; |
| 443 | v[off..off + 4].copy_from_slice(&rem.to_le_bytes()); |
| 444 | } |
| 445 | _ => {} |
| 446 | } |
| 447 | } |
| 448 | // Half the time keep the declared body length honest so mutations reach the body. |
| 449 | if v.len() >= FRAME_HEADER_LEN && self.rng.chance(1, 2) { |
| 450 | let body = (v.len() - FRAME_HEADER_LEN) as u32; |
| 451 | v[12..16].copy_from_slice(&body.to_le_bytes()); |
| 452 | } |
| 453 | v.truncate(self.cfg.limits.max_frame_body as usize + 2 * FRAME_HEADER_LEN); |
| 454 | v |
| 455 | } |
| 456 | |
| 457 | /// Run one input; returns true when it reached new coverage. |
| 458 | fn exec(&mut self, input: &[u8]) -> bool { |
| 459 | self.report.execs += 1; |
| 460 | self.report.largest_input = self.report.largest_input.max(input.len()); |
| 461 | self.probe.reset(); |
| 462 | let limits = self.cfg.limits; |
| 463 | let probe = &mut self.probe; |
| 464 | let t = self.target; |
| 465 | let (res, peak, total) = measured(|| t(input, &limits, probe)); |
| 466 | let out = match res { |
| 467 | Ok(o) => o, |
| 468 | Err(p) => { |
| 469 | let msg = p |
| 470 | .downcast_ref::<&str>() |
| 471 | .map(|s| s.to_string()) |
| 472 | .or_else(|| p.downcast_ref::<String>().cloned()) |
| 473 | .unwrap_or_default(); |
| 474 | self.report.violate("panic", msg, input); |
| 475 | return self.update_coverage(); |
| 476 | } |
| 477 | }; |
| 478 | self.report.peak_alloc = self.report.peak_alloc.max(peak); |
| 479 | self.report.peak_alloc_total = self.report.peak_alloc_total.max(total); |
| 480 | if peak as u64 > u64::from(limits.max_frame_body) { |
| 481 | self.report.violate( |
| 482 | "alloc_over_cap", |
| 483 | format!( |
| 484 | "allocation of {peak} bytes over cap {}", |
| 485 | limits.max_frame_body |
| 486 | ), |
| 487 | input, |
| 488 | ); |
| 489 | } |
| 490 | let end = declared_end(input).min(input.len()); |
| 491 | if self.probe.high_water > end { |
| 492 | self.report.violate( |
| 493 | "read_past_frame", |
| 494 | format!("read to {} past frame end {end}", self.probe.high_water), |
| 495 | input, |
| 496 | ); |
| 497 | } |
| 498 | for (kind, detail) in check_outcome(input, &out, &limits) { |
| 499 | self.report.violate(kind, detail, input); |
| 500 | } |
| 501 | // Trailing-bytes differential: a decision made on a complete frame (or a refusal |
| 502 | // other than truncation) must not depend on what follows the frame. |
| 503 | let truncated = matches!(out, TargetOutcome::Refused(WireRefusal::Truncated { .. })); |
| 504 | if !truncated { |
| 505 | let mut longer = input.to_vec(); |
| 506 | let n = 1 + self.rng.below(48); |
| 507 | longer.extend((0..n).map(|_| self.rng.next_u64() as u8)); |
| 508 | self.scratch.reset(); |
| 509 | let out2 = (self.target)(&longer, &limits, &mut self.scratch); |
| 510 | if out2 != out { |
| 511 | self.report.violate( |
| 512 | "read_past_frame", |
| 513 | "outcome changed when bytes were appended after the frame".into(), |
| 514 | input, |
| 515 | ); |
| 516 | } |
| 517 | } |
| 518 | classify(&out, &mut self.report.outcomes); |
| 519 | self.update_coverage() |
| 520 | } |
| 521 | |
| 522 | fn update_coverage(&mut self) -> bool { |
| 523 | let mut new = false; |
| 524 | let (virgin, edges) = (&mut self.virgin, &mut self.report.edges); |
| 525 | self.probe.for_each_hit(|i, c| { |
| 526 | let b = bucket(c); |
| 527 | if virgin[i] & b != b { |
| 528 | if virgin[i] == 0 { |
| 529 | *edges += 1; |
| 530 | } |
| 531 | virgin[i] |= b; |
| 532 | new = true; |
| 533 | } |
| 534 | }); |
| 535 | new |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | /// Run the fuzzer from `seeds` (valid frames) under `cfg`. |
| 540 | pub fn run(cfg: FuzzConfig, seeds: &[Vec<u8>]) -> FuzzReport { |
| 541 | run_target(cfg, seeds, server_decode) |
| 542 | } |
| 543 | |
| 544 | /// Run the fuzzer on another target (negative controls: decoders with planted bugs). |
| 545 | pub fn run_target(cfg: FuzzConfig, seeds: &[Vec<u8>], target: Target) -> FuzzReport { |
| 546 | let mut e = Engine { |
| 547 | target, |
| 548 | scratch: EdgeProbe::new(), |
| 549 | rng: SplitMix64(cfg.seed), |
| 550 | virgin: vec![0u8; EDGE_MAP_LEN], |
| 551 | probe: EdgeProbe::new(), |
| 552 | report: FuzzReport { |
| 553 | alloc_tracking: alloc_tracking_installed(), |
| 554 | seeds: seeds.len(), |
| 555 | ..Default::default() |
| 556 | }, |
| 557 | cfg, |
| 558 | }; |
| 559 | quiet_panics_on_this_thread(); |
| 560 | let start = Instant::now(); |
| 561 | for s in seeds { |
| 562 | e.exec(s); |
| 563 | e.report.corpus.push(s.clone()); |
| 564 | } |
| 565 | loop { |
| 566 | let stop = match e.cfg.budget { |
| 567 | Budget::Execs(n) => e.report.execs >= n, |
| 568 | Budget::Seconds(s) => { |
| 569 | e.report.execs.is_multiple_of(256) && start.elapsed().as_secs_f64() >= s |
| 570 | } |
| 571 | }; |
| 572 | if stop { |
| 573 | break; |
| 574 | } |
| 575 | let base = e.report.corpus[e.rng.below(e.report.corpus.len())].clone(); |
| 576 | let input = e.mutate(&base); |
| 577 | if e.exec(&input) && e.report.corpus.len() < e.cfg.max_corpus { |
| 578 | e.report.corpus.push(input); |
| 579 | e.report.corpus_found_at.push(e.report.execs); |
| 580 | } |
| 581 | } |
| 582 | e.report.elapsed_s = start.elapsed().as_secs_f64(); |
| 583 | let lines = crate::probe::instrumented_lines(); |
| 584 | e.report.sites_total = lines.len(); |
| 585 | e.report.sites_unreached = lines |
| 586 | .into_iter() |
| 587 | .filter(|l| !e.probe.sites_seen[*l as usize & (crate::probe::SITE_LINES - 1)]) |
| 588 | .collect(); |
| 589 | QUIET_PANICS.with(|q| q.set(false)); |
| 590 | e.report |
| 591 | } |
| 592 | |
| 593 | /// Replay of a saved corpus without instrumentation. |
| 594 | #[derive(Debug, Clone, Default)] |
| 595 | pub struct CorpusReplay { |
| 596 | pub entries: usize, |
| 597 | /// Entries that decoded and re-encoded to identical bytes (well-formed frames). |
| 598 | pub accepted_canonical: usize, |
| 599 | /// Malformed entries, by typed refusal kind. |
| 600 | pub refused: BTreeMap<String, usize>, |
| 601 | /// Entries that panicked, decoded non-canonically, or allocated over the cap. |
| 602 | pub violations: Vec<(usize, String)>, |
| 603 | pub peak_alloc: usize, |
| 604 | } |
| 605 | |
| 606 | /// Decode every corpus entry: each must be a canonical frame or a typed refusal. |
| 607 | pub fn replay_corpus(corpus: &[Vec<u8>], limits: &WireLimits) -> CorpusReplay { |
| 608 | let mut out = CorpusReplay { |
| 609 | entries: corpus.len(), |
| 610 | ..Default::default() |
| 611 | }; |
| 612 | quiet_panics_on_this_thread(); |
| 613 | for (i, input) in corpus.iter().enumerate() { |
| 614 | let (res, peak, _) = measured(|| target(input, limits)); |
| 615 | out.peak_alloc = out.peak_alloc.max(peak); |
| 616 | if peak as u64 > u64::from(limits.max_frame_body) { |
| 617 | out.violations |
| 618 | .push((i, format!("allocation {peak} over cap"))); |
| 619 | } |
| 620 | match res { |
| 621 | Err(_) => out.violations.push((i, "panic".into())), |
| 622 | Ok(o) => { |
| 623 | let v = check_outcome(input, &o, limits); |
| 624 | if !v.is_empty() { |
| 625 | out.violations.push((i, format!("{v:?}"))); |
| 626 | } else { |
| 627 | match &o { |
| 628 | TargetOutcome::Accepted { .. } => out.accepted_canonical += 1, |
| 629 | TargetOutcome::Refused(r) => { |
| 630 | *out.refused.entry(r.kind().to_string()).or_insert(0) += 1 |
| 631 | } |
| 632 | } |
| 633 | } |
| 634 | } |
| 635 | } |
| 636 | } |
| 637 | QUIET_PANICS.with(|q| q.set(false)); |
| 638 | out |
| 639 | } |
| 640 | |
| 641 | /// Serialise a corpus as `u32 count | (u32 len | bytes)*` (little endian). |
| 642 | pub fn corpus_to_bytes(corpus: &[Vec<u8>]) -> Vec<u8> { |
| 643 | let mut b = Vec::new(); |
| 644 | b.extend_from_slice(&(corpus.len() as u32).to_le_bytes()); |
| 645 | for c in corpus { |
| 646 | b.extend_from_slice(&(c.len() as u32).to_le_bytes()); |
| 647 | b.extend_from_slice(c); |
| 648 | } |
| 649 | b |
| 650 | } |
| 651 | |
| 652 | /// Parse [`corpus_to_bytes`] output; `None` if malformed. |
| 653 | pub fn corpus_from_bytes(b: &[u8]) -> Option<Vec<Vec<u8>>> { |
| 654 | let take4 = |at: usize| -> Option<usize> { |
| 655 | Some(u32::from_le_bytes(b.get(at..at + 4)?.try_into().ok()?) as usize) |
| 656 | }; |
| 657 | let n = take4(0)?; |
| 658 | let mut at = 4; |
| 659 | let mut out = Vec::new(); |
| 660 | for _ in 0..n { |
| 661 | let len = take4(at)?; |
| 662 | at += 4; |
| 663 | out.push(b.get(at..at + len)?.to_vec()); |
| 664 | at += len; |
| 665 | } |
| 666 | (at == b.len()).then_some(out) |
| 667 | } |
| 668 | |
| 669 | /// Encoded seed frames ([`crate::testkit::sample_frames`]) that fit `limits`. |
| 670 | pub fn seed_corpus(limits: &WireLimits) -> Vec<Vec<u8>> { |
| 671 | crate::testkit::sample_frames() |
| 672 | .iter() |
| 673 | .map(|f| encode_frame(f).expect("sample frames encode")) |
| 674 | .filter(|b| b.len() - FRAME_HEADER_LEN <= limits.max_frame_body as usize) |
| 675 | .collect() |
| 676 | } |
| 677 | |
| 678 | /// Malformed frames derived from every seed: wrong magic, version, kind (0 and 8), flags, |
| 679 | /// reserved byte, declared length one over the cap, one byte short, and one trailing byte |
| 680 | /// inside the declared body. Every one must be refused; they join the corpus as seeds. |
| 681 | pub fn malformed_seed_corpus(limits: &WireLimits) -> Vec<Vec<u8>> { |
| 682 | let mut out = Vec::new(); |
| 683 | for good in seed_corpus(limits) { |
| 684 | let with = |i: usize, v: u8| { |
| 685 | let mut b = good.clone(); |
| 686 | b[i] = v; |
| 687 | b |
| 688 | }; |
| 689 | out.push(with(0, b'X')); |
| 690 | out.push(with(4, 2)); |
| 691 | out.push(with(5, 0)); |
| 692 | out.push(with(5, 8)); |
| 693 | out.push(with(6, 1)); |
| 694 | out.push(with(7, 0x80)); |
| 695 | let mut over = good.clone(); |
| 696 | over[12..16].copy_from_slice(&(limits.max_frame_body.saturating_add(1)).to_le_bytes()); |
| 697 | out.push(over); |
| 698 | out.push(good[..good.len() - 1].to_vec()); |
| 699 | let mut trailing = good.clone(); |
| 700 | trailing.push(0); |
| 701 | let n = (trailing.len() - FRAME_HEADER_LEN) as u32; |
| 702 | trailing[12..16].copy_from_slice(&n.to_le_bytes()); |
| 703 | out.push(trailing); |
| 704 | } |
| 705 | out |
| 706 | } |
| 707 | |
| 708 | /// Decode check used by tests: decode `bytes` fully. |
| 709 | pub fn decode_exact(bytes: &[u8], limits: &WireLimits) -> Result<Frame, WireRefusal> { |
| 710 | let (f, n) = decode_frame(bytes, limits)?; |
| 711 | if n != bytes.len() { |
| 712 | return Err(WireRefusal::TrailingBytes { |
| 713 | at: n, |
| 714 | count: bytes.len() - n, |
| 715 | }); |
| 716 | } |
| 717 | Ok(f) |
| 718 | } |