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 👇

21.9 KB
Raw Blame
// ©AngelaMos | 2026
// verify.rs

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::Duration;

use lisdex_core::process::{self, ProcessError};

use crate::compile::{self, BuildSpec, DEFAULT_DRIVER, LeakCheck, LinkScheme};
use crate::coverage::{self, EdgeSet};
use crate::oracle::{
    self, EXEC_TIMEOUT_SECS, MIN_VALID_SEEDS, Observation, Rejection, RunStatus, SeedRun,
};

pub const COMPILE_TIMEOUT_SECS: u64 = 300;
pub const DIAGNOSTIC_LINES: usize = 12;
pub const MAX_SEEDS_PER_ORACLE: usize = 12;
pub const MAPS_DIR: &str = "maps";
pub const BINARIES_DIR: &str = "bin";
pub const PEN_DIR: &str = "pen";

#[derive(Debug, thiserror::Error)]
pub enum VerifyError {
    #[error(
        "{path} holds {found} readable seed(s); the coverage oracle needs at least {MIN_VALID_SEEDS}"
    )]
    TooFewSeeds { path: PathBuf, found: usize },
    #[error("io error at {path}: {source}")]
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
    #[error(
        "{SHOWMAP} produced no coverage map for {seed} even though the harness ran clean on it"
    )]
    NoCoverageMap { seed: PathBuf },
    #[error(transparent)]
    Process(#[from] ProcessError),
}

const SHOWMAP: &str = compile::SHOWMAP;

fn io(path: &Path) -> impl FnOnce(std::io::Error) -> VerifyError + '_ {
    move |source| VerifyError::Io {
        path: path.to_path_buf(),
        source,
    }
}

#[must_use]
pub fn sample(mut files: Vec<PathBuf>, limit: usize) -> Vec<PathBuf> {
    files.sort();
    if files.len() <= limit || limit == 0 {
        return files;
    }
    // Taking the first N of a sorted corpus takes N near-identical neighbours; an even
    // stride keeps the spread the inter-seed divergence oracle depends on. The stride is
    // inclusive of BOTH ends: `index * len / limit` never reaches the last file, so a
    // 13-file corpus silently dropped the one seed that carried the divergence.
    if limit == 1 {
        return vec![files[0].clone()];
    }
    (0..limit)
        .map(|index| files[index * (files.len() - 1) / (limit - 1)].clone())
        .collect()
}

fn read_dir(path: &Path) -> Result<Vec<PathBuf>, VerifyError> {
    let mut files = Vec::new();
    for entry in std::fs::read_dir(path).map_err(io(path))? {
        let entry = entry.map_err(io(path))?;
        if entry.path().is_file() {
            files.push(entry.path());
        }
    }
    Ok(files)
}

#[derive(Debug, Clone, Default)]
pub struct Corpus {
    pub valid: Vec<PathBuf>,
    pub invalid: Vec<PathBuf>,
}

impl Corpus {
    pub fn read(valid: &Path, invalid: Option<&Path>) -> Result<Self, VerifyError> {
        let all = read_dir(valid)?;
        let total = all.len();
        let found = sample(all, MAX_SEEDS_PER_ORACLE);
        if total > found.len() {
            eprintln!(
                "warning: {total} files in {} sampled down to {} for the oracles; a seed the \
                 oracles never run cannot reject a harness",
                valid.display(),
                found.len()
            );
        }
        if found.len() < MIN_VALID_SEEDS {
            return Err(VerifyError::TooFewSeeds {
                path: valid.to_path_buf(),
                found: found.len(),
            });
        }
        let rejected = match invalid {
            Some(dir) => sample(read_dir(dir)?, MAX_SEEDS_PER_ORACLE),
            None => Vec::new(),
        };
        Ok(Self {
            valid: found,
            invalid: rejected,
        })
    }
}

#[derive(Debug, Clone)]
pub struct Toolchain {
    pub includes: Vec<PathBuf>,
    pub defines: Vec<String>,
    pub cflags: Vec<String>,
    pub archives: Vec<PathBuf>,
    pub link_args: Vec<String>,
    pub driver: PathBuf,
}

impl Default for Toolchain {
    fn default() -> Self {
        Self {
            includes: Vec::new(),
            defines: Vec::new(),
            cflags: Vec::new(),
            archives: Vec::new(),
            link_args: Vec::new(),
            driver: PathBuf::from(DEFAULT_DRIVER),
        }
    }
}

