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 👇

23.3 KB
Raw Blame
// ©AngelaMos | 2026
// snapshot.rs

use std::path::{Path, PathBuf};

use lisdex_core::campaign::{CampaignId, CampaignStatus};
use lisdex_core::crash::Crash;
use lisdex_core::dedup;
use lisdex_core::report::SanitizerReport;
use lisdex_core::store::{Store, StoreError};
use lisdex_fuzz::plot::CoverageCurve;
use lisdex_fuzz::runner;
use lisdex_triage::classify::{self, Classification, DecidedBy};
use lisdex_triage::severity::Severity as TriageSeverity;

pub const SHORT_KEY_LEN: usize = 12;
pub const DISPLAYED_FRAMES: usize = 6;
pub const NO_KEY_REASON: &str = "refused: no symbolized frames to key on";
pub const NO_FRAMES_REASON: &str = "none survived the noise filter";

const UNPARSED_KIND: &str = "unparsed";
const UNKEYED_LABEL: &str = "unkeyed";

#[derive(Debug, thiserror::Error)]
pub enum MonitorError {
    #[error("store error: {0}")]
    Store(#[from] StoreError),
    #[error("no campaign {id} in {db}")]
    CampaignNotFound { id: i64, db: String },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
    Unclassified,
    Undefined,
    NotExploitable,
    ProbablyExploitable,
    Exploitable,
}

impl Severity {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Severity::Exploitable => "EXPLOITABLE",
            Severity::ProbablyExploitable => "PROBABLY_EXPLOITABLE",
            Severity::NotExploitable => "NOT_EXPLOITABLE",
            Severity::Undefined => "UNDEFINED",
            Severity::Unclassified => "UNCLASSIFIED",
        }
    }

    #[must_use]
    fn project(source: TriageSeverity) -> Severity {
        match source {
            TriageSeverity::Exploitable => Severity::Exploitable,
            TriageSeverity::ProbablyExploitable => Severity::ProbablyExploitable,
            TriageSeverity::NotExploitable => Severity::NotExploitable,
            TriageSeverity::Undefined => Severity::Undefined,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Decider {
    Casr,
    Lisdex,
}

impl Decider {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Decider::Casr => "casr",
            Decider::Lisdex => "lisdex",
        }
    }

    #[must_use]
    fn project(source: DecidedBy) -> Decider {
        match source {
            DecidedBy::Casr => Decider::Casr,
            DecidedBy::Lisdex => Decider::Lisdex,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Phase {
    Pending,
    Building,
    Fuzzing,
    Completed,
    Failed,
}

impl Phase {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Phase::Pending => "PENDING",
            Phase::Building => "BUILDING",
            Phase::Fuzzing => "FUZZING",
            Phase::Completed => "COMPLETED",
            Phase::Failed => "FAILED",
        }
    }

    #[must_use]
    pub fn is_live(self) -> bool {
        matches!(self, Phase::Building | Phase::Fuzzing)
    }

    #[must_use]
    fn project(source: CampaignStatus) -> Phase {
        match source {
            CampaignStatus::Pending => Phase::Pending,
            CampaignStatus::Building => Phase::Building,
            CampaignStatus::Fuzzing => Phase::Fuzzing,
            CampaignStatus::Completed => Phase::Completed,
            CampaignStatus::Failed => Phase::Failed,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Notice {
    NoCurveRecorded,
    NoInstanceStats,
    CoverageNotMonotonic,
    NoCampaignInStore,
    UnkeyedCrashes(usize),
}

impl Notice {
    #[must_use]
    pub fn message(self) -> String {
        match self {
            Notice::NoCurveRecorded => {
                "no coverage curve on disk yet; the campaign has not written its first sample"
                    .to_owned()
            }
            Notice::NoInstanceStats => {
                "no fuzzer instance has written stats under this findings directory".to_owned()
            }
            Notice::CoverageNotMonotonic => {
                "coverage fell, so this campaign was resumed and plot_data was concatenated; any first-to-last delta understates it"
                    .to_owned()
            }
            Notice::NoCampaignInStore => {
                "the store holds no campaign, so crashes and findings are unavailable".to_owned()
            }
            Notice::UnkeyedCrashes(count) => format!(
                "{count} crash(es) could not be keyed, so they are listed individually rather than merged"
            ),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CampaignView {
    pub id: i64,
    pub target: String,
    pub phase: Phase,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CurvePoint {
    pub secs: u64,
    pub edges: u64,
    pub corpus: u64,
    pub execs_per_sec: f64,
    pub total_execs: u64,
    pub saved_crashes: u64,
    pub map_density_pct: f64,
}

#[derive(Debug, Clone, PartialEq)]
pub struct InstanceView {
    pub name: String,
    pub is_main: bool,
    pub execs_done: u64,
    pub execs_per_sec: f64,
    pub edges_found: u64,
    pub total_edges: u64,
    pub saved_crashes: u64,
    pub map_density_pct: f64,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Totals {
    pub execs_done: u64,
    pub execs_per_sec: f64,
    pub edges_found: u64,
    pub total_edges: u64,
    pub saved_crashes: u64,
    pub map_density_pct: f64,
    pub afl_version: String,
}

impl Totals {
    #[must_use]
    pub fn edge_ratio(&self) -> f64 {
        if self.total_edges == 0 {
            return 0.0;
        }
        #[expect(clippy::cast_precision_loss)]
        let ratio = self.edges_found as f64 / self.total_edges as f64;
        ratio.clamp(0.0, 1.0)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FindingView {
    pub key: Option<String>,
    pub crash_count: usize,
    pub severity: Severity,
    pub class: String,
    pub kind: String,
    pub crash_site: Option<String>,
    pub frames: Vec<String>,
    pub input_bytes: usize,
    pub is_security_relevant: bool,
    pub decided_by: Option<Decider>,
    pub sanitizer_report: String,
}

impl FindingView {
    #[must_use]
    pub fn short_key(&self) -> String {
        match self.key.as_deref() {
            Some(key) => key
                .char_indices()
                .nth(SHORT_KEY_LEN)
                .map_or(key, |(at, _)| &key[..at])
                .to_owned(),
            None => UNKEYED_LABEL.to_owned(),
        }
    }

    #[must_use]
    pub fn is_keyed(&self) -> bool {
        self.key.is_some()
    }

    #[must_use]
    pub fn key_status(&self) -> String {
        self.key.clone().unwrap_or_else(|| NO_KEY_REASON.to_owned())
    }

    #[must_use]
    pub fn decider(&self) -> &'static str {
        self.decided_by.map_or("unclassified", Decider::as_str)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Source {
    pub db: PathBuf,
    pub findings: PathBuf,
    pub campaign: Option<i64>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Snapshot {
    campaign: Option<CampaignView>,
    curve: Vec<CurvePoint>,
    curve_instance: Option<String>,
    instances: Vec<InstanceView>,
    totals: Option<Totals>,
    findings: Vec<FindingView>,
    unkeyed_crashes: usize,
    total_crashes: usize,
    notices: Vec<Notice>,
}

impl Snapshot {
    pub fn read(source: &Source) -> Result<Snapshot, MonitorError> {
        let mut notices = Vec::new();
        let (campaign, crashes) = read_campaign(source, &mut notices)?;
        let (curve, curve_instance) = read_curve(&source.findings, &mut notices);
        let (instances, totals) = read_instances(&source.findings, &mut notices);
        let grouping = dedup::group_crashes(&crashes);
        let findings = build_findings(&grouping);
        if grouping.unkeyed_crashes() > 0 {
            notices.push(Notice::UnkeyedCrashes(grouping.unkeyed_crashes()));
        }

        Ok(Snapshot {
            campaign,
            curve,
            curve_instance,
            instances,
            totals,
            findings,
            unkeyed_crashes: grouping.unkeyed_crashes(),
            total_crashes: crashes.len(),
            notices,
        })
    }

    #[must_use]
    pub fn empty() -> Snapshot {
        Snapshot {
            campaign: None,
            curve: Vec::new(),
            curve_instance: None,
            instances: Vec::new(),
            totals: None,
            findings: Vec::new(),
            unkeyed_crashes: 0,
            total_crashes: 0,
            notices: Vec::new(),
        }
    }

    #[must_use]
    pub fn campaign(&self) -> Option<&CampaignView> {
        self.campaign.as_ref()
    }

    #[must_use]
    pub fn curve(&self) -> &[CurvePoint] {
        &self.curve
    }

    #[must_use]
    pub fn curve_instance(&self) -> Option<&str> {
        self.curve_instance.as_deref()
    }

    #[must_use]
    pub fn instances(&self) -> &[InstanceView] {
        &self.instances
    }

    #[must_use]
    pub fn totals(&self) -> Option<&Totals> {
        self.totals.as_ref()
    }

    #[must_use]
    pub fn findings(&self) -> &[FindingView] {
        &self.findings
    }

    #[must_use]
    pub fn unkeyed_crashes(&self) -> usize {
        self.unkeyed_crashes
    }

    #[must_use]
    pub fn total_crashes(&self) -> usize {
        self.total_crashes
    }

    #[must_use]
    pub fn distinct_bugs(&self) -> usize {
        self.findings.iter().filter(|f| f.is_keyed()).count()
    }

    #[must_use]
    pub fn notices(&self) -> &[Notice] {
        &self.notices
    }

    #[must_use]
    pub fn elapsed_secs(&self) -> u64 {
        self.curve.last().map_or(0, |point| point.secs)
    }

    #[must_use]
    pub fn peak_edges(&self) -> u64 {
        self.curve
            .iter()
            .map(|point| point.edges)
            .max()
            .unwrap_or(0)
    }

    #[must_use]
    pub fn lowest_edges(&self) -> u64 {
        self.curve
            .iter()
            .map(|point| point.edges)
            .min()
            .unwrap_or(0)
    }

    #[must_use]
    pub fn latest_execs_per_sec(&self) -> Option<f64> {
        self.curve.last().map(|point| point.execs_per_sec)
    }

    #[must_use]
    pub fn latest_corpus(&self) -> Option<u64> {
        self.curve.last().map(|point| point.corpus)
    }

    #[must_use]
    pub fn is_live(&self) -> bool {
        self.campaign
            .as_ref()
            .is_some_and(|campaign| campaign.phase.is_live())
    }
}

fn read_campaign(
    source: &Source,
    notices: &mut Vec<Notice>,
) -> Result<(Option<CampaignView>, Vec<Crash>), MonitorError> {
    if !source.db.exists() {
        notices.push(Notice::NoCampaignInStore);
        return Ok((None, Vec::new()));
    }
    let store = Store::open(&source.db)?;
    let selected = match source.campaign {
        Some(id) => {
            let campaign_id = CampaignId(id);
            let campaign =
                store
                    .get_campaign(campaign_id)?
                    .ok_or_else(|| MonitorError::CampaignNotFound {
                        id,
                        db: source.db.display().to_string(),
                    })?;
            Some((campaign_id, campaign))
        }
        None => store.list_campaigns()?.pop(),
    };

    let Some((campaign_id, campaign)) = selected else {
        notices.push(Notice::NoCampaignInStore);
        return Ok((None, Vec::new()));
    };

    let crashes = store.crashes_for_campaign(campaign_id)?;
    Ok((
        Some(CampaignView {
            id: campaign_id.0,
            target: campaign.target().to_owned(),
            phase: Phase::project(campaign.status()),
        }),
        crashes,
    ))
}

fn read_curve(findings: &Path, notices: &mut Vec<Notice>) -> (Vec<CurvePoint>, Option<String>) {
    let Ok(curve) = runner::read_curve(findings) else {
        notices.push(Notice::NoCurveRecorded);
        return (Vec::new(), None);
    };
    if curve.is_empty() {
        notices.push(Notice::NoCurveRecorded);
        return (Vec::new(), None);
    }
    if !curve.edges_are_monotonic() {
        notices.push(Notice::CoverageNotMonotonic);
    }
    let instance = runner::primary_instance(findings)
        .ok()
        .and_then(|dir| dir.file_name().map(|n| n.to_string_lossy().into_owned()));
    (points(&curve), instance)
}

fn points(curve: &CoverageCurve) -> Vec<CurvePoint> {
    curve
        .samples()
        .iter()
        .map(|sample| CurvePoint {
            secs: sample.relative_time,
            edges: sample.edges_found,
            corpus: sample.corpus_count,
            execs_per_sec: sample.execs_per_sec,
            total_execs: sample.total_execs,
            saved_crashes: sample.saved_crashes,
            map_density_pct: sample.map_size_pct,
        })
        .collect()
}

fn read_instances(
    findings: &Path,
    notices: &mut Vec<Notice>,
) -> (Vec<InstanceView>, Option<Totals>) {
    let Ok(instances) = runner::read_instance_stats(findings) else {
        notices.push(Notice::NoInstanceStats);
        return (Vec::new(), None);
    };
    if instances.is_empty() {
        notices.push(Notice::NoInstanceStats);
        return (Vec::new(), None);
    }

    let raw: Vec<_> = instances.iter().map(|i| i.stats.clone()).collect();
    let totals = runner::combine_stats(&raw).map(|combined| Totals {
        execs_done: combined.execs_done,
        execs_per_sec: combined.execs_per_sec,
        edges_found: combined.edges_found,
        total_edges: combined.total_edges,
        saved_crashes: combined.saved_crashes,
        map_density_pct: combined.bitmap_coverage_pct,
        afl_version: combined.afl_version,
    });

    let views = instances
        .iter()
        .map(|instance| InstanceView {
            name: instance.name.clone(),
            is_main: instance.is_main(),
            execs_done: instance.stats.execs_done,
            execs_per_sec: instance.stats.execs_per_sec,
            edges_found: instance.stats.edges_found,
            total_edges: instance.stats.total_edges,
            saved_crashes: instance.stats.saved_crashes,
            map_density_pct: instance.stats.bitmap_coverage_pct,
        })
        .collect();

    (views, totals)
}

fn build_findings(grouping: &dedup::Grouping<'_>) -> Vec<FindingView> {
    let mut findings: Vec<FindingView> = grouping
        .groups()
        .iter()
        .filter_map(|group| {
            group
                .representative()
                .map(|crash| finding(crash, group.len(), Some(group.key().to_owned())))
        })
        .collect();

    findings.extend(
        grouping
            .unkeyed()
            .iter()
            .map(|crash| finding(crash, 1, None)),
    );

    findings.sort_by(|left, right| {
        right
            .severity
            .cmp(&left.severity)
            .then(right.crash_count.cmp(&left.crash_count))
            .then(left.key.cmp(&right.key))
    });
    findings
}

fn finding(crash: &Crash, crash_count: usize, key: Option<String>) -> FindingView {
    let report = SanitizerReport::parse(crash.sanitizer_report());
    let classification = classify::classify(crash.sanitizer_report());

    FindingView {
        key,
        crash_count,
        severity: classification
            .as_ref()
            .map_or(Severity::Unclassified, |c| Severity::project(c.severity())),
        class: classification
            .as_ref()
            .map_or(UNPARSED_KIND, |c| c.class())
            .to_owned(),
        kind: report
            .as_ref()
            .map_or(UNPARSED_KIND, SanitizerReport::kind)
            .to_owned(),
        crash_site: report
            .as_ref()
            .and_then(SanitizerReport::crash_site)
            .map(str::to_owned),
        frames: report.as_ref().map_or_else(Vec::new, |r| {
            r.frames().iter().take(DISPLAYED_FRAMES).cloned().collect()
        }),
        input_bytes: crash.input().len(),
        is_security_relevant: classification
            .as_ref()
            .is_some_and(Classification::is_security_relevant),
        decided_by: classification
            .as_ref()
            .map(Classification::decided_by)
            .map(Decider::project),
        sanitizer_report: crash.sanitizer_report().to_owned(),
    }
}

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

    const KEY: &str = "2167ce84a15da0f82167ce84a15da0f82167ce84a15da0f82167ce84a15da0f8";

    fn view(severity: Severity, crash_count: usize, key: Option<&str>) -> FindingView {
        FindingView {
            key: key.map(str::to_owned),
            crash_count,
            severity,
            class: "heap-buffer-overflow".to_owned(),
            kind: "heap-buffer-overflow".to_owned(),
            crash_site: None,
            frames: Vec::new(),
            input_bytes: 0,
            is_security_relevant: true,
            decided_by: None,
            sanitizer_report: String::new(),
        }
    }

    #[test]
    fn severity_orders_exploitable_above_every_other_verdict() {
        let mut all = [
            Severity::NotExploitable,
            Severity::Exploitable,
            Severity::Unclassified,
            Severity::ProbablyExploitable,
            Severity::Undefined,
        ];
        all.sort_unstable();
        assert_eq!(
            all.last(),
            Some(&Severity::Exploitable),
            "the model sorts findings by this ordering and the view renders that order verbatim, so a wrong Ord puts the worst bug at the bottom of the operator's screen"
        );
        assert_eq!(all.first(), Some(&Severity::Unclassified));
    }

    #[test]
    fn every_triage_severity_projects_without_collapsing_two_into_one() {
        let projected = [
            TriageSeverity::Exploitable,
            TriageSeverity::ProbablyExploitable,
            TriageSeverity::NotExploitable,
            TriageSeverity::Undefined,
        ]
        .map(Severity::project);
        let mut unique = projected.to_vec();
        unique.sort_unstable();
        unique.dedup();
        assert_eq!(
            unique.len(),
            4,
            "a projection that maps two triage verdicts onto one monitor verdict would silently downgrade a finding"
        );
    }

    #[test]
    fn projected_severity_keeps_the_string_triage_decided() {
        assert_eq!(
            Severity::project(TriageSeverity::Exploitable).as_str(),
            TriageSeverity::Exploitable.as_str(),
            "the view prints this string; if the projection renames a verdict the screen disagrees with `lisdex crashes`"
        );
    }

    #[test]
    fn a_more_severe_bug_outranks_a_more_frequent_one() {
        let findings = {
            let mut all = vec![
                view(Severity::NotExploitable, 90, Some("aaa")),
                view(Severity::Exploitable, 1, Some("bbb")),
            ];
            all.sort_by(|left, right| {
                right
                    .severity
                    .cmp(&left.severity)
                    .then(right.crash_count.cmp(&left.crash_count))
                    .then(left.key.cmp(&right.key))
            });
            all
        };
        assert_eq!(
            findings[0].severity,
            Severity::Exploitable,
            "one exploitable write matters more than ninety non-exploitable reads, and the operator reads top-down"
        );
    }

    #[test]
    fn short_key_truncates_on_a_char_boundary_and_names_the_unkeyed() {
        assert_eq!(
            view(Severity::Exploitable, 1, Some(KEY)).short_key().len(),
            SHORT_KEY_LEN
        );
        assert_eq!(
            view(Severity::Exploitable, 1, None).short_key(),
            UNKEYED_LABEL
        );
    }

    #[test]
    fn a_key_shorter_than_the_display_width_is_not_padded_or_panicked_on() {
        assert_eq!(
            view(Severity::Exploitable, 1, Some("abc")).short_key(),
            "abc"
        );
    }

    #[test]
    fn edge_ratio_is_zero_when_the_map_size_is_unknown_rather_than_dividing_by_zero() {
        let totals = Totals {
            execs_done: 0,
            execs_per_sec: 0.0,
            edges_found: 10,
            total_edges: 0,
            saved_crashes: 0,
            map_density_pct: 0.0,
            afl_version: String::new(),
        };
        assert!((totals.edge_ratio() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn edge_ratio_is_clamped_so_a_gauge_can_consume_it_directly() {
        let totals = Totals {
            execs_done: 0,
            execs_per_sec: 0.0,
            edges_found: 9_000,
            total_edges: 3_000,
            saved_crashes: 0,
            map_density_pct: 0.0,
            afl_version: String::new(),
        };
        assert!(
            (totals.edge_ratio() - 1.0).abs() < f64::EPSILON,
            "ratatui's Gauge panics on a ratio outside 0..=1, so the model clamps rather than trusting two independently-read counters"
        );
    }

    #[test]
    fn only_a_live_phase_is_reported_live() {
        assert!(Phase::Fuzzing.is_live());
        assert!(Phase::Building.is_live());
        assert!(!Phase::Completed.is_live());
        assert!(!Phase::Failed.is_live());
        assert!(!Phase::Pending.is_live());
    }

    #[test]
    fn every_campaign_status_projects_to_a_distinct_phase() {
        let projected = [
            CampaignStatus::Pending,
            CampaignStatus::Building,
            CampaignStatus::Fuzzing,
            CampaignStatus::Completed,
            CampaignStatus::Failed,
        ]
        .map(Phase::project);
        let mut labels: Vec<&str> = projected.iter().map(|p| p.as_str()).collect();
        labels.sort_unstable();
        labels.dedup();
        assert_eq!(labels.len(), 5);
    }

    #[test]
    fn an_empty_snapshot_reports_nothing_rather_than_defaulting_to_zeroes_that_look_real() {
        let empty = Snapshot::empty();
        assert!(empty.campaign().is_none());
        assert!(empty.totals().is_none());
        assert!(empty.curve().is_empty());
        assert!(empty.findings().is_empty());
        assert_eq!(empty.distinct_bugs(), 0);
        assert_eq!(empty.elapsed_secs(), 0);
        assert_eq!(empty.peak_edges(), 0);
    }

    #[test]
    fn every_notice_carries_a_message_an_operator_can_act_on() {
        for notice in [
            Notice::NoCurveRecorded,
            Notice::NoInstanceStats,
            Notice::CoverageNotMonotonic,
            Notice::NoCampaignInStore,
            Notice::UnkeyedCrashes(3),
        ] {
            assert!(notice.message().len() > 20);
        }
    }

    #[test]
    fn the_unkeyed_notice_states_the_count_it_was_given() {
        assert!(Notice::UnkeyedCrashes(7).message().contains('7'));
        assert_ne!(
            Notice::UnkeyedCrashes(1).message(),
            Notice::UnkeyedCrashes(2).message(),
            "a notice that renders the same text for any count is not reporting the campaign's state"
        );
    }

    #[test]
    fn every_triage_decider_projects_to_a_distinct_label() {
        let labels = [DecidedBy::Casr, DecidedBy::Lisdex]
            .map(Decider::project)
            .map(Decider::as_str);
        assert_eq!(labels, ["casr", "lisdex"]);
    }

    #[test]
    fn an_unclassified_finding_names_no_decider_rather_than_debug_printing_one() {
        let unclassified = FindingView {
            decided_by: None,
            ..view(Severity::Unclassified, 1, None)
        };
        assert_eq!(unclassified.decider(), "unclassified");
    }

    #[test]
    fn a_finding_that_could_not_be_keyed_states_why_instead_of_showing_an_empty_field() {
        assert_eq!(
            view(Severity::Exploitable, 1, None).key_status(),
            NO_KEY_REASON
        );
        assert_eq!(view(Severity::Exploitable, 1, Some(KEY)).key_status(), KEY);
    }
}