Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

15.1 KB
Raw Blame
// ©AngelaMos | 2026
// real_campaign.rs

use std::path::PathBuf;

use lisdex_core::campaign::{Campaign, CampaignStatus, TreeProvenance};
use lisdex_core::crash::Crash;
use lisdex_core::store::Store;
use lisdex_monitor::snapshot::{MonitorError, Notice, Severity, Snapshot, Source};

const REAL_PLOT: &str = include_str!("../../lisdex-fuzz/tests/fixtures/plot_data.txt");
const REAL_HEAP_WRITE: &str = include_str!("../../lisdex-triage/tests/fixtures/heapw.txt");
const REAL_HEAP_READ: &str = include_str!("../../lisdex-triage/tests/fixtures/heapr.txt");

const KEYED_WRITE_REPORT: &str = "\
=================================================================
==53767==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x7bd6bfde0020 at pc 0x558474e40fd9
WRITE of size 32 at 0x7bd6bfde0020 thread T0
    #0 0x558474e40fd8 in png_handle_PLTE /src/libpng/pngrutil.c:992:4
    #1 0x558474e41111 in png_read_info /src/libpng/pngread.c:160:10
SUMMARY: AddressSanitizer: heap-buffer-overflow (/out/harness+0xcdfd8) in png_handle_PLTE
";

const KEYED_READ_REPORT: &str = "\
=================================================================
==53768==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x7bc207fe0020 at pc 0x55afa18b1a77
READ of size 1 at 0x7bc207fe0020 thread T0
    #0 0x55afa18b1a76 in png_handle_tRNS /src/libpng/pngrutil.c:1470:9
    #1 0x55afa18b2200 in png_read_info /src/libpng/pngread.c:171:10
SUMMARY: AddressSanitizer: heap-buffer-overflow (/out/harness+0x114a76) in png_handle_tRNS
";

const MAIN_STATS: &str = "\
start_time        : 1784982517
last_update       : 1784983139
run_time          : 600
fuzzer_pid        : 2790
cycles_done       : 64
execs_done        : 34283406
execs_per_sec     : 71170.98
execs_ps_last_min : 70000.00
corpus_count      : 1413
bitmap_cvg        : 19.74%
saved_crashes     : 80
saved_hangs       : 0
edges_found       : 13647
total_edges       : 69140
auto_dict_entries : 53
afl_banner        : lisdex_libpng_read
afl_version       : ++5.02c
target_mode       : persistent shmem_testcase deferred
";

const SECONDARY_STATS: &str = "\
start_time        : 1784982517
last_update       : 1784983139
run_time          : 600
fuzzer_pid        : 2791
cycles_done       : 58
execs_done        : 30000000
execs_per_sec     : 65000.00
execs_ps_last_min : 64000.00
corpus_count      : 1290
bitmap_cvg        : 18.80%
saved_crashes     : 60
saved_hangs       : 0
edges_found       : 13000
total_edges       : 69140
auto_dict_entries : 53
afl_banner        : lisdex_libpng_read
afl_version       : ++5.02c
target_mode       : persistent shmem_testcase deferred
";

struct Lab {
    root: PathBuf,
}

