forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

fuzz.rs191 lines, 6.2 KiBHistoryRawDownload
1//! Malformed input never panics, never hangs and never allocates without
2//! bound.
3//!
4//! Ten thousand mutations per format, from a fixed seed so a failure is
5//! reproducible: bit flips, truncations, byte injections and pure noise behind
6//! each format's signature. Every one of them must come back as `Ok` or as an
7//! `Err` — a decoder reached by a file picker is reached by every broken file
8//! on the disk.
9
10use std::path::{Path, PathBuf};
11
12const ROUNDS: usize = 10_000;
13
14fn fixtures() -> PathBuf {
15 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/stills")
16}
17
18/// xorshift64*, so every run mutates the same way.
19struct Rng(u64);
20
21impl Rng {
22 fn next(&mut self) -> u64 {
23 self.0 ^= self.0 << 13;
24 self.0 ^= self.0 >> 7;
25 self.0 ^= self.0 << 17;
26 self.0
27 }
28
29 fn below(&mut self, bound: usize) -> usize {
30 (self.next() % bound.max(1) as u64) as usize
31 }
32}
33
34/// One mutated copy of `seed`: a few bit flips, a truncation, or an injection.
35///
36/// `head` bounds where the flips land. Aiming them at the first few dozen
37/// bytes is what actually reaches the geometry and colour-type paths: spread
38/// over a whole file they nearly all land in the compressed data and stop at
39/// the first integrity check.
40fn mutate(rng: &mut Rng, seed: &[u8], head: Option<usize>) -> Vec<u8> {
41 let mut data = seed.to_vec();
42 let region = head.unwrap_or(data.len()).min(data.len());
43 match rng.below(4) {
44 0 => {
45 for _ in 0..1 + rng.below(8) {
46 let at = rng.below(region);
47 data[at] ^= 1 << rng.below(8);
48 }
49 }
50 1 => data.truncate(rng.below(data.len())),
51 2 => {
52 for _ in 0..1 + rng.below(16) {
53 let at = rng.below(region);
54 data[at] = (rng.next() & 0xff) as u8;
55 }
56 }
57 _ => {
58 // Keep the signature, replace the body with noise: this is the
59 // shape that exercises header fields hardest.
60 let keep = 12.min(data.len());
61 data.truncate(keep);
62 for _ in 0..rng.below(400) {
63 data.push((rng.next() & 0xff) as u8);
64 }
65 }
66 }
67 data
68}
69
70/// Recompute every chunk CRC of a mutated PNG.
71///
72/// Without this the checksum catches every mutation at the door and the
73/// decoder proper is never fuzzed at all — the sweep would prove only that
74/// CRC-32 works.
75fn repair_png_crcs(data: &mut [u8]) {
76 let mut at = 8usize;
77 while at + 12 <= data.len() {
78 let len = u32::from_be_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]) as usize;
79 if len > data.len() || at + 12 + len > data.len() {
80 return;
81 }
82 let crc = crc32(&data[at + 4..at + 8 + len]);
83 data[at + 8 + len..at + 12 + len].copy_from_slice(&crc.to_be_bytes());
84 at += 12 + len;
85 }
86}
87
88fn sweep(name: &str, seed_file: &str) {
89 let Ok(seed) = std::fs::read(fixtures().join(seed_file)) else {
90 eprintln!("skipped: fixtures/stills not generated; run scripts/gen-still-fixtures.sh");
91 return;
92 };
93 let mut rng = Rng(0x2545_f491_4f6c_dd1d ^ name.len() as u64);
94 let mut decoded = 0usize;
95 for round in 0..ROUNDS {
96 // Half the rounds aim at the header, half at the whole file.
97 let head = if round % 2 == 0 { Some(48) } else { None };
98 let mut data = mutate(&mut rng, &seed, head);
99 if seed_file.ends_with(".png") {
100 repair_png_crcs(&mut data);
101 }
102 // The call is the assertion: a panic here fails the test with the
103 // round number, and the round number plus the fixed seed reproduces it.
104 if let Ok(image) = ec_image::decode(&data) {
105 decoded += 1;
106 let pixels = image.to_rgba8();
107 assert_eq!(
108 pixels.len(),
109 (image.width as usize) * (image.height as usize) * 4,
110 "{name} round {round}: buffer does not match the dimensions"
111 );
112 }
113 // Header-only parsing must survive the same input.
114 let _ = ec_image::info(&data);
115 }
116 eprintln!("{name}: {ROUNDS} mutations, {decoded} still decoded");
117}
118
119#[test]
120fn png_survives_mutation() {
121 sweep("png", "tiny.png");
122}
123
124#[test]
125fn jpeg_survives_mutation() {
126 sweep("jpeg", "tiny.jpg");
127}
128
129#[test]
130fn webp_lossy_survives_mutation() {
131 sweep("webp-lossy", "tiny-lossy.webp");
132}
133
134#[test]
135fn webp_lossless_survives_mutation() {
136 sweep("webp-lossless", "tiny-lossless.webp");
137}
138
139#[test]
140fn arbitrary_bytes_behind_a_signature_are_refused_not_believed() {
141 let signatures: [&[u8]; 3] = [
142 &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a],
143 &[0xff, 0xd8, 0xff, 0xe0],
144 b"RIFF\x40\x00\x00\x00WEBPVP8 ",
145 ];
146 let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
147 for signature in signatures {
148 for _ in 0..ROUNDS / 4 {
149 let mut data = signature.to_vec();
150 for _ in 0..rng.below(200) {
151 data.push((rng.next() & 0xff) as u8);
152 }
153 let _ = ec_image::decode(&data);
154 let _ = ec_image::info(&data);
155 }
156 }
157}
158
159#[test]
160fn a_header_asking_for_more_pixels_than_the_limit_is_refused() {
161 // A PNG IHDR claiming 65535x65535 is 4 gigapixels: the limit must refuse
162 // it before any buffer is sized from those numbers.
163 let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
164 let mut ihdr = Vec::new();
165 ihdr.extend_from_slice(&65535u32.to_be_bytes());
166 ihdr.extend_from_slice(&65535u32.to_be_bytes());
167 ihdr.extend_from_slice(&[8, 6, 0, 0, 0]);
168 png.extend_from_slice(&(ihdr.len() as u32).to_be_bytes());
169 let start = png.len();
170 png.extend_from_slice(b"IHDR");
171 png.extend_from_slice(&ihdr);
172 let crc = crc32(&png[start..]);
173 png.extend_from_slice(&crc.to_be_bytes());
174 let err = ec_image::decode(&png).expect_err("4 gigapixels is past the limit");
175 assert!(format!("{err}").contains("limit"), "{err}");
176}
177
178fn crc32(data: &[u8]) -> u32 {
179 let mut c = 0xffff_ffffu32;
180 for &b in data {
181 c ^= u32::from(b);
182 for _ in 0..8 {
183 c = if c & 1 != 0 {
184 0xedb8_8320 ^ (c >> 1)
185 } else {
186 c >> 1
187 };
188 }
189 }
190 c ^ 0xffff_ffff
191}