-
-
Notifications
You must be signed in to change notification settings - Fork 28
Fuzz coverage error paths #344
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
346cfd4
move `uncompress2` -> `uncompress`
folkertdev c94cf3f
don't track codecov of the fuzzer itself
folkertdev 0ef2162
keep error paths for coverage on CI
folkertdev 7391563
feed the fuzzer chunked input
folkertdev 893cc15
cleanup
folkertdev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,54 +1,147 @@ | ||
#![no_main] | ||
use libfuzzer_sys::fuzz_target; | ||
//! This fuzzer is intended to find memory safety bugs and undefined behavior. The input entire | ||
//! input is processed, allowing for analysis of files of arbitrary size. It also speeds up | ||
//! coverage by disabling checksum validation and disregarding correctness of the results. | ||
//! | ||
//! This test must be run with `--features disable-checksum`. It's also suggested to initialize | ||
//! fuzzing with a corpus of real zlib/gzip files. Place the corpus in directory | ||
//! `corpus/uncompress` (the default corpus location). | ||
//! | ||
//! Then, the fuzzer can be run like: | ||
//! | ||
//! ``` | ||
//! cargo fuzz run uncompress --features disable-checksum -j$(nproc) | ||
//! ``` | ||
//! | ||
//! If not starting with an initial corpus, consider using the `-- -max_len=1048576` argument to | ||
//! test larger inputs. | ||
//! | ||
//! libfuzzer uses LLVM sanitizers to detect some classes of bugs and UB. For detecting | ||
//! Rust-specific UB, use Miri. Once a corpus with suitable coverage has been built, you can run | ||
//! Miri against the corpus by executing: | ||
//! ``` | ||
//! MIRIFLAGS=-Zmiri-disable-isolation cargo miri nextest run --bin uncompress --features disable-checksum | ||
//! ``` | ||
//! This assumes the corpus is located in the default directory of `corpus/uncompress`. If it | ||
//! isn't, specify the corpus directory with the `ZLIB_RS_CORPUS_DIR` environment variable. | ||
#![cfg_attr(not(any(miri, test)), no_main)] | ||
|
||
use zlib_rs::ReturnCode; | ||
use libfuzzer_sys::{fuzz_target, Corpus}; | ||
use libz_rs_sys::{ | ||
gz_header, inflate, inflateEnd, inflateGetHeader, inflateInit2_, z_stream, zlibVersion, | ||
}; | ||
use zlib_rs::{InflateFlush, ReturnCode}; | ||
|
||
fn uncompress_help(input: &[u8]) -> Vec<u8> { | ||
let mut dest_vec = vec![0u8; 1 << 16]; | ||
fuzz_target!(|input: &[u8]| -> Corpus { run(input) }); | ||
|
||
let mut dest_len = dest_vec.len() as std::ffi::c_ulong; | ||
let dest = dest_vec.as_mut_ptr(); | ||
fn run(input: &[u8]) -> Corpus { | ||
if input.is_empty() { | ||
return Corpus::Reject; | ||
} | ||
|
||
let source = input.as_ptr(); | ||
let source_len = input.len() as _; | ||
let mut stream = z_stream::default(); | ||
|
||
let err = unsafe { ::libz_rs_sys::uncompress(dest, &mut dest_len, source, source_len) }; | ||
let err = unsafe { | ||
inflateInit2_( | ||
&mut stream, | ||
15 + 32, // Support both zlib and gzip files. | ||
zlibVersion(), | ||
size_of::<z_stream>() as _, | ||
) | ||
}; | ||
assert_eq!(ReturnCode::from(err), ReturnCode::Ok); | ||
|
||
if err != 0 { | ||
panic!("error {:?}", ReturnCode::from(err)); | ||
} | ||
let mut extra = vec![0; 64]; | ||
let mut name = vec![0; 64]; | ||
let mut comment = vec![0; 64]; | ||
let mut header = gz_header { | ||
text: 0, | ||
time: 0, | ||
xflags: 0, | ||
os: 0, | ||
extra: extra.as_mut_ptr(), | ||
extra_len: 0, | ||
extra_max: 64, | ||
name: name.as_mut_ptr(), | ||
name_max: 64, | ||
comment: comment.as_mut_ptr(), | ||
comm_max: 64, | ||
hcrc: 0, | ||
done: 0, | ||
}; | ||
|
||
dest_vec.truncate(dest_len as usize); | ||
let err = unsafe { inflateGetHeader(&mut stream, &mut header) }; | ||
assert_eq!(ReturnCode::from(err), ReturnCode::Ok); | ||
|
||
dest_vec | ||
} | ||
let mut output = vec![0; input.len()]; | ||
let input_len: u64 = input.len().try_into().unwrap(); | ||
stream.next_out = output.as_mut_ptr(); | ||
stream.avail_out = output.len().try_into().unwrap(); | ||
|
||
fuzz_target!(|data: String| { | ||
// first, deflate the data using the standard zlib | ||
let mut length = 8 * 1024; | ||
let mut deflated = vec![0; length]; | ||
|
||
let error = unsafe { | ||
libz_ng_sys::compress( | ||
deflated.as_mut_ptr().cast(), | ||
&mut length, | ||
data.as_ptr().cast(), | ||
data.len(), | ||
) | ||
// Small enough to hit interesting cases, but large enough to hit the fast path | ||
let chunk_size = 64; | ||
|
||
// For code coverage (on CI), we want to keep inputs that triggered the error | ||
// branches, to get an accurate picture of what error paths we actually hit. | ||
// | ||
// It helps that on CI we start with a corpus of valid files: a mutation of such an | ||
// input is not a sequence of random bytes, but rather quite close to correct and | ||
// hence likely to hit interesting error conditions. | ||
let invalid_input = if cfg!(feature = "keep-invalid-in-corpus") { | ||
Corpus::Keep | ||
} else { | ||
Corpus::Reject | ||
}; | ||
|
||
let error = ReturnCode::from(error as i32); | ||
assert_eq!(ReturnCode::Ok, error); | ||
for chunk in input.chunks(chunk_size) { | ||
stream.next_in = chunk.as_ptr() as *mut u8; | ||
stream.avail_in = chunk.len() as _; | ||
|
||
deflated.truncate(length as _); | ||
let err = unsafe { inflate(&mut stream, InflateFlush::NoFlush as _) }; | ||
match ReturnCode::from(err) { | ||
ReturnCode::StreamEnd => { | ||
break; | ||
} | ||
ReturnCode::Ok => { | ||
continue; | ||
} | ||
ReturnCode::BufError => { | ||
let add_space: u32 = Ord::max(1024, output.len().try_into().unwrap()); | ||
output.resize(output.len() + add_space as usize, 0); | ||
|
||
let output = uncompress_help(&deflated); | ||
// If resize() reallocates, it may have moved in memory. | ||
stream.next_out = output.as_mut_ptr(); | ||
stream.avail_out += add_space; | ||
} | ||
_ => { | ||
unsafe { inflateEnd(&mut stream) }; | ||
return invalid_input; | ||
} | ||
} | ||
} | ||
|
||
if output != data.as_bytes() { | ||
let path = std::env::temp_dir().join("deflate.txt"); | ||
std::fs::write(&path, &data).unwrap(); | ||
eprintln!("saved input file to {path:?}"); | ||
let err = unsafe { inflateEnd(&mut stream) }; | ||
match ReturnCode::from(err) { | ||
ReturnCode::Ok => Corpus::Keep, | ||
_ => invalid_input, | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
#[cfg(miri)] | ||
use { | ||
crate::run, | ||
rstest::rstest, | ||
std::{fs::File, io::Read, path::PathBuf}, | ||
}; | ||
|
||
assert_eq!(output, data.as_bytes()); | ||
}); | ||
#[rstest] | ||
#[cfg(miri)] | ||
fn miri_corpus(#[files("${ZLIB_RS_CORPUS_DIR:-corpus/uncompress}/*")] path: PathBuf) { | ||
let mut input = File::open(path).unwrap(); | ||
let mut buf = Vec::new(); | ||
input.read_to_end(&mut buf).unwrap(); | ||
|
||
run(&buf); | ||
} | ||
} |
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would varying the chunk size make sense? Especially non-power-of-two chunk sizes seem like they could be useful for finding edge-cases.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It might, but I don't see how we could do that in a deterministic way and continue to use the compression corpus.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You could take the chunk size from the fuzz input, right? So for example interpreting the fuzz input as series of 1 byte chunk size + n bytes chunk data.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would that not mess with how effective the corpus is?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You could reformat the existing corpus into this format, right? In any case I guess this is better left as future improvement.