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
//! This crate implement parsing AFL status from `fuzzer_status` file generated by AFL instances.
//!
//! All status data is included in the [`AFLStat`] struct. Use `AFLStat::load` function to
//! load it from a specific `fuzzer_stats` file, or use `AFLStat::parse` function to parse a
//! [`AFLStat`] struct from the content of a `fuzzer_stats` file.
//!
//! [`AFLStat`]: struct.AFLStat.html
//!

use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::fs::File;
use std::io::{BufReader, Read};
use std::path::Path;
use std::str::FromStr;

///
/// The error type in this crate.
///
#[derive(Debug)]
pub enum Error {
    /// An IO error occured.
    IoError(std::io::Error),

    /// Failed to parse `fuzzer_stats` file.
    ParseError,
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Self::IoError(e)
    }
}

impl std::error::Error for Error { }

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::IoError(e) => f.write_fmt(format_args!("{}", e)),
            Error::ParseError => f.write_str("parse error"),
        }
    }
}

/// Result type in this crate.
pub type Result<T> = std::result::Result<T, Error>;

/// AFL status data.
///
/// This is the primary struct in this crate.
#[derive(Clone, Default, Debug)]
pub struct AFLStat {
    pub start_time: u64,
    pub last_update: u64,
    pub fuzzer_pid: u32,
    pub cycles_done: i32,
    pub execs_done: i64,
    pub execs_per_sec: f64,
    pub paths_total: i64,
    pub paths_favored: i64,
    pub paths_found: i64,
    pub paths_imported: i64,
    pub max_depth: i32,
    pub cur_path: i64,
    pub pending_favs: i64,
    pub pending_total: i64,
    pub variable_paths: i64,
    pub stability: f64,
    pub bitmap_cvg: f64,
    pub unique_crashes: i32,
    pub unique_hangs: i32,
    pub last_path: u64,
    pub last_crash: u64,
    pub last_hang: u64,
    pub execs_since_crash: i64,
    pub exec_timeout: i32,
    pub slowest_exec_ms: i32,
    pub peak_rss_mb: i32,
    pub afl_banner: String,
    pub afl_version: String,
    pub target_mode: String,
    pub command_line: String,
}

impl AFLStat {
    /// Parse the content of `fuzzer_stats` file.
    pub fn parse(text: &str) -> Result<Self> {
        let mut d = HashMap::<String, String>::new();
        for ln in text.lines() {
            if ln.trim().is_empty() {
                continue;
            }

            let ln_data: Vec<&str> = ln.split(':').map(|s| s.trim()).collect();
            if ln_data.len() != 2 {
                return Err(Error::ParseError);
            }
            d.insert(ln_data[0].to_owned(), ln_data[1].to_owned());
        }

        Self::parse_dict(&d)
    }