impl Lab {
    fn new(name: &str) -> Lab {
        let root = lisdex_core::scratch::unclaimed_path(&format!(
            "monitor-{name}-{:?}",
            std::thread::current().id()
        ));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).unwrap();
        Lab { root }
    }

    fn findings(&self) -> PathBuf {
        self.root.join("findings")
    }

    fn db(&self) -> PathBuf {
        self.root.join("lisdex.sqlite")
    }

    fn instance(&self, name: &str, stats: &str, plot: Option<&str>) -> &Lab {
        let dir = self.findings().join(name);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("fuzzer_stats"), stats).unwrap();
        if let Some(plot) = plot {
            std::fs::write(dir.join("plot_data"), plot).unwrap();
        }
        self
    }

    fn finished(&self) -> &Lab {
        let store = Store::open(self.db()).unwrap();
        let (id, _) = store.list_campaigns().unwrap().pop().unwrap();
        store
            .update_campaign_status(id, CampaignStatus::Completed)
            .unwrap();
        self
    }

    fn campaign(&self, target: &str, reports: &[&str]) -> &Lab {
        let store = Store::open(self.db()).unwrap();
        let mut campaign = Campaign::new(target, TreeProvenance::Field);
        let id = store.insert_campaign(&campaign).unwrap();
        campaign.advance(CampaignStatus::Building).unwrap();
        campaign.advance(CampaignStatus::Fuzzing).unwrap();
        store
            .update_campaign_status(id, CampaignStatus::Fuzzing)
            .unwrap();
        for (index, report) in reports.iter().enumerate() {
            store
                .insert_crash(&Crash::from_report(
                    id,
                    format!("input-{index}").into_bytes(),
                    *report,
                ))
                .unwrap();
        }
        self
    }

    fn source(&self) -> Source {
        Source {
            db: self.db(),
            findings: self.findings(),
            campaign: None,
        }
    }

    fn read(&self) -> Snapshot {
        Snapshot::read(&self.source()).unwrap()
    }
}

impl Drop for Lab {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.root);
    }
}

fn full_lab(name: &str) -> Lab {
    let lab = Lab::new(name);
    lab.instance("main", MAIN_STATS, Some(REAL_PLOT));
    lab.instance("secondary1", SECONDARY_STATS, None);
    lab.campaign(
        "lisdex_libpng_read",
        &[KEYED_WRITE_REPORT, KEYED_WRITE_REPORT, KEYED_READ_REPORT],
    );
    lab
}

#[test]
fn a_snapshot_of_a_real_campaign_carries_every_panel_the_monitor_renders() {
    let snapshot = full_lab("full").read();

    let campaign = snapshot.campaign().expect("the store holds a campaign");
    assert_eq!(campaign.target, "lisdex_libpng_read");
    assert!(campaign.phase.is_live());
    assert!(
        snapshot.curve().len() > 100,
        "the curve comes from the 600s magma libpng capture; a parser reading only the first rows would still look green on a two-row fixture"
    );
    assert_eq!(snapshot.instances().len(), 2);
    assert!(snapshot.totals().is_some());
    assert_eq!(snapshot.distinct_bugs(), 2);
    assert_eq!(snapshot.total_crashes(), 3);
}

#[test]
fn the_curve_comes_from_the_main_instance_when_several_are_running() {
    let lab = Lab::new("curve-source");
    lab.instance("secondary1", SECONDARY_STATS, Some(REAL_PLOT));
    lab.instance("main", MAIN_STATS, Some(REAL_PLOT));
    lab.campaign("libpng", &[]);
    assert_eq!(
        lab.read().curve_instance(),
        Some("main"),
        "instances share one coverage map, so the curve must be read from one authoritative instance rather than whichever the directory listing returned first"
    );
}

#[test]
fn a_single_instance_campaign_reads_its_curve_from_the_default_directory() {
    let lab = Lab::new("single");
    lab.instance("default", MAIN_STATS, Some(REAL_PLOT));
    lab.campaign("libpng", &[]);
    let snapshot = lab.read();
    assert_eq!(snapshot.curve_instance(), Some("default"));
    assert!(!snapshot.curve().is_empty());
}

#[test]
fn totals_take_the_highest_coverage_and_never_the_sum_of_it() {
    let totals = full_lab("totals")
        .read()
        .totals()
        .expect("two instances wrote stats")
        .clone();
    assert_eq!(
        totals.edges_found, 13_647,
        "instances share one coverage map and sync; summing edges_found would report 26647 edges the campaign never had"
    );
    assert_eq!(
        totals.execs_done, 64_283_406,
        "work really is additive across instances, unlike coverage"
    );
    assert_eq!(totals.saved_crashes, 140);
    assert_eq!(totals.afl_version, "++5.02c");
}

#[test]
fn the_edge_ratio_a_gauge_consumes_matches_the_counters_it_came_from() {
    let totals = full_lab("ratio").read().totals().unwrap().clone();
    let expected = 13_647.0_f64 / 69_140.0_f64;
    assert!((totals.edge_ratio() - expected).abs() < 1e-9);
    assert!((0.0..=1.0).contains(&totals.edge_ratio()));
}

