-
Notifications
You must be signed in to change notification settings - Fork 8
/
basic_fuzzer_multithread.rs
263 lines (231 loc) · 8.31 KB
/
basic_fuzzer_multithread.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
//! A libfuzzer-like fuzzer with llmp-multithreading support and restarts
//! The example harness is built for libpng.
//! In this example, you will see the use of the `launcher` feature.
//! The `launcher` will spawn new processes for each cpu core.
use mimalloc::MiMalloc;
#[global_allocator]
static GLOBAL: MiMalloc = MiMalloc;
use core::time::Duration;
use std::collections::hash_map::Iter;
use std::{env, path::PathBuf};
use clap::{self, Parser};
use libafl::prelude::MultiMonitor;
use libafl::prelude::RandPrintablesGenerator;
use libafl::{
bolts::{
core_affinity::Cores,
current_nanos,
launcher::Launcher,
rands::StdRand,
shmem::{ShMemProvider, StdShMemProvider},
tuples::tuple_list,
},
corpus::{InMemoryCorpus, OnDiskCorpus},
events::EventConfig,
executors::{inprocess::InProcessExecutor, ExitKind},
feedbacks::{CrashFeedback, MaxMapFeedback},
fuzzer::{Fuzzer, StdFuzzer},
inputs::BytesInput,
mutators::scheduled::{havoc_mutations, StdScheduledMutator},
observers::StdMapObserver,
schedulers::QueueScheduler,
stages::mutational::StdMutationalStage,
state::StdState,
Error,
};
use cairo_rs::hint_processor::builtin_hint_processor::builtin_hint_processor_definition::BuiltinHintProcessor;
use cairo_rs::types::program::Program;
use cairo_rs::types::relocatable::MaybeRelocatable;
use cairo_rs::vm::runners::cairo_runner::CairoRunner;
use cairo_rs::vm::vm_core::VirtualMachine;
use num_bigint::BigInt;
use num_bigint::Sign;
use std::any::Any;
use std::fs;
mod parse_json;
use crate::parse_json::parse_json;
mod utils;
fn timeout_from_millis_str(time: &str) -> Result<Duration, Error> {
Ok(Duration::from_millis(time.parse()?))
}
#[derive(Debug, Parser)]
struct Opt {
#[arg(
long,
value_parser = Cores::from_cmdline,
help = "Spawn a client in each of the provided cores. Broker runs in the 0th core. 'all' to select all available cores. 'none' to run a client without binding to any core. eg: '1,2-4,6' selects the cores 1,2,3,4,6.",
name = "CORES"
)]
cores: Cores,
#[arg(long, help = "Set an initial corpus directory", name = "INPUT")]
input: Vec<PathBuf>,
#[arg(
long,
help = "Set the output directory, default is ./out",
name = "OUTPUT",
default_value = "./out"
)]
output: PathBuf,
#[arg(long, help = "Set the artefact of the contract", name = "CONTRACT")]
contract: PathBuf,
#[arg(
long,
help = "Set the artefact of the contract",
name = "ITERATION",
default_value = "-1"
)]
iteration: i64,
#[arg(
value_parser = timeout_from_millis_str,
long,
help = "Set the exeucution timeout in milliseconds, default is 10000",
name = "TIMEOUT",
default_value = "10000"
)]
timeout: Duration,
}
/// Coverage map with explicit assignments due to the lack of instrumentation
static mut SIGNALS: [u8; 16] = [0; 16];
/// Assign a signal to the signals map
fn signals_set(idx: usize) {
unsafe { SIGNALS[idx] = 1 };
}
fn runner(json: &String, func_name: String, args_num: u64, data: isize) {
//println!("====> Running function : {}", func_name);
//println!("");
let program = Program::from_string(json, Some(&func_name)).unwrap();
let mut cairo_runner = cairo_runner!(program);
let mut vm = vm!();
let hint_processor = BuiltinHintProcessor::new_empty();
let entrypoint = match program
.identifiers
.get(&format!("__main__.{}", &func_name))
.unwrap()
.pc
{
Some(value) => value,
None => return,
};
cairo_runner.initialize_builtins(&mut vm).unwrap();
cairo_runner.initialize_segments(&mut vm, None);
let value = &MaybeRelocatable::from((data, 0));
let mut args = Vec::<&dyn Any>::new();
args.push(value);
for _i in 0..args_num {
args.push(value);
}
let _var = cairo_runner.run_from_entrypoint(
entrypoint,
args,
false,
true,
true,
&mut vm,
&hint_processor,
);
let mut stdout = Vec::<u8>::new();
cairo_runner.write_output(&mut vm, &mut stdout).unwrap();
}
pub fn main() {
let opt = Opt::parse();
let cores = opt.cores;
let contract = opt
.contract
.to_str()
.expect("Fuzzer needs path to contract");
let iter = opt.iteration;
println!("Number of iter : {}", iter);
println!(
"Workdir: {:?}",
env::current_dir().unwrap().to_string_lossy().to_string()
);
let shmem_provider = StdShMemProvider::new().expect("Failed to init shared memory");
let monitor = MultiMonitor::new(|s| println!("{}", s));
let functions = parse_json(&contract.to_string());
let contents =
fs::read_to_string(&contract.to_string()).expect("Should have been able to read the file");
let mut run_client = |_state: Option<_>, mut mgr, _core_id| {
let observer =
unsafe { StdMapObserver::new_from_ptr("signals", SIGNALS.as_mut_ptr(), SIGNALS.len()) };
// Feedback to rate the interestingness of an input
let mut feedback = MaxMapFeedback::new(&observer);
// A feedback to choose if an input is a solution or not
let mut objective = CrashFeedback::new();
// create a State from scratch
let mut state = StdState::new(
// RNG
StdRand::with_seed(current_nanos()),
// Corpus that will be evolved, we keep it in memory for performance
InMemoryCorpus::new(),
// Corpus in which we store solutions (crashes in this example),
// on disk so the user can get them after stopping the fuzzer
OnDiskCorpus::new(PathBuf::from("./crashes")).unwrap(),
// States of the feedbacks.
// The feedbacks can report the data that should persist in the State.
&mut feedback,
// Same for objective feedbacks
&mut objective,
)
.unwrap();
// A queue policy to get testcasess from the corpus
let scheduler = QueueScheduler::new();
// A fuzzer with feedbacks and a corpus scheduler
let mut fuzzer = StdFuzzer::new(scheduler, feedback, objective);
// The wrapped harness function
let mut harness = |_input: &BytesInput| {
for function in functions.clone() {
signals_set(1); // set SIGNALS[1]
runner(&contents, function.name, function.num_args, 2);
signals_set(2); // set SIGNALS[2]
}
ExitKind::Ok
};
// Create the executor for an in-process function with just one observer
let mut executor = InProcessExecutor::new(
&mut harness,
tuple_list!(observer),
&mut fuzzer,
&mut state,
&mut mgr,
)?;
// Generator of printable bytearrays of max size 32
let mut generator = RandPrintablesGenerator::new(32);
// Generate 8 initial inputs
state
.generate_initial_inputs(&mut fuzzer, &mut executor, &mut generator, &mut mgr, 8)
.expect("Failed to generate the initial corpus");
// Setup a mutational stage with a basic bytes mutator
let mutator = StdScheduledMutator::new(havoc_mutations());
let mut stages = tuple_list!(StdMutationalStage::new(mutator));
if iter == -1 {
fuzzer
.fuzz_loop(&mut stages, &mut executor, &mut state, &mut mgr)
.expect("Error in the fuzzing loop");
} else {
fuzzer
.fuzz_loop_for(
&mut stages,
&mut executor,
&mut state,
&mut mgr,
iter as u64,
)
.expect("Error in the fuzzing loop");
}
Ok(())
};
match Launcher::builder()
.shmem_provider(shmem_provider)
.configuration(EventConfig::from_name("default"))
.monitor(monitor)
.run_client(&mut run_client)
.cores(&cores)
.stdout_file(Some("/dev/null"))
.build()
.launch()
{
Ok(()) => (),
Err(Error::ShuttingDown) => println!("Fuzzing stopped by user. Good bye."),
Err(err) => panic!("Failed to run launcher: {:?}", err),
}
}