    fn parse_dict(d: &HashMap<String, String>) -> Result<Self> {
        let mut stat = Self::default();

        if let Some(value) = d.get("start_time") {
            stat.start_time = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("last_update") {
            stat.last_update = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("fuzzer_pid") {
            stat.fuzzer_pid = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("cycles_done") {
            stat.cycles_done = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("execs_done") {
            stat.execs_done = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("execs_per_sec") {
            stat.execs_per_sec = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("paths_total") {
            stat.paths_total = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("paths_favored") {
            stat.paths_favored = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("paths_found") {
            stat.paths_found = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("paths_imported") {
            stat.paths_imported = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("max_depth") {
            stat.max_depth = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("cur_path") {
            stat.cur_path = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("pending_favs") {
            stat.pending_favs = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("pending_total") {
            stat.pending_total = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("variable_paths") {
            stat.variable_paths = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("stability") {
            stat.stability = Self::parse_percentage(value)?;
        }

        if let Some(value) = d.get("bitmap_cvg") {
            stat.bitmap_cvg = Self::parse_percentage(value)?;
        }

        if let Some(value) = d.get("unique_crashes") {
            stat.unique_crashes = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("unique_hangs") {
            stat.unique_hangs = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("last_path") {
            stat.last_path = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("last_crash") {
            stat.last_crash = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("last_hang") {
            stat.last_hang = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("execs_since_crash") {
            stat.execs_since_crash = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("exec_timeout") {
            stat.exec_timeout = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("slowest_exec_ms") {
            stat.slowest_exec_ms = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("peak_rss_mb") {
            stat.peak_rss_mb = Self::parse_value(value)?;
        }

        if let Some(value) = d.get("afl_banner") {
            stat.afl_banner = value.clone();
        }

        if let Some(value) = d.get("afl_version") {
            stat.afl_version = value.clone();
        }

        if let Some(value) = d.get("target_mode") {
            stat.target_mode = value.clone();
        }

        if let Some(value) = d.get("command_line") {
            stat.command_line = value.clone();
        }

        Ok(stat)
    }

    fn parse_value<T>(text: &str) -> Result<T>
        where T: FromStr {
        T::from_str(text)
            .map_err(|_| Error::ParseError)
    }

    fn parse_percentage(text: &str) -> Result<f64> {
        if text.is_empty() {
            return Err(Error::ParseError);
        }

        if !text.ends_with('%') {
            return Err(Error::ParseError);
        }

        let text = text.trim_end_matches('%');
        f64::from_str(text)
            .map(|x| x / 100.0)
            .map_err(|_| Error::ParseError)
    }

    /// Load AFL status data from the given `fuzzer_stats` file.
    ///
    /// ### Example
    ///
    /// ```ignore
    /// let stat = AFLStat::load("path/to/fuzz/dir/fuzzer_stats").unwrap();
    /// ```
    pub fn load(stat_file: &Path) -> Result<Self> {
        let text = {
            let file = File::open(stat_file)?;
            let mut reader = BufReader::new(file);
            let mut buf = String::new();
            reader.read_to_string(&mut buf)?;
            buf
        };
        Self::parse(&text)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_value_ok() {
        assert_eq!(10, AFLStat::parse_value::<i32>("10").unwrap());
    }

    #[test]
    fn parse_value_bad() {
        assert!(AFLStat::parse_value::<i32>("10x").is_err());
    }

    #[test]
    fn parse_percentage_ok() {
        assert_eq!(0.25, AFLStat::parse_percentage("25%").unwrap());
        assert_eq!(1.25, AFLStat::parse_percentage("125%").unwrap());
    }

    #[test]
    fn parse_percentage_bad() {
        assert!(AFLStat::parse_percentage("%").is_err());
        assert!(AFLStat::parse_percentage("0.25").is_err());
    }

    #[test]
    fn parse_afl_stat_from_dict_ok() {
        let mut d = HashMap::<String, String>::new();
        d.insert(String::from("start_time"), String::from("1587396831"));
        d.insert(String::from("last_update"), String::from("1587488608"));
        d.insert(String::from("fuzzer_pid"), String::from("23661"));
        d.insert(String::from("cycles_done"), String::from("1"));
        d.insert(String::from("execs_done"), String::from("354214"));
        d.insert(String::from("execs_per_sec"), String::from("3.86"));
        d.insert(String::from("paths_total"), String::from("6204"));
        d.insert(String::from("paths_favored"), String::from("631"));
        d.insert(String::from("paths_found"), String::from("451"));
        d.insert(String::from("paths_imported"), String::from("4642"));
        d.insert(String::from("max_depth"), String::from("3"));
        d.insert(String::from("cur_path"), String::from("2580"));
        d.insert(String::from("pending_favs"), String::from("513"));
        d.insert(String::from("pending_total"), String::from("5983"));
        d.insert(String::from("variable_paths"), String::from("6198"));
        d.insert(String::from("stability"), String::from("63.45%"));
        d.insert(String::from("bitmap_cvg"), String::from("91.79%"));
        d.insert(String::from("unique_crashes"), String::from("43"));
        d.insert(String::from("unique_hangs"), String::from("245"));
        d.insert(String::from("last_path"), String::from("1587488588"));
        d.insert(String::from("last_crash"), String::from("1587487142"));
        d.insert(String::from("last_hang"), String::from("1587486568"));
        d.insert(String::from("execs_since_crash"), String::from("354214"));
        d.insert(String::from("exec_timeout"), String::from("1000"));
        d.insert(String::from("slowest_exec_ms"), String::from("1250"));
        d.insert(String::from("peak_rss_mb"), String::from("0"));
        d.insert(String::from("afl_banner"), String::from("fuzzer0"));
        d.insert(String::from("afl_version"), String::from("++2.62c"));
        d.insert(String::from("target_mode"), String::from("default"));
        d.insert(String::from("command_line"), String::from("afl-fuzz arg1 arg2"));
        let stat = AFLStat::parse_dict(&d).unwrap();
        assert_correct_stat(&stat);
    }

    #[test]
    fn parse_afl_stat_from_dict_bad() {
        // The `stability` field is changed: the percentage sign (%) is removed.
        // This should trigger an error from `AFLStat::parse_dict`.
        let mut d = HashMap::<String, String>::new();
        d.insert(String::from("start_time"), String::from("1587396831"));
        d.insert(String::from("last_update"), String::from("1587488608"));
        d.insert(String::from("fuzzer_pid"), String::from("23661"));
        d.insert(String::from("cycles_done"), String::from("1"));
        d.insert(String::from("execs_done"), String::from("354214"));
        d.insert(String::from("execs_per_sec"), String::from("3.86"));
        d.insert(String::from("paths_total"), String::from("6204"));
        d.insert(String::from("paths_favored"), String::from("631"));
        d.insert(String::from("paths_found"), String::from("451"));
        d.insert(String::from("paths_imported"), String::from("4642"));
        d.insert(String::from("max_depth"), String::from("3"));
        d.insert(String::from("cur_path"), String::from("2580"));
        d.insert(String::from("pending_favs"), String::from("513"));
        d.insert(String::from("pending_total"), String::from("5983"));
        d.insert(String::from("variable_paths"), String::from("6198"));
        d.insert(String::from("stability"), String::from("63.45"));
        d.insert(String::from("bitmap_cvg"), String::from("91.79%"));
        d.insert(String::from("unique_crashes"), String::from("43"));
        d.insert(String::from("unique_hangs"), String::from("245"));
        d.insert(String::from("last_path"), String::from("1587488588"));
        d.insert(String::from("last_crash"), String::from("1587487142"));
        d.insert(String::from("last_hang"), String::from("1587486568"));
        d.insert(String::from("execs_since_crash"), String::from("354214"));
        d.insert(String::from("exec_timeout"), String::from("1000"));
        d.insert(String::from("slowest_exec_ms"), String::from("1250"));
        d.insert(String::from("peak_rss_mb"), String::from("0"));
        d.insert(String::from("afl_banner"), String::from("fuzzer0"));
        d.insert(String::from("afl_version"), String::from("++2.62c"));
        d.insert(String::from("target_mode"), String::from("default"));
        d.insert(String::from("command_line"), String::from("afl-fuzz arg1 arg2"));
        assert!(AFLStat::parse_dict(&d).is_err());
    }

    #[test]
    fn parse_afl_stat_ok() {
        let raw_stat = r#"
            start_time        : 1587396831
            last_update       : 1587488608
            fuzzer_pid        : 23661
            cycles_done       : 1
            execs_done        : 354214
            execs_per_sec     : 3.86
            paths_total       : 6204
            paths_favored     : 631
            paths_found       : 451
            paths_imported    : 4642
            max_depth         : 3
            cur_path          : 2580
            pending_favs      : 513
            pending_total     : 5983
            variable_paths    : 6198
            stability         : 63.45%
            bitmap_cvg        : 91.79%
            unique_crashes    : 43
            unique_hangs      : 245
            last_path         : 1587488588
            last_crash        : 1587487142
            last_hang         : 1587486568
            execs_since_crash : 354214
            exec_timeout      : 1000
            slowest_exec_ms   : 1250
            peak_rss_mb       : 0
            afl_banner        : fuzzer0
            afl_version       : ++2.62c
            target_mode       : default
            command_line      : afl-fuzz arg1 arg2
        "#;
        let stat = AFLStat::parse(raw_stat).unwrap();
        assert_correct_stat(&stat);
    }

    fn assert_correct_stat(stat: &AFLStat) {
        assert_eq!(1587396831, stat.start_time);
        assert_eq!(1587488608, stat.last_update);
        assert_eq!(23661, stat.fuzzer_pid);
        assert_eq!(1, stat.cycles_done);
        assert_eq!(354214, stat.execs_done);
        assert!((3.86 - stat.execs_per_sec).abs() < 1e-8);
        assert_eq!(6204, stat.paths_total);
        assert_eq!(631, stat.paths_favored);
        assert_eq!(451, stat.paths_found);
        assert_eq!(4642, stat.paths_imported);
        assert_eq!(3, stat.max_depth);
        assert_eq!(2580, stat.cur_path);
        assert_eq!(513, stat.pending_favs);
        assert_eq!(5983, stat.pending_total);
        assert_eq!(6198, stat.variable_paths);
        assert!((0.6345 - stat.stability).abs() < 1e-8);
        assert!((0.9179 - stat.bitmap_cvg).abs() < 1e-8);
        assert_eq!(43, stat.unique_crashes);
        assert_eq!(245, stat.unique_hangs);
        assert_eq!(1587488588, stat.last_path);
        assert_eq!(1587487142, stat.last_crash);
        assert_eq!(1587486568, stat.last_hang);
        assert_eq!(354214, stat.execs_since_crash);
        assert_eq!(1000, stat.exec_timeout);
        assert_eq!(1250, stat.slowest_exec_ms);
        assert_eq!(0, stat.peak_rss_mb);
        assert_eq!("fuzzer0", stat.afl_banner);
        assert_eq!("++2.62c", stat.afl_version);
        assert_eq!("default", stat.target_mode);
        assert_eq!("afl-fuzz arg1 arg2", stat.command_line);
    }

    #[test]
    fn parse_afl_stat_bad() {
        // The `stability` field is modified: the percentage sign (%) is removed. This is expected
        // to trigger a parse error.
        let raw_stat = r#"
            start_time        : 1587396831
            last_update       : 1587488608
            fuzzer_pid        : 23661
            cycles_done       : 1
            execs_done        : 354214
            execs_per_sec     : 3.86
            paths_total       : 6204
            paths_favored     : 631
            paths_found       : 451
            paths_imported    : 4642
            max_depth         : 3
            cur_path          : 2580
            pending_favs      : 513
            pending_total     : 5983
            variable_paths    : 6198
            stability         : 63.45
            bitmap_cvg        : 91.79%
            unique_crashes    : 43
            unique_hangs      : 245
            last_path         : 1587488588
            last_crash        : 1587487142
            last_hang         : 1587486568
            execs_since_crash : 354214
            exec_timeout      : 1000
            slowest_exec_ms   : 1250
            peak_rss_mb       : 0
            afl_banner        : fuzzer0
            afl_version       : ++2.62c
            target_mode       : default
            command_line      : afl-fuzz arg1 arg2
        "#;
        assert!(AFLStat::parse(raw_stat).is_err());
    }
}