// B79. Compilation is 31.1% of all discards - the largest bucket - so this is the message a
// user meets more often than any other, and it was capable of carrying nothing at all.
//
// Two ways it could come out empty and both are closed here. The compiler writes to stderr and
// nothing to stdout, which used to leave a blank first line on the capture; that is fixed at
// the source in `process`, and the trim keeps a blank line the COMPILER emitted from doing the
// same thing. The second way survives any capture fix: `run.success` with no binary on disk
// produces a genuinely empty output, and there is nothing to quote. The command line is always
// available and always actionable - it names the include roots, the archives and the link
// arguments, which is exactly what the original report turned out to be about.
fn compile_diagnostic(run: &process::Execution) -> String {
    let tail = run.tail(DIAGNOSTIC_LINES);
    let trimmed = tail.trim();
    if !trimmed.is_empty() {
        return trimmed.to_owned();
    }
    format!(
        "the compiler wrote no diagnostic; the command was: {}",
        run.command_line
    )
}

// B80. The bench does not get to choose its link scheme; the archives decide it. Every archive
// has to carry a numbering of its own for the harness's own instrumentation to be safely
// numbered behind it, so ONE bitcode or uninstrumented archive puts the whole link back on the
// shipped shape - where the guard in oracle 3b refuses a verdict rather than reading a
// renumbering as a coverage gain.
#[must_use]
pub fn link_scheme(archives: &[PathBuf]) -> LinkScheme {
    if !archives.is_empty() && archives.iter().all(|a| coverage::is_pcguard_archive(a)) {
        LinkScheme::PcGuard
    } else {
        LinkScheme::Lto
    }
}

impl Toolchain {
    #[must_use]
    pub fn spec(&self, source: &Path, output: &Path) -> BuildSpec {
        let mut spec = BuildSpec::new(source, output);
        spec.includes.clone_from(&self.includes);
        spec.defines.clone_from(&self.defines);
        spec.cflags.clone_from(&self.cflags);
        spec.archives.clone_from(&self.archives);
        spec.link_args.clone_from(&self.link_args);
        spec.driver.clone_from(&self.driver);
        spec.scheme = link_scheme(&self.archives);
        spec
    }
}

#[derive(Debug, Clone)]
pub struct Verdict {
    pub label: String,
    pub source: PathBuf,
    pub binary: PathBuf,
    pub outcome: Result<EdgeSet, Rejection>,
    pub observation: Option<Observation>,
}

#[derive(Debug, Clone)]
pub struct Bench {
    pub work: PathBuf,
    pub corpus: Corpus,
    pub toolchain: Toolchain,
}

impl Bench {
    #[must_use]
    pub fn new(work: impl Into<PathBuf>, corpus: Corpus, toolchain: Toolchain) -> Self {
        Self {
            work: work.into(),
            corpus,
            toolchain,
        }
    }

    fn build(&self, source: &Path, binary: &Path) -> Result<Option<Rejection>, VerifyError> {
        if let Some(parent) = binary.parent() {
            std::fs::create_dir_all(parent).map_err(io(parent))?;
        }
        let _ = std::fs::remove_file(binary);
        let spec = self.toolchain.spec(source, binary);
        let run = process::run(
            &compile::build_command(&spec),
            Duration::from_secs(COMPILE_TIMEOUT_SECS),
        )?;
        if run.success && binary.is_file() {
            return Ok(None);
        }
        Ok(Some(Rejection::CompileFailed {
            diagnostic: compile_diagnostic(&run),
        }))
    }

    fn exercise(
        binary: &Path,
        seed: &Path,
        map: &Path,
        leaks: LeakCheck,
        pen: &Path,
    ) -> Result<SeedRun, VerifyError> {
        // afl-showmap returns 0 on a genuine SEGV, so the exit status has to come from a
        // direct run. That run is also the only path where LeakSanitizer fires, because
        // afl-fuzz injects detect_leaks=0 into every child.
        //
        // Both runs happen inside the pen: a candidate that takes a corpus string as a
        // path has already created and truncated files named by corpus bytes, and it did
        // it in whatever directory the user launched lisdex from.
        let direct = process::run(
            &compile::exercise_command(binary, seed, leaks).cwd(pen),
            Duration::from_secs(EXEC_TIMEOUT_SECS),
        )?;
        let status = if direct.timed_out {
            RunStatus::TimedOut
        } else if direct.success {
            RunStatus::Clean
        } else {
            RunStatus::NonZeroExit
        };

        let _ = std::fs::remove_file(map);
        process::run(
            &compile::showmap_command(binary, seed, map).cwd(pen),
            Duration::from_secs(EXEC_TIMEOUT_SECS * 2),
        )?;
        let coverage = match std::fs::read_to_string(map) {
            Ok(text) => coverage::parse_showmap(&text),
            Err(_) if status != RunStatus::Clean => EdgeSet::new(),
            Err(_) => {
                return Err(VerifyError::NoCoverageMap {
                    seed: seed.to_path_buf(),
                });
            }
        };

        Ok(SeedRun {
            seed: seed.to_path_buf(),
            map: coverage,
            status,
            stderr: direct.stderr,
        })
    }

