-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathfuzz.rs
More file actions
1035 lines (953 loc) Β· 42.5 KB
/
fuzz.rs
File metadata and controls
1035 lines (953 loc) Β· 42.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::*;
use anyhow::{anyhow, bail, Error};
use console::{style, Term};
use glob::glob;
use std::{
env,
fs::File,
io::Write,
path::Path,
process::{self, Stdio},
sync::{Arc, Mutex},
thread,
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use strip_ansi_escapes::strip_str;
use twox_hash::XxHash64;
/// Main logic for managing fuzzers and the fuzzing process in ziggy.
/// ## Initial minimization logic
/// When launching fuzzers, if initial corpora exist, they are merged together and we minimize it
/// with both AFL++ and Honggfuzz.
/// ```text
/// # bash pseudocode
/// cp all_afl_corpora/* corpus/* corpus_tmp/
/// # run afl++ minimization
/// afl++_minimization -i corpus_tmp -o corpus_minimized
/// # in parallel, run honggfuzz minimization
/// honggfuzz_minimization -i corpus_tmp -o corpus_minimized
/// rm -rf corpus corpus_tmp
/// mv corpus_minimized corpus
/// afl++ -i corpus -o all_afl_corpora &
/// honggfuzz -i corpus -o corpus
/// ```
/// The `all_afl_corpora` directory corresponds to the `output/target_name/afl/**/queue/` directories.
impl Fuzz {
pub fn corpus(&self) -> String {
self.corpus
.display()
.to_string()
.replace("{ziggy_output}", &self.ziggy_output.display().to_string())
.replace("{target_name}", &self.target)
}
pub fn corpus_tmp(&self) -> String {
format!("{}/corpus_tmp/", self.output_target())
}
pub fn corpus_minimized(&self) -> String {
format!("{}/corpus_minimized/", self.output_target(),)
}
pub fn output_target(&self) -> String {
if self.fuzz_binary() {
self.ziggy_output.display().to_string()
} else {
format!("{}/{}", self.ziggy_output.display(), &self.target)
}
}
/// Returns true if AFL++ is enabled
pub fn afl(&self) -> bool {
!self.no_afl
}
/// Returns true if Honggfuzz is enabled
// This definition could be a one-liner but it was expanded for clarity
pub fn honggfuzz(&self) -> bool {
if self.fuzz_binary() {
// We cannot use honggfuzz in binary mode
false
} else if self.no_afl {
// If we have "no_afl" set then honggfuzz is always enabled
true
} else {
// If honggfuzz is not disabled, we use it if there are more than 1 jobs
!self.no_honggfuzz && self.jobs > 1
}
}
fn fuzz_binary(&self) -> bool {
self.binary.is_some()
}
fn check_bin_target(&self, path: &std::path::Path) -> Result<(), Error> {
if !path.is_file() {
if let Some(path) = self.binary.as_ref() {
bail!("file not found `{}`", path.display());
}
bail!("no bin target named `{}`", self.target)
}
Ok(())
}
// Manages the continuous running of fuzzers
pub fn fuzz(&mut self, common: &Common) -> Result<(), anyhow::Error> {
if !self.fuzz_binary() {
let build = Build {
no_afl: !self.afl(),
no_honggfuzz: !self.honggfuzz(),
release: self.release,
asan: self.asan,
};
build.build().context("Failed to build the fuzzers")?;
}
self.target = if let Some(binary) = self.binary.as_ref() {
binary.display().to_string()
} else {
find_target(&self.target).context("β οΈ couldn't find target when fuzzing")?
};
let time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis();
let crash_dir = format!("{}/crashes/{time}", self.output_target());
let crash_path = Path::new(&crash_dir);
fs::create_dir_all(crash_path)?;
fs::create_dir_all(format!("{}/logs", self.output_target()))?;
fs::create_dir_all(format!("{}/queue", self.output_target()))?;
if Path::new(&self.corpus()).exists() {
if self.minimize {
fs::create_dir_all(self.corpus_tmp())
.context("Could not create temporary corpus")?;
self.copy_corpora()
.context("Could not move all seeds to temporary corpus")?;
let _ = fs::remove_dir_all(self.corpus_minimized());
self.run_minimization()
.context("Failure while minimizing")?;
fs::remove_dir_all(self.corpus()).context("Could not remove shared corpus")?;
fs::rename(self.corpus_minimized(), self.corpus())
.context("Could not move minimized corpus over")?;
fs::remove_dir_all(self.corpus_tmp())
.context("Could not remove temporary corpus")?;
}
} else {
fs::create_dir_all(self.corpus())?;
}
// We create an initial corpus file, so that AFL++ starts-up properly if corpus is empty
let is_empty = fs::read_dir(self.corpus())?.next().is_none(); // check if corpus has some seeds
if is_empty {
let mut initial_corpus = File::create(self.corpus() + "/init")?;
writeln!(&mut initial_corpus, "00000000")?;
drop(initial_corpus);
}
let mut processes = self.spawn_new_fuzzers()?;
self.start_time = Instant::now();
let mut last_synced_created_time: Option<SystemTime> = None;
let mut last_sync_time = Instant::now();
let mut afl_output_ok = false;
if self.no_afl && self.coverage_worker {
bail!("cannot use --no-afl with --coverage-worker!");
}
// We prepare builds for the coverage worker
if self.coverage_worker {
Cover::clean_old_cov()?;
Cover::build_runner()?;
}
let cov_start_time = Arc::new(Mutex::new(None));
let cov_end_time = Arc::new(Mutex::new(Instant::now()));
let coverage_now_running = Arc::new(Mutex::new(false));
let workspace_root = if !self.fuzz_binary() && self.coverage_worker {
cargo_metadata::MetadataCommand::new()
.exec()?
.workspace_root
.to_string()
} else {
String::default()
};
let target = self.target.clone();
let main_corpus = self.corpus();
let output_target = self.output_target();
let mut crashes = (String::new(), String::new());
common.shutdown_deferred(); // handle termination signals gracefully
loop {
let sleep_duration = Duration::from_secs(1);
thread::sleep(sleep_duration);
if common.is_terminated() {
eprintln!("Shutting down...");
let res = (
stop_fuzzers(&processes),
self.sync_corpora(last_synced_created_time).map(|_| ()),
self.sync_crashes(crash_path),
);
return res.0.and(res.1).and(res.2);
}
let coverage_status = match (
self.coverage_worker,
*coverage_now_running.lock().unwrap(),
cov_end_time.lock().unwrap().elapsed().as_secs() / 60,
) {
(true, false, wait) if wait < self.coverage_interval => {
format!("waiting {} minutes", self.coverage_interval - wait)
}
(true, false, _) => String::from("starting"),
(true, true, _) => String::from("running"),
(false, _, _) => String::from("disabled"),
};
let current_crashes = self.print_stats(&coverage_status);
if coverage_status.as_str() == "starting" {
*coverage_now_running.lock().unwrap() = true;
let main_corpus = main_corpus.clone();
let target = target.clone();
let workspace_root = workspace_root.clone();
let output_target = output_target.clone();
let cov_start_time = Arc::clone(&cov_start_time);
let cov_end_time = Arc::clone(&cov_end_time);
let coverage_now_running = Arc::clone(&coverage_now_running);
thread::spawn(move || {
let mut seen_new_entry = false;
let prev_start_time = {
let unlocked = cov_start_time.lock().unwrap();
*unlocked
};
*cov_start_time.lock().unwrap() = Some(Instant::now());
let entries = std::fs::read_dir(&main_corpus).unwrap();
for entry in entries.flatten().map(|e| e.path()) {
// We only want to run corpus entries created since the last time we ran.
let created = entry
.metadata()
.unwrap()
.created()
.unwrap()
.elapsed()
.unwrap_or_default();
if prev_start_time.map_or(Duration::MAX, |s| s.elapsed()) >= created {
let _ = process::Command::new(
super::target_dir().join("coverage/debug").join(&target),
)
.arg(entry)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
seen_new_entry = true;
}
}
if seen_new_entry {
let coverage_dir = output_target + "/coverage";
let _ = fs::remove_dir_all(&coverage_dir);
Cover::run_grcov(&target, "html", &coverage_dir, &workspace_root).unwrap();
}
*cov_end_time.lock().unwrap() = Instant::now();
*coverage_now_running.lock().unwrap() = false;
});
}
if !afl_output_ok {
if let Ok(afl_log) =
fs::read_to_string(format!("{}/logs/afl.log", self.output_target()))
{
if afl_log.contains("ready to roll") {
afl_output_ok = true;
} else if afl_log.contains("/proc/sys/kernel/core_pattern")
|| afl_log.contains("/sys/devices/system/cpu")
{
stop_fuzzers(&processes)?;
eprintln!("We highly recommend you configure your system for better performance:\n");
eprintln!(" cargo afl system-config\n");
eprintln!(
"Or set AFL_SKIP_CPUFREQ and AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES\n"
);
return Ok(());
}
}
}
// Copy crash files from AFL++ and Honggfuzz's outputs
if current_crashes != crashes {
crashes = current_crashes;
self.sync_crashes(crash_path)?;
}
// Sync corpus dirs
if last_sync_time.elapsed() > Duration::from_mins(self.corpus_sync_interval) {
last_synced_created_time = self.sync_corpora(last_synced_created_time)?;
last_sync_time = Instant::now();
}
if !processes
.iter_mut()
.all(|p| p.try_wait().is_ok_and(|exited| exited.is_none()))
{
stop_fuzzers(&processes)?;
return Ok(());
}
}
}
/// Copy crashes from AFL++ or Honggfuzz's outputs into `target_dir`
fn sync_crashes(&self, target_dir: &Path) -> Result<(), anyhow::Error> {
let crash_dirs = glob(&format!("{}/afl/*/crashes", self.output_target()))
.map_err(|_| anyhow!("Failed to read crashes glob pattern"))?
.flatten()
.chain(std::iter::once(PathBuf::from(format!(
"{}/honggfuzz/{}",
self.output_target(),
self.target
))));
for crash_dir in crash_dirs {
if let Ok(crashes) = fs::read_dir(crash_dir) {
for crash_input in crashes.flatten() {
let file_name = crash_input.file_name();
let to_path = target_dir.join(&file_name);
if ["README.txt", "HONGGFUZZ.REPORT.TXT", "input"]
.iter()
.all(|name| name != &file_name)
&& !to_path.exists()
{
fs::copy(crash_input.path(), to_path)?;
}
}
}
}
Ok(())
}
/// Sync shared corpora
///
/// Copy-over each live corpus to the shared corpus directory, where each file name is usually its hash.
/// If both fuzzers are running, copy over AFL++'s queue for consumption by Honggfuzz.
fn sync_corpora(
&self,
last_synced: Option<SystemTime>,
) -> Result<Option<SystemTime>, anyhow::Error> {
let now = SystemTime::now();
let afl_files = self
.afl()
.then_some(
glob(&format!(
"{}/afl/mainaflfuzzer/queue/*",
self.output_target(),
))?
.flatten(),
)
.into_iter()
.flatten();
let hfuzz_files = self
.honggfuzz()
.then_some(glob(&format!("{}/honggfuzz/corpus/*", self.output_target()))?.flatten())
.into_iter()
.flatten();
let mut latest = last_synced;
let potentially_new_files = afl_files.chain(hfuzz_files).filter(|file| {
file.metadata().is_ok_and(|metadata| {
let Ok(created) = metadata.created() else {
return false;
};
// be conservative and consider some too old files
if last_synced.is_none_or(|synced| synced - Duration::from_secs(1) < created) {
latest = latest.max(Some(created));
true
} else {
false
}
})
});
let queue_path = PathBuf::from(format!("{}/queue", self.output_target()));
let corpus_path = PathBuf::from(format!("{}/corpus", self.output_target()));
for file in potentially_new_files {
if self.honggfuzz() {
if let Some(file_name) = file.file_name() {
let target = queue_path.join(file_name);
if !target.exists() {
let _ = fs::copy(&file, target);
}
}
}
// Hash the file to get its file name
if let Ok(bytes) = fs::read(&file) {
let mut hash = XxHash64::oneshot(0, &bytes);
// linear probing (bounded)
for _ in 0..1024 {
let target = corpus_path.join(format!("{hash:x}"));
if !target.exists() {
let _ = fs::copy(&file, target);
break;
} else if target
.metadata()
.is_ok_and(|m| m.len() == bytes.len() as u64)
&& fs::read(target).is_ok_and(|t| t == bytes)
{
break;
}
hash = hash.wrapping_add(1);
}
}
}
Ok(latest.min(Some(now)))
}
// Spawns new fuzzers
pub fn spawn_new_fuzzers(&self) -> Result<Vec<process::Child>, anyhow::Error> {
// No fuzzers for you
if self.no_afl && self.no_honggfuzz {
bail!("Pick at least one fuzzer.\nNote: -b/--binary implies --no-honggfuzz");
}
let mut fuzzer_handles = vec![];
// The cargo executable
let cargo = env::var("CARGO").unwrap_or_else(|_| String::from("cargo"));
let (afl_jobs, honggfuzz_jobs) = {
if self.no_afl {
(0, self.jobs)
} else if self.no_honggfuzz || self.fuzz_binary() {
(self.jobs, 0)
} else {
// we assign roughly 2/3 to AFL++, 1/3 to honggfuzz, however do
// not apply more than 4 jobs to honggfuzz
let hfuzz = ((self.jobs + 1) / 3).min(4);
(self.jobs - hfuzz, hfuzz)
}
};
if honggfuzz_jobs > 4 {
eprintln!("Warning: running more honggfuzz jobs than 4 is not effective");
}
if afl_jobs > 0 {
std::fs::create_dir_all(format!("{}/afl", self.output_target()))?;
// https://aflplus.plus/docs/fuzzing_in_depth/#c-using-multiple-cores
let afl_modes = [
"explore", "fast", "coe", "lin", "quad", "exploit", "rare", "explore", "fast",
"mmopt",
];
for job_num in 0..afl_jobs {
let is_main_instance = job_num == 0;
// We set the fuzzer name, and if it's the main or a secondary fuzzer
let fuzzer_name = match is_main_instance {
true => String::from("-Mmainaflfuzzer"),
false => format!("-Ssecondaryfuzzer{job_num}"),
};
// We only sync to the shared corpus if Honggfuzz is also running
let use_shared_corpus = match (self.no_honggfuzz, job_num) {
(false, 0) => format!("-F{}", &self.corpus()),
_ => String::new(),
};
let use_initial_corpus_dir = match (&self.initial_corpus, job_num) {
(Some(initial_corpus), 0) => {
format!("-F{}", &initial_corpus.display().to_string())
}
_ => String::new(),
};
// 10% of secondary fuzzers have the MOpt mutator enabled
let mopt_mutator = match job_num % 10 {
9 => "-L0",
_ => "",
};
// Power schedule
let power_schedule = afl_modes
.get(job_num as usize % afl_modes.len())
.unwrap_or(&"fast");
// Old queue cycling
let old_queue_cycling = match job_num % 10 {
8 => "-Z",
_ => "",
};
// Only few instances do cmplog
let cmplog_options = match job_num {
1 => "-l2a",
3 => "-l1",
14 => "-l2a",
22 => "-l3at",
_ => "-c-", // disable Cmplog, needs AFL++ 4.08a
};
// AFL timeout is in ms so we convert the value
let timeout_option_afl = match self.timeout {
Some(t) => format!("-t{}", t * 1000),
None => String::new(),
};
let memory_option_afl = match &self.memory_limit {
Some(m) => format!("-m{m}"),
None => String::new(),
};
let dictionary_option = match &self.dictionary {
Some(d) => format!("-x{}", &d.display().to_string()),
None => String::new(),
};
let mutation_option = match job_num / 5 {
0..=1 => "-P600",
2..=3 => "-Pexplore",
_ => "-Pexploit",
};
let input_format_option = self.config.input_format_flag();
let log_destination = || match job_num {
0 => File::create(format!("{}/logs/afl.log", self.output_target()))
.unwrap()
.into(),
1 => File::create(format!("{}/logs/afl_1.log", self.output_target()))
.unwrap()
.into(),
_ => process::Stdio::null(),
};
let final_sync = match job_num {
0 => "AFL_FINAL_SYNC",
_ => "_DUMMY_VAR",
};
let target_path = self.binary.clone().unwrap_or_else(|| {
if self.release {
super::target_dir()
.join(format!("afl/release/{}", self.target))
.into_std_path_buf()
} else if self.asan && job_num == 0 {
super::target_dir()
.join(format!(
"afl/{}/debug/{}",
target_triple::TARGET,
self.target
))
.into_std_path_buf()
} else {
super::target_dir()
.join(format!("afl/debug/{}", self.target))
.into_std_path_buf()
}
});
self.check_bin_target(target_path.as_path())?;
let mut afl_flags = self.afl_flags.clone();
if is_main_instance {
for path in &self.foreign_sync_dirs {
afl_flags.push(format!("-F {}", path.display()));
}
}
fuzzer_handles.push(
process::Command::new(&cargo)
.args(
[
"afl",
"fuzz",
&fuzzer_name,
&format!("-i{}", self.corpus()),
&format!("-p{power_schedule}"),
&format!("-o{}/afl", self.output_target()),
&format!("-g{}", self.min_length),
&format!("-G{}", self.max_length),
&use_shared_corpus,
&use_initial_corpus_dir,
old_queue_cycling,
cmplog_options,
mopt_mutator,
mutation_option,
input_format_option,
&timeout_option_afl,
&memory_option_afl,
&dictionary_option,
]
.iter()
.filter(|a| !a.is_empty()),
)
.args(afl_flags)
.arg(target_path)
.env("AFL_AUTORESUME", "1")
.env("AFL_TESTCACHE_SIZE", "100")
.env("AFL_FAST_CAL", "1")
.env("AFL_FORCE_UI", "1")
.env("AFL_IGNORE_UNKNOWN_ENVS", "1")
.env("AFL_CMPLOG_ONLY_NEW", "1")
.env("AFL_DISABLE_TRIM", "1")
.env("AFL_NO_WARN_INSTABILITY", "1")
.env("AFL_FUZZER_STATS_UPDATE_INTERVAL", "10")
.env("AFL_IMPORT_FIRST", "1")
.env(final_sync, "1")
.env("AFL_IGNORE_SEED_PROBLEMS", "1")
.stdout(log_destination())
.stderr(log_destination())
.spawn()?,
);
}
eprintln!("{} afl ", style(" Launched").green().bold());
}
if honggfuzz_jobs > 0 {
let dictionary_option = match &self.dictionary {
Some(d) => format!("-w{}", &d.display().to_string()),
None => String::new(),
};
let timeout_option = match self.timeout {
Some(t) => format!("-t{t}"),
None => String::new(),
};
let memory_option = match &self.memory_limit {
Some(m) => format!("--rlimit_as{m}"),
None => String::new(),
};
self.check_bin_target(
super::target_dir()
.join("honggfuzz")
.join(target_triple::TARGET)
.join("release")
.join(&self.target)
.as_std_path(),
)?;
// The `script` invocation is a trick to get the correct TTY output for honggfuzz
fuzzer_handles.push(
process::Command::new("script")
.args([
"--flush",
"--quiet",
"-c",
&format!("{cargo} hfuzz run {}", &self.target),
"/dev/null",
])
.env("HFUZZ_BUILD_ARGS", "--features=ziggy/honggfuzz")
.env("CARGO_TARGET_DIR", super::target_dir().join("honggfuzz"))
.env(
"HFUZZ_WORKSPACE",
format!("{}/honggfuzz", self.output_target()),
)
.env(
"HFUZZ_RUN_ARGS",
format!(
"--input={} -o{}/honggfuzz/corpus -n{honggfuzz_jobs} -F{} --dynamic_input={}/queue {timeout_option} {dictionary_option} {memory_option}",
self.corpus(),
self.output_target(),
self.max_length,
self.output_target(),
),
)
.stdin(std::process::Stdio::null())
.stderr(File::create(format!(
"{}/logs/honggfuzz.log",
self.output_target()
))?)
.stdout(File::create(format!(
"{}/logs/honggfuzz.log",
self.output_target()
))?)
.spawn()?,
);
eprintln!(
"{} honggfuzz ",
style(" Launched").green().bold()
);
}
eprintln!("\nSee more live information by running:");
if afl_jobs > 0 {
eprintln!(
" {}",
style(format!("tail -f {}/logs/afl.log", self.output_target())).bold()
);
}
if afl_jobs > 1 {
eprintln!(
" {}",
style(format!("tail -f {}/logs/afl_1.log", self.output_target())).bold()
);
}
if honggfuzz_jobs > 0 {
eprintln!(
" {}",
style(format!(
"tail -f {}/logs/honggfuzz.log",
self.output_target()
))
.bold()
);
}
Ok(fuzzer_handles)
}
fn all_seeds(&self) -> Result<Vec<PathBuf>> {
Ok(glob(&format!("{}/afl/*/queue/*", self.output_target()))
.map_err(|_| anyhow!("Failed to read AFL++ queue glob pattern"))?
.chain(
glob(&format!("{}/*", self.corpus()))
.map_err(|_| anyhow!("Failed to read Honggfuzz corpus glob pattern"))?,
)
.flatten()
.filter(|f| f.is_file())
.collect())
}
// Copy all corpora into `corpus`
pub fn copy_corpora(&self) -> Result<()> {
self.all_seeds()?.iter().for_each(|s| {
let _ = fs::copy(
s.to_str().unwrap_or_default(),
format!(
"{}/{}",
&self.corpus_tmp(),
s.file_name()
.unwrap_or_default()
.to_str()
.unwrap_or_default(),
),
);
});
Ok(())
}
pub fn run_minimization(&self) -> Result<()> {
let term = Term::stdout();
term.write_line(&format!(
"\n {}",
&style("Running minimization").magenta().bold()
))?;
let input_corpus = &self.corpus_tmp();
let minimized_corpus = &self.corpus_minimized();
let old_corpus_size = fs::read_dir(input_corpus).map_or_else(
|_| String::from("err"),
|corpus| format!("{}", corpus.count()),
);
let engine = match (self.no_afl, self.no_honggfuzz, self.jobs) {
(false, false, 1) => FuzzingEngines::AFLPlusPlus,
(false, false, _) => FuzzingEngines::All,
(false, true, _) => FuzzingEngines::AFLPlusPlus,
(true, false, _) => FuzzingEngines::Honggfuzz,
(true, true, _) => bail!("Pick at least one fuzzer"),
};
let mut minimization_args = Minimize {
target: self.target.clone(),
input_corpus: PathBuf::from(input_corpus),
output_corpus: PathBuf::from(minimized_corpus),
ziggy_output: self.ziggy_output.clone(),
jobs: self.jobs,
timeout: self.timeout.unwrap_or(5000),
engine,
};
match minimization_args.minimize() {
Ok(()) => {
let new_corpus_size = fs::read_dir(minimized_corpus).map_or_else(
|_| String::from("err"),
|corpus| format!("{}", corpus.count()),
);
term.move_cursor_up(1)?;
if new_corpus_size == *"err" || new_corpus_size == *"0" {
bail!("Please check the logs and make sure the right version of the fuzzers are installed");
}
term.write_line(&format!(
"{} the corpus ({} -> {} files) \n",
style(" Minimized").magenta().bold(),
old_corpus_size,
new_corpus_size
))?;
}
Err(_) => {
bail!("Please check the logs, this might be an oom error");
}
}
Ok(())
}
pub fn print_stats(&self, cov_worker_status: &str) -> (String, String) {
let fuzzer_name = format!(" {} ", self.target);
let reset = "\x1b[0m";
let gray = "\x1b[1;90m";
let red = "\x1b[1;91m";
let green = "\x1b[1;92m";
let yellow = "\x1b[1;93m";
let purple = "\x1b[1;95m";
let blue = "\x1b[1;96m";
// First step: execute afl-whatsup
let mut afl_status = format!("{green}running{reset} β");
let mut afl_total_execs = String::new();
let mut afl_instances = String::new();
let mut afl_speed = String::new();
let mut afl_coverage = String::new();
let mut afl_crashes = String::new();
let mut afl_timeouts = String::new();
let mut afl_new_finds = String::new();
let mut afl_faves = String::new();
if !self.afl() {
afl_status = format!("{yellow}disabled{reset} ");
} else {
let cargo = env::var("CARGO").unwrap_or_else(|_| String::from("cargo"));
let afl_stats_process = process::Command::new(&cargo)
.args([
"afl",
"whatsup",
"-s",
&format!("{}/afl", self.output_target()),
])
.output();
if let Ok(process) = afl_stats_process {
let s = std::str::from_utf8(&process.stdout).unwrap_or_default();
for mut line in s.split('\n') {
line = line.trim();
if let Some(total_execs) = line.strip_prefix("Total execs : ") {
afl_total_execs =
String::from(total_execs.split(',').next().unwrap_or_default());
} else if let Some(instances) = line.strip_prefix("Fuzzers alive : ") {
afl_instances = String::from(instances);
} else if let Some(speed) = line.strip_prefix("Cumulative speed : ") {
afl_speed = String::from(speed);
} else if let Some(coverage) = line.strip_prefix("Coverage reached : ") {
afl_coverage = String::from(coverage);
} else if let Some(crashes) = line.strip_prefix("Crashes saved : ") {
afl_crashes = String::from(crashes);
} else if let Some(timeouts) = line.strip_prefix("Hangs saved : ") {
afl_timeouts = String::from(timeouts.split(' ').next().unwrap_or_default());
} else if let Some(new_finds) = line.strip_prefix("Time without finds : ") {
afl_new_finds =
String::from(new_finds.split(',').next().unwrap_or_default());
} else if let Some(pending_items) = line.strip_prefix("Pending items : ") {
afl_faves = String::from(
pending_items
.split(',')
.next()
.unwrap_or_default()
.strip_suffix(" faves")
.unwrap_or_default(),
);
}
}
}
}
// Second step: Get stats from honggfuzz logs
let mut hf_status = format!("{green}running{reset} β");
let mut hf_total_execs = String::new();
let mut hf_threads = String::new();
let mut hf_speed = String::new();
let mut hf_coverage = String::new();
let mut hf_crashes = String::new();
let mut hf_timeouts = String::new();
let mut hf_new_finds = String::new();
if !self.honggfuzz() {
hf_status = format!("{yellow}disabled{reset} ");
} else {
let hf_stats_process = process::Command::new("tail")
.args([
"-n300",
&format!("{}/logs/honggfuzz.log", self.output_target()),
])
.output();
if let Ok(process) = hf_stats_process {
let s = std::str::from_utf8(&process.stdout).unwrap_or_default();
for raw_line in s.split('\n') {
let stripped_line = strip_str(raw_line);
let line = stripped_line.trim();
if let Some(total_execs) = line.strip_prefix("Iterations : ") {
hf_total_execs =
String::from(total_execs.split(' ').next().unwrap_or_default());
} else if let Some(threads) = line.strip_prefix("Threads : ") {
hf_threads = String::from(threads.split(',').next().unwrap_or_default());
} else if let Some(speed) = line.strip_prefix("Speed : ") {
hf_speed = String::from(
speed
.split("[avg: ")
.nth(1)
.unwrap_or_default()
.strip_suffix(']')
.unwrap_or_default(),
) + "/sec";
} else if let Some(coverage) = line.strip_prefix("Coverage : ") {
hf_coverage = String::from(
coverage
.split('[')
.nth(1)
.unwrap_or_default()
.split(']')
.next()
.unwrap_or_default(),
);
} else if let Some(crashes) = line.strip_prefix("Crashes : ") {
hf_crashes = String::from(crashes.split(' ').next().unwrap_or_default());
} else if let Some(timeouts) = line.strip_prefix("Timeouts : ") {
hf_timeouts = String::from(timeouts.split(' ').next().unwrap_or_default());
} else if let Some(new_finds) = line.strip_prefix("Cov Update : ") {
hf_new_finds = String::from(new_finds.trim());
hf_new_finds = String::from(
hf_new_finds
.strip_prefix("0 days ")
.unwrap_or(&hf_new_finds),
);
hf_new_finds = String::from(
hf_new_finds
.strip_prefix("00 hrs ")
.unwrap_or(&hf_new_finds),
);
hf_new_finds = String::from(
hf_new_finds
.strip_prefix("00 mins ")
.unwrap_or(&hf_new_finds),
);
hf_new_finds = String::from(
hf_new_finds.strip_suffix(" ago").unwrap_or(&hf_new_finds),
);
}
}
}
}
// Third step: Get global stats
let mut total_run_time = time_humanize::HumanTime::from(self.start_time.elapsed())
.to_text_en(
time_humanize::Accuracy::Rough,
time_humanize::Tense::Present,
);
if total_run_time == "now" {
total_run_time = String::from("...");
}
// Fifth step: Print stats
let mut screen = String::new();
// We start by clearing the screen
screen += "\x1B[1;1H\x1B[2J";
screen += &format!("ββ {blue}ziggy{reset} {purple}rocking{reset} βββββββββ{fuzzer_name:β^25.25}ββββββββββββββββββ{blue}/{red}////{reset}βββ\n");
screen += &format!(
"β{gray}run time :{reset} {total_run_time:17.17} {blue}/{red}///{reset} β\n"
);
screen += &format!("ββ {blue}afl++{reset} {afl_status:0}βββββββββββββββββββββββββββββββββββββββββββββββββββββ{blue}/{red}///{reset}ββ€\n");
if !afl_status.contains("disabled") {
screen += &format!("β {gray}instances :{reset} {afl_instances:17.17} β {gray}best coverage :{reset} {afl_coverage:11.11} {blue}/{red}//{reset} β\n");
if afl_crashes == "0" {
screen += &format!("β{gray}cumulative speed :{reset} {afl_speed:17.17} β {gray}crashes saved :{reset} {afl_crashes:11.11} {blue}/{red}/{reset} β\n");
} else {
screen += &format!("β{gray}cumulative speed :{reset} {afl_speed:17.17} β {gray}crashes saved :{reset} {red}{afl_crashes:11.11}{reset} {blue}/{red}/{reset} β\n");
}
screen += &format!(
"β {gray}total execs :{reset} {afl_total_execs:17.17} β{gray}timeouts saved :{reset} {afl_timeouts:17.17} β\n"
);
screen += &format!("β {gray}top inputs todo :{reset} {afl_faves:17.17} β {gray}no find for :{reset} {afl_new_finds:17.17} β\n");
}
screen += &format!(
"ββ {blue}honggfuzz{reset} {hf_status:0}ββββββββββββββββββββββββββββββββββββββββββββββββββ¬βββββ\n"
);
if !hf_status.contains("disabled") {
screen += &format!("β {gray}threads :{reset} {hf_threads:17.17} β {gray}coverage :{reset} {hf_coverage:17.17} β\n");
if hf_crashes == "0" {
screen += &format!("β{gray}average speed :{reset} {hf_speed:17.17} β {gray}crashes saved :{reset} {hf_crashes:17.17} β\n");
} else {
screen += &format!("β{gray}average speed :{reset} {hf_speed:17.17} β {gray}crashes saved :{reset} {red}{hf_crashes:17.17}{reset} β\n");
}
screen += &format!("β {gray}total execs :{reset} {hf_total_execs:17.17} β{gray}timeouts saved :{reset} {hf_timeouts:17.17} β\n");
screen += &format!("β β {gray}no find for :{reset} {hf_new_finds:17.17} β\n");
}
if self.coverage_worker {
screen += &format!(
"ββ {blue}coverage{reset} {green}enabled{reset} ββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ\n"
);
// TODO Add countdown
screen += &format!("β{gray}status :{reset} {cov_worker_status:20.20} β\n");
screen += "ββββββββββββββββββββββββββββββββ";
} else {
screen += "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
}
eprintln!("{screen}");
(afl_crashes, hf_crashes)
}
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Debug)]
pub enum FuzzingConfig {
Generic,
Binary,
Text,
Blockchain,
}
impl FuzzingConfig {
fn input_format_flag(&self) -> &str {
match self {
Self::Text => "-atext",
Self::Binary => "-abinary",
_ => "",
}
}
}