#[test]
fn a_crash_seen_twice_is_one_finding_that_counts_two() {
    let findings = full_lab("dedup").read().findings().to_vec();
    let repeated = findings
        .iter()
        .find(|finding| finding.crash_count == 2)
        .expect("the write overflow was stored twice under one key");
    assert!(repeated.is_keyed());
    assert_eq!(repeated.crash_site.as_deref(), Some("png_handle_PLTE"));
}

#[test]
fn a_write_overflow_outranks_a_read_overflow_on_screen() {
    let findings = full_lab("severity-order").read().findings().to_vec();
    assert_eq!(
        findings[0].severity,
        Severity::Exploitable,
        "the read/write axis is the dominant severity factor, and the operator reads the list top-down"
    );
    assert_eq!(findings[0].crash_site.as_deref(), Some("png_handle_PLTE"));
    assert_eq!(
        findings[1].severity,
        Severity::NotExploitable,
        "a heap read overflow is not exploitable by the shipped classifier, whatever a severity table would have published"
    );
}

#[test]
fn unsymbolized_captures_appear_as_findings_that_were_never_keyed() {
    let lab = Lab::new("unkeyed");
    lab.instance("main", MAIN_STATS, Some(REAL_PLOT));
    lab.campaign("libpng", &[REAL_HEAP_WRITE, REAL_HEAP_READ]);
    let snapshot = lab.read();
    assert_eq!(
        snapshot.distinct_bugs(),
        0,
        "these are real captures taken unsymbolized, so keying them would key on a module offset shared by every crash of that kind"
    );
    assert_eq!(snapshot.unkeyed_crashes(), 2);
    assert_eq!(snapshot.findings().len(), 2);
    assert!(
        snapshot.notices().contains(&Notice::UnkeyedCrashes(2)),
        "the refusal to key is the model's decision, so the model states it; a renderer inventing that sentence could contradict dedup without a single test going red"
    );
    for finding in snapshot.findings() {
        assert!(!finding.is_keyed());
        assert_eq!(finding.short_key(), "unkeyed");
    }
}

#[test]
fn an_unsymbolized_capture_is_still_classified_even_though_it_cannot_be_keyed() {
    let lab = Lab::new("unkeyed-severity");
    lab.instance("main", MAIN_STATS, Some(REAL_PLOT));
    lab.campaign("libpng", &[REAL_HEAP_WRITE]);
    let snapshot = lab.read();
    let finding = &snapshot.findings()[0];
    assert_eq!(
        finding.severity,
        Severity::Exploitable,
        "refusing to key a crash must not also discard its severity; the operator still needs to see it"
    );
    assert!(finding.is_security_relevant);
    assert!(finding.decided_by.is_some());
}

#[test]
fn a_findings_directory_that_does_not_exist_yet_is_a_notice_not_an_error() {
    let lab = Lab::new("no-findings");
    lab.campaign("libpng", &[]);
    let snapshot = lab.read();
    assert!(snapshot.notices().contains(&Notice::NoCurveRecorded));
    assert!(snapshot.notices().contains(&Notice::NoInstanceStats));
    assert!(
        snapshot.campaign().is_some(),
        "a campaign that has been recorded but has not started fuzzing must still render"
    );
}

#[test]
fn a_store_that_does_not_exist_yet_is_a_notice_not_an_error() {
    let lab = Lab::new("no-db");
    lab.instance("main", MAIN_STATS, Some(REAL_PLOT));
    let snapshot = lab.read();
    assert!(snapshot.notices().contains(&Notice::NoCampaignInStore));
    assert!(snapshot.campaign().is_none());
    assert!(
        !snapshot.curve().is_empty(),
        "a live campaign writes its curve before anything asks the store for it"
    );
}

#[test]
fn a_resumed_campaign_is_reported_as_resumed_rather_than_silently_understated() {
    let lab = Lab::new("resumed");
    let concatenated = format!("{REAL_PLOT}{}", strip_header(REAL_PLOT));
    lab.instance("main", MAIN_STATS, Some(&concatenated));
    lab.campaign("libpng", &[]);
    assert!(
        lab.read().notices().contains(&Notice::CoverageNotMonotonic),
        "resuming genuinely concatenates plot_data, and a first-to-last delta computed over the join understates coverage"
    );
}