    fn observe(&self, label: &str, binary: &Path) -> Result<Observation, VerifyError> {
        let maps = self.work.join(MAPS_DIR).join(label);
        std::fs::create_dir_all(&maps).map_err(io(&maps))?;
        let pen = self.work.join(PEN_DIR).join(label);
        std::fs::create_dir_all(&pen).map_err(io(&pen))?;
        let mut observation = Observation::default();
        for (index, seed) in self.corpus.valid.iter().enumerate() {
            let map = maps.join(format!("valid-{index}.map"));
            let run = Self::exercise(binary, seed, &map, LeakCheck::Enforce, &pen)?;
            // The execution oracle runs before any coverage oracle, so once one seed is
            // dirty the verdict is settled and the remaining runs are wasted work.
            let dirty = run.status != RunStatus::Clean;
            observation.valid.push(run);
            if dirty {
                return Ok(observation);
            }
        }
        // A leak on a malformed input can be the library's own error path, which is a
        // finding rather than a reason to throw the harness away.
        for (index, seed) in self.corpus.invalid.iter().enumerate() {
            let map = maps.join(format!("invalid-{index}.map"));
            observation
                .invalid
                .push(Self::exercise(binary, seed, &map, LeakCheck::Ignore, &pen)?);
        }
        Ok(observation)
    }

