-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathcargo-afl.rs
580 lines (528 loc) Β· 19.6 KB
/
cargo-afl.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
use clap::crate_version;
use std::env;
use std::ffi::{OsStr, OsString};
use std::io;
use std::process::{self, Command, ExitStatus, Stdio};
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::{Duration, Instant};
#[path = "../common.rs"]
mod common;
fn main() {
if !common::archive_file_path(None).exists() {
let version = common::afl_rustc_version();
eprintln!(
"AFL LLVM runtime is not built with Rust {version}, run `cargo \
install --force afl` to build it."
);
process::exit(1);
}
let app_matches = clap_app().get_matches();
// This unwrap is okay because we set SubcommandRequiredElseHelp at the top level, and afl is
// the only subcommand
let afl_matches = app_matches.subcommand_matches("afl").unwrap();
match afl_matches.subcommand() {
Some(("analyze", sub_matches)) => {
let args = sub_matches
.get_many::<OsString>("afl-analyze args")
.unwrap_or_default();
run_afl(args, "afl-analyze", None);
}
Some(("cmin", sub_matches)) => {
let args = sub_matches
.get_many::<OsString>("afl-cmin args")
.unwrap_or_default();
run_afl(args, "afl-cmin", None);
}
Some(("fuzz", sub_matches)) => {
let args = sub_matches
.get_many::<OsString>("afl-fuzz args")
.unwrap_or_default();
let timeout = sub_matches.get_one::<u64>("max_total_time").copied();
if timeout.is_some() {
eprintln!(
"`--max_total_time` is deprecated and will be removed in a \
future version of afl.rs. Please use `-V seconds`."
);
}
run_afl(args, "afl-fuzz", timeout);
}
Some(("gotcpu", sub_matches)) => {
let args = sub_matches
.get_many::<OsString>("afl-gotcpu args")
.unwrap_or_default();
run_afl(args, "afl-gotcpu", None);
}
Some(("plot", sub_matches)) => {
let args = sub_matches
.get_many::<OsString>("afl-plot args")
.unwrap_or_default();
run_afl(args, "afl-plot", None);
}
Some(("showmap", sub_matches)) => {
let args = sub_matches
.get_many::<OsString>("afl-showmap args")
.unwrap_or_default();
run_afl(args, "afl-showmap", None);
}
Some(("tmin", sub_matches)) => {
let args = sub_matches
.get_many::<OsString>("afl-tmin args")
.unwrap_or_default();
run_afl(args, "afl-tmin", None);
}
Some(("whatsup", sub_matches)) => {
let args = sub_matches
.get_many::<OsString>("afl-whatsup args")
.unwrap_or_default();
run_afl(args, "afl-whatsup", None);
}
Some((subcommand, sub_matches)) => {
let args = sub_matches.get_many::<OsString>("").unwrap_or_default();
run_cargo(subcommand, args);
}
// unreachable due to SubcommandRequiredElseHelp on "afl" subcommand
None => unreachable!(),
}
}
#[allow(clippy::too_many_lines)]
fn clap_app() -> clap::Command {
use clap::{value_parser, Arg, Command};
Command::new("cargo afl")
.display_name("cargo")
.subcommand_required(true)
.arg_required_else_help(true)
.subcommand(
Command::new("afl")
.version(crate_version!())
.subcommand_required(true)
.arg_required_else_help(true)
.allow_external_subcommands(true)
.external_subcommand_value_parser(value_parser!(OsString))
.override_usage("cargo afl [SUBCOMMAND or Cargo SUBCOMMAND]")
.after_help(
"In addition to the subcommands above, Cargo subcommands are also \
supported (see `cargo help` for a list of all Cargo subcommands).",
)
.subcommand(
Command::new("analyze")
.about("Invoke afl-analyze")
.allow_hyphen_values(true)
.disable_help_subcommand(true)
.disable_help_flag(true)
.disable_version_flag(true)
.arg(
Arg::new("afl-analyze args")
.value_parser(value_parser!(OsString))
.num_args(0..),
),
)
.subcommand(
Command::new("cmin")
.about("Invoke afl-cmin")
.allow_hyphen_values(true)
.disable_help_subcommand(true)
.disable_help_flag(true)
.disable_version_flag(true)
.arg(
Arg::new("afl-cmin args")
.value_parser(value_parser!(OsString))
.num_args(0..),
),
)
.subcommand(
Command::new("fuzz")
.about("Invoke afl-fuzz")
.allow_hyphen_values(true)
.disable_help_subcommand(true)
.disable_help_flag(true)
.disable_version_flag(true)
.arg(
Arg::new("max_total_time")
.long("max_total_time")
.num_args(1)
.value_parser(value_parser!(u64))
.help("Maximum amount of time to run the fuzzer"),
)
.arg(
Arg::new("afl-fuzz args")
.value_parser(value_parser!(OsString))
.num_args(0..),
),
)
.subcommand(
Command::new("gotcpu")
.about("Invoke afl-gotcpu")
.allow_hyphen_values(true)
.disable_help_subcommand(true)
.disable_help_flag(true)
.disable_version_flag(true)
.arg(
Arg::new("afl-gotcpu args")
.value_parser(value_parser!(OsString))
.num_args(0..),
),
)
.subcommand(
Command::new("plot")
.about("Invoke afl-plot")
.allow_hyphen_values(true)
.disable_help_subcommand(true)
.disable_help_flag(true)
.disable_version_flag(true)
.arg(
Arg::new("afl-plot args")
.value_parser(value_parser!(OsString))
.num_args(0..),
),
)
.subcommand(
Command::new("showmap")
.about("Invoke afl-showmap")
.allow_hyphen_values(true)
.disable_help_subcommand(true)
.disable_help_flag(true)
.disable_version_flag(true)
.arg(
Arg::new("afl-showmap args")
.value_parser(value_parser!(OsString))
.num_args(0..),
),
)
.subcommand(
Command::new("tmin")
.about("Invoke afl-tmin")
.allow_hyphen_values(true)
.disable_help_subcommand(true)
.disable_help_flag(true)
.disable_version_flag(true)
.arg(
Arg::new("afl-tmin args")
.value_parser(value_parser!(OsString))
.num_args(0..),
),
)
.subcommand(
Command::new("whatsup")
.about("Invoke afl-whatsup")
.allow_hyphen_values(true)
.disable_help_subcommand(true)
.disable_help_flag(true)
.disable_version_flag(true)
.arg(
Arg::new("afl-whatsup args")
.value_parser(value_parser!(OsString))
.num_args(0..),
),
),
)
}
fn run_timeout_terminate(mut cmd: Command, timeout: Option<u64>) -> Result<ExitStatus, io::Error> {
let timeout = match timeout {
Some(timeout) => Duration::from_secs(timeout),
None => return cmd.status(),
};
let start_time = Instant::now();
let mut child = cmd.spawn()?;
let pid = child.id();
let pair = Arc::new((Mutex::new(false), Condvar::new()));
let (stop_mutex, condvar) = &*pair;
let thread_handle = {
let pair = pair.clone();
thread::spawn(move || -> Result<(), io::Error> {
// This thread will wait until the child process has exited, or the
// timeout has elapsed, whichever comes first. If the timeout
// elapses, and the process is still running, it will send SIGTERM
// to the child process.
let (stop_mutex, condvar) = &*pair;
let mut stop = stop_mutex.lock().unwrap();
loop {
let elapsed = start_time.elapsed();
if elapsed >= timeout {
break;
}
let dur = timeout - elapsed;
let results = condvar.wait_timeout(stop, dur).unwrap();
stop = results.0;
if *stop {
// Blocking waitid call on the main thread has returned,
// thus the child process has terminated
return Ok(());
}
if results.1.timed_out() {
break;
}
}
// Since the waitid call on the main thread is using WNOWAIT, the
// child process won't be cleaned up (until after this thread
// exits and the main thread calls wait) and thus its PID won't be
// reused by another, unrelated process.
unsafe {
#[allow(clippy::cast_possible_wrap)]
let ret = libc::kill(pid as i32, libc::SIGTERM);
if ret == -1 {
return Err(io::Error::last_os_error());
}
}
Ok(())
})
};
unsafe {
// Block until the child process terminates, but leave it in a waitable
// state still
let ret = libc::waitid(
libc::P_PID,
pid,
std::ptr::null_mut(),
libc::WEXITED | libc::WNOWAIT,
);
if ret == -1 {
return Err(io::Error::last_os_error());
}
}
{
let mut stop = stop_mutex.lock().unwrap();
*stop = true;
}
// Tell the timeout thread to stop, wake it, and wait for it to exit
condvar.notify_one();
thread_handle.join().unwrap()?;
// Clean up zombie and get exit status (this won't block, because the child
// process has terminated and is still waitable)
child.wait()
}
fn run_afl<I, S>(args: I, tool: &str, timeout: Option<u64>)
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let cmd_path = common::afl_dir(None).join("bin").join(tool);
let mut cmd = Command::new(cmd_path);
cmd.args(args);
let status = run_timeout_terminate(cmd, timeout).unwrap();
#[cfg(target_os = "macos")]
if tool == "afl-fuzz" && !status.success() {
let sudo_cmd_path = common::afl_dir(None).join("bin").join("afl-system-config");
eprintln!(
"
If you see an error message like `shmget() failed` above, try running the following command:
sudo {}
Note: You will be prompted to enter your password.",
sudo_cmd_path.display()
);
}
process::exit(status.code().unwrap_or(1));
}
fn run_cargo<I, S>(subcommand: &str, args: I)
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
#![allow(clippy::similar_names)]
let cargo_path = env::var("CARGO").expect("Could not determine `cargo` path");
// add some flags to sanitizers to make them work with Rust code
let asan_options = env::var("ASAN_OPTIONS").unwrap_or_default();
let asan_options =
format!("detect_odr_violation=0:abort_on_error=1:symbolize=0:{asan_options}");
let tsan_options = env::var("TSAN_OPTIONS").unwrap_or_default();
let tsan_options = format!("report_signal_unsafe=0:{tsan_options}");
// The new LLVM pass manager was enabled in rustc 1.59.
let version_meta = rustc_version::version_meta().unwrap();
let passes = if (version_meta.semver.minor >= 59 || is_nightly())
&& version_meta.llvm_version.map_or(true, |v| v.major >= 13)
{
"sancov-module"
} else {
"sancov"
};
// `-C codegen-units=1` is needed to work around link errors
// https://github.com/rust-fuzz/afl.rs/pull/193#issuecomment-933550430
let mut rustflags = format!(
"-C debug-assertions \
-C overflow_checks \
-C passes={passes} \
-C codegen-units=1 \
-C llvm-args=-sanitizer-coverage-level=3 \
-C llvm-args=-sanitizer-coverage-trace-pc-guard \
-C llvm-args=-sanitizer-coverage-prune-blocks=0 \
-C opt-level=3 \
-C target-cpu=native "
);
if cfg!(not(feature = "no_cfg_fuzzing")) {
rustflags.push_str("--cfg fuzzing ");
}
if cfg!(target_os = "linux") {
// work around https://github.com/rust-fuzz/afl.rs/issues/141 /
// https://github.com/rust-lang/rust/issues/53945, can be removed once
// those are fixed.
rustflags.push_str("-Clink-arg=-fuse-ld=gold ");
}
// RUSTFLAGS are not used by rustdoc, instead RUSTDOCFLAGS are used. Since
// doctests will try to link against afl-llvm-rt, set up RUSTDOCFLAGS to
// have doctests built the same as other code to avoid issues with doctests.
let mut rustdocflags = rustflags.clone();
rustflags.push_str(&format!(
"-l afl-llvm-rt \
-L {} ",
common::afl_llvm_rt_dir(None).display()
));
// add user provided flags
rustflags.push_str(&env::var("RUSTFLAGS").unwrap_or_default());
rustdocflags.push_str(&env::var("RUSTDOCFLAGS").unwrap_or_default());
let status = Command::new(cargo_path)
.arg(subcommand)
.args(args)
.env("RUSTFLAGS", &rustflags)
.env("RUSTDOCFLAGS", &rustdocflags)
.env("ASAN_OPTIONS", asan_options)
.env("TSAN_OPTIONS", tsan_options)
.status()
.unwrap();
process::exit(status.code().unwrap_or(1));
}
fn is_nightly() -> bool {
Command::new("rustc")
.args(["-Z", "help"])
.stderr(Stdio::null())
.status()
.unwrap()
.success()
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use assert_cmd::Command;
use std::os::unix::ffi::OsStringExt;
#[test]
fn test_app() {
clap_app().debug_assert();
}
#[test]
fn display_name() {
assert!(
String::from_utf8(cargo_afl(&["-V"]).output().unwrap().stdout)
.unwrap()
.starts_with("cargo-afl")
);
}
#[test]
fn afl_required_else_help() {
assert_eq!(
String::from_utf8(command().arg("--help").output().unwrap().stdout).unwrap(),
String::from_utf8(command().output().unwrap().stderr).unwrap()
);
}
#[test]
fn subcommand_required_else_help() {
assert_eq!(
String::from_utf8(cargo_afl(&["--help"]).output().unwrap().stdout).unwrap(),
String::from_utf8(cargo_afl::<&OsStr>(&[]).output().unwrap().stderr).unwrap()
);
}
#[test]
fn external_subcommands_allow_invalid_utf8() {
let _arg_matches = clap_app()
.try_get_matches_from([
OsStr::new("cargo"),
OsStr::new("afl"),
OsStr::new("test"),
&invalid_utf8(),
])
.unwrap();
}
const SUBCOMMANDS: &[&str] = &[
"analyze", "cmin", "fuzz", "gotcpu", "plot", "showmap", "tmin", "whatsup",
];
#[test]
fn subcommands_allow_invalid_utf8() {
for &subcommand in SUBCOMMANDS.iter() {
let _arg_matches = clap_app()
.try_get_matches_from([
OsStr::new("cargo"),
OsStr::new("afl"),
OsStr::new(subcommand),
&invalid_utf8(),
])
.unwrap();
}
}
#[test]
fn subcommands_allow_hyphen_values() {
for &subcommand in SUBCOMMANDS.iter() {
let _arg_matches = clap_app()
.try_get_matches_from(["cargo", "afl", subcommand, "-i", "--input"])
.unwrap();
}
}
#[test]
fn subcommands_help_subcommand_disabled() {
assert!(
String::from_utf8(cargo_afl(&["help"]).output().unwrap().stdout)
.unwrap()
.starts_with("Usage:")
);
for &subcommand in SUBCOMMANDS.iter() {
assert!(
!String::from_utf8(cargo_afl(&[subcommand, "help"]).output().unwrap().stdout)
.unwrap()
.starts_with("Usage:")
);
}
}
#[test]
fn subcommands_help_flag_disabled() {
assert!(
String::from_utf8(cargo_afl(&["--help"]).output().unwrap().stdout)
.unwrap()
.starts_with("Usage:")
);
for &subcommand in SUBCOMMANDS.iter() {
assert!(!String::from_utf8(
cargo_afl(&[subcommand, "--help"]).output().unwrap().stdout
)
.unwrap()
.starts_with("Usage:"));
}
}
#[test]
fn subcommands_version_flag_disabled() {
assert!(
String::from_utf8(cargo_afl(&["-V"]).output().unwrap().stdout)
.unwrap()
.starts_with("cargo-afl")
);
for &subcommand in SUBCOMMANDS.iter() {
assert!(
!String::from_utf8(cargo_afl(&[subcommand, "-V"]).output().unwrap().stdout)
.unwrap()
.starts_with("cargo-afl")
);
}
}
#[test]
fn max_total_time_is_deprecated() {
assert!(String::from_utf8(
cargo_afl(&["fuzz", "--max_total_time=0"])
.output()
.unwrap()
.stderr
)
.unwrap()
.starts_with("`--max_total_time` is deprecated"));
}
fn cargo_afl<T: AsRef<OsStr>>(args: &[T]) -> Command {
let mut command = command();
command.arg("afl").args(args);
command
}
fn command() -> Command {
Command::cargo_bin("cargo-afl").unwrap()
}
fn invalid_utf8() -> OsString {
OsString::from_vec(vec![0xfe])
}
#[test]
fn invalid_utf8_is_invalid() {
assert!(String::from_utf8(invalid_utf8().into_vec()).is_err());
}
}