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
// ladder.rs
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use crate::harness::{self, Harness, HarnessError};
use crate::naming::{Polarity, polarity_of};
pub const OSS_FUZZ_PROJECTS: &str = "projects";
// Opening a file is the discriminator, not doing I/O. libpng's `pngtest.c` calls `fopen`
// and then hands the FILE to `png_init_io`, which is the shallow-state trap Hopper names
// and the crash lisdex already had; zlib's `examples/zpipe.c` does plenty of `fread` but
// never opens anything, and it is the consumer whose order signal we want. A rule that
// banned all stdio would have thrown zpipe.c away with pngtest.c.
pub const FILE_OPENING_CALLS: &[&str] = &[
"fopen", "fopen64", "freopen", "fdopen", "tmpfile", "open", "open64", "openat", "creat",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub enum Tier {
InTreeFuzzTarget,
OssFuzzTarget,
MemoryConsumer,
FrequentConsumer,
}
impl Tier {
#[must_use]
pub fn describe(self) -> &'static str {
match self {
Tier::InTreeFuzzTarget => "the library's own in-tree fuzz target",
Tier::OssFuzzTarget => "the fuzz target google/oss-fuzz ships for this library",
Tier::MemoryConsumer => "an in-tree consumer that never opens a file",
Tier::FrequentConsumer => "the in-tree consumer whose calls are the most common",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct Sequence {
pub tier: Tier,
pub origin: PathBuf,
pub calls: Vec<String>,
}
impl Sequence {
#[must_use]
pub fn names(&self) -> &[String] {
&self.calls
}
#[must_use]
pub fn contains(&self, name: &str) -> bool {
self.calls.iter().any(|call| call == name)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
pub struct Ladder {
pub chosen: Option<Sequence>,
pub fuzz_targets: usize,
pub consumers: usize,
}
impl Ladder {
#[must_use]
pub fn contains(&self, name: &str) -> bool {
self.chosen
.as_ref()
.is_some_and(|sequence| sequence.contains(name))
}
}
fn opens_a_file(calls: &[String]) -> bool {
calls
.iter()
.any(|call| FILE_OPENING_CALLS.contains(&call.as_str()))
}
// Frequency is the LAST tier and it is never averaged across files, because averaging is
// the mechanism that fails: over libpng's consumers `png_init_io` appears in 68% and
// `png_set_read_fn` in 56%, so the merged answer points straight at the SEGV. Here it only
// picks WHICH single file to copy, and only after the three shaped tiers came up empty.
fn commonness(calls: &[String], across: &BTreeMap<String, usize>) -> usize {
calls
.iter()
.map(|call| across.get(call).copied().unwrap_or_default())
.sum()
}
fn frequencies(files: &[Harness]) -> BTreeMap<String, usize> {
let mut counted = BTreeMap::new();
for file in files {
for call in &file.calls {
*counted.entry(call.clone()).or_insert(0) += 1;
}
}
counted
}
pub const DIRECTION_PURE_READ: u8 = 3;
pub const DIRECTION_NEUTRAL: u8 = 2;
pub const DIRECTION_ROUND_TRIP: u8 = 1;
pub const DIRECTION_PURE_WRITE: u8 = 0;
// A VERDICT, never a sum. Summing read words minus write words is dominated by how much a
// file does rather than which direction it does it in: lz4's `round_trip_stream_fuzzer.c`
// makes 49 calls and out-summed `decompress_fuzzer.c`, so the ladder handed a decode fuzzer
// the call order of a file that compresses first. One write-side call is enough to say this
// file is not a decoder, however many decode calls sit beside it.
//
// Only the library's OWN calls vote. `fread` carries the word "read" and nothing else in
// brotli's `run_decode_fuzzer.c` - a runner that fopens a file and calls the real target -
// carries any direction word at all, so counting libc graded a file-reading runner a purer
// decoder than `decode_fuzzer.c` and it won the tier on length.
fn direction(calls: &[String], declared: &BTreeSet<String>) -> (u8, usize) {
let mut reads = 0;
let mut writes = 0;
for call in calls.iter().filter(|call| declared.contains(call.as_str())) {
// The trailing-digit strip used to live here as a local workaround, because
// `polarity_of` could not see the verb in `tj3Compress8` and touching it would have
// moved producer selection too. It is in `carries_word` now (B70), measured at 13
// verdict gains and 0 regressions, so the local copy is deleted rather than kept.
match polarity_of(call) {
Some(Polarity::Read) => reads += 1,
Some(Polarity::Write) => writes += 1,
None => {}
}
}
let verdict = match (reads > 0, writes > 0) {
(true, false) => DIRECTION_PURE_READ,
(false, false) => DIRECTION_NEUTRAL,
(true, true) => DIRECTION_ROUND_TRIP,
(false, true) => DIRECTION_PURE_WRITE,
};
// The count breaks ties INSIDE a verdict and never across one, so it can prefer
// libjpeg-turbo's `decompress.cc` over the equally-pure `transform.cc` without ever
// letting a big round-trip file outweigh a small decoder.
(verdict, reads)
}
// Shape outranks frequency at EVERY tier, which is why not-opening-a-file is the first key
// rather than a filter applied only to consumers. brotli ships two files carrying the
// LibFuzzer entry symbol and one of them is `run_decode_fuzzer.c`, a `main()` that fopens a
// path and calls the real target - a runner, not a harness, and it won its tier on length.
type Shape = (bool, (u8, usize), usize, usize);
fn shape_rank(
file: &Harness,
across: &BTreeMap<String, usize>,
declared: &BTreeSet<String>,
) -> Shape {
(
!opens_a_file(&file.calls),
direction(&file.calls, declared),
commonness(&file.calls, across),
file.calls.len(),
)
}
fn best_of(
files: Vec<Harness>,
tier: Tier,
across: &BTreeMap<String, usize>,
declared: &BTreeSet<String>,
) -> Option<Sequence> {
let mut best: Option<(Shape, Harness)> = None;
for file in files {
let shape = shape_rank(&file, across, declared);
// The shortest path wins ties, so a rerun on the same tree never returns a
// different sequence.
let better = match &best {
None => true,
Some((top, chosen)) => shape > *top || (shape == *top && file.path < chosen.path),
};
if better {
best = Some((shape, file));
}
}
best.map(|(_, file)| Sequence {
tier,
origin: file.path,
calls: file.calls,
})
}
fn oss_fuzz_targets(checkout: &Path, project: &str) -> Result<Vec<Harness>, HarnessError> {
let directory = checkout.join(OSS_FUZZ_PROJECTS).join(project);
if !directory.is_dir() {
return Ok(Vec::new());
}
harness::discover(&directory)
}
// Four tiers, first hit wins, and the order is the finding rather than a preference: raw
// frequency alone works on libarchive (97.2% of consumers), zlib (11/11) and libjpeg-turbo
// (17/17) and FAILS on libpng, so a design that reached for it first would be right three
// times out of four and wrong on the library the whole niche is named after.
pub fn select(
source: &Path,
fuzz_targets: &[Harness],
oss_fuzz: Option<&Path>,
project: &str,
declared: &BTreeSet<String>,
) -> Result<Ladder, HarnessError> {
let consumers = harness::discover_consumers(source)?;
let across = frequencies(&consumers);
let mut chosen = best_of(
fuzz_targets.to_vec(),
Tier::InTreeFuzzTarget,
&frequencies(fuzz_targets),
declared,
);
if chosen.is_none()
&& let Some(checkout) = oss_fuzz
{
let external = oss_fuzz_targets(checkout, project)?;
chosen = best_of(
external.clone(),
Tier::OssFuzzTarget,
&frequencies(&external),
declared,
);
}
if chosen.is_none() {
let memory: Vec<Harness> = consumers
.iter()
.filter(|file| !opens_a_file(&file.calls))
.cloned()
.collect();
chosen = best_of(memory, Tier::MemoryConsumer, &across, declared);
}
if chosen.is_none() {
chosen = best_of(consumers.clone(), Tier::FrequentConsumer, &across, declared);
}
Ok(Ladder {
chosen,
fuzz_targets: fuzz_targets.len(),
consumers: consumers.len(),
})
}
#[cfg(test)]
mod tests {
use super::*;
fn mined(path: &str, calls: &[&str]) -> Harness {
Harness {
path: PathBuf::from(path),
calls: calls.iter().map(|call| (*call).to_owned()).collect(),
}
}
// Every name a fixture mentions counts as declared unless a test says otherwise, so
// the direction verdict sees the library calls it is meant to weigh.
fn declaring(names: &[&str]) -> BTreeSet<String> {
names.iter().map(|name| (*name).to_owned()).collect()
}
fn tree(label: &str, files: &[(&str, &str)]) -> PathBuf {
let root = lisdex_core::scratch::path(&format!("surface-ladder-{label}"));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
for (path, body) in files {
let full = root.join(path);
std::fs::create_dir_all(full.parent().unwrap()).unwrap();
std::fs::write(&full, body).unwrap();
}
root
}
#[test]
fn the_decode_target_beats_the_compress_targets_beside_it() {
let root = tree("polarity", &[]);
let targets = vec![
mined("ossfuzz/compress_fuzzer.c", &["LZ4_compress_default"]),
mined("ossfuzz/decompress_fuzzer.c", &["LZ4_decompress_safe"]),
];
let ladder = select(
&root,
&targets,
None,
"lz4",
&declaring(&["LZ4_compress_default", "LZ4_decompress_safe"]),
)
.unwrap();
let chosen = ladder.chosen.unwrap();
assert_eq!(chosen.tier, Tier::InTreeFuzzTarget);
assert!(
chosen.origin.ends_with("decompress_fuzzer.c"),
"alphabetical order and file order both lead with the compressor: {chosen:?}"
);
}
// The measured failure, not a hypothetical one: lz4's real round_trip_stream_fuzzer.c
// mines 49 calls, so under a summed read-minus-write score it beat decompress_fuzzer.c
// outright and the ladder returned the compressor's call order. The fixture keeps that
// shape - the round trip carries MORE decode calls than the pure decoder and wins every
// other key in shape_rank - so only the direction verdict can decide it.
#[test]
fn a_round_trip_target_loses_to_a_pure_decoder_it_outweighs_on_every_other_key() {
let root = tree("roundtrip", &[]);
let targets = vec![
mined(
"ossfuzz/a_round_trip_fuzzer.c",
&[
"LZ4_decompress_safe",
"LZ4_decompress_safe_partial",
"LZ4_decompress_safe_usingDict",
"LZ4_compress_default",
],
),
mined("ossfuzz/z_decompress_fuzzer.c", &["LZ4_decompress_safe"]),
];
let chosen = select(
&root,
&targets,
None,
"lz4",
&declaring(&[
"LZ4_decompress_safe",
"LZ4_decompress_safe_partial",
"LZ4_decompress_safe_usingDict",
"LZ4_compress_default",
]),
)
.unwrap()
.chosen
.unwrap();
assert!(
chosen.origin.ends_with("z_decompress_fuzzer.c"),
"one compress call is enough to disqualify a file, however many decode calls \
sit beside it: {chosen:?}"
);
}
#[test]
fn a_consumer_that_opens_a_file_loses_to_one_that_does_not() {
let root = tree(
"memory",
&[
(
"contrib/pngtest.c",
"int main(void) { FILE *f = fopen(\"x\", \"rb\"); png_init_io(p, f); \
png_read_image(p); return 0; }",
),
(
"contrib/pngmem.c",
"int main(void) { png_set_read_fn(p, &s, cb); png_read_info(p, i); return 0; }",
),
],
);
let chosen = select(
&root,
&[],
None,
"libpng",
&declaring(&[
"png_init_io",
"png_read_image",
"png_set_read_fn",
"png_read_info",
]),
)
.unwrap()
.chosen
.unwrap();
assert_eq!(chosen.tier, Tier::MemoryConsumer);
assert!(
chosen.origin.ends_with("pngmem.c"),
"the fopen consumer carries more read words and would win on any other key: \
{chosen:?}"
);
assert!(!chosen.contains("png_init_io"), "{chosen:?}");
}
#[test]
fn an_in_tree_fuzz_target_outranks_every_consumer() {
let root = tree(
"tiers",
&[(
"examples/zpipe.c",
"int main(void) { inflateInit(&s); inflate(&s, 0); inflateEnd(&s); return 0; }",
)],
);
let targets = vec![mined("fuzz/f.c", &["uncompress"])];
let ladder = select(
&root,
&targets,
None,
"zlib",
&declaring(&["uncompress", "inflate", "inflateInit", "inflateEnd"]),
)
.unwrap();
let chosen = ladder.chosen.as_ref().unwrap();
assert_eq!(chosen.tier, Tier::InTreeFuzzTarget);
assert_eq!(ladder.consumers, 1, "the consumer was still counted");
}
#[test]
fn a_tree_with_no_fuzz_target_falls_to_its_consumers() {
let root = tree(
"consumer",
&[(
"examples/zpipe.c",
"int main(void) { inflateInit(&s); inflate(&s, 0); inflateEnd(&s); return 0; }",
)],
);
let chosen = select(
&root,
&[],
None,
"zlib",
&declaring(&["inflate", "inflateInit", "inflateEnd"]),
)
.unwrap()
.chosen
.unwrap();
assert_eq!(chosen.tier, Tier::MemoryConsumer);
assert_eq!(
chosen.names(),
["inflateInit", "inflate", "inflateEnd"],
"the author initialises before inflating and that order is the whole point"
);
}
#[test]
fn the_oss_fuzz_checkout_is_only_read_for_the_project_asked_for() {
let root = tree("ossfuzz", &[]);
let checkout = tree(
"ossfuzz-checkout",
&[
(
"projects/zlib/zlib_uncompress_fuzzer.cc",
"int LLVMFuzzerTestOneInput(const uint8_t *d, size_t n) { uncompress(a, b, d, n); return 0; }",
),
(
"projects/libpng/libpng_read_fuzzer.cc",
"int LLVMFuzzerTestOneInput(const uint8_t *d, size_t n) { png_read_info(p, i); return 0; }",
),
],
);
let chosen = select(
&root,
&[],
Some(&checkout),
"zlib",
&declaring(&["uncompress", "png_read_info"]),
)
.unwrap()
.chosen
.unwrap();
assert_eq!(chosen.tier, Tier::OssFuzzTarget);
assert!(chosen.contains("uncompress"), "{chosen:?}");
assert!(!chosen.contains("png_read_info"), "{chosen:?}");
}
#[test]
fn a_checkout_without_the_project_is_not_a_hit() {
let root = tree("nomatch", &[]);
let checkout = tree(
"nomatch-checkout",
&[(
"projects/libpng/libpng_read_fuzzer.cc",
"int LLVMFuzzerTestOneInput(const uint8_t *d, size_t n) { png_read_info(p, i); return 0; }",
)],
);
let ladder = select(
&root,
&[],
Some(&checkout),
"zlib",
&declaring(&["png_read_info"]),
)
.unwrap();
assert!(ladder.chosen.is_none(), "{ladder:?}");
}
// Isolates the file-opening key AT TIER 1, where the memory-consumer filter cannot
// reach. Gutting the key alone left every other control green: the consumer test is
// alibied by that filter, and brotli's real runner is already demoted by the
// declared-only rule. Both targets here are pure readers with the same declared read
// count, so direction ties and the one that fopens is longer - it wins every later key.
#[test]
fn a_fuzz_target_that_opens_a_file_loses_even_when_it_reads_as_much() {
let root = tree("openkey", &[]);
let targets = vec![
mined(
"fuzz/a_via_file.c",
&["fopen", "png_read_info", "png_read_end"],
),
mined("fuzz/z_via_memory.c", &["png_read_info", "png_read_end"]),
];
let chosen = select(
&root,
&targets,
None,
"libpng",
&declaring(&["png_read_info", "png_read_end"]),
)
.unwrap()
.chosen
.unwrap();
assert!(
chosen.origin.ends_with("z_via_memory.c"),
"a target that opens a file teaches an order we cannot replay: {chosen:?}"
);
}
// Isolates the trailing-digit strip on its own. `identifier_words` splits
// `tj3Compress8` into ["tj3", "Compress8"], so without the strip the compressor's own
// fuzz target carries NO write signal, `tj3LoadImage8` gives it a read one, and it
// grades a pure decoder. The decoder here is deliberately the shorter, less common file
// so nothing but the direction verdict can save it.
#[test]
fn a_version_digit_does_not_hide_the_word_compress() {
let root = tree("digits", &[]);
let targets = vec![
mined(
"fuzz/a_compress.cc",
&["tj3Compress8", "tj3LoadImage8", "tj3Init", "tj3Destroy"],
),
mined("fuzz/z_decompress.cc", &["tj3Decompress8"]),
];
let chosen = select(
&root,
&targets,
None,
"libjpeg-turbo",
&declaring(&[
"tj3Compress8",
"tj3LoadImage8",
"tj3Init",
"tj3Destroy",
"tj3Decompress8",
]),
)
.unwrap()
.chosen
.unwrap();
assert!(
chosen.origin.ends_with("z_decompress.cc"),
"tj3Compress8 must read as a write call: {chosen:?}"
);
}
// Isolates the declared-only filter. `fread` carries the word "read", and it is the
// ONLY direction word in brotli's `run_decode_fuzzer.c` - a runner, not a harness - so
// counting libc graded it a pure decoder. The runner is longer and would win every
// later key, and it is given no fopen here so the file-opening rule cannot alibi this.
#[test]
fn libc_does_not_vote_on_which_way_a_target_reads() {
let root = tree("libc", &[]);
let targets = vec![
mined(
"fuzz/a_runner.c",
&["fread", "malloc", "memcpy", "free", "fclose"],
),
mined("fuzz/z_decode.c", &["BrotliDecoderDecompressStream"]),
];
let chosen = select(
&root,
&targets,
None,
"brotli",
&declaring(&["BrotliDecoderDecompressStream"]),
)
.unwrap()
.chosen
.unwrap();
assert!(
chosen.origin.ends_with("z_decode.c"),
"only the library's own calls may set the direction: {chosen:?}"
);
}
#[test]
fn a_tree_with_nothing_to_mine_yields_no_sequence_rather_than_an_error() {
let root = tree("empty", &[("src/lib.c", "int helper(void) { return 0; }")]);
let ladder = select(&root, &[], None, "lib", &declaring(&["helper"])).unwrap();
assert!(ladder.chosen.is_none());
assert_eq!(ladder.consumers, 0);
}
}