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 👇

13.7 KB
Raw Blame
// ©AngelaMos | 2026
// plan.rs

pub const FUZZ_DATA: &str = "data";
pub const FUZZ_SIZE: &str = "size";
pub const CURSOR_STRUCT: &str = "lisdex_cursor";
pub const CURSOR_LOCAL: &str = "lisdex_input";
pub const CALLBACK_BUDGET: &str = "LISDEX_CALLBACK_BUDGET";
pub const MAX_CALLBACK_CALLS: u32 = 4096;
pub const NUL_COPY_LOCAL: &str = "lisdex_text";
pub const OUT_LOCAL: &str = "lisdex_out";
pub const OUT_LEN_LOCAL: &str = "lisdex_out_len";
pub const OUT_CAPACITY: &str = "LISDEX_OUT_CAPACITY";
pub const MAX_OUT_BYTES: usize = 65536;
pub const AUX_LOCAL: &str = "lisdex_aux";
pub const FILLED_LOCAL: &str = "lisdex_filled";
pub const SIZED_LOCAL: &str = "lisdex_sized";
pub const SIZED_LEN_SUFFIX: &str = "_len";
pub const AUX_CAPACITY: &str = "LISDEX_AUX_CAPACITY";
// lz4's own decompress_fuzzer.c uses `64 * 1024 - 1` for its large external dictionary, so
// this is that size rather than a round number: a dictionary at or above 64 KiB takes a
// different path inside LZ4 than one below it, and the authors picked the boundary.
pub const MAX_AUX_BYTES: usize = 64 * 1024 - 1;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Value {
    Data { cast: Option<String> },
    Size,
    Null,
    Zero,
    Literal(String),
    Local(String),
    AddressOf(String),
    AddressOfField { local: String, field: String },
    Callback(String),
    Cursor,
    NulTerminated,
    // A caller-allocated output buffer belongs to the HARNESS, so its extent is not
    // something to infer about the library - it is something the harness declares and the
    // library is obliged to honour. That is what separates it from the out-params that
    // must stay refused: png_read_image and tj3Decompress8 take no capacity at all, so
    // the size is knowledge the caller is expected to already hold.
    OutBuffer { cast: Option<String> },
    OutCapacity,
    // A SECOND readable byte buffer is a second input, and the fuzzer supplies one. Handing
    // it the same pointer as the first is not a memory-safety lie - both reads are in bounds
    // - but it is not what the authors do, and lz4's own fuzzer says why in a comment:
    // `/* Prepare the dictionary. The data doesn't matter for decompression. */` above a
    // `memset(dict, 0, dictSize)`. What matters about an auxiliary buffer is its SIZE and
    // that it is distinct memory, not its contents.
    AuxBuffer { cast: Option<String> },
    AuxCapacity,
    // A buffer whose extent no PARAMETER states but a MACRO does. It is not the same thing as
    // `OutBuffer`: that one is a capacity the harness invented and the library is under
    // contract to honour, while this one is a size the header itself computes from a record
    // the library has already filled in. `PNG_IMAGE_SIZE(image)` is libpng saying, in its own
    // header, exactly how many bytes `png_image_finish_read` is going to write.
    SizedBuffer { local: String, cast: Option<String> },
    // A NUMBER the header states, which is a different claim from `Zero`. `Zero` is a Config
    // pinned because nothing could say what it should be - the invented constant an upward step
    // may not copy. This one is `PNG_IMAGE_ROW_STRIDE(image)`: libpng computing the stride from
    // the record it just filled, which is the same knowledge `SizedBuffer` gets its length from.
    Stated(String),
}

