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 👇

7.3 KB
Raw Blame
// ©AngelaMos | 2026
// corpus.rs

use std::path::Path;
use std::process::{Command, Stdio};
use std::time::Duration;

pub const AFL_CMIN_BIN: &str = "afl-cmin";

const ARG_INPUT: &str = "-i";
const ARG_OUTPUT: &str = "-o";
const ARG_TIMEOUT: &str = "-t";
const ARG_WORKERS: &str = "-T";
const ARG_EDGES_ONLY: &str = "-e";
const ARG_SEPARATOR: &str = "--";
const ARG_INPUT_PLACEHOLDER: &str = "@@";
const ENV_SKIP_CPUFREQ: &str = "AFL_SKIP_CPUFREQ";
const ENV_NO_AFFINITY: &str = "AFL_NO_AFFINITY";
const ENV_ENABLED: &str = "1";

#[derive(Debug, thiserror::Error)]
pub enum CorpusError {
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    #[error("the input corpus at {0} holds no file to minimize")]
    EmptyInput(String),
    #[error("{AFL_CMIN_BIN} exited with {status}")]
    CminFailed { status: String },
    #[error(
        "{AFL_CMIN_BIN} reported success but wrote no file, so accepting its output would replace a working corpus of {input} with nothing"
    )]
    EmptyOutput { input: usize },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Reduction {
    pub before: usize,
    pub after: usize,
}

impl Reduction {
    #[must_use]
    pub fn removed(self) -> usize {
        self.before.saturating_sub(self.after)
    }

    #[must_use]
    pub fn is_reduction(self) -> bool {
        self.after < self.before
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CminInvocation<'a> {
    pub target: &'a Path,
    pub input: &'a Path,
    pub output: &'a Path,
    pub workers: usize,
    pub timeout: Duration,
}

#[must_use]
pub fn cmin_command(invocation: CminInvocation<'_>) -> Command {
    let mut command = Command::new(AFL_CMIN_BIN);
    command
        .arg(ARG_INPUT)
        .arg(invocation.input)
        .arg(ARG_OUTPUT)
        .arg(invocation.output)
        .arg(ARG_TIMEOUT)
        .arg(invocation.timeout.as_millis().to_string())
        .arg(ARG_WORKERS)
        .arg(invocation.workers.max(1).to_string())
        .arg(ARG_EDGES_ONLY)
        .env(ENV_SKIP_CPUFREQ, ENV_ENABLED)
        .env(ENV_NO_AFFINITY, ENV_ENABLED)
        .arg(ARG_SEPARATOR)
        .arg(invocation.target)
        .arg(ARG_INPUT_PLACEHOLDER)
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    command
}

pub fn count_files(dir: &Path) -> std::io::Result<usize> {
    if !dir.is_dir() {
        return Ok(0);
    }
    let mut count = 0;
    for entry in std::fs::read_dir(dir)? {
        if entry?.file_type()?.is_file() {
            count += 1;
        }
    }
    Ok(count)
}

pub fn minimize_corpus(invocation: CminInvocation<'_>) -> Result<Reduction, CorpusError> {
    let before = count_files(invocation.input)?;
    if before == 0 {
        return Err(CorpusError::EmptyInput(
            invocation.input.display().to_string(),
        ));
    }

    let status = cmin_command(invocation).status()?;
    if !status.success() {
        return Err(CorpusError::CminFailed {
            status: status.to_string(),
        });
    }

    let after = count_files(invocation.output)?;
    if after == 0 {
        return Err(CorpusError::EmptyOutput { input: before });
    }

    Ok(Reduction { before, after })
}

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

    fn invocation<'a>(input: &'a Path, output: &'a Path, target: &'a Path) -> CminInvocation<'a> {
        CminInvocation {
            target,
            input,
            output,
            workers: 4,
            timeout: Duration::from_secs(1),
        }
    }

    fn scratch(name: &str) -> PathBuf {
        let dir = lisdex_core::scratch::path(&format!("corpus-{name}"));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).expect("scratch");
        dir
    }

    #[test]
    fn the_command_names_both_directories_and_the_target_after_a_separator() {
        let command = cmin_command(invocation(
            Path::new("/seeds"),
            Path::new("/distilled"),
            Path::new("/out/harness"),
        ));
        let args: Vec<String> = command
            .get_args()
            .map(|arg| arg.to_string_lossy().into_owned())
            .collect();
        assert_eq!(command.get_program(), AFL_CMIN_BIN);
        assert!(
            args.windows(2)
                .any(|p| p[0] == ARG_INPUT && p[1] == "/seeds")
        );
        assert!(
            args.windows(2)
                .any(|p| p[0] == ARG_OUTPUT && p[1] == "/distilled")
        );
        assert!(args.windows(2).any(|p| p[0] == ARG_WORKERS && p[1] == "4"));
        let separator = args
            .iter()
            .position(|arg| arg == ARG_SEPARATOR)
            .expect("the target has to sit behind --, or cmin reads it as its own option");
        assert_eq!(args[separator + 1], "/out/harness");
        assert_eq!(
            args[separator + 2],
            ARG_INPUT_PLACEHOLDER,
            "afl-fuzz drives these harnesses through persistent mode with no filename, but cmin runs one exec per input through afl-showmap and hands the file over as an argument; without @@ it feeds stdin instead and reports 'no instrumentation output detected'"
        );
    }

    #[test]
    fn a_worker_count_of_zero_is_raised_to_one_rather_than_passed_through() {
        let mut inv = invocation(
            Path::new("/seeds"),
            Path::new("/distilled"),
            Path::new("/out/harness"),
        );
        inv.workers = 0;
        let command = cmin_command(inv);
        let args: Vec<String> = command
            .get_args()
            .map(|arg| arg.to_string_lossy().into_owned())
            .collect();
        assert!(
            args.windows(2).any(|p| p[0] == ARG_WORKERS && p[1] == "1"),
            "-T 0 is not a worker count cmin accepts, and a caller deriving it from a failed core probe would otherwise pass one through"
        );
    }

    #[test]
    fn an_empty_input_corpus_is_refused_before_the_tool_is_run() {
        let input = scratch("empty-in");
        let output = scratch("empty-out");
        let target = scratch("empty-target").join("harness");
        let err = minimize_corpus(invocation(&input, &output, &target))
            .expect_err("an empty corpus cannot be minimized");
        assert!(
            matches!(err, CorpusError::EmptyInput(_)),
            "running cmin on nothing would either fail obscurely or succeed with nothing, and neither tells the operator their corpus path was wrong"
        );
    }

    #[test]
    fn counting_ignores_directories_and_a_missing_path_counts_zero() {
        let dir = scratch("counting");
        std::fs::write(dir.join("a"), b"x").unwrap();
        std::fs::write(dir.join("b"), b"y").unwrap();
        std::fs::create_dir(dir.join("sub")).unwrap();
        assert_eq!(count_files(&dir).unwrap(), 2);
        assert_eq!(count_files(&dir.join("absent")).unwrap(), 0);
    }

    #[test]
    fn a_reduction_reports_what_it_removed_and_knows_when_it_removed_nothing() {
        let reduced = Reduction {
            before: 100,
            after: 12,
        };
        assert_eq!(reduced.removed(), 88);
        assert!(reduced.is_reduction());

        let unchanged = Reduction {
            before: 12,
            after: 12,
        };
        assert_eq!(unchanged.removed(), 0);
        assert!(
            !unchanged.is_reduction(),
            "a corpus that was already minimal is a valid outcome, not a failure, and must not be reported as one"
        );
    }
}