Skip to main content

ziggy_honggfuzz_1/
lib.rs

1//! ## About Honggfuzz
2//! 
3//! Honggfuzz is a security oriented fuzzer with powerful analysis options. Supports evolutionary, feedback-driven fuzzing based on code coverage (software- and hardware-based).
4//! 
5//! * project homepage [honggfuzz.com](http://honggfuzz.com/)
6//! * project repository [github.com/google/honggfuzz](https://github.com/google/honggfuzz)
7//! * this upstream project is maintained by Google, but ...
8//! * this is NOT an official Google product
9//! 
10//! ## Compatibility
11//! 
12//! * __Rust__: stable, beta, nightly
13//! * __OS__: GNU/Linux, macOS, FreeBSD, NetBSD, Android, WSL (Windows Subsystem for Linux)
14//! * __Arch__: x86_64, x86, arm64-v8a, armeabi-v7a, armeabi
15//! * __Sanitizer__: none, address, thread, leak 
16//! 
17//! ## Dependencies
18//! 
19//! ### Linux
20//! 
21//! * C compiler: `cc`
22//! * GNU Make: `make`
23//! * GNU Binutils development files for the BFD library: `libbfd.h`
24//! * libunwind development files: `libunwind.h`
25//! * liblzma development files
26//! 
27//! For example on Debian and its derivatives:
28//! 
29//! ```sh
30//! sudo apt install build-essential binutils-dev libunwind-dev
31//! ```
32//! 
33//! ## How to use this crate
34//! 
35//! Install honggfuzz commands to build with instrumentation and fuzz
36//! 
37//! ```sh
38//! # installs hfuzz and honggfuzz subcommands in cargo
39//! cargo install honggfuzz
40//! ```
41//! 
42//! Add to your dependencies
43//! 
44//! ```toml
45//! [dependencies]
46//! honggfuzz = "0.5"
47//! ```
48//! 
49//! Create a target to fuzz
50//! 
51//! ```rust,should_panic
52//! use honggfuzz::fuzz;
53//! 
54//! fn main() {
55//!     // Here you can parse `std::env::args and 
56//!     // setup / initialize your project
57//! 
58//!     // You have full control over the loop but
59//!     // you're supposed to call `fuzz` ad vitam aeternam
60//!     loop {
61//!         // The fuzz macro gives an arbitrary object (see `arbitrary crate`)
62//!         // to a closure-like block of code.
63//!         // For performance reasons, it is recommended that you use the native type
64//!         // `&[u8]` when possible.
65//!         // Here, this slice will contain a "random" quantity of "random" data.
66//!         fuzz!(|data: &[u8]| {
67//!             if data.len() != 3 {return}
68//!             if data[0] != b'h' {return}
69//!             if data[1] != b'e' {return}
70//!             if data[2] != b'y' {return}
71//!             panic!("BOOM")
72//!         });
73//!     }
74//! }
75//! 
76//! ```
77//! 
78//! Fuzz for fun and profit !
79//! 
80//! ```sh
81//! # builds with fuzzing instrumentation and then fuzz the "example" target
82//! cargo hfuzz run example
83//! ```
84//! 
85//! Once you got a crash, replay it easily in a debug environment
86//! 
87//! ```sh
88//! # builds the target in debug mode and replays automatically the crash in gdb
89//! cargo hfuzz run-debug example fuzzing_workspace/*.fuzz
90//! ```
91//! 
92//! You can also build and run your project without compile-time software instrumentation (LLVM's SanCov passes)
93//! 
94//! This allows you for example to try hardware-only feedback driven fuzzing:
95//! 
96//! ```sh
97//! # builds without fuzzing instrumentation and then fuzz the "example" target using hardware-based feedback
98//! HFUZZ_RUN_ARGS="--linux_perf_ipt_block --linux_perf_instr --linux_perf_branch" cargo hfuzz run-no-instr example
99//! ```
100//! 
101//! Clean
102//! 
103//! ```sh
104//! # a wrapper on "cargo clean" which cleans the fuzzing_target directory
105//! cargo hfuzz clean 
106//! ```
107//! 
108//! Version
109//! 
110//! ```sh
111//! cargo hfuzz version
112//! ```
113//! 
114//! ### Environment variables
115//! 
116//! #### `RUSTFLAGS`
117//! 
118//! You can use `RUSTFLAGS` to send additional arguments to `rustc`.
119//! 
120//! For instance, you can enable the use of LLVM's [sanitizers](https://github.com/japaric/rust-san).
121//! This is a recommended option if you want to test your `unsafe` rust code but it will have an impact on performance.
122//! 
123//! ```sh
124//! RUSTFLAGS="-Z sanitizer=address" cargo hfuzz run example
125//! ```
126//! 
127//! #### `HFUZZ_BUILD_ARGS`
128//! 
129//! You can use `HFUZZ_BUILD_ARGS` to send additional arguments to `cargo build`.
130//! 
131//! #### `HFUZZ_RUN_ARGS`
132//! 
133//! You can use `HFUZZ_RUN_ARGS` to send additional arguments to `honggfuzz`.
134//! See [USAGE](https://github.com/google/honggfuzz/blob/master/docs/USAGE.md) for the list of those.
135//! 
136//! For example:
137//! 
138//! ```sh
139//! # 1 second of timeout
140//! # use 12 fuzzing thread
141//! # be verbose
142//! # stop after 1000000 fuzzing iteration
143//! # exit upon crash
144//! HFUZZ_RUN_ARGS="-t 1 -n 12 -v -N 1000000 --exit_upon_crash" cargo hfuzz run example
145//! ```
146//! 
147//! #### `HFUZZ_DEBUGGER`
148//! 
149//! By default we use `rust-lldb` but you can change it to `rust-gdb`, `gdb`, `/usr/bin/lldb-7` ...
150//! 
151//! #### `CARGO_TARGET_DIR`
152//! 
153//! Target compilation directory, defaults to `hfuzz_target` to not clash with `cargo build`'s default `target` directory.
154//! 
155//! #### `HFUZZ_WORKSPACE`
156//! 
157//! Honggfuzz working directory, defaults to `hfuzz_workspace`.
158//! 
159//! #### `HFUZZ_INPUT`
160//! 
161//! Honggfuzz input files (also called "corpus"), defaults to `$HFUZZ_WORKSPACE/{TARGET}/input`.
162//! 
163//! ## Conditional compilation
164//! 
165//! Sometimes, it is necessary to make some specific adaptation to your code to yield a better fuzzing efficiency.
166//! 
167//! For instance:
168//! - Make you software behavior as much as possible deterministic on the fuzzing input
169//!   - [PRNG](https://en.wikipedia.org/wiki/Pseudorandom_number_generator)s must be seeded with a constant or the fuzzer input
170//!   - Behavior shouldn't change based on the computer's clock.
171//!   - Avoid potential undeterministic behavior from racing threads.
172//!   - ...
173//! - Never ever call `std::process::exit()`.
174//! - Disable logging and other unnecessary functionalities.
175//! - Try to avoid modifying global state when possible.
176//! 
177//! 
178//! When building with `cargo hfuzz`, the argument `--cfg fuzzing` is passed to `rustc` to allow you to condition the compilation of those adaptations thanks to the `cfg` macro like so:
179//! 
180//! ```rust
181//! # use rand::{self, Rng, SeedableRng};
182//! # use rand_chacha;
183//! # fn main() {
184//! #[cfg(fuzzing)]
185//! let mut rng = rand_chacha::ChaCha8Rng::from_seed(&[0]);
186//! #[cfg(not(fuzzing))]
187//! let mut rng = rand::thread_rng();
188//! # }
189//! ```
190//! 
191//! Also, when building in debug mode, the `fuzzing_debug` argument is added in addition to `fuzzing`.
192//! 
193//! For more information about conditional compilation, please see the [reference](https://doc.rust-lang.org/reference/attributes.html#conditional-compilation).
194//! 
195//! ## Relevant documentation about honggfuzz
196//! * [USAGE](https://github.com/google/honggfuzz/blob/master/docs/USAGE.md)
197//! * [FeedbackDrivenFuzzing](https://github.com/google/honggfuzz/blob/master/docs/FeedbackDrivenFuzzing.md)
198//! * [PersistentFuzzing](https://github.com/google/honggfuzz/blob/master/docs/PersistentFuzzing.md)
199//! 
200//! ## About Rust fuzzing
201//!  
202//! There is other projects providing Rust fuzzing support at [github.com/rust-fuzz](https://github.com/rust-fuzz). 
203//!  
204//! You'll find support for [AFL](https://github.com/rust-fuzz/afl.rs) and LLVM's [LibFuzzer](https://github.com/rust-fuzz/cargo-fuzz) and there is also a [trophy case](https://github.com/rust-fuzz/trophy-case) ;-) .
205//! 
206//! This crate was inspired by those projects!
207
208/// Re-export of arbitrary crate used to generate structured inputs
209#[cfg(feature = "arbitrary")]
210pub use arbitrary;
211
212#[cfg(all(fuzzing, not(fuzzing_debug)))]
213extern "C" {
214    fn HF_ITER(buf_ptr: *mut *const u8, len_ptr: *mut usize );
215}
216
217/// Fuzz a closure by passing it a `&[u8]`
218///
219/// This slice contains a "random" quantity of "random" data.
220///
221/// For perstistent fuzzing to work, you have to call it ad vita aeternam in an infinite loop.
222///
223/// The closure is assumed to be unwind-safe, which might be unsafe. For more info, check the
224/// [`std::panic::UnwindSafe`] trait.
225///
226/// ```rust,should_panic
227/// # use honggfuzz::fuzz;
228/// # fn main() {
229/// loop {
230///     fuzz(|data|{
231///         if data.len() != 3 {return}
232///         if data[0] != b'h' {return}
233///         if data[1] != b'e' {return}
234///         if data[2] != b'y' {return}
235///         panic!("BOOM")
236///     });
237/// }
238/// # }
239/// ```
240#[cfg(not(fuzzing))]
241#[allow(unused_variables)]
242pub fn fuzz<F>(closure: F) where F: FnOnce(&[u8]) {
243    eprintln!("This executable hasn't been built with \"cargo hfuzz\".");
244    eprintln!("Try executing \"cargo hfuzz build\" and check out \"hfuzz_target\" directory.");
245    eprintln!("Or execute \"cargo hfuzz run TARGET\"");
246    std::process::exit(17);
247}
248
249// Registers a panic hook that aborts the process before unwinding.
250// It is useful to abort before unwinding so that the fuzzer will then be
251// able to analyse the process stack frames to tell different bugs apart.
252#[cfg(all(fuzzing, not(fuzzing_debug)))]
253lazy_static::lazy_static! {
254    static ref PANIC_HOOK: () = {
255        std::panic::set_hook(Box::new(|_| {
256            std::process::abort();
257        }))
258    };
259}
260
261#[cfg(all(fuzzing, not(fuzzing_debug)))]
262pub fn fuzz<F>(closure: F) where F: FnOnce(&[u8]) {
263    use std::mem::MaybeUninit;
264
265    // sets panic hook if not already done
266    lazy_static::initialize(&PANIC_HOOK);
267
268    // get buffer from honggfuzz runtime
269    let buf;
270
271    let mut buf_ptr = MaybeUninit::<*const u8>::uninit();
272    let mut len_ptr = MaybeUninit::<usize>::uninit();
273
274    unsafe {
275        HF_ITER(buf_ptr.as_mut_ptr(), len_ptr.as_mut_ptr());
276        buf = ::std::slice::from_raw_parts(buf_ptr.assume_init(), len_ptr.assume_init());
277    }
278
279    // We still catch unwinding panics just in case the fuzzed code modifies
280    // the panic hook.
281    // If so, the fuzzer will be unable to tell different bugs apart and you will
282    // only be able to find one bug at a time before fixing it to then find a new one.
283    // The closure is assumed to be unwind-safe, which might be unsafe. For more info, check the
284    // [`std::panic::UnwindSafe`] trait.
285    let did_panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
286        closure(buf);
287    })).is_err();
288
289    if did_panic {
290        // hopefully the custom panic hook will be called before and abort the
291        // process before the stack frames are unwinded.
292        std::process::abort();
293    }
294}
295
296#[cfg(all(fuzzing, fuzzing_debug))]
297pub fn fuzz<F>(closure: F) where F: FnOnce(&[u8]) {
298    use std::env;
299    use std::fs::File;
300    use memmap2::MmapOptions;
301    
302    let filename = env::var("CARGO_HONGGFUZZ_CRASH_FILENAME").unwrap_or_else(|_|{
303        eprintln!("error: Environment variable CARGO_HONGGFUZZ_CRASH_FILENAME not set. Try launching with \"cargo hfuzz run-debug TARGET CRASH_FILENAME [ ARGS ... ]\"");
304        std::process::exit(1);
305    });
306
307    let file = File::open(&filename).unwrap_or_else(|_|{
308        eprintln!("error: failed to open \"{}\"", &filename);
309        std::process::exit(1);
310    });
311
312    let mmap = unsafe {MmapOptions::new().map(&file)}.unwrap_or_else(|_|{
313        eprintln!("error: failed to mmap file \"{}\"", &filename);
314        std::process::exit(1);
315    });
316
317    closure(&mmap);
318
319    eprintln!("This crashfile didn't trigger any panics...");
320    eprintln!("Are you sure that you selected the correct crashfile and that your program's behavior is entirely deterministic and only dependent on the fuzzing input?");
321    std::process::exit(2);
322}
323
324#[cfg(feature = "arbitrary")]
325#[macro_export]
326#[doc(hidden)]
327macro_rules! _arbitrary_fuzz {
328    (|$buf:ident: $dty:ty| $body:block) => {
329        $crate::fuzz(|$buf| {
330            let $buf: $dty = {
331                use $crate::arbitrary::{Arbitrary, Unstructured};
332
333                let mut buf = Unstructured::new($buf);
334                if let Ok(buf) = Arbitrary::arbitrary(&mut buf) {
335                    buf
336                } else {
337                    return
338                }
339            };
340
341            $body
342        });
343    };
344}
345
346/// Fuzz a closure-like block of code by passing it an object of arbitrary type.
347///
348/// You can choose the type of the argument using the syntax as in the example below.
349/// Please check out the `arbitrary` crate to see which types are available.
350///
351/// For performance reasons, it is recommended that you use the native type `&[u8]` when possible.
352///
353/// For perstistent fuzzing to work, you have to call it ad vita aeternam in an infinite loop.
354///
355/// ```rust,should_panic
356/// # use honggfuzz::fuzz;
357/// # fn main() {
358/// loop {
359///     fuzz!(|data: &[u8]| {
360///         if data.len() != 3 {return}
361///         if data[0] != b'h' {return}
362///         if data[1] != b'e' {return}
363///         if data[2] != b'y' {return}
364///         panic!("BOOM")
365///     });
366/// }
367/// # }
368/// ```
369
370#[macro_export]
371macro_rules! fuzz {
372    (|$buf:ident| $body:block) => {
373        $crate::fuzz(|$buf| $body);
374    };
375    (|$buf:ident: &[u8]| $body:block) => {
376        $crate::fuzz(|$buf| $body);
377    };
378    (|$buf:ident: $dty:ty| $body:block) => {
379        $crate::_arbitrary_fuzz!(|$buf: $dty| $body);
380    };
381}
382