#[test]
fn one_campaign_run_is_not_reported_as_resumed() {
    assert!(
        !full_lab("not-resumed")
            .read()
            .notices()
            .contains(&Notice::CoverageNotMonotonic),
        "if this fires on a single unmodified capture the monotonicity check is a constant and proves nothing about the resumed case"
    );
}

#[test]
fn with_no_campaign_named_the_most_recent_one_is_shown() {
    let lab = Lab::new("latest");
    lab.instance("main", MAIN_STATS, Some(REAL_PLOT));
    let store = Store::open(lab.db()).unwrap();
    for target in ["libpng", "libtiff", "openjpeg"] {
        store
            .insert_campaign(&Campaign::new(target, TreeProvenance::Field))
            .unwrap();
    }
    drop(store);
    assert_eq!(lab.read().campaign().unwrap().target, "openjpeg");
}

#[test]
fn a_named_campaign_is_shown_instead_of_the_most_recent_one() {
    let lab = Lab::new("named");
    lab.instance("main", MAIN_STATS, Some(REAL_PLOT));
    let store = Store::open(lab.db()).unwrap();
    let mut first = None;
    for target in ["libpng", "libtiff"] {
        let id = store
            .insert_campaign(&Campaign::new(target, TreeProvenance::Field))
            .unwrap();
        first.get_or_insert(id);
    }
    drop(store);
    let source = Source {
        campaign: Some(first.unwrap().0),
        ..lab.source()
    };
    let snapshot = Snapshot::read(&source).unwrap();
    assert_eq!(snapshot.campaign().unwrap().target, "libpng");
}

#[test]
fn naming_a_campaign_the_store_does_not_hold_is_an_error_not_an_empty_screen() {
    let lab = Lab::new("missing-campaign");
    lab.campaign("libpng", &[]);
    let source = Source {
        campaign: Some(9999),
        ..lab.source()
    };
    let err = Snapshot::read(&source).unwrap_err();
    assert!(
        matches!(err, MonitorError::CampaignNotFound { id: 9999, .. }),
        "silently falling back to another campaign would show an operator numbers from a run they did not ask about"
    );
}

#[test]
fn a_finished_campaign_is_not_reported_as_live_even_though_its_stats_files_remain() {
    let lab = full_lab("finished");
    lab.finished();
    let snapshot = lab.read();
    assert!(
        !snapshot.is_live(),
        "afl-fuzz leaves fuzzer_stats on disk after it exits, so instance count can never be the liveness signal; only the campaign's own phase is"
    );
    assert_eq!(
        snapshot.instances().len(),
        2,
        "the dead instances must still be readable; the fix is to stop calling them running, not to hide them"
    );
}

#[test]
fn a_running_campaign_is_reported_as_live() {
    assert!(
        full_lab("still-running").read().is_live(),
        "if this is false for a fuzzing campaign the liveness check is a constant and proves nothing about the finished case"
    );
}

#[test]
fn elapsed_and_peak_come_from_the_curve_the_campaign_actually_wrote() {
    let snapshot = full_lab("elapsed").read();
    assert_eq!(snapshot.elapsed_secs(), 600);
    assert_eq!(
        snapshot.peak_edges(),
        13_647,
        "the peak comes from the curve on disk, not from the stats file; reading it from the wrong source would report the first sample as the best one"
    );
}

#[test]
fn instance_roles_are_reported_so_a_reader_can_tell_which_map_is_authoritative() {
    let snapshot = full_lab("roles").read();
    let main = snapshot
        .instances()
        .iter()
        .find(|instance| instance.is_main)
        .expect("one instance is the main");
    assert_eq!(main.name, "main");
    assert_eq!(snapshot.instances().iter().filter(|i| i.is_main).count(), 1);
}

fn strip_header(plot: &str) -> String {
    plot.lines()
        .filter(|line| !line.trim_start().starts_with('#'))
        .collect::<Vec<_>>()
        .join("\n")
}