impl Value {
    // The corpus is the BYTES, so a length alone does not count. `OutBuffer`/`OutCapacity`
    // describe memory the harness allocated and are the two values that made the defect
    // below look like a bound argument.
    #[must_use]
    pub fn carries_corpus(&self) -> bool {
        matches!(
            self,
            Value::Data { .. } | Value::Cursor | Value::NulTerminated
        )
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Init {
    Uninitialised,
    Null,
    ZeroBytes,
    Capacity,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Stmt {
    Declare {
        ty: String,
        name: String,
        init: Init,
    },
    SetField {
        local: String,
        field: String,
        value: Value,
    },
    Call {
        function: String,
        args: Vec<Value>,
        capture: Option<Binding>,
    },
    Discard {
        local: String,
    },
    BailIfNull {
        local: String,
    },
    BailIfZero {
        local: String,
    },
    // Allocated where it is USED rather than in the prologue, and that placement is the whole
    // reason it is a statement instead of a scaffolding flag. The size comes from a macro read
    // over a record the library fills in, so it states nothing until the call that fills it has
    // run - `PNG_IMAGE_SIZE(image)` before `png_image_begin_read_from_memory` is zero.
    //
    // `frees` names the sized buffers allocated BEFORE this one, because they are the only ones
    // in scope at this bail. The prologue's own three are emitted from the plan's flags.
    AllocSized {
        local: String,
        length: String,
        size: String,
        frees: Vec<String>,
    },
    FreeSized {
        local: String,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Binding {
    pub ty: String,
    pub name: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallbackStub {
    pub name: String,
    pub return_ty: String,
    pub params: Vec<String>,
    pub kind: CallbackKind,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallbackKind {
    Benign,
    ReadFromCursor { buffer: usize, count: usize },
}

// Four independent scaffolding needs, each derived from the arguments the plan actually
// binds and each read by name in the emitter. Not the boolean-blindness the lint is aimed at
// - there is no call site that passes them positionally - and `SurfaceArgs` carries the same
// allow for the same reason.
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(clippy::struct_excessive_bools)]
pub struct HarnessPlan {
    pub entry: String,
    pub includes: Vec<String>,
    pub needs_cursor: bool,
    pub needs_nul_copy: bool,
    pub needs_out_buffer: bool,
    pub needs_aux_buffer: bool,
    pub callbacks: Vec<CallbackStub>,
    pub body: Vec<Stmt>,
    // Named separately from `body` because "which calls came from the author's own sequence
    // rather than from our rules" is the one thing a reader of the emitted C cannot recover,
    // and it is what has to be asserted to prove the replay happened at all.
    pub replayed: Vec<String>,
    // The same argument, for the calls the author made AFTER the entry point. These are kept
    // apart from `replayed` because the two are judged differently: a replayed call is setup
    // the entry point needs, while an extension is a longer sequence that has to earn its
    // place against the shorter one it extends (D4 oracle 3b).
    pub extended: Vec<String>,
}

impl HarnessPlan {
    #[must_use]
    pub fn new(entry: impl Into<String>) -> Self {
        Self {
            entry: entry.into(),
            includes: Vec::new(),
            needs_cursor: false,
            needs_nul_copy: false,
            needs_out_buffer: false,
            needs_aux_buffer: false,
            callbacks: Vec::new(),
            body: Vec::new(),
            replayed: Vec::new(),
            extended: Vec::new(),
        }
    }

    #[must_use]
    pub fn with_include(mut self, header: impl Into<String>) -> Self {
        self.includes.push(header.into());
        self
    }

    #[must_use]
    pub fn with_callback(mut self, stub: CallbackStub) -> Self {
        if matches!(stub.kind, CallbackKind::ReadFromCursor { .. }) {
            self.needs_cursor = true;
        }
        self.callbacks.push(stub);
        self
    }

    #[must_use]
    pub fn with(mut self, statement: Stmt) -> Self {
        if let Stmt::Call { args, .. } = &statement {
            if args.contains(&Value::Cursor) {
                self.needs_cursor = true;
            }
            if args.contains(&Value::NulTerminated) {
                self.needs_nul_copy = true;
            }
            if args
                .iter()
                .any(|value| matches!(value, Value::OutBuffer { .. }))
            {
                self.needs_out_buffer = true;
            }
            if args
                .iter()
                .any(|value| matches!(value, Value::AuxBuffer { .. }))
            {
                self.needs_aux_buffer = true;
            }
        }
        self.body.push(statement);
        self
    }

    // A harness whose finished body never mentions the fuzzer's input is not a harness, it
    // is a constant program: every seed drives identical coverage and any crash it reports
    // is one we manufactured. libarchive's `archive_read_data(struct archive *, void *,
    // size_t)` reached rank 1 and EMITTED, because `struct archive` is a stream record so
    // the signature grades StreamDriven, and StreamDriven means the corpus arrives through
    // some other call - which the replay then failed to bring. The six calls it did replay
    // are all handle plumbing and the emitted C referenced neither `data` nor `size`.
    //
    // The test belongs on the finished body rather than on the signature, because whether
    // the corpus arrives at all is decided by what the replay brought with it, and that is
    // not knowable until the plan is assembled. A cursor-reading callback counts: it is how
    // a genuinely stream-driven harness feeds the library.
    #[must_use]
    pub fn binds_corpus(&self) -> bool {
        if self.needs_cursor || self.needs_nul_copy {
            return true;
        }
        self.body.iter().any(|statement| match statement {
            Stmt::Call { args, .. } => args.iter().any(Value::carries_corpus),
            Stmt::SetField { value, .. } => value.carries_corpus(),
            _ => false,
        })
    }
}

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

    // The buffer and the capacity both belong to the HARNESS, so a body built only from
    // them is a constant program however many arguments it resolved. This is the exact
    // argument list `archive_read_data` emitted.
    #[test]
    fn a_body_holding_only_the_harnesss_own_buffer_does_not_bind_the_corpus() {
        let plan = HarnessPlan::new("archive_read_data").with(Stmt::Call {
            function: "archive_read_data".to_owned(),
            args: vec![
                Value::Local("ctx".to_owned()),
                Value::OutBuffer { cast: None },
                Value::OutCapacity,
            ],
            capture: None,
        });
        assert!(!plan.binds_corpus());
    }

    // Isolates the value test from the statement walk: same shape, one argument swapped.
    #[test]
    fn the_same_body_binds_the_corpus_once_one_argument_is_the_data() {
        let plan = HarnessPlan::new("archive_read_open_memory").with(Stmt::Call {
            function: "archive_read_open_memory".to_owned(),
            args: vec![
                Value::Local("ctx".to_owned()),
                Value::Data { cast: None },
                Value::Size,
            ],
            capture: None,
        });
        assert!(plan.binds_corpus());
    }

    // Isolates the statement walk from the value test: zlib's `z_stream` shape hands the
    // corpus over by assignment, never as an argument, so a walk that only read Call args
    // would refuse every stream decoder in the set.
    #[test]
    fn a_corpus_delivered_by_field_assignment_still_counts_as_bound() {
        let plan = HarnessPlan::new("inflate").with(Stmt::SetField {
            local: "ctx".to_owned(),
            field: "next_in".to_owned(),
            value: Value::Data { cast: None },
        });
        assert!(plan.binds_corpus());
    }

    // A length carries no bytes. Counting it would have let `archive_read_data` through on
    // its capacity argument the moment that argument was spelled `Size` instead.
    #[test]
    fn the_corpus_length_on_its_own_is_not_the_corpus() {
        let plan = HarnessPlan::new("configure").with(Stmt::Call {
            function: "configure".to_owned(),
            args: vec![Value::Local("ctx".to_owned()), Value::Size],
            capture: None,
        });
        assert!(!plan.binds_corpus());
    }

    #[test]
    fn a_read_callback_forces_the_cursor_in() {
        let plan = HarnessPlan::new("png_read_info").with_callback(CallbackStub {
            name: "lisdex_read".to_owned(),
            return_ty: "void".to_owned(),
            params: vec!["png_structp".to_owned(), "png_bytep".to_owned()],
            kind: CallbackKind::ReadFromCursor {
                buffer: 1,
                count: 2,
            },
        });
        assert!(plan.needs_cursor);
    }

    #[test]
    fn a_benign_callback_does_not_force_the_cursor_in() {
        let plan = HarnessPlan::new("expat_parse").with_callback(CallbackStub {
            name: "lisdex_on_element".to_owned(),
            return_ty: "void".to_owned(),
            params: vec!["void *".to_owned()],
            kind: CallbackKind::Benign,
        });
        assert!(!plan.needs_cursor);
    }

    #[test]
    fn passing_the_cursor_to_a_call_forces_it_in() {
        let plan = HarnessPlan::new("png_read_info").with(Stmt::Call {
            function: "png_set_read_fn".to_owned(),
            args: vec![
                Value::Local("png".to_owned()),
                Value::Cursor,
                Value::Callback("lisdex_read".to_owned()),
            ],
            capture: None,
        });
        assert!(plan.needs_cursor);
    }

    #[test]
    fn a_plain_plan_needs_no_cursor() {
        let plan = HarnessPlan::new("png_image_begin_read_from_memory")
            .with_include("png.h")
            .with(Stmt::Declare {
                ty: "png_image".to_owned(),
                name: "image".to_owned(),
                init: Init::ZeroBytes,
            });
        assert!(!plan.needs_cursor);
        assert_eq!(plan.includes, vec!["png.h".to_owned()]);
    }
}