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 👇
Go aicertificationcloud-engineeringcybercybersecuritycybersecurity-analystcybersecurity-certificationcybersecurity-certificationscybersecurity-educationcybersecurity-jobscybersecurity-portfoliocybersecurity-projectscybersecurity-toolsgrchackinglearningpentestingproject-repositoryprojetcspython
// ©AngelaMos | 2026
// minimize.rs
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::Duration;
use lisdex_core::report::SanitizerReport;
use crate::runner::{self, RunnerError};
pub const AFL_TMIN_BIN: &str = "afl-tmin";
const ARG_INPUT: &str = "-i";
const ARG_OUTPUT: &str = "-o";
const ARG_MEMORY: &str = "-m";
const ARG_TIMEOUT: &str = "-t";
const ARG_EDGES_ONLY: &str = "-e";
const ARG_SEPARATOR: &str = "--";
const MEM_LIMIT_UNLIMITED: &str = "none";
const ENV_TMIN_EXACT: &str = "AFL_TMIN_EXACT";
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 MinimizeError {
#[error("io error: {0}")]
Io(#[from] std::io::Error),
#[error("could not reproduce the crash to establish its identity: {0}")]
Runner(#[from] RunnerError),
#[error("{AFL_TMIN_BIN} exited with {status} and produced no usable output")]
TminFailed { status: String },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
Minimized {
key: String,
bytes_before: u64,
bytes_after: u64,
},
RejectedForIdentity {
expected: String,
produced: Option<String>,
},
RefusedUnkeyed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TminInvocation<'a> {
pub target: &'a Path,
pub input: &'a Path,
pub output: &'a Path,
pub timeout: Duration,
}
#[must_use]
pub fn verdict(
expected: Option<&str>,
produced: Option<&str>,
bytes_before: u64,
bytes_after: u64,
) -> Outcome {
let Some(expected) = expected else {
return Outcome::RefusedUnkeyed;
};
match produced {
Some(produced) if produced == expected => Outcome::Minimized {
key: expected.to_owned(),
bytes_before,
bytes_after,
},
produced => Outcome::RejectedForIdentity {
expected: expected.to_owned(),
produced: produced.map(str::to_owned),
},
}
}
#[must_use]
pub fn tmin_command(invocation: TminInvocation<'_>) -> Command {
let mut command = Command::new(AFL_TMIN_BIN);
command
.arg(ARG_INPUT)
.arg(invocation.input)
.arg(ARG_OUTPUT)
.arg(invocation.output)
.arg(ARG_MEMORY)
.arg(MEM_LIMIT_UNLIMITED)
.arg(ARG_TIMEOUT)
.arg(invocation.timeout.as_millis().to_string())
.arg(ARG_EDGES_ONLY)
.env(ENV_TMIN_EXACT, ENV_ENABLED)
.env(ENV_SKIP_CPUFREQ, ENV_ENABLED)
.env(ENV_NO_AFFINITY, ENV_ENABLED)
.arg(ARG_SEPARATOR)
.arg(invocation.target)
.stdout(Stdio::null())
.stderr(Stdio::null());
command
}
pub fn identity(
target: &Path,
input: &Path,
timeout: Duration,
) -> Result<Option<String>, RunnerError> {
let reproduction = runner::reproduce(target, input, timeout)?;
Ok(SanitizerReport::parse(&reproduction.output).and_then(|report| report.stack_hash()))
}
pub fn minimize(
invocation: TminInvocation<'_>,
reproduce_timeout: Duration,
) -> Result<Outcome, MinimizeError> {
let expected = identity(invocation.target, invocation.input, reproduce_timeout)?;
if expected.is_none() {
return Ok(Outcome::RefusedUnkeyed);
}
let status = tmin_command(invocation).status()?;
if !status.success() || !invocation.output.exists() {
return Err(MinimizeError::TminFailed {
status: status.to_string(),
});
}
let bytes_before = std::fs::metadata(invocation.input)?.len();
let bytes_after = std::fs::metadata(invocation.output)?.len();
let produced = identity(invocation.target, invocation.output, reproduce_timeout)?;
let outcome = verdict(
expected.as_deref(),
produced.as_deref(),
bytes_before,
bytes_after,
);
if matches!(outcome, Outcome::RejectedForIdentity { .. }) {
std::fs::remove_file(invocation.output)?;
}
Ok(outcome)
}
#[cfg(test)]
mod tests {
use std::ffi::OsStr;
use std::path::PathBuf;
use super::*;
const KEY: &str = "5cb9f19ccde1a943";
const OTHER_KEY: &str = "80722b352fbccbd5";
const BEFORE: u64 = 4096;
const AFTER: u64 = 128;
fn invocation() -> TminInvocation<'static> {
TminInvocation {
target: Path::new("/out/afl/harness"),
input: Path::new("/findings/crashes/id:000000"),
output: Path::new("/tmp/min"),
timeout: Duration::from_secs(5),
}
}
#[test]
fn a_minimized_input_that_keeps_its_key_is_accepted() {
assert_eq!(
verdict(Some(KEY), Some(KEY), BEFORE, AFTER),
Outcome::Minimized {
key: KEY.to_owned(),
bytes_before: BEFORE,
bytes_after: AFTER,
}
);
}
#[test]
fn a_minimized_input_that_proves_a_different_bug_is_rejected() {
assert_eq!(
verdict(Some(KEY), Some(OTHER_KEY), BEFORE, AFTER),
Outcome::RejectedForIdentity {
expected: KEY.to_owned(),
produced: Some(OTHER_KEY.to_owned()),
},
"afl-tmin accepts ANY crash unless AFL_TMIN_EXACT is set, and even then it compares its own coverage bitmap rather than the symbolized stack lisdex publishes; a smaller input that crashes elsewhere is not a reproducer for this bug"
);
}
#[test]
fn a_minimized_input_that_stops_crashing_identifiably_is_rejected() {
assert_eq!(
verdict(Some(KEY), None, BEFORE, AFTER),
Outcome::RejectedForIdentity {
expected: KEY.to_owned(),
produced: None,
}
);
}
#[test]
fn a_crash_with_no_key_is_refused_rather_than_minimized_blind() {
assert_eq!(
verdict(None, Some(KEY), BEFORE, AFTER),
Outcome::RefusedUnkeyed,
"with no identity to preserve there is nothing to verify preservation against, so the reduction cannot be shown to be sound"
);
assert_eq!(verdict(None, None, BEFORE, AFTER), Outcome::RefusedUnkeyed);
}
#[test]
fn the_invocation_asks_for_exact_identity_and_edges_only() {
let command = tmin_command(invocation());
let args: Vec<&OsStr> = command.get_args().collect();
assert!(
args.contains(&OsStr::new(ARG_EDGES_ONLY)),
"-e is upstream's own paired recommendation for AFL_TMIN_EXACT"
);
let exact = command
.get_envs()
.find(|(key, _)| *key == OsStr::new(ENV_TMIN_EXACT))
.map(|(_, value)| value);
assert_eq!(
exact,
Some(Some(OsStr::new(ENV_ENABLED))),
"without AFL_TMIN_EXACT afl-tmin returns 1 on the first crash it sees without ever comparing traces, so it will happily walk a PoC from one bug to another"
);
}
#[test]
fn the_invocation_lifts_the_memory_limit_for_a_sanitizer_build() {
let command = tmin_command(invocation());
let args: Vec<String> = command
.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect();
let at = args.iter().position(|a| a == ARG_MEMORY).unwrap();
assert_eq!(
args[at + 1],
MEM_LIMIT_UNLIMITED,
"an ASAN build reserves terabytes of address space and dies instantly under afl-tmin's default limit"
);
}
#[test]
fn the_target_comes_after_the_separator() {
let command = tmin_command(invocation());
let args: Vec<String> = command
.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect();
let at = args.iter().position(|a| a == ARG_SEPARATOR).unwrap();
assert_eq!(
args[at + 1],
PathBuf::from("/out/afl/harness").to_string_lossy()
);
}
}