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 πŸ‘‡

feat(lisdex): B96 (a)(b)(c) - the callback renderer is alive, and it still moves zero trees

CarterPerez-dev871c1932220e
diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/synth.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/synth.rs
index 7c06543a..e8b2736f 100644
--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/synth.rs
+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/synth.rs
@@ -8,14 +8,18 @@ use lisdex_surface::naming::polarity_of;
use lisdex_surface::rank::Candidate;
use lisdex_surface::signature;
use lisdex_surface::signature::{
- Analysis, Fuzzability, Param, ParamRole, Pointee, Shape, handle_key,
+ Analysis, Fuzzability, Param, ParamRole, Pointee, Prototype, Shape, handle_key,
};
use crate::plan::{
- Binding, FILLED_LOCAL, HarnessPlan, Init, OUT_LEN_LOCAL, SIZED_LEN_SUFFIX, SIZED_LOCAL, Stmt,
- Value,
+ Binding, CallbackKind, CallbackStub, FILLED_LOCAL, HarnessPlan, Init, OUT_LEN_LOCAL,
+ SIZED_LEN_SUFFIX, SIZED_LOCAL, Stmt, Value,
};
+pub const CALLBACK_STUB_PREFIX: &str = "lisdex_cb";
+pub const BYTE_SINK_SPELLINGS: [&str; 4] = ["void *", "char *", "unsigned char *", "signed char *"];
+pub const COUNT_SPELLINGS: [&str; 6] = ["int", "long", "unsigned", "size_t", "ssize_t", "short"];
+
pub const CONTEXT_LOCAL: &str = "ctx";
pub const RESULT_LOCAL: &str = "rc";
pub const MAX_POPULATED_FIELDS: usize = 4;
@@ -774,6 +778,76 @@ fn sized_by_macro(
sizing.offer(param)
}
+#[must_use]
+pub fn callback_name(index: usize) -> String {
+ format!("{CALLBACK_STUB_PREFIX}{index}")
+}
+
+fn prototype_of(param: &Param) -> Option<&Prototype> {
+ match &param.shape {
+ Shape::Pointer {
+ pointee: Pointee::Function(prototype),
+ ..
+ } => prototype.as_ref(),
+ _ => None,
+ }
+}
+
+fn spells_byte_sink(spelling: &str) -> bool {
+ let text = spelling.trim();
+ text.ends_with('*')
+ && BYTE_SINK_SPELLINGS
+ .iter()
+ .any(|prefix| text.starts_with(prefix))
+}
+
+fn spells_count(spelling: &str) -> bool {
+ let text = spelling.trim();
+ !text.contains('*')
+ && COUNT_SPELLINGS
+ .iter()
+ .any(|word| text.split_whitespace().any(|token| token == *word))
+}
+
+// A read callback is (sink, count) ADJACENT, never the first pointer in the list: libtiff's
+// `TIFFReadWriteProc` is `tmsize_t (void *, void *, tmsize_t)` where argument 0 is the opaque
+// handle and argument 1 is the sink, and both spell `void *`. Adjacency is what separates
+// them, and requiring an integral RETURN is what separates a reader from a writer's twin.
+fn read_kind(prototype: &Prototype) -> CallbackKind {
+ if prototype.returns_void() {
+ return CallbackKind::Benign;
+ }
+ for index in 0..prototype.params.len().saturating_sub(1) {
+ if spells_byte_sink(&prototype.params[index]) && spells_count(&prototype.params[index + 1])
+ {
+ return CallbackKind::ReadFromCursor {
+ buffer: index,
+ count: index + 1,
+ };
+ }
+ }
+ CallbackKind::Benign
+}
+
+fn callback_stubs(candidate: &Candidate) -> Vec<CallbackStub> {
+ candidate
+ .params
+ .iter()
+ .zip(&candidate.analysis.roles)
+ .enumerate()
+ .filter(|(_, (_, role))| **role == ParamRole::Callback)
+ .filter_map(|(index, (param, _))| {
+ let prototype = prototype_of(param)?;
+ Some(CallbackStub {
+ name: callback_name(index),
+ return_ty: prototype.returns.clone(),
+ params: prototype.params.clone(),
+ kind: read_kind(prototype),
+ })
+ })
+ .collect()
+}
+
fn bind(
index: usize,
param: &Param,
@@ -865,7 +939,16 @@ fn bind(
}
Ok(Value::Zero)
}
- ParamRole::Callback => Err(Refusal::NeedsCallback { param: label }),
+ // A stub can only be written from a PROTOTYPE. `FunctionNoPrototype` states a return
+ // type and nothing else, so a body written for it would guess the arguments the
+ // library is about to pass, and the refusal stands.
+ ParamRole::Callback => {
+ if prototype_of(param).is_some() {
+ Ok(Value::Callback(callback_name(index)))
+ } else {
+ Err(Refusal::NeedsCallback { param: label })
+ }
+ }
ParamRole::Path => Err(Refusal::PathEntry),
ParamRole::Stream => Err(Refusal::UnsupportedShape { param: label }),
ParamRole::Output
@@ -1021,6 +1104,7 @@ fn admissible(candidate: &Candidate) -> Result<(), Refusal> {
.iter()
.find(|verb| carries_word(&candidate.name, &[verb]))
&& candidate.params.iter().any(is_path_capable)
+ && !hands_over_its_io(candidate)
{
return Err(Refusal::FilesystemVerb {
verb: (*verb).to_owned(),
@@ -1053,6 +1137,10 @@ pub fn is_configurator(candidate: &Candidate) -> bool {
is_configuration_shape(&candidate.params)
}
+fn hands_over_its_io(candidate: &Candidate) -> bool {
+ candidate.analysis.roles.contains(&ParamRole::Callback)
+}
+
fn is_path_capable(param: &Param) -> bool {
matches!(
&param.shape,
@@ -1557,6 +1645,9 @@ pub fn plan_candidate_with(
let mut emitted = BTreeSet::new();
let mut base = HarnessPlan::new(candidate.name.clone()).with_include(include);
+ for stub in callback_stubs(candidate) {
+ base = base.with_callback(stub);
+ }
if let Some(statement) = indirect_extent_local(candidate) {
base = base.with(statement);
}
@@ -4482,7 +4573,7 @@ mod tests {
"read_fn",
"png_rw_ptr",
Shape::Pointer {
- pointee: Pointee::Function,
+ pointee: Pointee::Function(None),
is_const: false,
},
),
diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/extract.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/extract.rs
index a6b7ce71..15fc5005 100644
--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/extract.rs
+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/extract.rs
@@ -8,7 +8,7 @@ use std::sync::{Mutex, PoisonError};
use clang::diagnostic::{Diagnostic, Severity};
use clang::{Clang, Entity, EntityKind, Index, Type, TypeKind};
-use crate::signature::{Param, Pointee, Returns, Shape, handle_key};
+use crate::signature::{Param, Pointee, Prototype, Returns, Shape, handle_key};
static PARSE_LOCK: Mutex<()> = Mutex::new(());
thread_local! {
@@ -226,6 +226,20 @@ fn record_name(ty: &Type) -> String {
.unwrap_or_else(|| ty.get_display_name())
}
+fn prototype_of(ty: &Type) -> Option<Prototype> {
+ Some(Prototype {
+ returns: ty
+ .get_result_type()?
+ .get_canonical_type()
+ .get_display_name(),
+ params: ty
+ .get_argument_types()?
+ .iter()
+ .map(|argument| argument.get_canonical_type().get_display_name())
+ .collect(),
+ })
+}
+
fn pointee_of(ty: &Type) -> Pointee {
match ty.get_kind() {
TypeKind::UChar => Pointee::UnsignedChar,
@@ -233,7 +247,8 @@ fn pointee_of(ty: &Type) -> Pointee {
TypeKind::CharS | TypeKind::CharU => Pointee::Char,
TypeKind::Void => Pointee::Void,
TypeKind::Record => Pointee::Record(record_name(ty)),
- TypeKind::FunctionPrototype | TypeKind::FunctionNoPrototype => Pointee::Function,
+ TypeKind::FunctionPrototype => Pointee::Function(prototype_of(ty)),
+ TypeKind::FunctionNoPrototype => Pointee::Function(None),
TypeKind::Pointer => ty.get_pointee_type().map_or(Pointee::Other, |inner| {
Pointee::Pointer(Box::new(pointee_of(&inner.get_canonical_type())))
}),
@@ -810,7 +825,7 @@ pub fn parse_header(path: &Path, options: &ParseOptions) -> Result<Vec<Declared>
#[cfg(test)]
mod tests {
use super::*;
- use crate::signature::{Pointee, Shape};
+ use crate::signature::{Pointee, Prototype, Shape};
use std::path::PathBuf;
fn header(label: &str, body: &str) -> PathBuf {
@@ -1399,9 +1414,37 @@ int png_image_finish_read(png_image *image, void *buffer);
assert_eq!(
function.params[2].shape,
Shape::Pointer {
- pointee: Pointee::Function,
+ pointee: Pointee::Function(Some(Prototype {
+ returns: "void".to_owned(),
+ params: vec![
+ "struct ctx *".to_owned(),
+ "unsigned char *".to_owned(),
+ "unsigned long".to_owned(),
+ ],
+ })),
is_const: false,
- }
+ },
+ "a callback that is recognised but carries no prototype cannot have a stub body \
+ written for it, which is the whole reason B96 needed the payload"
+ );
+ }
+
+ #[test]
+ fn a_callback_with_no_prototype_carries_no_prototype() {
+ let found = parse(
+ "callbacknoproto",
+ "struct ctx;\n\
+ void set_read(struct ctx *c, void (*fn)());\n",
+ );
+ let function = named(&found, "set_read");
+ assert_eq!(
+ function.params[1].shape,
+ Shape::Pointer {
+ pointee: Pointee::Function(None),
+ is_const: false,
+ },
+ "an unprototyped function pointer states a return type and nothing else, so \
+ guessing its arguments is exactly what the refusal must keep refusing"
);
}
diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/signature.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/signature.rs
index 0baf915c..04dd3197 100644
--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/signature.rs
+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/signature.rs
@@ -19,6 +19,8 @@ pub const AFFINITY_SHARED_TOKENS: usize = 100;
pub const STREAM_RECORDS: &[&str] = &["FILE", "_IO_FILE", "__sFILE"];
+pub const VOID_SPELLING: &str = "void";
+
pub const LENGTH_NAMES: &[&str] = &[
"size",
"len",
@@ -102,6 +104,19 @@ impl Fuzzability {
}
}
+#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
+pub struct Prototype {
+ pub returns: String,
+ pub params: Vec<String>,
+}
+
+impl Prototype {
+ #[must_use]
+ pub fn returns_void(&self) -> bool {
+ self.returns == VOID_SPELLING
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub enum Pointee {
UnsignedChar,
@@ -110,7 +125,7 @@ pub enum Pointee {
Void,
Integral,
Record(String),
- Function,
+ Function(Option<Prototype>),
// What the second indirection points AT, because the answer decides whether a double
// pointer is a slot the library fills or a buffer the caller must size, and collapsing
// it to a leaf made those two indistinguishable. `png_bytep *` and `struct
@@ -479,7 +494,7 @@ pub fn registered_stream(params: &[Param]) -> Option<String> {
matches!(
&param.shape,
Shape::Pointer {
- pointee: Pointee::Function,
+ pointee: Pointee::Function(_),
..
}
)
@@ -625,7 +640,7 @@ fn lone_pointer_is_path(param: &Param) -> bool {
fn provisional_role(param: &Param) -> ParamRole {
match &param.shape {
Shape::Pointer { pointee, is_const } => match pointee {
- Pointee::Function => ParamRole::Callback,
+ Pointee::Function(_) => ParamRole::Callback,
Pointee::Record(name) if STREAM_RECORDS.contains(&name.as_str()) => ParamRole::Stream,
Pointee::Record(_) | Pointee::Pointer(_) | Pointee::Other => ParamRole::Context,
byte if byte.is_byte_sized() => {
@@ -817,7 +832,7 @@ mod tests {
let params = [
pointer("handle", Pointee::Record("png_struct".to_owned()), false),
pointer("io_ptr", Pointee::Void, false),
- pointer("read_fn", Pointee::Function, false),
+ pointer("read_fn", Pointee::Function(None), false),
];
let analysis = analyze(&params);
assert_eq!(analysis.roles[2], ParamRole::Callback);
@@ -1054,7 +1069,7 @@ mod tests {
let params = [
pointer("png_ptr", Pointee::Record("png_struct".to_owned()), false),
pointer("io_ptr", Pointee::Void, false),
- pointer("read_fn", Pointee::Function, false),
+ pointer("read_fn", Pointee::Function(None), false),
];
assert_eq!(registered_stream(&params).as_deref(), Some("png_struct"));
}