    pub fn verify(
        &self,
        source: &Path,
        label: &str,
        parent: Option<&BTreeMap<PathBuf, EdgeSet>>,
        accepted: &EdgeSet,
    ) -> Result<Verdict, VerifyError> {
        let binary = self.work.join(BINARIES_DIR).join(label);
        if let Some(rejection) = self.build(source, &binary)? {
            return Ok(Verdict {
                label: label.to_owned(),
                source: source.to_path_buf(),
                binary,
                outcome: Err(rejection),
                observation: None,
            });
        }
        let observation = self.observe(label, &binary)?;
        let outcome = oracle::judge(&observation, parent, accepted);
        Ok(Verdict {
            label: label.to_owned(),
            source: source.to_path_buf(),
            binary,
            outcome,
            observation: Some(observation),
        })
    }
}

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

    fn scratch(label: &str) -> PathBuf {
        let dir = lisdex_core::scratch::path(&format!("harness-verify-{label}"));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn seeded(label: &str, count: usize) -> PathBuf {
        let dir = scratch(label);
        for index in 0..count {
            let byte = u8::try_from(index & 0xFF).unwrap_or_default();
            std::fs::write(dir.join(format!("seed-{index:03}")), [byte]).unwrap();
        }
        dir
    }

    #[test]
    fn a_corpus_smaller_than_the_oracle_floor_is_an_error_not_a_pass() {
        let dir = seeded("tiny", 1);
        assert!(matches!(
            Corpus::read(&dir, None),
            Err(VerifyError::TooFewSeeds { found: 1, .. })
        ));
    }

    #[test]
    fn a_corpus_is_read_deterministically() {
        let dir = seeded("determinism", 5);
        let once = Corpus::read(&dir, None).unwrap();
        let twice = Corpus::read(&dir, None).unwrap();
        assert_eq!(once.valid, twice.valid);
    }

    #[test]
    fn a_large_corpus_is_capped_but_stays_spread() {
        let files: Vec<PathBuf> = (0..100).map(|i| PathBuf::from(format!("{i:03}"))).collect();
        let taken = sample(files, 10);
        assert_eq!(taken.len(), 10);
        assert_eq!(taken[0], PathBuf::from("000"));
        assert_eq!(taken[9], PathBuf::from("099"));
    }

    #[test]
    fn the_last_file_is_always_reachable() {
        // `index * len / limit` never selects the last entry, so a 13-file corpus dropped
        // the seed that carried the divergence and the harness was falsely rejected.
        for total in MAX_SEEDS_PER_ORACLE + 1..MAX_SEEDS_PER_ORACLE * 3 {
            let files: Vec<PathBuf> = (0..total)
                .map(|i| PathBuf::from(format!("{i:04}")))
                .collect();
            let last = files[total - 1].clone();
            let taken = sample(files, MAX_SEEDS_PER_ORACLE);
            assert_eq!(taken.len(), MAX_SEEDS_PER_ORACLE);
            assert!(taken.contains(&last), "{total} files dropped the last one");
        }
    }

    #[test]
    fn a_sample_never_repeats_a_file() {
        let files: Vec<PathBuf> = (0..13).map(|i| PathBuf::from(format!("{i:03}"))).collect();
        let taken = sample(files, 12);
        let unique: std::collections::BTreeSet<&PathBuf> = taken.iter().collect();
        assert_eq!(unique.len(), taken.len());
    }

    #[test]
    fn a_corpus_at_or_below_the_cap_is_taken_whole() {
        let files: Vec<PathBuf> = (0..4).map(|i| PathBuf::from(format!("{i}"))).collect();
        assert_eq!(sample(files.clone(), 12), files);
    }

    #[test]
    fn an_invalid_corpus_is_optional() {
        let dir = seeded("optional", 3);
        let corpus = Corpus::read(&dir, None).unwrap();
        assert!(corpus.invalid.is_empty());
    }

    // B79. Compilation is the largest discard bucket, so an unactionable message here is the
    // one users meet most. These three pin what the rejection may never be.
    fn execution(output: &str, success: bool) -> process::Execution {
        process::Execution {
            command_line: "afl-clang-lto -I/src h.c -o h.bin /out/libpng16.a".to_owned(),
            code: if success { Some(0) } else { Some(1) },
            success,
            timed_out: false,
            truncated: false,
            output: output.to_owned(),
            stderr: String::new(),
            duration: Duration::from_secs(1),
        }
    }

    #[test]
    fn a_compiler_that_said_something_has_that_something_quoted() {
        let diagnostic = compile_diagnostic(&execution(
            "h.c:8:10: fatal error: 'libarchive/archive.h' file not found\n1 error generated.",
            false,
        ));
        assert!(diagnostic.contains("file not found"));
        assert!(!diagnostic.contains("the command was"));
    }

    // The case no capture fix reaches: the compiler exits 0 and leaves no binary, so there is
    // genuinely nothing to quote. The command line names the include roots and archives, which
    // is what the original report turned out to be about.
    #[test]
    fn a_compiler_that_said_nothing_still_names_the_command_that_failed() {
        let diagnostic = compile_diagnostic(&execution("", true));
        assert!(diagnostic.contains("afl-clang-lto"));
        assert!(diagnostic.contains("-I/src"));
    }

    // Whitespace is not a diagnostic. A capture holding only newlines rendered as an empty
    // message for exactly as long as this rule was missing.
    #[test]
    fn a_diagnostic_of_pure_whitespace_is_treated_as_no_diagnostic_at_all() {
        let diagnostic = compile_diagnostic(&execution("\n   \n\n", false));
        assert!(
            diagnostic.contains("the command was"),
            "blank capture rendered as {diagnostic:?}"
        );
    }

    // And the rejection the user actually reads never comes out blank after the colon.
    #[test]
    fn the_rendered_rejection_always_carries_text_after_the_colon() {
        for output in ["", "\n\n", "\n--- stderr ---\ncannot find -lcrypto"] {
            let rejection = Rejection::CompileFailed {
                diagnostic: compile_diagnostic(&execution(output, false)),
            };
            let rendered = rejection.to_string();
            let after = rendered
                .split_once("does not compile: ")
                .expect("the rejection names itself")
                .1;
            assert!(
                !after.trim_start().is_empty() && !after.starts_with('\n'),
                "rendered as {rendered:?}"
            );
        }
    }

    // B80's remaining half. The bench does not choose its scheme; the archives do. These four
    // pin the whole decision table, because every arm of it changes what the oracles may claim.
    fn archive_of(name: &str, body: &[u8]) -> PathBuf {
        let path = lisdex_core::scratch::path(&format!("scheme-{name}")).with_extension("a");
        let mut bytes = b"!<arch>\n".to_vec();
        bytes.extend_from_slice(format!("{:<16}", "m.o/").as_bytes());
        bytes.extend_from_slice(format!("{:<12}{:<6}{:<6}{:<8}", 0, 0, 0, 644).as_bytes());
        bytes.extend_from_slice(format!("{:<10}", body.len()).as_bytes());
        bytes.extend_from_slice(b"\x60\n");
        bytes.extend_from_slice(body);
        std::fs::write(&path, bytes).expect("fixture");
        path
    }

    #[test]
    fn an_archive_whose_numbering_is_fixed_puts_the_bench_on_the_matching_scheme() {
        let path = archive_of("pcg", b"\x7fELF\x02\x01\x01\x00..__sancov_guards..");
        assert_eq!(
            link_scheme(std::slice::from_ref(&path)),
            LinkScheme::PcGuard
        );
        let _ = std::fs::remove_file(path);
    }

    #[test]
    fn a_bitcode_archive_leaves_the_bench_on_the_shipped_scheme() {
        let path = archive_of("lto", b"BC\xc0\xde\x00\x01\x02\x03");
        assert_eq!(link_scheme(std::slice::from_ref(&path)), LinkScheme::Lto);
        let _ = std::fs::remove_file(path);
    }

    // One archive is enough to lose it. A harness numbered behind a library that is itself
    // renumbered at link is no better off than one numbered in front of it.
    #[test]
    fn one_incomparable_archive_puts_the_whole_link_back_on_the_shipped_scheme() {
        let good = archive_of("mix-pcg", b"\x7fELF\x02\x01\x01\x00..__sancov_guards..");
        let bad = archive_of("mix-lto", b"BC\xc0\xde\x00\x01\x02\x03");
        assert_eq!(
            link_scheme(&[good.clone(), bad.clone()]),
            LinkScheme::Lto,
            "a PCGUARD archive beside a bitcode one does not make the pair comparable"
        );
        let _ = std::fs::remove_file(good);
        let _ = std::fs::remove_file(bad);
    }

    // A header-only target passes no archive at all, and reordering nothing is not a scheme.
    #[test]
    fn no_archives_at_all_is_not_a_reason_to_change_compilers() {
        assert_eq!(link_scheme(&[]), LinkScheme::Lto);
    }

    #[test]
    fn the_scheme_reaches_the_build_spec_the_bench_actually_runs() {
        let path = archive_of("spec", b"\x7fELF\x02\x01\x01\x00..__sancov_guards..");
        let mut toolchain = Toolchain::default();
        toolchain.archives.push(path.clone());
        let spec = toolchain.spec(Path::new("/w/h.c"), Path::new("/w/h.bin"));
        assert_eq!(spec.scheme, LinkScheme::PcGuard);
        assert_eq!(
            compile::build_command(&spec).program,
            compile::CC_PCGUARD,
            "resolving the scheme and never passing it on would be silently inert"
        );
        let _ = std::fs::remove_file(path);
    }

    #[test]
    fn the_toolchain_reaches_the_build_spec() {
        let mut toolchain = Toolchain::default();
        toolchain.archives.push(PathBuf::from("/out/libpng16.a"));
        toolchain.link_args.push("-lz".to_owned());
        toolchain.includes.push(PathBuf::from("/src"));
        let spec = toolchain.spec(Path::new("/w/h.c"), Path::new("/w/h.bin"));
        let line = compile::build_command(&spec).command_line();
        assert!(line.contains("libpng16.a"));
        assert!(line.contains("-lz"));
        assert!(line.contains("-I/src"));
    }

    #[test]
    fn a_source_that_does_not_compile_is_a_rejection_not_an_error() {
        // The host has no afl-clang-lto, so this asserted nothing there. It now states
        // that plainly instead of passing silently.
        if lisdex_core::process::resolve_on_path(compile::CC).is_none() {
            eprintln!(
                "skipped: {} is not on PATH, run this in the container",
                compile::CC
            );
            return;
        }
        let work = scratch("nocompile");
        let seeds = seeded("nocompile-seeds", 3);
        let source = work.join("broken.c");
        std::fs::write(&source, "this is not c\n").unwrap();
        let bench = Bench::new(
            &work,
            Corpus::read(&seeds, None).unwrap(),
            Toolchain {
                driver: PathBuf::from("/nonexistent/libAFLDriver.a"),
                ..Toolchain::default()
            },
        );
        let verdict = bench
            .verify(&source, "broken", None, &EdgeSet::new())
            .expect("a source that does not compile is a rejection, never an error");
        assert!(matches!(
            verdict.outcome,
            Err(Rejection::CompileFailed { .. })
        ));
    }

    #[test]
    fn a_run_is_penned_so_a_target_cannot_write_into_the_callers_directory() {
        let command = compile::exercise_command(
            Path::new("/w/h.bin"),
            Path::new("/seeds/a.png"),
            LeakCheck::Ignore,
        )
        .cwd("/w/pen");
        assert_eq!(command.cwd.as_deref(), Some(Path::new("/w/pen")));
    }
}