-
Notifications
You must be signed in to change notification settings - Fork 15
/
core.rs
2448 lines (2366 loc) · 107 KB
/
core.rs
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
//! The core components that setup and manage the fuzzer.
use std::cell::{Ref, RefCell, RefMut};
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::simd;
use std::sync::mpsc::{channel, sync_channel, Sender, SyncSender};
use std::sync::{Arc, Barrier, RwLock};
use std::thread;
use std::time;
use applevisor as av;
use regex as re;
use crate::backtrace::*;
use crate::caches::*;
use crate::config::*;
use crate::corpus::*;
use crate::coverage::*;
use crate::crash::*;
use crate::error::*;
use crate::exceptions::*;
use crate::hooks::*;
use crate::loader::*;
use crate::memory::*;
use crate::mutator::*;
use crate::tracer::*;
use crate::utils::*;
thread_local!(
/// A per-thread global keystone instance used to assemble ARM instructions.
pub static KSE: keystone_engine::Keystone =
keystone_engine::Keystone::new(
keystone_engine::Arch::ARM64,
keystone_engine::Mode::LITTLE_ENDIAN)
.expect("Could not initialize Keystone engine");
/// A per-thread global capstone instance used to disassemble ARM instructions.
pub static CSE: capstone::Capstone = capstone::Capstone::new_raw(
capstone::Arch::ARM64,
capstone::Mode::Arm,
capstone::NO_EXTRA_MODE,
Some(capstone::Endian::Little),
)
.expect("Could not initialize Capstone engine");
);
/// Structure that contains runtime information from the fuzzer.
pub struct HyperPomInfo {
/// The time at which the fuzzer started.
pub start_time: time::Instant,
/// The number of testcases.
pub nb_testcases: u64,
/// The number of crashes.
pub nb_crashes: u64,
/// The number of unique crashes.
pub nb_uniq_crashes: u64,
/// The number of timeouts.
pub nb_timeouts: u64,
/// The number of coverage paths.
pub nb_paths: u64,
}
impl HyperPomInfo {
/// Creates a new object info.
pub fn new() -> Self {
Self {
start_time: time::Instant::now(),
nb_testcases: 0,
nb_crashes: 0,
nb_uniq_crashes: 0,
nb_timeouts: 0,
nb_paths: 0,
}
}
}
impl Default for HyperPomInfo {
fn default() -> Self {
Self::new()
}
}
impl std::ops::Add<WorkerInfo> for HyperPomInfo {
type Output = Self;
fn add(self, other: WorkerInfo) -> Self {
Self {
start_time: self.start_time,
nb_testcases: self.nb_testcases + other.nb_testcases,
nb_crashes: self.nb_crashes + other.nb_crashes,
nb_uniq_crashes: self.nb_uniq_crashes + other.nb_uniq_crashes,
nb_timeouts: self.nb_timeouts + other.nb_timeouts,
nb_paths: self.nb_paths + other.nb_paths,
}
}
}
impl std::ops::AddAssign<WorkerInfo> for HyperPomInfo {
fn add_assign(&mut self, other: WorkerInfo) {
*self = Self {
start_time: self.start_time,
nb_testcases: self.nb_testcases + other.nb_testcases,
nb_crashes: self.nb_crashes + other.nb_crashes,
nb_uniq_crashes: self.nb_uniq_crashes + other.nb_uniq_crashes,
nb_timeouts: self.nb_timeouts + other.nb_timeouts,
nb_paths: self.nb_paths + other.nb_paths,
};
}
}
// -----------------------------------------------------------------------------------------------
// Hyperpom - Main Object
// -----------------------------------------------------------------------------------------------
/// The main fuzzer object.
///
/// # HyperPom
///
/// This structure offers the main interface to start and interact with the fuzzer. A new instance
/// can be created using [`HyperPom::new`] and expects four arguments.
///
/// * A [`crate::config::Config`] object that contains the parameters used to configure the
/// fuzzer (the number of workers to instanciate, the path to the corpus directory, the seed for
/// the PRNG, etc.).
/// * An implementation of the [`crate::loader::Loader`] trait, to give the necessary tools and
/// information to the fuzzer so that workers can load the targeted program.
/// * A *Global Data* structure, which is a generic type used by the fuzzer to share data between
/// all workers.
/// * A *Local Data* structure, which is a generic type that gets cloned passed to each workers so
/// they can store local data.
///
/// Once the different objects needed have been instanciated, the fuzzer can be run using
/// [`HyperPom::fuzz`]. It will create as many threads as defined by the configuration and
/// instanciate one worker in it. Each worker run independently while occasionally sharing some
/// information (coverage, global data, corpus, etc.).
///
/// For more information about fuzzing workers, refer to [`Worker`].
///
/// # Example
///
/// ```
/// use hyperpom::config::Config;
/// use hyperpom::core::HyperPom;
/// use hyperpom::loader::Loader;
///
/// #[derive(Clone)]
/// pub struct GlobalData(u32);
///
/// #[derive(Clone)]
/// pub struct LocalData(u32);
///
/// #[derive(Clone)]
/// pub struct DummyLoader;
///
/// impl Loader for DummyLoader {
/// // [...]
/// }
///
/// // We instanciate a global data object.
/// let gdata = GlobalData(0);
/// // We instanciate a local data object.
/// let ldata = LocalData(0);
///
/// // `loader` contains the methods that will load and map the program from the file `binary`.
/// let loader = DummyLoader::new("./binary");
///
/// // We create a configuration for the fuzzer.
/// let config = Config::builder(0x10000000, "/tmp/hyperpom/", "/tmp/corpus/")
/// .nb_workers(64)
/// .seed(0xdeadbeef)
/// .timeout(std::time::Duration::new(60, 0))
/// .iterations(Some(1))
/// .build();
///
/// // We instanciate the fuzzer and pass the previous arguments to it.
/// let mut hp = HyperPom::<DummyLoader, LocalData, GlobalData>::new(config, loader, ldata, gdata)
/// .unwrap();
///
/// // The fuzzer can now be started.
/// hp.fuzz().expect("fuzzing failed");
/// ```
pub struct HyperPom<L: 'static + Loader, LD, GD> {
/// Object that contains the different hooks applied to the fuzzed binary.
hooks: Hooks<LD, GD>,
/// Data local to a [`Worker`] that cannot be shared with other [`Worker`] instances.
ldata: LD,
/// Global data shared between all [`Worker`] instances.
gdata: Arc<RwLock<GD>>,
/// Global coverage data aggregating all workers coverage and allowing to decide if a testcase
/// should be kept or not.
global_coverage: GlobalCoverage,
/// User-defined binary loader responsible for mapping the binary and initializing the
/// fuzzer's state (registers, heap, stack, etc.).
loader: L,
/// Number of [`Worker`]s spawned by the fuzzer.
nb_workers: u32,
/// Global physical memory vma for the hypervisor.
/// More information can be found in the documentation for [`PhysMemAllocator`].
pma: PhysMemAllocator,
/// The fuzzer's working directory.
working_directory: PathBuf,
/// The fuzzer's random generator.
rand: Random,
/// The corpus manager shared between all workers.
corpus: Corpus,
/// A copy of the initial configuration structure.
config: Config<LD, GD>,
/// The Apple hypervisor's virtual machine instance for the current process.
_vm: av::VirtualMachine,
}
impl<
L: 'static + Loader + Loader<LD = LD> + Loader<GD = GD>,
LD: 'static + Clone + Send,
GD: 'static + Clone + Send + Sync,
> HyperPom<L, LD, GD>
{
/// Creates a new instance of the fuzzer.
pub fn new(config: ConfigData<LD, GD>, loader: L, ldata: LD, gdata: GD) -> Result<Self> {
// Checks the number of fuzzing workers to spawn.
let max = Self::max_worker_count()?;
let config = if let ConfigData::Fuzzer(inner_config) = config {
inner_config
} else {
return Err(CoreError::InvalidConfiguration)?;
};
if config.nb_workers > max {
// Returns an error if the user tries to spawn more workers than authorized by the
// hypervisor.
return Err(CoreError::TooManyWorkers(max))?;
}
// Initializes the random number generator using the user-provided seed.
let mut rand = Random::new(config.seed);
// Creates the main corpus object.
let mut corpus = Corpus::new(
rand.split(),
// We can unwrap here because we made sure that a fuzzer configuration was passed to
// the function which can't have its corpus directory be None.
&config.corpus_directory.as_ref().unwrap(),
// We can unwrap here because we made sure that a fuzzer configuration was passed to
// the function which can't have its working directory be None.
&config.working_directory.as_ref().unwrap(),
config.load_corpus_at_init,
)?;
// Loads the corpus from a user-provided directory
corpus.load_from_dir(config.max_testcase_size)?;
Ok(Self {
hooks: Hooks::<LD, GD>::new(),
ldata,
gdata: Arc::new(RwLock::new(gdata)),
global_coverage: GlobalCoverage::new(loader.coverage_ranges()?),
loader,
nb_workers: config.nb_workers,
pma: PhysMemAllocator::new(config.as_size)?,
// We can unwrap here because we made sure that a fuzzer configuration was passed to
// the function which can't have its corpus directory be None.
working_directory: config.working_directory.as_ref().unwrap().clone(),
rand,
corpus,
config,
_vm: av::VirtualMachine::new()?,
})
}
/// Returns the maximum number of [`Worker`]s that can be instanciated for the fuzzer
/// (i.e. the number of [`applevisor::Vcpu`] that can be created).
pub fn max_worker_count() -> Result<u32> {
Ok(av::Vcpu::get_max_count()?)
}
/// Starts the fuzzer.
///
/// This function creates one thread per [`Worker`].
/// Each [`Worker`] gets:
///
/// * a copy of the [`Config`];
/// * a copy of the [`Loader`];
/// * a copy of the [`Hooks`];
/// * a local data instance;
/// * a shared reference to the global data;
/// * a shared reference to the corpus;
///
/// [`Worker`]s also get a reference to the global physical memory `pma`, so that each
/// instance can set up its own virtual address space backed by a single [`PhysMemAllocator`].
///
/// # Panic
///
/// [`Worker`]s are expected to be resilient and responsible for handling their own errors. If
/// an error cannot be handled, the thread should panic.
pub fn fuzz(&mut self) -> Result<()> {
// Creates the fuzzer working directory.
fs::create_dir_all(&self.working_directory)?;
// This channel is used by the worker threads to push `WorkerInfo` objects back to the
// main thread. This object contains information about the number of testcases and crashes
// created over a given time interval.
let (msg_tx, msg_rx) = channel::<WorkerInfo>();
// Barrier to make workers wait before the initial corpus has been loaded and the global
// coverage info updated.
let barrier = Arc::new(Barrier::new(self.nb_workers as usize));
// Loop that creates the worker threads.
// Worker handles contain information about a fuzzing thread (thread handle, latest thread
// heartbeat to detect timeouts) and are identified by their VcpuInstance.
let mut worker_handles = (0..self.nb_workers)
.map(|i| {
// Since the Vcpu is created inside the thread, this channel is used to
// retrieve its corresponding VcpuInstance. Having access to the VcpuInstance
// from the main thread is necessary to be able to stop a Vcpu from the main
// thread when it times out.
let (instance_tx, instance_rx) = sync_channel::<av::VcpuInstance>(0);
// All the necessary information is cloned before being moved into the spawned
// thread.
let worker_name = format!("worker_{:02}", i);
let pma = self.pma.clone();
let loader = self.loader.clone();
let ldata = self.ldata.clone();
let gdata = self.gdata.clone();
let hooks = self.hooks.clone();
let corpus = self.corpus.clone();
let global_coverage = self.global_coverage.clone();
let tx = msg_tx.clone();
let rand = self.rand.split();
let working_directory = self.working_directory.join(&worker_name);
let iterations = self.config.iterations;
let config = self.config.clone();
let barrier = Arc::clone(&barrier);
// Spawns the worker thread.
let handle = thread::Builder::new()
.name(worker_name)
.spawn(move || -> Result<()> {
// Creates a new fuzzing worker.
let mut worker = Worker::new(
av::Vcpu::new()?,
pma,
loader,
hooks,
ldata,
gdata,
global_coverage,
tx,
instance_tx,
rand,
corpus,
working_directory,
config,
barrier,
)?;
// Initializes the workers address space, its state, maps the binary and
// applies hooks.
worker.init()?;
// Starts the fuzzing process. The first worker is responsible for running
// the testcases in the corpus and initialize the global coverage paths.
worker.run(i == 0, iterations)?;
Ok(())
})
.expect("An error occured while spawning a worker thread");
// Receives the VcpuInstance of the thread we've just created.
let instance = instance_rx.recv().unwrap();
let handle = WorkerHandle::new(handle);
(instance, handle)
})
.collect::<HashMap<_, _>>();
// Stats variables.
let mut info = HyperPomInfo::new();
let mut corpus_loaded = false;
loop {
// Iterates over the messages sent from the threads containing information about the
// number of testcases and crashes that where generated over a given time interval.
while let Some(wi) = msg_rx.try_iter().next() {
if let Some(handle) = worker_handles.get_mut(&wi.instance) {
if !corpus_loaded {
corpus_loaded = true;
info.start_time = time::Instant::now();
}
handle.latest_ping = time::Instant::now();
info += wi;
}
}
if corpus_loaded {
// Displays the current fuzzers statistics.
self.loader.display_info(&info);
}
// Iterates over thread handles to see if they timed out or if we need to join
// terminated threads.
worker_handles.drain_filter(|instance, handle| {
// If there is still an handle associated to this thread...
if let Some(join_handle) = handle.join_handle.as_mut() {
// ... and the thread has finished running...
if join_handle.is_finished() {
match handle.join_handle.take() {
// ... then join the thread.
Some(h) => h
.join()
.expect("An error occured while joining threads")
.expect("thread panicked"),
None => {}
};
true
} else {
// ... otherwise check if it has timed out and stop the Vcpu if that's the
// case. The worker will resume execution from a sane point on its own.
if time::Instant::now() - handle.latest_ping > self.config.timeout {
av::Vcpu::stop(&[*instance]).expect("could not stop Vcpu");
}
false
}
} else {
true
}
});
// If no more threads are present in `worker_handles` then break out from the loop and
// return from the function.
if worker_handles.is_empty() {
break;
}
// TODO: Maybe add a setting for this.
thread::sleep(std::time::Duration::new(0, 1000));
}
Ok(())
}
}
// -----------------------------------------------------------------------------------------------
// Hyperpom - Worker
// -----------------------------------------------------------------------------------------------
/// Stores the thread handle associated to a worker as well as the latest time the worker gave a
/// sign of life.
pub struct WorkerHandle {
/// Handle to the worker's underlying thread.
join_handle: Option<thread::JoinHandle<Result<()>>>,
/// Time when the thread last sent a message to the main thread. This is used to detect
/// timeouts to reset the corresponding worker.
latest_ping: time::Instant,
}
impl WorkerHandle {
/// Creates a new worker handle object.
fn new(handle: thread::JoinHandle<Result<()>>) -> Self {
Self {
join_handle: Some(handle),
latest_ping: time::Instant::now(),
}
}
}
/// Stores information about the number of testcases, crashes and timeouts that occured during a
/// given time interval.
///
/// This object is sent from worker threads back to the main one through an [`std::sync::mpsc`]
/// channel and then aggregated to generate statistics about the current fuzzing campain.
#[derive(Debug)]
pub struct WorkerInfo {
/// [`VcpuInstance`](crate::applevisor::VcpuInstance) of the associated thread.
instance: av::VcpuInstance,
/// The number of testcases.
nb_testcases: u64,
/// The number of crashes.
nb_crashes: u64,
/// The number of unique crashes.
nb_uniq_crashes: u64,
/// The number of timeouts.
nb_timeouts: u64,
/// The number of paths.
nb_paths: u64,
}
impl WorkerInfo {
/// Creates a new object containing information about a worker's results.
fn new(instance: av::VcpuInstance) -> Self {
Self {
instance,
nb_testcases: 0,
nb_crashes: 0,
nb_uniq_crashes: 0,
nb_timeouts: 0,
nb_paths: 0,
}
}
}
/// A fuzzing worker
///
/// # Role of Fuzzing Workers in the Fuzzer
///
/// Workers are core components of the fuzzing process and each of them operates in its own
/// dedicated thread. A worker primarily setup and manages fuzzing-related operations, but the
/// actual execution is handled by an [`Executor`] instance.
///
/// ```text
///
/// +--------------------+
/// | |
/// | HYPERPOM |
/// | |
/// +---------++---------+
/// ||
/// ||
/// +-----------------------+-----------++-----------+-----------------------+
/// | | | |
/// | | | |
/// +--------+--------+ +--------+--------+ +--------+--------+ +--------+--------+
/// | WORKER | | WORKER | | WORKER | | WORKER |
/// | | | | | | | |
/// | +-------------+ | | +-------------+ | | +-------------+ | | +-------------+ |
/// | | | | | | | | | | | | | | | |
/// | | EXECUTOR | | | | EXECUTOR | | | | EXECUTOR | | | | EXECUTOR | |
/// | | | | | | | | | | | | | | | |
/// | +-------------+ | | +-------------+ | | +-------------+ | | +-------------+ |
/// +-----------------+ +-----------------+ +-----------------+ +-----------------+
/// ```
///
/// Before fuzzing actually starts, workers go through an initialization phase that performs the
/// following operations:
///
/// * creation of the worker's working directory;
/// * calling the [`Executor::init`] function (sets up the initial address space, registers,
/// etc.);
/// * loading the initial corpus.
///
/// Then, when [`Worker::run`] is called, the following operations are performed in a loop:
///
/// * restoring registers and the virtual address space using snapshots;
/// * resetting coverage and backtrace information;
/// * loading a testcase and mutates it;
/// * running the [`Loader::pre_exec`](crate::loader::Loader::pre_exec) hook;
/// * running the testcase using [`Executor::vcpu_run`];
/// * running the [`Loader::post_exec`](crate::loader::Loader::post_exec) hook;
/// * checking if a crash or a timeout occured;
/// * if a crash occured, rerun the testcase with the backtrace hooks enabled and check if the
/// crash is already known;
/// * if it's a new crash, store it;
/// * checking if new paths have been covered by the current testcase;
/// * if new paths have been covered, update the
/// [`GlobalCoverage`](crate::coverage::GlobalCoverage) object and add the testcase to the
/// corpus.
///
/// # Switching Between Coverage and Backtrace Hooks
///
/// Handling a hook is very expensive because of the context switch between the guest VM and the
/// hypervisor. The fewer number of hooks we have to handle, the better the performances will be.
///
/// Hyperpom implements different hook types, with each their own drawbacks that may or may not be
/// mitigable.
///
/// * Tracer hooks are not taken into account here, because we are not expecting tracing to be
/// enabled while fuzzing.
/// * Exit hooks stop the execution altogether, so it's essentially 0 cost.
/// * Custom hooks have to be executed everytime, there's not much we can do here.
/// * Coverage hooks is one of the most expensive hook type, because it is applied to branch and
/// comparison instructions on the whole binary. As explained in
/// [`GlobalCoverage`](crate::coverage::GlobalCoverage), to reduce the performance hit, these
/// hooks are removed as soon as the path is covered, making them effectively one-shot hooks
/// that won't impact subsequent iterations.
///
/// Which leaves us with backtrace hooks. These hooks are also expensive since they are placed on
/// function entries and exits. However, we don't need them for every iteration, we're only
/// interested in getting the backtrace when a crash occurs.
///
/// The solution implemented in this fuzzer is to use two separate address spaces. Both have the
/// same target binary loaded, the custom hooks applied, etc. But only one has the covrage hooks,
/// while the other has the backtrace hooks. During normal execution, the address space with
/// coverage hooks is used, but when a crash occurs, we switch to the one with the backtrace hooks.
/// We compute the backtrace and see if the crash is stable, before switch back to coverage hooks.
///
/// The obvious downside is how much memory we're using. Since we have two address spaces and their
/// corresponding snapshots, we're essentially mutliplying memory usage by four for a single
/// worker. However, we don't need to apply and remove hooks at every crash occurence, which can
/// become costly, especially for large binaries. Hopefully, binaries that require huge memory
/// allocations are uncommon enough that the chosen solution won't be a limitation.
#[allow(rustdoc::private_intra_doc_links)]
pub struct Worker<L: Loader, LD, GD> {
/// The [`Executor`] instance for this worker.
executor: Executor<L, LD, GD>,
/// The [`applevisor::Vcpu`] instance for this worker.
instance: av::VcpuInstance,
/// [`std::sync::mpsc`] channel used to send statistics from the worker to [`HyperPom`].
channel_tx: Sender<WorkerInfo>,
/// A shared reference to the global corpus.
corpus: Corpus,
/// An instance of the mutation engine.
mutator: Mutator,
/// The working directory of the current worker.
working_directory: PathBuf,
/// An instance to the crash handling object.
crash_handler: CrashHandler,
/// A synchronization barrier used during the initialization of the fuzzer. It makes all
/// workers wait for the worker responsible for loading the corpus.
barrier: Arc<Barrier>,
}
impl<L: Loader + Loader<LD = LD> + Loader<GD = GD>, LD: Clone, GD: Clone> Worker<L, LD, GD> {
/// Creates a new instance of a fuzzing worker.
#[allow(clippy::too_many_arguments)]
fn new(
vcpu: av::Vcpu,
pma: PhysMemAllocator,
loader: L,
hooks: Hooks<LD, GD>,
ldata: LD,
gdata: Arc<RwLock<GD>>,
global_coverage: GlobalCoverage,
channel_tx: Sender<WorkerInfo>,
instance_tx: SyncSender<av::VcpuInstance>,
mut rand: Random,
corpus: Corpus,
working_directory: PathBuf,
config: Config<LD, GD>,
barrier: Arc<Barrier>,
) -> Result<Self> {
let instance = vcpu.get_instance();
instance_tx.send(instance).unwrap();
let crash_handler = CrashHandler::new(working_directory.join("crashes"), rand.split())?;
let mutator = Mutator::new(rand.split());
Ok(Self {
executor: Executor::new_hyperpom(
vcpu,
pma,
loader,
hooks,
ldata,
gdata,
global_coverage,
config,
)?,
instance,
channel_tx,
corpus,
mutator,
working_directory,
crash_handler,
barrier,
})
}
/// Initializes the worker thread by setting up its working directory, its registers and
/// address space before taking snapshots.
fn init(&mut self) -> Result<()> {
// Creates the thread's working directory.
fs::create_dir_all(&self.working_directory)?;
// Initializes the executor.
self.executor.init()?;
Ok(())
}
/// Loads the initial testcases found in the user provided corpus directory as well as
/// testcases from past runs if there are any.
fn load_corpus(&mut self, wi: &mut WorkerInfo) -> Result<()> {
println!("Loading corpus...");
let inner = self.corpus.inner.read().unwrap();
for (_, testcase) in inner.testcases.iter() {
// If we have default testcases (i.e. empty testcases that were created as a starting
// point for the mutation process), they won't have a path because they weren't loaded
// from the disk. We can just skip them because they won't bring much in terms of
// coverage.
if testcase.path.is_none() {
continue;
}
// We can unwrap here because we've checked that path is not None.
println!("Loading: {}", &testcase.path.as_ref().unwrap().display());
let _ = self.executor.run(Some(testcase))?;
// Updates the global coverage.
if let Some(new_paths) = self
.executor
.global_coverage
.update_new_coverage(&self.executor.cdata)
{
wi.nb_paths += new_paths;
}
// Restores memory and registers.
self.executor.restore_snapshot(SnapshotAction::Restore)?;
// Resets coverage and backtrace information for the next iteration.
self.executor.cdata.clear();
self.executor.bdata.clear();
}
println!("Corpus loaded!");
Ok(())
}
/// If a testcase caused a crash, rerun it a second time with backtrace hooks. If the resulting
/// backtrace is not already known, the crash is stored. This function can also be used to
/// verify if a crash is stable by running it `crash_verif_iterations` times and making sure
/// the resulting backtrace is always the same.
fn get_crash_backtrace(&mut self, crash: &Testcase) -> Result<Option<u64>> {
self.executor
.restore_snapshot(SnapshotAction::SwitchToBacktrace)?;
// Switch to the address space where the backtrace hooks were applied.
let mut saved_hash = None;
for _ in 0..self.executor.config.crash_verif_iterations {
// Resets coverage and backtrace information for the next iteration.
self.executor.cdata.clear();
self.executor.bdata.clear();
// Restores memory and registers.
self.executor.restore_snapshot(SnapshotAction::Restore)?;
// Runs the testcase.
match self.executor.run(Some(crash))? {
ExitKind::Crash(_) => {
if let Some(hash) = saved_hash {
// If hashes differ from one execution to the next, the crash is unstable
// and can be ignored.
if Backtrace::get_crash_hash(&self.executor.bdata) != hash {
return Ok(None);
} else {
continue;
}
} else {
saved_hash = Some(Backtrace::get_crash_hash(&self.executor.bdata));
continue;
}
}
_ => return Ok(None),
}
}
Ok(saved_hash)
}
/// Starts the fuzzing loop.
#[allow(clippy::never_loop)]
fn run(&mut self, init_corpus: bool, mut iterations: Option<u64>) -> Result<()> {
let mut latest_ping = time::Instant::now();
let mut worker_info = WorkerInfo::new(self.instance);
let mut reset = false;
let mut keep_testcase = false;
// Corpus loading.
if init_corpus {
self.load_corpus(&mut worker_info)
.expect("could not load corpus");
}
self.barrier.wait();
// Cloning the loader for borrowing-related reasons, not optimal but it should not be too
// much of an issue.
let mut loader = self.executor.loader.clone();
let mut testcase = self.corpus.get_testcase();
let mut seed = self.mutator.mutate(
&loader,
testcase.get_data_mut(),
self.executor.config.max_testcase_size,
self.executor.config.max_nb_mutations,
);
let mut prev_cov = Coverage::new();
loop {
// If the number of paths in the global coverage is greater than the latest one we
// saved, it means new paths have been added and we need to removes coverage hooks
// for the new paths.
if self.executor.config.remove_coverage_hooks_on_hit
&& prev_cov.count() < self.executor.global_coverage.count()
{
let inner = self.executor.global_coverage.inner.read().unwrap();
// For each new paths in the global coverage, we remove the associated hook in the
// virtual address space.
for addr in inner.coverage.set.difference(&prev_cov.set) {
self.executor.hooks.revert_coverage_hooks(
*addr as u64,
&mut self.executor.vma.borrow_mut(),
&mut self.executor.vma.borrow_snapshot_mut(),
)?;
}
// Our reference coverage is updated with the current global values.
prev_cov = self.executor.global_coverage.cloned();
}
'reset: loop {
if reset {
// Restores the virtual address space and the registers using our snapshotted
// values.
self.executor.restore_snapshot(SnapshotAction::Restore)?;
}
if !keep_testcase {
// Resets backtrace information for the next iteration.
self.executor.bdata.clear();
// Gets a new testcase from the corpus and mutates it.
testcase = self.corpus.get_testcase();
seed = self.mutator.mutate(
&loader,
testcase.get_data_mut(),
self.executor.config.max_testcase_size,
self.executor.config.max_nb_mutations,
);
}
loop {
match loader.load_testcase(&mut self.executor, testcase.get_data())? {
// The next iteration will fetch a new testcase without resetting the
// fuzzer's state.
LoadTestcaseAction::New => {
keep_testcase = false;
reset = false;
}
// The next iteration will fetch a new testcase and reset the fuzzer's
// state.
LoadTestcaseAction::NewAndReset => {
keep_testcase = false;
reset = true;
}
// The next iteration will keep the current testcase without resetting the
// fuzzer's state.
LoadTestcaseAction::Keep => {
keep_testcase = true;
reset = false;
}
// The next iteration will keep the current testcase and reset the fuzzer's
// state.
LoadTestcaseAction::KeepAndReset => {
keep_testcase = true;
reset = true;
}
// The current testcase could not be loaded by the fuzzer, we fetch a new
// one and retry without resetting the fuzzer's state.
LoadTestcaseAction::Invalid => {
keep_testcase = false;
reset = false;
continue 'reset;
}
// The current testcase could not be loaded by the fuzzer, we fetch a new
// one and retry after resetting the fuzzer's state.
LoadTestcaseAction::InvalidAndReset => {
keep_testcase = false;
reset = true;
continue 'reset;
}
}
break;
}
break;
}
let exec_time_start = time::Instant::now();
let ek = {
// Executes our pre execution hook before we start fuzzing.
let pre_exec_ret = loader.pre_exec(&mut self.executor)?;
// Checks if the pre execution hook worked.
if let ExitKind::Continue = pre_exec_ret {
// Sets the return address to an unmapped address in order to detect when the
// program returns. Not sure if it's a good idea to have the fuzzer do it
// instead of the user, but we'll see.
self.executor.vcpu.set_reg(av::Reg::LR, END_ADDR)?;
// Fuzzing time.
let exec_ret = match iterations.as_mut() {
Some(0) => break,
Some(x) => {
*x -= 1;
self.executor.vcpu_run()?
}
None => self.executor.vcpu_run()?,
};
// Runs our post-exec hook and returns the execution result.
loader.post_exec(&mut self.executor)?;
exec_ret
} else {
pre_exec_ret
}
};
let exec_time_end = time::Instant::now();
// Updates the testcase execution time and coverage.
testcase.exec_time = exec_time_end - exec_time_start;
testcase.coverage = self.executor.cdata.clone();
// Increases the number of testcases executed thus far.
worker_info.nb_testcases += 1;
// Tells the main thread that we're still alive and sends the current worker info as
// well.
if time::Instant::now() - latest_ping > time::Duration::new(1, 0) {
latest_ping = time::Instant::now();
let tmp_worker_info = worker_info;
worker_info = WorkerInfo::new(self.executor.vcpu.get_instance());
self.channel_tx.send(tmp_worker_info).unwrap();
}
// Checks if current iteration returned because of a timeout or a crash.
match ek {
ExitKind::Crash(title) => {
// Saves the current coverage data because checking the crash's stability
// will overwrite it.
let cdata = self.executor.cdata.clone();
let hash = self.get_crash_backtrace(&testcase)?;
if let Some(hash) = hash {
// Checks if the crash is already known.
let new_crash = self.executor.global_coverage.update_new_crashes(hash);
if new_crash && self.executor.config.save_crashes {
self.crash_handler.store_crash(
&loader,
&title,
&testcase,
&self.executor,
false,
)?;
worker_info.nb_uniq_crashes += 1;
}
worker_info.nb_crashes += 1;
}
// Performs a full memory restore with the snapshot that contains the
// coverage and tracing hooks.
self.executor
.restore_snapshot(SnapshotAction::SwitchToCoverage)?;
// Restores the executor's coverage data.
self.executor.cdata = cdata;
// Always resets after a crash.
reset = true;
keep_testcase = false;
}
ExitKind::Timeout => {
if self.executor.config.save_timeouts {
self.crash_handler.store_crash(
&loader,
"Timeout",
&testcase,
&self.executor,
true,
)?;
}
worker_info.nb_timeouts += 1;
// Always resets after a timeout.
reset = true;
keep_testcase = false;
// For timeouts, we skip the testcase addition to the corpus.
continue;
}
_ => {}
}
// Updates the global coverage map if our testcase is not empty and if we will request
// a new testcase after this iteration.
if !testcase.is_empty() && !keep_testcase {
if let Some(new_paths) = self
.executor
.global_coverage
.update_new_coverage(&self.executor.cdata)
{
// Sets the testcase seed.
let mut testcase = testcase.clone();
testcase.set_seed(seed);
// Adds the testcase to the corpus if it generated new paths.
self.corpus.add_testcase(testcase)?;
worker_info.nb_paths += new_paths;
}
}
}
Ok(())
}
}
// -----------------------------------------------------------------------------------------------
// Hyperpom - Executor
// -----------------------------------------------------------------------------------------------
/// Virtual address space snapshot types.
pub enum SnapshotAction {
/// Restores the address space using the corresponding the snapshot.
Restore,
/// Switches the current address space to the one with coverage hooks.
SwitchToCoverage,
/// Switches the current address space to the one with backtrace hooks.
SwitchToBacktrace,
}
/// The address space type currently in use.
pub enum VirtMemMode {
/// Address space where coverage hooks are applied.
Coverage,
/// Address space where backtrace hooks are applied.
Backtrace,
}
/// A wrapper structure for the *coverage* and *backtrace* address spaces. The current mode is
/// defined by the value stored in `mode` which is either [`VirtMemMode::Coverage`] or
/// [`VirtMemMode::Backtrace`].
pub struct VirtMem {
/// The address space type currently in use by the fuzzer.
pub mode: VirtMemMode,
/// The address space where coverage hooks are applied.
pub covtrace: RefCell<VirtMemAllocator>,
/// Snapshot of the address space where coverage hooks are applied.
pub covtrace_snapshot: RefCell<VirtMemAllocator>,
/// The address space where backtrace hooks are applied.
pub backtrace: RefCell<VirtMemAllocator>,
/// Snapshot of the address space where backtrace hooks are applied.
pub backtrace_snapshot: RefCell<VirtMemAllocator>,
}
impl VirtMem {
/// Creates a new virtual memory wrapper structure.
pub fn new(pma: PhysMemAllocator) -> Result<Self> {
Ok(Self {
mode: VirtMemMode::Coverage,
covtrace: RefCell::new(VirtMemAllocator::new(pma.clone())?),
covtrace_snapshot: RefCell::new(VirtMemAllocator::new(pma.clone())?),
backtrace: RefCell::new(VirtMemAllocator::new(pma.clone())?),
backtrace_snapshot: RefCell::new(VirtMemAllocator::new(pma)?),
})
}
/// Borrows the address space in the current mode.
pub fn borrow(&self) -> Ref<'_, VirtMemAllocator> {
match self.mode {
VirtMemMode::Coverage => self.covtrace.borrow(),
VirtMemMode::Backtrace => self.backtrace.borrow(),
}
}
/// Mutably borrows the address space in the current mode.
pub fn borrow_mut(&self) -> RefMut<'_, VirtMemAllocator> {
match self.mode {
VirtMemMode::Coverage => self.covtrace.borrow_mut(),
VirtMemMode::Backtrace => self.backtrace.borrow_mut(),