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
feat(lisdex): M1 walking skeleton - magma libpng gate re-finds PNG003
CarterPerez-dev3134e2df8337
diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.lock b/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.lockindex 3355e1f2..c257645d 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.lock+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.lock@@ -2,13 +2,293 @@# It is not intended for manual editing.version = 4+[[package]]+name = "ahash"+version = "0.8.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"+dependencies = [+ "cfg-if",+ "once_cell",+ "version_check",+ "zerocopy",+]++[[package]]+name = "anstream"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"+dependencies = [+ "anstyle",+ "anstyle-parse",+ "anstyle-query",+ "anstyle-wincon",+ "colorchoice",+ "is_terminal_polyfill",+ "utf8parse",+]++[[package]]+name = "anstyle"+version = "1.0.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"++[[package]]+name = "anstyle-parse"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"+dependencies = [+ "utf8parse",+]++[[package]]+name = "anstyle-query"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"+dependencies = [+ "windows-sys",+]++[[package]]+name = "anstyle-wincon"+version = "3.0.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"+dependencies = [+ "anstyle",+ "once_cell_polyfill",+ "windows-sys",+]++[[package]]+name = "bitflags"+version = "2.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"++[[package]]+name = "block-buffer"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"+dependencies = [+ "generic-array",+]++[[package]]+name = "cc"+version = "1.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5add81bb678e6cb321aff7fa0dc7689ad82b112dbc032cea19f91d6b8e3582b9"+dependencies = [+ "find-msvc-tools",+ "shlex",+]++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "clap"+version = "4.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d91e0c145792ef73a6ad36d27c75ac09f1832222a3c209689d90f534685ee5b7"+dependencies = [+ "clap_builder",+ "clap_derive",+]++[[package]]+name = "clap_builder"+version = "4.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f09628afdcc538b57f3c6341e9c8e9970f18e4a481690a64974d7023bd33548b"+dependencies = [+ "anstream",+ "anstyle",+ "clap_lex",+ "strsim",+]++[[package]]+name = "clap_derive"+version = "4.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "syn 3.0.3",+]++[[package]]+name = "clap_lex"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"++[[package]]+name = "colorchoice"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"++[[package]]+name = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+dependencies = [+ "libc",+]++[[package]]+name = "crypto-common"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+dependencies = [+ "generic-array",+ "typenum",+]++[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer",+ "crypto-common",+]++[[package]]+name = "fallible-iterator"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"++[[package]]+name = "fallible-streaming-iterator"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"++[[package]]+name = "find-msvc-tools"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"++[[package]]+name = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]++[[package]]+name = "hashbrown"+version = "0.14.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"+dependencies = [+ "ahash",+]++[[package]]+name = "hashlink"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"+dependencies = [+ "hashbrown",+]++[[package]]+name = "heck"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"++[[package]]+name = "is_terminal_polyfill"+version = "1.70.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"++[[package]]+name = "libc"+version = "0.2.189"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"++[[package]]+name = "libsqlite3-sys"+version = "0.30.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"+dependencies = [+ "cc",+ "pkg-config",+ "vcpkg",+]++[[package]]+name = "lisdex"+version = "0.0.0"+dependencies = [+ "clap",+ "lisdex-core",+ "lisdex-fuzz",+]+[[package]]name = "lisdex-core"version = "0.0.0"dependencies = [+ "rusqlite",+ "sha2","thiserror",]+[[package]]+name = "lisdex-fuzz"+version = "0.0.0"+dependencies = [+ "lisdex-core",+ "thiserror",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "once_cell_polyfill"+version = "1.70.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"++[[package]]+name = "pkg-config"+version = "0.3.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"+[[package]]name = "proc-macro2"version = "1.0.107"@@ -27,6 +307,60 @@ dependencies = ["proc-macro2",]+[[package]]+name = "rusqlite"+version = "0.32.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"+dependencies = [+ "bitflags",+ "fallible-iterator",+ "fallible-streaming-iterator",+ "hashlink",+ "libsqlite3-sys",+ "smallvec",+]++[[package]]+name = "sha2"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "digest",+]++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "smallvec"+version = "1.15.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"++[[package]]+name = "strsim"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]+[[package]]name = "syn"version = "3.0.3"@@ -55,11 +389,70 @@ checksum = "43cbfe0cf76104d42a574802844187e84a305e531ed54455f11fbde0f10541cd"dependencies = ["proc-macro2","quote",- "syn",+ "syn 3.0.3",]+[[package]]+name = "typenum"+version = "1.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"+[[package]]name = "unicode-ident"version = "1.0.24"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"++[[package]]+name = "utf8parse"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"++[[package]]+name = "vcpkg"+version = "0.2.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"++[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "zerocopy"+version = "0.8.55"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.55"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fe976fb70c78cd64cccfe3a6fc142244e8a77b70959b30faf9d0ac37ee228eb"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.toml b/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.tomlindex f5f64874..ab41b909 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.toml+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.toml@@ -13,6 +13,14 @@ authors = ["Carter Perez <[email protected]>"][workspace.dependencies]thiserror = "2"+rusqlite = { version = "0.32", features = ["bundled"] }+sha2 = "0.10"+clap = { version = "4", features = ["derive"] }+lisdex-core = { path = "crates/lisdex-core" }+lisdex-fuzz = { path = "crates/lisdex-fuzz" }++[workspace.lints.rust]+unsafe_code = "deny"[workspace.lints.clippy]all = { level = "warn", priority = -1 }diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/Dockerfile.dev b/PROJECTS/advanced/zero-day-vulnerability-scanner/Dockerfile.devnew file mode 100644index 00000000..c69e63b0--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/Dockerfile.dev@@ -0,0 +1,50 @@+# ©AngelaMos | 2026+# Dockerfile.dev++FROM aflplusplus/aflplusplus:v5.02c++ARG RUST_VERSION=1.97.0+ARG MAGMA_COMMIT=75d1ae7b180443a778b8830c79176ca5f93642ac++ENV DEBIAN_FRONTEND=noninteractive+ENV LLVM_BIN=/usr/lib/llvm-20/bin+ENV RUSTUP_HOME=/usr/local/rustup+ENV CARGO_HOME=/usr/local/cargo+ENV CARGO_TARGET_DIR=/cargo-target+ENV PATH=/usr/local/cargo/bin:/usr/lib/llvm-20/bin:$PATH+ENV MAGMA_ROOT=/opt/magma+ENV MAGMA_WORK=/opt/magma-work+ENV AFL_PATH=/usr/local/lib/afl+ENV AFL_DRIVER=/usr/local/lib/afl/libAFLDriver.a++RUN apt-get update && apt-get install -y --no-install-recommends \+ autoconf \+ automake \+ libtool \+ pkg-config \+ zlib1g-dev \+ libclang-dev \+ bison \+ flex \+ curl \+ ca-certificates \+ git \+ make \+ patch \+ xxd \+ sqlite3 \+ && rm -rf /var/lib/apt/lists/*++RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \+ | sh -s -- -y --no-modify-path --profile minimal \+ --default-toolchain "$RUST_VERSION" \+ --component rustfmt --component clippy \+ && chmod -R a+w "$CARGO_HOME" "$RUSTUP_HOME"++RUN git clone https://github.com/HexHive/magma.git "$MAGMA_ROOT" \+ && git -C "$MAGMA_ROOT" checkout "$MAGMA_COMMIT" \+ && mkdir -p "$MAGMA_WORK"++RUN mkdir -p "$CARGO_TARGET_DIR"++WORKDIR /workdiff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/Cargo.toml b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/Cargo.tomlindex ad994cdb..a6ebfd4b 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/Cargo.toml+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/Cargo.toml@@ -14,3 +14,5 @@ workspace = true[dependencies]thiserror.workspace = true+rusqlite.workspace = true+sha2.workspace = truediff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/campaign.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/campaign.rsindex 8bb9c978..b7e04142 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/campaign.rs+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/campaign.rs@@ -1,6 +1,9 @@// ©AngelaMos | 2026// campaign.rs+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub struct CampaignId(pub i64);+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum CampaignStatus {Pending,@@ -16,9 +19,34 @@ impl CampaignStatus {use CampaignStatus::{Building, Completed, Failed, Fuzzing, Pending};matches!((self, next),- (Pending, Building) | (Building, Fuzzing | Failed) | (Fuzzing, Completed | Failed)+ (Pending, Building | Failed)+ | (Building, Fuzzing | Failed)+ | (Fuzzing, Completed | Failed))}++ #[must_use]+ pub fn as_str(self) -> &'static str {+ match self {+ CampaignStatus::Pending => "pending",+ CampaignStatus::Building => "building",+ CampaignStatus::Fuzzing => "fuzzing",+ CampaignStatus::Completed => "completed",+ CampaignStatus::Failed => "failed",+ }+ }++ #[must_use]+ pub fn from_db_str(value: &str) -> Option<CampaignStatus> {+ match value {+ "pending" => Some(CampaignStatus::Pending),+ "building" => Some(CampaignStatus::Building),+ "fuzzing" => Some(CampaignStatus::Fuzzing),+ "completed" => Some(CampaignStatus::Completed),+ "failed" => Some(CampaignStatus::Failed),+ _ => None,+ }+ }}#[derive(Debug, thiserror::Error, Clone, Copy, PartialEq, Eq)]@@ -43,6 +71,14 @@ impl Campaign {}}+ #[must_use]+ pub(crate) fn from_stored(target: impl Into<String>, status: CampaignStatus) -> Self {+ Self {+ target: target.into(),+ status,+ }+ }+#[must_use]pub fn status(&self) -> CampaignStatus {self.status@@ -112,4 +148,34 @@ mod tests {fn pending_may_not_skip_to_fuzzing() {assert!(!CampaignStatus::Pending.can_transition_to(CampaignStatus::Fuzzing));}++ #[test]+ fn pending_may_fail_so_a_setup_error_is_recordable() {+ assert!(CampaignStatus::Pending.can_transition_to(CampaignStatus::Failed));+ }++ #[test]+ fn status_round_trips_through_db_string() {+ for status in [+ CampaignStatus::Pending,+ CampaignStatus::Building,+ CampaignStatus::Fuzzing,+ CampaignStatus::Completed,+ CampaignStatus::Failed,+ ] {+ assert_eq!(CampaignStatus::from_db_str(status.as_str()), Some(status));+ }+ }++ #[test]+ fn from_db_str_rejects_unknown_value() {+ assert_eq!(CampaignStatus::from_db_str("bogus"), None);+ }++ #[test]+ fn from_stored_preserves_target_and_status() {+ let campaign = Campaign::from_stored("libpng", CampaignStatus::Fuzzing);+ assert_eq!(campaign.target(), "libpng");+ assert_eq!(campaign.status(), CampaignStatus::Fuzzing);+ }}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/config.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/config.rsnew file mode 100644index 00000000..08a1f230--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/config.rs@@ -0,0 +1,64 @@+// ©AngelaMos | 2026+// config.rs++use std::time::Duration;++pub const DEFAULT_CAMPAIGN_DURATION_SECS: u64 = 3600;+pub const DEFAULT_PARALLEL_JOBS: usize = 1;+pub const DEFAULT_TRIALS: usize = 30;+pub const DEFAULT_REPRODUCE_TIMEOUT_MS: u64 = 10_000;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum LlmTier {+ None,+ #[default]+ Local,+ Api,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Config {+ pub llm_tier: LlmTier,+ pub campaign_duration: Duration,+ pub parallel_jobs: usize,+ pub trials: usize,+ pub reproduce_timeout: Duration,+}++impl Default for Config {+ fn default() -> Self {+ Self {+ llm_tier: LlmTier::default(),+ campaign_duration: Duration::from_secs(DEFAULT_CAMPAIGN_DURATION_SECS),+ parallel_jobs: DEFAULT_PARALLEL_JOBS,+ trials: DEFAULT_TRIALS,+ reproduce_timeout: Duration::from_millis(DEFAULT_REPRODUCE_TIMEOUT_MS),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn default_llm_tier_is_local() {+ assert_eq!(LlmTier::default(), LlmTier::Local);+ }++ #[test]+ fn default_config_uses_named_constants() {+ let config = Config::default();+ assert_eq!(config.llm_tier, LlmTier::Local);+ assert_eq!(+ config.campaign_duration,+ Duration::from_secs(DEFAULT_CAMPAIGN_DURATION_SECS)+ );+ assert_eq!(config.parallel_jobs, DEFAULT_PARALLEL_JOBS);+ assert_eq!(config.trials, DEFAULT_TRIALS);+ assert_eq!(+ config.reproduce_timeout,+ Duration::from_millis(DEFAULT_REPRODUCE_TIMEOUT_MS)+ );+ }+}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/crash.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/crash.rsnew file mode 100644index 00000000..a70350b3--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/crash.rs@@ -0,0 +1,80 @@+// ©AngelaMos | 2026+// crash.rs++use crate::campaign::CampaignId;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub struct CrashId(pub i64);++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Crash {+ campaign_id: CampaignId,+ input: Vec<u8>,+ sanitizer_report: String,+ stack_hash: Option<String>,+}++impl Crash {+ #[must_use]+ pub fn new(+ campaign_id: CampaignId,+ input: impl Into<Vec<u8>>,+ sanitizer_report: impl Into<String>,+ stack_hash: Option<String>,+ ) -> Self {+ Self {+ campaign_id,+ input: input.into(),+ sanitizer_report: sanitizer_report.into(),+ stack_hash,+ }+ }++ #[must_use]+ pub fn campaign_id(&self) -> CampaignId {+ self.campaign_id+ }++ #[must_use]+ pub fn input(&self) -> &[u8] {+ &self.input+ }++ #[must_use]+ pub fn sanitizer_report(&self) -> &str {+ &self.sanitizer_report+ }++ #[must_use]+ pub fn stack_hash(&self) -> Option<&str> {+ self.stack_hash.as_deref()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn new_crash_exposes_all_fields() {+ let crash = Crash::new(+ CampaignId(7),+ b"\x89PNG\r\n".to_vec(),+ "ERROR: AddressSanitizer: heap-buffer-overflow",+ Some("deadbeef".to_owned()),+ );+ assert_eq!(crash.campaign_id(), CampaignId(7));+ assert_eq!(crash.input(), b"\x89PNG\r\n");+ assert_eq!(+ crash.sanitizer_report(),+ "ERROR: AddressSanitizer: heap-buffer-overflow"+ );+ assert_eq!(crash.stack_hash(), Some("deadbeef"));+ }++ #[test]+ fn unreproduced_crash_has_no_stack_hash() {+ let crash = Crash::new(CampaignId(1), b"junk".to_vec(), "", None);+ assert_eq!(crash.stack_hash(), None);+ }+}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/lib.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/lib.rsindex 0507572d..7ba84b2b 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/lib.rs+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/lib.rs@@ -2,3 +2,7 @@// lib.rspub mod campaign;+pub mod config;+pub mod crash;+pub mod report;+pub mod store;diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/report.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/report.rsnew file mode 100644index 00000000..0dde2f99--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/report.rs@@ -0,0 +1,543 @@+// ©AngelaMos | 2026+// report.rs++use std::fmt::Write;++use sha2::{Digest, Sha256};++pub const STACK_HASH_FRAMES: usize = 5;++const ERROR_MARKER: &str = "ERROR: ";+const WARNING_MARKER: &str = "WARNING: ";+const UBSAN_MARKER: &str = ": runtime error: ";+const UBSAN_SANITIZER: &str = "UndefinedBehaviorSanitizer";+const SANITIZER_KIND_SEPARATOR: &str = ": ";+const KIND_ON_ADDRESS: &str = " on address";+const KIND_ON_UNKNOWN_ADDRESS: &str = " on unknown address";+const FRAME_PREFIX: char = '#';+const FRAME_SYMBOL_MARKER: &str = "in ";+const BUILD_ID_GROUP: &str = " (BuildId:";+const MODULE_GROUP_OPEN: &str = " (";+const MODULE_OFFSET_MARKER: &str = "+0x";+const UNSYMBOLIZED_SYMBOL: &str = "<unknown>";+const MODULE_TAG_SEPARATOR: char = '@';+const PATH_SEPARATOR: char = '/';+const LOCATION_SEPARATOR: char = ':';++const NOISE_FRAME_PREFIXES: [&str; 7] = [+ "__asan",+ "__ubsan",+ "__msan",+ "__sanitizer",+ "__interceptor",+ "__libc",+ "_start",+];++const NOISE_FRAME_EXACT: [&str; 6] = [+ "kill",+ "abort",+ "raise",+ "main",+ "LLVMFuzzerRunDriver",+ "ExecuteFilesOnyByOne",+];++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct SanitizerReport {+ sanitizer: String,+ kind: String,+ frames: Vec<String>,+}++impl SanitizerReport {+ #[must_use]+ pub fn parse(text: &str) -> Option<SanitizerReport> {+ let lines: Vec<&str> = text.lines().collect();+ let (header_index, sanitizer, kind) = find_header(&lines)?;+ Some(SanitizerReport {+ sanitizer,+ kind,+ frames: parse_frames(&lines[header_index + 1..]),+ })+ }++ #[must_use]+ pub fn sanitizer(&self) -> &str {+ &self.sanitizer+ }++ #[must_use]+ pub fn kind(&self) -> &str {+ &self.kind+ }++ #[must_use]+ pub fn frames(&self) -> &[String] {+ &self.frames+ }++ #[must_use]+ pub fn significant_frames(&self) -> Vec<&str> {+ self.frames+ .iter()+ .map(String::as_str)+ .filter(|frame| !is_noise_frame(frame))+ .collect()+ }++ #[must_use]+ pub fn crash_site(&self) -> Option<&str> {+ self.significant_frames().first().copied()+ }++ #[must_use]+ pub fn stack_hash(&self) -> Option<String> {+ let significant = self.significant_frames();+ let frames = if significant.is_empty() {+ self.frames.iter().map(String::as_str).collect()+ } else {+ significant+ };+ if frames.is_empty() {+ return None;+ }+ let mut hasher = Sha256::new();+ hasher.update(self.kind.as_bytes());+ for frame in frames.iter().take(STACK_HASH_FRAMES) {+ hasher.update(b"\n");+ hasher.update(frame.as_bytes());+ }+ let digest = hasher.finalize();+ let mut hex = String::with_capacity(digest.len() * 2);+ for byte in digest {+ let _ = write!(hex, "{byte:02x}");+ }+ Some(hex)+ }+}++fn is_noise_frame(frame: &str) -> bool {+ NOISE_FRAME_EXACT.contains(&frame)+ || NOISE_FRAME_PREFIXES+ .iter()+ .any(|prefix| frame.starts_with(prefix))+}++fn find_header(lines: &[&str]) -> Option<(usize, String, String)> {+ for marker in [ERROR_MARKER, WARNING_MARKER] {+ for (index, line) in lines.iter().enumerate() {+ if let Some(found) = line.find(marker) {+ let after = &line[found + marker.len()..];+ if let Some((sanitizer, remainder)) = after.split_once(SANITIZER_KIND_SEPARATOR) {+ return Some((index, sanitizer.to_owned(), normalize_kind(remainder)));+ }+ }+ }+ }++ for (index, line) in lines.iter().enumerate() {+ if let Some(found) = line.find(UBSAN_MARKER) {+ let message = line[found + UBSAN_MARKER.len()..].trim();+ return Some((index, UBSAN_SANITIZER.to_owned(), message.to_owned()));+ }+ }++ None+}++fn normalize_kind(remainder: &str) -> String {+ let cut = [KIND_ON_UNKNOWN_ADDRESS, KIND_ON_ADDRESS]+ .iter()+ .filter_map(|marker| remainder.find(marker))+ .min()+ .unwrap_or(remainder.len());+ remainder[..cut].trim().to_owned()+}++fn parse_frames(lines: &[&str]) -> Vec<String> {+ let mut frames = Vec::new();+ for line in lines {+ let trimmed = line.trim_start();+ if !trimmed.starts_with(FRAME_PREFIX) {+ if frames.is_empty() {+ continue;+ }+ break;+ }+ if let Some(symbol) = parse_frame_symbol(trimmed) {+ frames.push(symbol);+ }+ }+ frames+}++fn parse_frame_symbol(frame: &str) -> Option<String> {+ let after_prefix = frame.strip_prefix(FRAME_PREFIX)?;+ let after_number = after_prefix.trim_start_matches(|c: char| c.is_ascii_digit());+ let after_address = after_number.trim_start();+ let remainder = match after_address.split_once(' ') {+ Some((_address, rest)) => rest.trim(),+ None => "",+ };++ if let Some(symbol_part) = remainder.strip_prefix(FRAME_SYMBOL_MARKER) {+ let symbol = clean_symbol(symbol_part);+ if symbol.is_empty() {+ return None;+ }+ return Some(symbol);+ }++ Some(unsymbolized_identity(remainder))+}++fn clean_symbol(raw: &str) -> String {+ let mut symbol = raw.trim();++ if let Some(at) = symbol.rfind(BUILD_ID_GROUP) {+ symbol = symbol[..at].trim_end();+ }++ if let Some(at) = symbol+ .rfind(MODULE_GROUP_OPEN)+ .filter(|_| symbol.ends_with(')'))+ {+ let inner = &symbol[at + MODULE_GROUP_OPEN.len()..symbol.len() - 1];+ if inner.contains(MODULE_OFFSET_MARKER) {+ symbol = symbol[..at].trim_end();+ }+ }++ if let Some(at) = symbol+ .rfind(' ')+ .filter(|at| is_source_location(&symbol[at + 1..]))+ {+ symbol = symbol[..at].trim_end();+ }++ if let Some(at) = symbol+ .rfind(' ')+ .filter(|at| is_source_path(&symbol[at + 1..]))+ {+ symbol = symbol[..at].trim_end();+ }++ if let Some(at) = symbol.rfind(MODULE_OFFSET_MARKER) {+ let suffix = &symbol[at + MODULE_OFFSET_MARKER.len()..];+ if !suffix.is_empty() && suffix.chars().all(|c| c.is_ascii_hexdigit()) {+ symbol = symbol[..at].trim_end();+ }+ }++ symbol.trim().to_owned()+}++fn is_source_location(token: &str) -> bool {+ match token.rsplit_once(LOCATION_SEPARATOR) {+ Some((head, tail)) => {+ !head.is_empty() && !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit())+ }+ None => false,+ }+}++fn is_source_path(token: &str) -> bool {+ token.contains(PATH_SEPARATOR) && !token.ends_with(')')+}++fn unsymbolized_identity(remainder: &str) -> String {+ let module = remainder+ .find('(')+ .map(|open| &remainder[open + 1..])+ .and_then(|rest| rest.split_once(MODULE_OFFSET_MARKER))+ .map(|(path, _offset)| path)+ .map(|path| path.rsplit(PATH_SEPARATOR).next().unwrap_or(path));++ match module {+ Some(name) if !name.is_empty() => {+ format!("{UNSYMBOLIZED_SYMBOL}{MODULE_TAG_SEPARATOR}{name}")+ }+ _ => UNSYMBOLIZED_SYMBOL.to_owned(),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ const PNG003_CANARY: &str = "\+Monitor not running. Canaries will be disabled.+AddressSanitizer:DEADLYSIGNAL+=================================================================+==29092==ERROR: AddressSanitizer: SEGV on unknown address 0x0000000071a4 (pc 0x7fa6518a053b bp 0x7ffee6c0b1d0 sp 0x7ffee6c0b1a8 T0)+==29092==The signal is caused by a READ memory access.+ #0 0x7fa6518a053b in kill (/lib/x86_64-linux-gnu/libc.so.6+0x4553b) (BuildId: 8e9fd827446c24067541ac5390e6f527fb5947bb)+ #1 0x55a5aee02220 in magma_log /opt/magma/magma/src/canary.c:92:5+ #2 0x55a5aee68dae in MAGMA_png_handle_PLTE /opt/magma-work/libpng/repo/pngrutil.c:992:4+ #3 0x55a5aee25cc0 in MAGMA_png_read_info /opt/magma-work/libpng/repo/pngread.c:160:10+ #4 0x55a5aee0aaa6 in LLVMFuzzerTestOneInput /work/harnesses/libpng_read.c:83:5+ #5 0x55a5aee02c81 in ExecuteFilesOnyByOne /AFLplusplus/utils/aflpp_driver/aflpp_driver.c:288:7+ #6 0x55a5aee02a99 in LLVMFuzzerRunDriver /AFLplusplus/utils/aflpp_driver/aflpp_driver.c++SUMMARY: AddressSanitizer: SEGV (/lib/x86_64-linux-gnu/libc.so.6+0x4553b) in kill+";++ const STACK_OVERFLOW: &str = "\+==67==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7b8c74f00028 at pc 0x56173e83d882 bp 0x7ffd573834b0 sp 0x7ffd57382c70+WRITE of size 24 at 0x7b8c74f00028 thread T0+ #0 0x56173e83d881 in __asan_memcpy (/t/harness+0x10e881)+ #1 0x56173e8c1234 in LLVMFuzzerTestOneInput /t/planted.c:7:9+SUMMARY: AddressSanitizer: stack-buffer-overflow (/t/harness+0x10e881) in __asan_memcpy+";++ #[test]+ fn parses_sanitizer_and_kind_from_segv_report() {+ let report = SanitizerReport::parse(PNG003_CANARY).unwrap();+ assert_eq!(report.sanitizer(), "AddressSanitizer");+ assert_eq!(report.kind(), "SEGV");+ }++ #[test]+ fn parses_kind_from_overflow_report() {+ let report = SanitizerReport::parse(STACK_OVERFLOW).unwrap();+ assert_eq!(report.kind(), "stack-buffer-overflow");+ }++ #[test]+ fn extracts_frame_symbols_in_order() {+ let report = SanitizerReport::parse(PNG003_CANARY).unwrap();+ assert_eq!(+ report.frames(),+ [+ "kill",+ "magma_log",+ "MAGMA_png_handle_PLTE",+ "MAGMA_png_read_info",+ "LLVMFuzzerTestOneInput",+ "ExecuteFilesOnyByOne",+ "LLVMFuzzerRunDriver",+ ]+ );+ }++ #[test]+ fn extracts_frame_without_source_location() {+ let report = SanitizerReport::parse(PNG003_CANARY).unwrap();+ assert_eq!(report.frames().last().unwrap(), "LLVMFuzzerRunDriver");+ }++ #[test]+ fn returns_none_for_non_sanitizer_output() {+ assert!(SanitizerReport::parse("nothing interesting here").is_none());+ assert!(SanitizerReport::parse("").is_none());+ }++ #[test]+ fn stack_hash_ignores_addresses() {+ let rebased = PNG003_CANARY+ .replace("0x55a5aee02220", "0x7f0000001111")+ .replace("0x55a5aee68dae", "0x7f0000002222")+ .replace("29092", "31337");+ let original = SanitizerReport::parse(PNG003_CANARY).unwrap();+ let moved = SanitizerReport::parse(&rebased).unwrap();+ assert_eq!(original.stack_hash(), moved.stack_hash());+ }++ #[test]+ fn stack_hash_differs_for_different_stacks() {+ let a = SanitizerReport::parse(PNG003_CANARY).unwrap();+ let b = SanitizerReport::parse(STACK_OVERFLOW).unwrap();+ assert_ne!(a.stack_hash(), b.stack_hash());+ }++ #[test]+ fn stack_hash_is_hex_sha256() {+ let report = SanitizerReport::parse(PNG003_CANARY).unwrap();+ let hash = report.stack_hash().unwrap();+ assert_eq!(hash.len(), 64);+ assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));+ }++ const UNSYMBOLIZED: &str = "\+==12==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000018 at pc 0x4a1+ #0 0x7f0c8a2 (/lib/x86_64-linux-gnu/libc.so.6+0x21b97)+ #1 0x7f0c8b3 (/out/libpng.so+0x1234) (BuildId: aabb)+";++ const FUNCTION_OFFSET: &str = "\+==13==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000018 at pc 0x4a1+ #0 0x4a1 in png_handle_PLTE+0x1c4 (/out/libpng.so+0x4a1)+";++ const RELATIVE_DEBUG_PATH: &str = "\+==14==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000018 at pc 0x4a1+ #0 0x55a in png_handle_PLTE pngrutil.c:992:4+";++ const UBSAN_ONLY: &str = "\+pngrutil.c:1204:7: runtime error: left shift of negative value -1+ #0 0x55a in png_do_read_transform pngrtran.c:1204:7+ #1 0x55b in png_read_row pngread.c:100:3+";++ const UBSAN_THEN_ASAN: &str = "\+pngrutil.c:1204:7: runtime error: left shift of negative value -1+ #0 0x55a in ubsan_only_frame pngrtran.c:1204:7+ #1 0x55b in also_ubsan pngread.c:100:3++==15==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000018 at pc 0x4a1+ #0 0x4a1 in the_real_asan_frame pngrutil.c:992:4+ #1 0x4a2 in png_read_info pngread.c:160:10+";++ const LEAK_REPORT: &str = "\+==16==ERROR: LeakSanitizer: detected memory leaks+ #0 0x4a1 in malloc (/out/harness+0x1000)+ #1 0x4a2 in png_malloc pngmem.c:50:3+";++ const CPP_SYMBOL: &str = "\+==17==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000018 at pc 0x4a1+ #0 0x4a1 in (anonymous namespace)::parse(char const*) /src/a.cc:5:1+";++ #[test]+ fn unsymbolized_frames_are_kept_not_dropped() {+ let report = SanitizerReport::parse(UNSYMBOLIZED).unwrap();+ assert_eq!(+ report.frames().len(),+ 2,+ "unsymbolized frames must not be silently dropped"+ );+ assert!(report.stack_hash().is_some());+ }++ #[test]+ fn unsymbolized_frames_exclude_build_specific_offsets() {+ let report = SanitizerReport::parse(UNSYMBOLIZED).unwrap();+ for frame in report.frames() {+ assert!(+ !frame.contains("+0x"),+ "frame {frame} embeds a build-specific offset"+ );+ }+ }++ #[test]+ fn function_offset_is_stripped_from_symbol() {+ let report = SanitizerReport::parse(FUNCTION_OFFSET).unwrap();+ assert_eq!(report.frames(), ["png_handle_PLTE"]);+ }++ #[test]+ fn relative_debug_path_is_not_part_of_symbol() {+ let report = SanitizerReport::parse(RELATIVE_DEBUG_PATH).unwrap();+ assert_eq!(report.frames(), ["png_handle_PLTE"]);+ }++ #[test]+ fn absolute_and_relative_debug_paths_hash_identically() {+ let absolute = SanitizerReport::parse(+ "==1==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x1 at pc 0x2\n #0 0x55a in png_handle_PLTE /src/libpng/pngrutil.c:992:4\n",+ )+ .unwrap();+ let relative = SanitizerReport::parse(RELATIVE_DEBUG_PATH).unwrap();+ assert_eq!(absolute.stack_hash(), relative.stack_hash());+ }++ #[test]+ fn line_number_changes_do_not_change_the_hash() {+ let shifted = RELATIVE_DEBUG_PATH.replace("pngrutil.c:992:4", "pngrutil.c:1050:4");+ let original = SanitizerReport::parse(RELATIVE_DEBUG_PATH).unwrap();+ let moved = SanitizerReport::parse(&shifted).unwrap();+ assert_eq!(original.stack_hash(), moved.stack_hash());+ }++ #[test]+ fn parses_ubsan_only_report() {+ let report = SanitizerReport::parse(UBSAN_ONLY).unwrap();+ assert_eq!(report.sanitizer(), "UndefinedBehaviorSanitizer");+ assert!(report.kind().contains("left shift of negative value"));+ assert_eq!(report.frames().len(), 2);+ assert!(report.stack_hash().is_some());+ }++ #[test]+ fn frames_are_anchored_to_the_matched_error_line() {+ let report = SanitizerReport::parse(UBSAN_THEN_ASAN).unwrap();+ assert_eq!(report.kind(), "heap-buffer-overflow");+ assert_eq!(+ report.frames(),+ ["the_real_asan_frame", "png_read_info"],+ "frames must come from the same report as the kind"+ );+ }++ #[test]+ fn leak_report_kind_is_not_a_stray_token() {+ let report = SanitizerReport::parse(LEAK_REPORT).unwrap();+ assert_eq!(report.sanitizer(), "LeakSanitizer");+ assert_ne!(report.kind(), "detected");+ assert!(report.kind().contains("memory leaks"));+ }++ #[test]+ fn cpp_demangled_symbol_survives_intact() {+ let report = SanitizerReport::parse(CPP_SYMBOL).unwrap();+ assert_eq!(+ report.frames(),+ ["(anonymous namespace)::parse(char const*)"]+ );+ }++ #[test]+ fn crash_site_skips_sanitizer_and_driver_frames() {+ let report = SanitizerReport::parse(PNG003_CANARY).unwrap();+ assert_eq!(report.crash_site(), Some("magma_log"));+ let overflow = SanitizerReport::parse(STACK_OVERFLOW).unwrap();+ assert_eq!(overflow.crash_site(), Some("LLVMFuzzerTestOneInput"));+ }++ #[test]+ fn noise_frames_do_not_dominate_the_stack_hash() {+ let report = SanitizerReport::parse(PNG003_CANARY).unwrap();+ let significant = report.significant_frames();+ assert!(!significant.contains(&"kill"));+ assert!(!significant.contains(&"LLVMFuzzerRunDriver"));+ assert!(significant.contains(&"MAGMA_png_handle_PLTE"));+ }++ #[test]+ fn driver_frame_churn_does_not_change_the_hash() {+ let with_extra_driver = PNG003_CANARY.replace(+ " #5 0x55a5aee02c81 in ExecuteFilesOnyByOne /AFLplusplus/utils/aflpp_driver/aflpp_driver.c:288:7",+ " #5 0x55a5aee02c81 in ExecuteFilesOnyByOne /AFLplusplus/utils/aflpp_driver/aflpp_driver.c:288:7\n #6 0x1 in __asan_extra_thing /x/y.c:1:1",+ );+ let original = SanitizerReport::parse(PNG003_CANARY).unwrap();+ let noisy = SanitizerReport::parse(&with_extra_driver).unwrap();+ assert_eq!(original.stack_hash(), noisy.stack_hash());+ }++ #[test]+ fn report_without_frames_has_no_stack_hash() {+ let report = SanitizerReport::parse(+ "==1==ERROR: AddressSanitizer: SEGV on unknown address 0x0 (pc 0x1)\n",+ )+ .unwrap();+ assert!(report.frames().is_empty());+ assert!(+ report.stack_hash().is_none(),+ "a frameless report must not produce a dedup key"+ );+ }++ #[test]+ fn stack_hash_uses_only_top_frames() {+ let mut deeper = PNG003_CANARY.to_string();+ deeper.push_str(" #7 0xdeadbeef in extra_frame /tmp/other.c:1:1\n");+ let original = SanitizerReport::parse(PNG003_CANARY).unwrap();+ let extended = SanitizerReport::parse(&deeper).unwrap();+ assert_eq!(original.stack_hash(), extended.stack_hash());+ }+}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/store.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/store.rsnew file mode 100644index 00000000..f1752435--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-core/src/store.rs@@ -0,0 +1,240 @@+// ©AngelaMos | 2026+// store.rs++use std::path::Path;++use rusqlite::{Connection, params};++use crate::campaign::{Campaign, CampaignId, CampaignStatus};+use crate::crash::{Crash, CrashId};++const BUSY_TIMEOUT_MS: u64 = 5000;++const MIGRATE_SQL: &str = "\+PRAGMA foreign_keys = ON;+PRAGMA journal_mode = WAL;+CREATE TABLE IF NOT EXISTS campaigns (+ id INTEGER PRIMARY KEY,+ target TEXT NOT NULL,+ status TEXT NOT NULL+);+CREATE TABLE IF NOT EXISTS crashes (+ id INTEGER PRIMARY KEY,+ campaign_id INTEGER NOT NULL REFERENCES campaigns(id),+ input BLOB NOT NULL,+ sanitizer_report TEXT NOT NULL,+ stack_hash TEXT+);+CREATE INDEX IF NOT EXISTS idx_crashes_campaign ON crashes(campaign_id);";++const INSERT_CAMPAIGN_SQL: &str = "INSERT INTO campaigns (target, status) VALUES (?1, ?2)";+const SELECT_CAMPAIGN_SQL: &str = "SELECT target, status FROM campaigns WHERE id = ?1";+const UPDATE_CAMPAIGN_STATUS_SQL: &str = "UPDATE campaigns SET status = ?1 WHERE id = ?2";+const INSERT_CRASH_SQL: &str = "INSERT INTO crashes (campaign_id, input, sanitizer_report, stack_hash) VALUES (?1, ?2, ?3, ?4)";+const SELECT_CRASHES_SQL: &str = "SELECT campaign_id, input, sanitizer_report, stack_hash FROM crashes WHERE campaign_id = ?1 ORDER BY id";++#[derive(Debug, thiserror::Error)]+pub enum StoreError {+ #[error("database error: {0}")]+ Sqlite(#[from] rusqlite::Error),+ #[error("unknown campaign status in database: {0}")]+ UnknownStatus(String),+ #[error("no campaign with id {0} in the store")]+ CampaignNotFound(i64),+}++pub struct Store {+ conn: Connection,+}++impl Store {+ pub fn open(path: impl AsRef<Path>) -> Result<Self, StoreError> {+ let store = Self {+ conn: Connection::open(path)?,+ };+ store.migrate()?;+ Ok(store)+ }++ pub fn open_in_memory() -> Result<Self, StoreError> {+ let store = Self {+ conn: Connection::open_in_memory()?,+ };+ store.migrate()?;+ Ok(store)+ }++ fn migrate(&self) -> Result<(), StoreError> {+ self.conn+ .busy_timeout(std::time::Duration::from_millis(BUSY_TIMEOUT_MS))?;+ self.conn.execute_batch(MIGRATE_SQL)?;+ Ok(())+ }++ pub fn insert_campaign(&self, campaign: &Campaign) -> Result<CampaignId, StoreError> {+ self.conn.execute(+ INSERT_CAMPAIGN_SQL,+ params![campaign.target(), campaign.status().as_str()],+ )?;+ Ok(CampaignId(self.conn.last_insert_rowid()))+ }++ pub fn get_campaign(&self, id: CampaignId) -> Result<Option<Campaign>, StoreError> {+ let row = self+ .conn+ .query_row(SELECT_CAMPAIGN_SQL, params![id.0], |row| {+ Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))+ });+ match row {+ Ok((target, status_str)) => {+ let status = CampaignStatus::from_db_str(&status_str)+ .ok_or(StoreError::UnknownStatus(status_str))?;+ Ok(Some(Campaign::from_stored(target, status)))+ }+ Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),+ Err(err) => Err(err.into()),+ }+ }++ pub fn update_campaign_status(+ &self,+ id: CampaignId,+ status: CampaignStatus,+ ) -> Result<(), StoreError> {+ let changed = self+ .conn+ .execute(UPDATE_CAMPAIGN_STATUS_SQL, params![status.as_str(), id.0])?;+ if changed == 0 {+ return Err(StoreError::CampaignNotFound(id.0));+ }+ Ok(())+ }++ pub fn insert_crash(&self, crash: &Crash) -> Result<CrashId, StoreError> {+ self.conn.execute(+ INSERT_CRASH_SQL,+ params![+ crash.campaign_id().0,+ crash.input(),+ crash.sanitizer_report(),+ crash.stack_hash(),+ ],+ )?;+ Ok(CrashId(self.conn.last_insert_rowid()))+ }++ pub fn crashes_for_campaign(&self, id: CampaignId) -> Result<Vec<Crash>, StoreError> {+ let mut stmt = self.conn.prepare(SELECT_CRASHES_SQL)?;+ let crashes = stmt+ .query_map(params![id.0], |row| {+ Ok(Crash::new(+ CampaignId(row.get::<_, i64>(0)?),+ row.get::<_, Vec<u8>>(1)?,+ row.get::<_, String>(2)?,+ row.get::<_, Option<String>>(3)?,+ ))+ })?+ .collect::<Result<Vec<_>, _>>()?;+ Ok(crashes)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn campaign_round_trips_through_store() {+ let store = Store::open_in_memory().unwrap();+ let mut campaign = Campaign::new("libpng");+ campaign.advance(CampaignStatus::Building).unwrap();+ let id = store.insert_campaign(&campaign).unwrap();+ let loaded = store.get_campaign(id).unwrap().unwrap();+ assert_eq!(loaded, campaign);+ }++ #[test]+ fn get_missing_campaign_returns_none() {+ let store = Store::open_in_memory().unwrap();+ assert!(store.get_campaign(CampaignId(999)).unwrap().is_none());+ }++ #[test]+ fn update_campaign_status_persists() {+ let store = Store::open_in_memory().unwrap();+ let id = store.insert_campaign(&Campaign::new("libpng")).unwrap();+ store+ .update_campaign_status(id, CampaignStatus::Building)+ .unwrap();+ let loaded = store.get_campaign(id).unwrap().unwrap();+ assert_eq!(loaded.status(), CampaignStatus::Building);+ }++ #[test]+ fn crashes_round_trip_and_link_to_campaign() {+ let store = Store::open_in_memory().unwrap();+ let id = store.insert_campaign(&Campaign::new("libpng")).unwrap();+ let crash = Crash::new(+ id,+ b"\x89PNG\r\n\x1a\n".to_vec(),+ "ERROR: AddressSanitizer: heap-buffer-overflow",+ Some("abc123".to_owned()),+ );+ store.insert_crash(&crash).unwrap();+ let crashes = store.crashes_for_campaign(id).unwrap();+ assert_eq!(crashes, vec![crash]);+ }++ #[test]+ fn crash_without_stack_hash_round_trips_as_null() {+ let store = Store::open_in_memory().unwrap();+ let id = store.insert_campaign(&Campaign::new("libpng")).unwrap();+ let crash = Crash::new(id, b"unreproduced".to_vec(), "", None);+ store.insert_crash(&crash).unwrap();+ let loaded = store.crashes_for_campaign(id).unwrap();+ assert_eq!(loaded[0].stack_hash(), None);+ }++ #[test]+ fn binary_input_with_embedded_nuls_round_trips_exactly() {+ let store = Store::open_in_memory().unwrap();+ let id = store.insert_campaign(&Campaign::new("libpng")).unwrap();+ let raw: Vec<u8> = vec![0x00, 0xff, 0x89, 0x00, 0x0a, 0xc3, 0x28];+ store+ .insert_crash(&Crash::new(id, raw.clone(), "report", None))+ .unwrap();+ let loaded = store.crashes_for_campaign(id).unwrap();+ assert_eq!(loaded[0].input(), raw.as_slice());+ }++ #[test]+ fn updating_a_missing_campaign_is_an_error_not_a_silent_noop() {+ let store = Store::open_in_memory().unwrap();+ let err = store+ .update_campaign_status(CampaignId(9999), CampaignStatus::Completed)+ .unwrap_err();+ assert!(matches!(err, StoreError::CampaignNotFound(9999)));+ }++ #[test]+ fn crashes_for_campaign_without_crashes_is_empty() {+ let store = Store::open_in_memory().unwrap();+ let id = store.insert_campaign(&Campaign::new("libpng")).unwrap();+ assert!(store.crashes_for_campaign(id).unwrap().is_empty());+ }++ #[test]+ fn data_persists_across_reopen() {+ let path =+ std::env::temp_dir().join(format!("lisdex-store-test-{}.sqlite", std::process::id()));+ let _ = std::fs::remove_file(&path);+ let id = {+ let store = Store::open(&path).unwrap();+ store.insert_campaign(&Campaign::new("libpng")).unwrap()+ };+ let store = Store::open(&path).unwrap();+ let loaded = store.get_campaign(id).unwrap().unwrap();+ assert_eq!(loaded.target(), "libpng");+ std::fs::remove_file(&path).unwrap();+ }+}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-fuzz/Cargo.toml b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-fuzz/Cargo.tomlnew file mode 100644index 00000000..833a14d3--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-fuzz/Cargo.toml@@ -0,0 +1,17 @@+# ©AngelaMos | 2026+# Cargo.toml++[package]+name = "lisdex-fuzz"+version = "0.0.0"+edition.workspace = true+rust-version.workspace = true+license.workspace = true+authors.workspace = true++[lints]+workspace = true++[dependencies]+thiserror.workspace = true+lisdex-core.workspace = truediff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-fuzz/src/lib.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-fuzz/src/lib.rsnew file mode 100644index 00000000..e53a0171--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-fuzz/src/lib.rs@@ -0,0 +1,6 @@+// ©AngelaMos | 2026+// lib.rs++pub mod runner;+pub mod stats;+pub mod symbolize;diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-fuzz/src/runner.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-fuzz/src/runner.rsnew file mode 100644index 00000000..2d15dd62--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-fuzz/src/runner.rs@@ -0,0 +1,454 @@+// ©AngelaMos | 2026+// runner.rs++use std::io::Read;+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};+use std::time::{Duration, Instant};++use lisdex_core::campaign::CampaignId;+use lisdex_core::config::DEFAULT_REPRODUCE_TIMEOUT_MS;+use lisdex_core::crash::Crash;+use lisdex_core::report::SanitizerReport;++use crate::stats::{FuzzerStats, STATS_FILE_NAME, StatsError};++pub const AFL_FUZZ_BIN: &str = "afl-fuzz";+pub const DEFAULT_INSTANCE: &str = "default";+pub const MAX_REPORT_BYTES: usize = 256 * 1024;++const REPRODUCE_POLL_MS: u64 = 25;+const ENV_ASAN_OPTIONS: &str = "ASAN_OPTIONS";+const ENV_UBSAN_OPTIONS: &str = "UBSAN_OPTIONS";+const SANITIZER_OPTIONS: &str = "symbolize=0:detect_leaks=0:handle_segv=1";+const CRASHES_DIR: &str = "crashes";+const CRASH_PREFIX: &str = "id:";+const MEM_LIMIT_UNLIMITED: &str = "none";+const ARG_INPUT: &str = "-i";+const ARG_OUTPUT: &str = "-o";+const ARG_MEMORY: &str = "-m";+const ARG_CMPLOG: &str = "-c";+const ARG_DURATION: &str = "-V";+const ARG_SKIP_DETERMINISTIC: &str = "-d";+const ARG_SEPARATOR: &str = "--";+const ENV_SKIP_CPUFREQ: &str = "AFL_SKIP_CPUFREQ";+const ENV_NO_AFFINITY: &str = "AFL_NO_AFFINITY";+const ENV_NO_UI: &str = "AFL_NO_UI";+const ENV_MISSING_CRASHES: &str = "AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES";+const ENV_BENCH_UNTIL_CRASH: &str = "AFL_BENCH_UNTIL_CRASH";+const ENV_ENABLED: &str = "1";++#[derive(Debug, thiserror::Error)]+pub enum RunnerError {+ #[error("io error: {0}")]+ Io(#[from] std::io::Error),+ #[error("stats error: {0}")]+ Stats(#[from] StatsError),+ #[error(+ "{AFL_FUZZ_BIN} failed before writing stats ({status}); check the {AFL_FUZZ_BIN} output above"+ )]+ AflFailed { status: String },+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Reproduction {+ pub output: String,+ pub timed_out: bool,+ pub truncated: bool,+}++#[derive(Debug, Clone, PartialEq)]+pub struct RunOutcome {+ pub clean_exit: bool,+ pub stats: FuzzerStats,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct AflOptions {+ pub target: PathBuf,+ pub cmplog: Option<PathBuf>,+ pub seeds: PathBuf,+ pub findings: PathBuf,+ pub duration: Option<Duration>,+ pub bench_until_crash: bool,+ pub skip_deterministic: bool,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct AflInvocation {+ pub program: String,+ pub args: Vec<String>,+ pub envs: Vec<(String, String)>,+}++impl AflOptions {+ #[must_use]+ pub fn invocation(&self) -> AflInvocation {+ let mut args = vec![+ ARG_INPUT.to_owned(),+ self.seeds.display().to_string(),+ ARG_OUTPUT.to_owned(),+ self.findings.display().to_string(),+ ARG_MEMORY.to_owned(),+ MEM_LIMIT_UNLIMITED.to_owned(),+ ];++ if let Some(duration) = self.duration {+ args.push(ARG_DURATION.to_owned());+ args.push(duration.as_secs().to_string());+ }++ if let Some(cmplog) = &self.cmplog {+ args.push(ARG_CMPLOG.to_owned());+ args.push(cmplog.display().to_string());+ }++ if self.skip_deterministic {+ args.push(ARG_SKIP_DETERMINISTIC.to_owned());+ }++ args.push(ARG_SEPARATOR.to_owned());+ args.push(self.target.display().to_string());++ let mut envs = vec![+ (ENV_SKIP_CPUFREQ.to_owned(), ENV_ENABLED.to_owned()),+ (ENV_NO_AFFINITY.to_owned(), ENV_ENABLED.to_owned()),+ (ENV_NO_UI.to_owned(), ENV_ENABLED.to_owned()),+ (ENV_MISSING_CRASHES.to_owned(), ENV_ENABLED.to_owned()),+ ];+ if self.bench_until_crash {+ envs.push((ENV_BENCH_UNTIL_CRASH.to_owned(), ENV_ENABLED.to_owned()));+ }++ AflInvocation {+ program: AFL_FUZZ_BIN.to_owned(),+ args,+ envs,+ }+ }+}++#[must_use]+pub fn crashes_dir(findings: &Path) -> PathBuf {+ findings.join(DEFAULT_INSTANCE).join(CRASHES_DIR)+}++pub fn instance_dirs(findings: &Path) -> Result<Vec<PathBuf>, RunnerError> {+ if !findings.is_dir() {+ return Ok(Vec::new());+ }+ let mut dirs = Vec::new();+ for entry in std::fs::read_dir(findings)? {+ let entry = entry?;+ if entry.file_type()?.is_dir() && entry.path().join(STATS_FILE_NAME).is_file() {+ dirs.push(entry.path());+ }+ }+ dirs.sort();+ Ok(dirs)+}++pub fn discover_crash_inputs(findings: &Path) -> Result<Vec<PathBuf>, RunnerError> {+ let mut roots = instance_dirs(findings)?;+ let default_dir = findings.join(DEFAULT_INSTANCE);+ if roots.is_empty() && default_dir.is_dir() {+ roots.push(default_dir);+ }++ let mut inputs = Vec::new();+ for root in roots {+ let dir = root.join(CRASHES_DIR);+ if !dir.is_dir() {+ continue;+ }+ for entry in std::fs::read_dir(&dir)? {+ let entry = entry?;+ if !entry.file_type()?.is_file() {+ continue;+ }+ if entry+ .file_name()+ .to_string_lossy()+ .starts_with(CRASH_PREFIX)+ {+ inputs.push(entry.path());+ }+ }+ }+ inputs.sort();+ Ok(inputs)+}++pub fn read_stats(findings: &Path) -> Result<FuzzerStats, RunnerError> {+ let path = findings.join(DEFAULT_INSTANCE).join(STATS_FILE_NAME);+ let text = std::fs::read_to_string(path)?;+ Ok(FuzzerStats::parse(&text)?)+}++pub fn reproduce(+ target: &Path,+ input: &Path,+ timeout: Duration,+) -> Result<Reproduction, RunnerError> {+ let mut child = Command::new(target)+ .arg(input)+ .env(ENV_ASAN_OPTIONS, SANITIZER_OPTIONS)+ .env(ENV_UBSAN_OPTIONS, SANITIZER_OPTIONS)+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::piped())+ .spawn()?;++ let started = Instant::now();+ let mut timed_out = false;+ loop {+ if child.try_wait()?.is_some() {+ break;+ }+ if started.elapsed() >= timeout {+ child.kill()?;+ child.wait()?;+ timed_out = true;+ break;+ }+ std::thread::sleep(Duration::from_millis(REPRODUCE_POLL_MS));+ }++ let mut raw = Vec::new();+ if let Some(mut stderr) = child.stderr.take() {+ stderr+ .by_ref()+ .take(MAX_REPORT_BYTES as u64)+ .read_to_end(&mut raw)?;+ }+ let truncated = raw.len() >= MAX_REPORT_BYTES;+ let raw_text = String::from_utf8_lossy(&raw).into_owned();++ Ok(Reproduction {+ output: crate::symbolize::symbolize_report(&raw_text),+ timed_out,+ truncated,+ })+}++pub fn harvest(+ campaign_id: CampaignId,+ target: &Path,+ findings: &Path,+) -> Result<(Vec<Crash>, Vec<String>), RunnerError> {+ let timeout = Duration::from_millis(DEFAULT_REPRODUCE_TIMEOUT_MS);+ let mut crashes = Vec::new();+ let mut problems = Vec::new();++ for input_path in discover_crash_inputs(findings)? {+ let input = match std::fs::read(&input_path) {+ Ok(bytes) => bytes,+ Err(err) => {+ problems.push(format!("{}: unreadable ({err})", input_path.display()));+ continue;+ }+ };+ let reproduction = match reproduce(target, &input_path, timeout) {+ Ok(reproduction) => reproduction,+ Err(err) => {+ problems.push(format!("{}: not reproduced ({err})", input_path.display()));+ crashes.push(Crash::new(campaign_id, input, String::new(), None));+ continue;+ }+ };+ if reproduction.timed_out {+ problems.push(format!(+ "{}: hung, killed after timeout",+ input_path.display()+ ));+ }+ if reproduction.truncated {+ problems.push(format!("{}: report truncated", input_path.display()));+ }+ let stack_hash = SanitizerReport::parse(&reproduction.output).and_then(|r| r.stack_hash());+ if stack_hash.is_none() {+ problems.push(format!(+ "{}: no parseable sanitizer report, stored without a dedup key",+ input_path.display()+ ));+ }+ crashes.push(Crash::new(+ campaign_id,+ input,+ reproduction.output,+ stack_hash,+ ));+ }++ Ok((crashes, problems))+}++pub fn run(options: &AflOptions) -> Result<RunOutcome, RunnerError> {+ let invocation = options.invocation();+ let mut command = Command::new(&invocation.program);+ command.args(&invocation.args);+ for (key, value) in &invocation.envs {+ command.env(key, value);+ }+ let status = command.status()?;+ let measured = read_stats(&options.findings).map_err(|cause| match cause {+ RunnerError::Io(_) if !status.success() => RunnerError::AflFailed {+ status: status.to_string(),+ },+ other => other,+ })?;+ Ok(RunOutcome {+ clean_exit: status.success(),+ stats: measured,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn options() -> AflOptions {+ AflOptions {+ target: PathBuf::from("/out/afl/harness"),+ cmplog: Some(PathBuf::from("/out/cmplog/harness")),+ seeds: PathBuf::from("/corpus"),+ findings: PathBuf::from("/findings"),+ duration: Some(Duration::from_mins(1)),+ bench_until_crash: true,+ skip_deterministic: true,+ }+ }++ fn scratch(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("lisdex-runner-{}-{name}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }++ #[test]+ fn invocation_uses_afl_fuzz_with_input_and_output() {+ let inv = options().invocation();+ assert_eq!(inv.program, AFL_FUZZ_BIN);+ let i = inv.args.iter().position(|a| a == ARG_INPUT).unwrap();+ assert_eq!(inv.args[i + 1], "/corpus");+ let o = inv.args.iter().position(|a| a == ARG_OUTPUT).unwrap();+ assert_eq!(inv.args[o + 1], "/findings");+ }++ #[test]+ fn invocation_disables_memory_limit_for_asan() {+ let inv = options().invocation();+ let m = inv.args.iter().position(|a| a == ARG_MEMORY).unwrap();+ assert_eq!(inv.args[m + 1], MEM_LIMIT_UNLIMITED);+ }++ #[test]+ fn invocation_passes_cmplog_binary() {+ let inv = options().invocation();+ let c = inv.args.iter().position(|a| a == ARG_CMPLOG).unwrap();+ assert_eq!(inv.args[c + 1], "/out/cmplog/harness");+ }++ #[test]+ fn invocation_omits_cmplog_when_absent() {+ let mut opts = options();+ opts.cmplog = None;+ let inv = opts.invocation();+ assert!(!inv.args.iter().any(|a| a == ARG_CMPLOG));+ }++ #[test]+ fn invocation_puts_target_after_separator() {+ let inv = options().invocation();+ let sep = inv.args.iter().position(|a| a == ARG_SEPARATOR).unwrap();+ assert_eq!(inv.args[sep + 1], "/out/afl/harness");+ assert_eq!(inv.args.len(), sep + 2);+ }++ #[test]+ fn invocation_encodes_duration_in_seconds() {+ let inv = options().invocation();+ let v = inv.args.iter().position(|a| a == ARG_DURATION).unwrap();+ assert_eq!(inv.args[v + 1], "60");+ }++ #[test]+ fn invocation_omits_duration_when_unbounded() {+ let mut opts = options();+ opts.duration = None;+ let inv = opts.invocation();+ assert!(!inv.args.iter().any(|a| a == ARG_DURATION));+ }++ #[test]+ fn invocation_honours_skip_deterministic_flag() {+ let inv = options().invocation();+ assert!(inv.args.iter().any(|a| a == ARG_SKIP_DETERMINISTIC));+ let mut opts = options();+ opts.skip_deterministic = false;+ assert!(+ !opts+ .invocation()+ .args+ .iter()+ .any(|a| a == ARG_SKIP_DETERMINISTIC)+ );+ }++ #[test]+ fn invocation_sets_container_safe_environment() {+ let inv = options().invocation();+ for key in [+ ENV_SKIP_CPUFREQ,+ ENV_NO_AFFINITY,+ ENV_NO_UI,+ ENV_MISSING_CRASHES,+ ] {+ assert!(+ inv.envs.iter().any(|(k, v)| k == key && v == ENV_ENABLED),+ "missing env {key}"+ );+ }+ }++ #[test]+ fn invocation_sets_bench_until_crash_only_when_requested() {+ let inv = options().invocation();+ assert!(inv.envs.iter().any(|(k, _)| k == ENV_BENCH_UNTIL_CRASH));+ let mut opts = options();+ opts.bench_until_crash = false;+ assert!(+ !opts+ .invocation()+ .envs+ .iter()+ .any(|(k, _)| k == ENV_BENCH_UNTIL_CRASH)+ );+ }++ #[test]+ fn discover_finds_crash_inputs_and_ignores_readme() {+ let findings = scratch("discover");+ let dir = crashes_dir(&findings);+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("README.txt"), "not a crash").unwrap();+ std::fs::write(dir.join("id:000001,sig:11,src:000007"), b"second").unwrap();+ std::fs::write(dir.join("id:000000,sig:06,src:000000"), b"first").unwrap();++ let found = discover_crash_inputs(&findings).unwrap();+ assert_eq!(found.len(), 2);+ let names: Vec<String> = found+ .iter()+ .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())+ .collect();+ assert!(names.iter().all(|n| n.starts_with(CRASH_PREFIX)));+ assert_eq!(names[0], "id:000000,sig:06,src:000000");+ }++ #[test]+ fn discover_returns_empty_when_no_crashes_directory() {+ let findings = scratch("empty");+ assert!(discover_crash_inputs(&findings).unwrap().is_empty());+ }+}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-fuzz/src/stats.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-fuzz/src/stats.rsnew file mode 100644index 00000000..b32c832a--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-fuzz/src/stats.rs@@ -0,0 +1,144 @@+// ©AngelaMos | 2026+// stats.rs++pub const STATS_FILE_NAME: &str = "fuzzer_stats";++const FIELD_EXECS_DONE: &str = "execs_done";+const FIELD_EXECS_PER_SEC: &str = "execs_per_sec";+const FIELD_SAVED_CRASHES: &str = "saved_crashes";+const FIELD_BITMAP_CVG: &str = "bitmap_cvg";+const FIELD_EDGES_FOUND: &str = "edges_found";+const FIELD_TOTAL_EDGES: &str = "total_edges";+const FIELD_AFL_VERSION: &str = "afl_version";+const PERCENT_SUFFIX: char = '%';++#[derive(Debug, thiserror::Error, PartialEq, Eq)]+pub enum StatsError {+ #[error("fuzzer_stats is missing field {0}")]+ MissingField(&'static str),+ #[error("fuzzer_stats field {field} has unparsable value {value}")]+ BadValue { field: &'static str, value: String },+}++#[derive(Debug, Clone, PartialEq)]+pub struct FuzzerStats {+ pub execs_done: u64,+ pub execs_per_sec: f64,+ pub saved_crashes: u64,+ pub bitmap_coverage_pct: f64,+ pub edges_found: u64,+ pub total_edges: u64,+ pub afl_version: String,+}++impl FuzzerStats {+ pub fn parse(text: &str) -> Result<FuzzerStats, StatsError> {+ Ok(FuzzerStats {+ execs_done: integer(text, FIELD_EXECS_DONE)?,+ execs_per_sec: decimal(text, FIELD_EXECS_PER_SEC)?,+ saved_crashes: integer(text, FIELD_SAVED_CRASHES)?,+ bitmap_coverage_pct: decimal(text, FIELD_BITMAP_CVG)?,+ edges_found: integer(text, FIELD_EDGES_FOUND)?,+ total_edges: integer(text, FIELD_TOTAL_EDGES)?,+ afl_version: field(text, FIELD_AFL_VERSION)?.to_owned(),+ })+ }+}++fn field<'a>(text: &'a str, name: &'static str) -> Result<&'a str, StatsError> {+ for line in text.lines() {+ let Some((key, value)) = line.split_once(':') else {+ continue;+ };+ if key.trim() == name {+ return Ok(value.trim());+ }+ }+ Err(StatsError::MissingField(name))+}++fn integer(text: &str, name: &'static str) -> Result<u64, StatsError> {+ let raw = field(text, name)?;+ raw.parse().map_err(|_| StatsError::BadValue {+ field: name,+ value: raw.to_owned(),+ })+}++fn decimal(text: &str, name: &'static str) -> Result<f64, StatsError> {+ let raw = field(text, name)?;+ let cleaned = raw.trim_end_matches(PERCENT_SUFFIX);+ cleaned.parse().map_err(|_| StatsError::BadValue {+ field: name,+ value: raw.to_owned(),+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ const REAL_STATS: &str = "\+start_time : 1784982517+last_update : 1784983139+run_time : 0+fuzzer_pid : 2790+cycles_done : 0+execs_done : 17895+execs_per_sec : 31728.72+execs_ps_last_min : 0.00+corpus_count : 161+bitmap_cvg : 11.13%+saved_crashes : 1+saved_hangs : 0+edges_found : 1791+total_edges : 16089+auto_dict_entries : 15+afl_banner : /opt/magma-work/out/libpng/afl/lisdex_libpng_read+afl_version : ++5.02c+target_mode : persistent shmem_testcase deferred+";++ #[test]+ fn parses_real_afl_stats_file() {+ let stats = FuzzerStats::parse(REAL_STATS).unwrap();+ assert_eq!(stats.execs_done, 17895);+ assert!((stats.execs_per_sec - 31728.72).abs() < f64::EPSILON);+ assert_eq!(stats.saved_crashes, 1);+ assert!((stats.bitmap_coverage_pct - 11.13).abs() < f64::EPSILON);+ assert_eq!(stats.edges_found, 1791);+ assert_eq!(stats.total_edges, 16089);+ assert_eq!(stats.afl_version, "++5.02c");+ }++ #[test]+ fn strips_percent_suffix_from_coverage() {+ let stats = FuzzerStats::parse(REAL_STATS).unwrap();+ assert!((stats.bitmap_coverage_pct - 11.13).abs() < f64::EPSILON);+ }++ #[test]+ fn missing_field_is_an_error_not_a_silent_zero() {+ let err = FuzzerStats::parse("execs_done : 5\n").unwrap_err();+ assert!(matches!(err, StatsError::MissingField(_)));+ }++ #[test]+ fn unparsable_value_is_an_error() {+ let text = REAL_STATS.replace("execs_done : 17895", "execs_done : lots");+ let err = FuzzerStats::parse(&text).unwrap_err();+ assert_eq!(+ err,+ StatsError::BadValue {+ field: FIELD_EXECS_DONE,+ value: "lots".to_owned()+ }+ );+ }++ #[test]+ fn tolerates_trailing_whitespace_in_values() {+ let stats = FuzzerStats::parse(REAL_STATS).unwrap();+ assert_eq!(stats.afl_version, "++5.02c");+ }+}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-fuzz/src/symbolize.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-fuzz/src/symbolize.rsnew file mode 100644index 00000000..e7e712a5--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-fuzz/src/symbolize.rs@@ -0,0 +1,260 @@+// ©AngelaMos | 2026+// symbolize.rs++use std::collections::BTreeMap;+use std::io::Write;+use std::path::Path;+use std::process::{Command, Stdio};++pub const LLVM_SYMBOLIZER_BIN: &str = "llvm-symbolizer";++const UNKNOWN_SYMBOL: &str = "??";+const FRAME_PREFIX: char = '#';+const MODULE_OFFSET_MARKER: &str = "+0x";+const HEX_RADIX: u32 = 16;++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct FrameLocation {+ pub line: usize,+ pub module: String,+ pub offset: u64,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Symbol {+ pub function: String,+ pub location: String,+}++#[must_use]+pub fn frame_locations(report: &str) -> Vec<FrameLocation> {+ let mut found = Vec::new();+ for (index, line) in report.lines().enumerate() {+ let trimmed = line.trim_start();+ if !trimmed.starts_with(FRAME_PREFIX) {+ continue;+ }+ let Some(marker) = line.find(MODULE_OFFSET_MARKER) else {+ continue;+ };+ let Some(open) = line[..marker].rfind('(') else {+ continue;+ };+ let Some(close) = line[marker..].find(')').map(|at| marker + at) else {+ continue;+ };+ let inner = &line[open + 1..close];+ let Some((module, offset_text)) = inner.split_once(MODULE_OFFSET_MARKER) else {+ continue;+ };+ let Ok(offset) = u64::from_str_radix(offset_text, HEX_RADIX) else {+ continue;+ };+ found.push(FrameLocation {+ line: index,+ module: module.to_owned(),+ offset,+ });+ }+ found+}++#[must_use]+pub fn apply_symbols(report: &str, symbols: &BTreeMap<(String, u64), Symbol>) -> String {+ let locations = frame_locations(report);+ let mut by_line: BTreeMap<usize, &Symbol> = BTreeMap::new();+ for location in &locations {+ if let Some(symbol) = symbols+ .get(&(location.module.clone(), location.offset))+ .filter(|symbol| symbol.function != UNKNOWN_SYMBOL)+ {+ by_line.insert(location.line, symbol);+ }+ }++ let mut out = String::with_capacity(report.len());+ for (index, line) in report.lines().enumerate() {+ if let Some(symbol) = by_line.get(&index) {+ let head = line+ .find(MODULE_OFFSET_MARKER)+ .and_then(|marker| line[..marker].rfind('('))+ .map_or(line, |open| &line[..open]);+ out.push_str(head.trim_end());+ out.push_str(" in ");+ out.push_str(&symbol.function);+ if symbol.location != UNKNOWN_SYMBOL && !symbol.location.is_empty() {+ out.push(' ');+ out.push_str(&symbol.location);+ }+ } else {+ out.push_str(line);+ }+ out.push('\n');+ }+ out+}++#[must_use]+pub fn parse_symbolizer_output(+ text: &str,+ offsets: &[u64],+ module: &str,+) -> BTreeMap<(String, u64), Symbol> {+ let mut symbols = BTreeMap::new();+ let mut lines = text.lines();+ for offset in offsets {+ let Some(function) = lines.next() else {+ break;+ };+ let location = lines.next().unwrap_or(UNKNOWN_SYMBOL);+ if lines+ .clone()+ .next()+ .is_some_and(|next| next.trim().is_empty())+ {+ lines.next();+ }+ symbols.insert(+ (module.to_owned(), *offset),+ Symbol {+ function: function.trim().to_owned(),+ location: location.trim().to_owned(),+ },+ );+ }+ symbols+}++#[must_use]+pub fn symbolize_report(report: &str) -> String {+ let locations = frame_locations(report);+ if locations.is_empty() {+ return report.to_owned();+ }++ let mut by_module: BTreeMap<String, Vec<u64>> = BTreeMap::new();+ for location in &locations {+ by_module+ .entry(location.module.clone())+ .or_default()+ .push(location.offset);+ }++ let mut symbols = BTreeMap::new();+ for (module, offsets) in by_module {+ if !Path::new(&module).is_file() {+ continue;+ }+ if let Some(resolved) = run_symbolizer(&module, &offsets) {+ symbols.extend(resolved);+ }+ }++ apply_symbols(report, &symbols)+}++fn run_symbolizer(module: &str, offsets: &[u64]) -> Option<BTreeMap<(String, u64), Symbol>> {+ let mut child = Command::new(LLVM_SYMBOLIZER_BIN)+ .arg(format!("--obj={module}"))+ .arg("--functions=short")+ .arg("--demangle")+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()+ .ok()?;++ {+ let stdin = child.stdin.as_mut()?;+ for offset in offsets {+ writeln!(stdin, "0x{offset:x}").ok()?;+ }+ }++ let output = child.wait_with_output().ok()?;+ let text = String::from_utf8_lossy(&output.stdout);+ Some(parse_symbolizer_output(&text, offsets, module))+}++#[cfg(test)]+mod tests {+ use super::*;++ const RAW: &str = "\+==38182==ERROR: AddressSanitizer: SEGV on unknown address 0x9526 (pc 0x7fb bp 0x7ff sp 0x7ff T0)+ #0 0x7f66678b253b (/lib/x86_64-linux-gnu/libc.so.6+0x4553b) (BuildId: 8e9f)+ #1 0x555a29663260 (/opt/out/harness+0x163260) (BuildId: bda3)+ #2 0x555a296caa6e (/opt/out/harness+0x1caa6e) (BuildId: bda3)+";++ #[test]+ fn extracts_module_and_offset_from_unsymbolized_frames() {+ let found = frame_locations(RAW);+ assert_eq!(found.len(), 3);+ assert_eq!(found[1].module, "/opt/out/harness");+ assert_eq!(found[1].offset, 0x0016_3260);+ assert_eq!(found[1].line, 2);+ }++ #[test]+ fn ignores_lines_that_are_not_frames() {+ let found = frame_locations("no frames here\njust text\n");+ assert!(found.is_empty());+ }++ #[test]+ fn rewrites_frames_with_resolved_symbols() {+ let mut symbols = BTreeMap::new();+ symbols.insert(+ ("/opt/out/harness".to_owned(), 0x0016_3260),+ Symbol {+ function: "magma_log".to_owned(),+ location: "/opt/magma/src/canary.c:92:5".to_owned(),+ },+ );+ let out = apply_symbols(RAW, &symbols);+ assert!(out.contains("#1 0x555a29663260 in magma_log /opt/magma/src/canary.c:92:5"));+ assert!(out.contains("#0 0x7f66678b253b (/lib/x86_64-linux-gnu/libc.so.6+0x4553b)"));+ }++ #[test]+ fn unresolved_symbols_leave_the_frame_untouched() {+ let mut symbols = BTreeMap::new();+ symbols.insert(+ ("/opt/out/harness".to_owned(), 0x0016_3260),+ Symbol {+ function: UNKNOWN_SYMBOL.to_owned(),+ location: UNKNOWN_SYMBOL.to_owned(),+ },+ );+ let out = apply_symbols(RAW, &symbols);+ assert!(out.contains("(/opt/out/harness+0x163260)"));+ assert!(!out.contains(" in ??"));+ }++ #[test]+ fn parses_symbolizer_pairs_in_order() {+ let text = "magma_log\n/opt/magma/src/canary.c:92:5\n\nMAGMA_png_handle_PLTE\n/repo/pngrutil.c:992:4\n\n";+ let offsets = [0x0016_3260_u64, 0x001c_aa6e_u64];+ let symbols = parse_symbolizer_output(text, &offsets, "/opt/out/harness");+ assert_eq!(+ symbols+ .get(&("/opt/out/harness".to_owned(), 0x0016_3260))+ .unwrap()+ .function,+ "magma_log"+ );+ assert_eq!(+ symbols+ .get(&("/opt/out/harness".to_owned(), 0x001c_aa6e))+ .unwrap()+ .location,+ "/repo/pngrutil.c:992:4"+ );+ }++ #[test]+ fn symbolizing_a_report_without_frames_is_a_noop() {+ assert_eq!(symbolize_report("nothing here\n"), "nothing here\n");+ }+}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex/Cargo.toml b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex/Cargo.tomlnew file mode 100644index 00000000..e05003ee--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex/Cargo.toml@@ -0,0 +1,22 @@+# ©AngelaMos | 2026+# Cargo.toml++[package]+name = "lisdex"+version = "0.0.0"+edition.workspace = true+rust-version.workspace = true+license.workspace = true+authors.workspace = true++[lints]+workspace = true++[[bin]]+name = "lisdex"+path = "src/main.rs"++[dependencies]+clap.workspace = true+lisdex-core.workspace = true+lisdex-fuzz.workspace = truediff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex/src/main.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex/src/main.rsnew file mode 100644index 00000000..64a5d99a--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex/src/main.rs@@ -0,0 +1,254 @@+// ©AngelaMos | 2026+// main.rs++use std::error::Error;+use std::path::PathBuf;+use std::process::ExitCode;+use std::time::Duration;++use clap::{Parser, Subcommand};+use lisdex_core::campaign::{Campaign, CampaignId, CampaignStatus};+use lisdex_core::report::SanitizerReport;+use lisdex_core::store::Store;+use lisdex_fuzz::runner::{self, AflOptions};++const UNKNOWN_TARGET: &str = "unknown";+const UNPARSED_KIND: &str = "unparsed";+const NO_STACK_HASH: &str = "none";+const STACK_HASH_SHORT_LEN: usize = 16;+const DISPLAYED_FRAMES: usize = 6;++#[derive(Parser)]+#[command(+ name = "lisdex",+ version,+ about = "keyless local zero-day parser fuzzer"+)]+struct Cli {+ #[command(subcommand)]+ command: Command,+}++#[derive(Subcommand)]+enum Command {+ #[command(about = "run an AFL++ campaign against an instrumented harness")]+ Fuzz(FuzzArgs),+ #[command(about = "list the crashes persisted for a campaign")]+ Crashes(CrashesArgs),+}++#[derive(clap::Args)]+struct FuzzArgs {+ #[arg(long, help = "instrumented harness binary to fuzz")]+ target: PathBuf,+ #[arg(long, help = "cmplog-instrumented build of the same harness")]+ cmplog: Option<PathBuf>,+ #[arg(long, help = "directory of seed inputs")]+ seeds: PathBuf,+ #[arg(long, help = "afl-fuzz output directory")]+ findings: PathBuf,+ #[arg(long, help = "sqlite database to persist the campaign and crashes")]+ db: PathBuf,+ #[arg(long, help = "campaign wall-clock limit in seconds")]+ duration: Option<u64>,+ #[arg(long, help = "campaign label (defaults to the target file name)")]+ label: Option<String>,+ #[arg(long, help = "stop as soon as the first crash is found")]+ until_crash: bool,+ #[arg(+ long,+ action = clap::ArgAction::Set,+ default_value_t = true,+ help = "skip afl-fuzz deterministic stages"+ )]+ skip_deterministic: bool,+}++#[derive(clap::Args)]+struct CrashesArgs {+ #[arg(long, help = "sqlite database written by a previous campaign")]+ db: PathBuf,+ #[arg(long, help = "campaign id to list")]+ campaign: i64,+}++fn main() -> ExitCode {+ match dispatch() {+ Ok(()) => ExitCode::SUCCESS,+ Err(err) => {+ eprintln!("lisdex: {err}");+ ExitCode::FAILURE+ }+ }+}++fn dispatch() -> Result<(), Box<dyn Error>> {+ match &Cli::parse().command {+ Command::Fuzz(args) => fuzz(args),+ Command::Crashes(args) => crashes(args),+ }+}++fn fuzz(args: &FuzzArgs) -> Result<(), Box<dyn Error>> {+ let label = args.label.clone().unwrap_or_else(|| {+ args.target+ .file_name()+ .map_or(UNKNOWN_TARGET.to_owned(), |name| {+ name.to_string_lossy().into_owned()+ })+ });++ let store = Store::open(&args.db)?;+ let mut campaign = Campaign::new(label.clone());+ let campaign_id = store.insert_campaign(&campaign)?;++ for status in [CampaignStatus::Building, CampaignStatus::Fuzzing] {+ campaign.advance(status)?;+ store.update_campaign_status(campaign_id, status)?;+ }++ let options = AflOptions {+ target: args.target.clone(),+ cmplog: args.cmplog.clone(),+ seeds: args.seeds.clone(),+ findings: args.findings.clone(),+ duration: args.duration.map(Duration::from_secs),+ bench_until_crash: args.until_crash,+ skip_deterministic: args.skip_deterministic,+ };++ println!("campaign {} target {label}", campaign_id.0);+ println!("running {}", runner::AFL_FUZZ_BIN);++ let outcome = match runner::run(&options) {+ Ok(outcome) => outcome,+ Err(err) => {+ fail_campaign(&store, &mut campaign, campaign_id);+ return Err(err.into());+ }+ };++ let (harvested, problems) =+ match runner::harvest(campaign_id, &options.target, &options.findings) {+ Ok(result) => result,+ Err(err) => {+ fail_campaign(&store, &mut campaign, campaign_id);+ return Err(err.into());+ }+ };++ let mut persisted = 0usize;+ let mut store_problems = Vec::new();+ for crash in &harvested {+ match store.insert_crash(crash) {+ Ok(_) => persisted += 1,+ Err(err) => store_problems.push(format!("crash not persisted: {err}")),+ }+ }++ let stats = &outcome.stats;+ println!("afl_version {}", stats.afl_version);+ println!("clean_exit {}", outcome.clean_exit);+ println!("execs_done {}", stats.execs_done);+ println!("execs_per_sec {:.2}", stats.execs_per_sec);+ println!(+ "edges {} / {} ({:.2}%)",+ stats.edges_found, stats.total_edges, stats.bitmap_coverage_pct+ );+ println!("crashes_saved {}", stats.saved_crashes);+ println!("crashes_persisted {persisted}");++ for crash in &harvested {+ let report = SanitizerReport::parse(crash.sanitizer_report());+ println!(+ " {} {} bytes {} {}",+ short_hash(crash.stack_hash()),+ crash.input().len(),+ report.as_ref().map_or(UNPARSED_KIND, |r| r.kind()),+ report+ .as_ref()+ .and_then(SanitizerReport::crash_site)+ .unwrap_or_default()+ );+ }++ for problem in problems.iter().chain(store_problems.iter()) {+ eprintln!("warning: {problem}");+ }++ if stats.saved_crashes > 0 && harvested.is_empty() {+ eprintln!(+ "warning: {} saved by {} but none harvested; check the instance layout under {}",+ stats.saved_crashes,+ runner::AFL_FUZZ_BIN,+ options.findings.display()+ );+ }++ if !outcome.clean_exit || !store_problems.is_empty() {+ fail_campaign(&store, &mut campaign, campaign_id);+ return Err(format!(+ "{} exited uncleanly or crashes were lost; campaign {} marked failed",+ runner::AFL_FUZZ_BIN,+ campaign_id.0+ )+ .into());+ }++ campaign.advance(CampaignStatus::Completed)?;+ store.update_campaign_status(campaign_id, CampaignStatus::Completed)?;++ Ok(())+}++fn fail_campaign(store: &Store, campaign: &mut Campaign, campaign_id: CampaignId) {+ if campaign.advance(CampaignStatus::Failed).is_err() {+ return;+ }+ if let Err(err) = store.update_campaign_status(campaign_id, CampaignStatus::Failed) {+ eprintln!("warning: could not record failed status: {err}");+ }+}++fn short_hash(hash: Option<&str>) -> String {+ match hash {+ Some(value) => value+ .char_indices()+ .nth(STACK_HASH_SHORT_LEN)+ .map_or(value, |(at, _)| &value[..at])+ .to_owned(),+ None => NO_STACK_HASH.to_owned(),+ }+}++fn crashes(args: &CrashesArgs) -> Result<(), Box<dyn Error>> {+ let store = Store::open(&args.db)?;+ let campaign_id = CampaignId(args.campaign);+ let campaign = store+ .get_campaign(campaign_id)?+ .ok_or("no such campaign in store")?;++ println!(+ "campaign {} target {} status {:?}",+ campaign_id.0,+ campaign.target(),+ campaign.status()+ );++ for crash in store.crashes_for_campaign(campaign_id)? {+ let report = SanitizerReport::parse(crash.sanitizer_report());+ println!(+ " stack_hash {} input {} bytes kind {}",+ crash.stack_hash().unwrap_or(NO_STACK_HASH),+ crash.input().len(),+ report.as_ref().map_or(UNPARSED_KIND, |r| r.kind())+ );+ if let Some(report) = report {+ for frame in report.frames().iter().take(DISPLAYED_FRAMES) {+ println!(" {frame}");+ }+ }+ }++ Ok(())+}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/dev.compose.yml b/PROJECTS/advanced/zero-day-vulnerability-scanner/dev.compose.ymlnew file mode 100644index 00000000..f49a22f8--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/dev.compose.yml@@ -0,0 +1,29 @@+# ©AngelaMos | 2026+# dev.compose.yml++name: lisdex-dev++services:+ toolchain:+ build:+ context: .+ dockerfile: Dockerfile.dev+ image: lisdex-dev-toolchain:latest+ container_name: lisdex-dev-toolchain+ init: true+ shm_size: 2gb+ environment:+ AFL_SKIP_CPUFREQ: "1"+ AFL_NO_AFFINITY: "1"+ AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES: "1"+ RUST_BACKTRACE: "1"+ volumes:+ - .:/work+ - cargo-target:/cargo-target+ - magma-work:/opt/magma-work+ working_dir: /work+ command: ["sleep", "infinity"]++volumes:+ cargo-target:+ magma-work:diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/harnesses/libpng_read.c b/PROJECTS/advanced/zero-day-vulnerability-scanner/harnesses/libpng_read.cnew file mode 100644index 00000000..62034597--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/harnesses/libpng_read.c@@ -0,0 +1,143 @@+// ©AngelaMos | 2026+// libpng_read.c++#include <setjmp.h>+#include <stddef.h>+#include <stdint.h>+#include <stdlib.h>+#include <string.h>++#include "png.h"++#define LISDEX_SIG_BYTES 8+#define LISDEX_MAX_ALLOC (64u * 1024u * 1024u)+#define LISDEX_MAX_PIXELS (1u << 24)++typedef struct {+ const uint8_t *data;+ size_t size;+ size_t offset;+} lisdex_buffer;++static void lisdex_read(png_structp png, png_bytep out, size_t count)+{+ lisdex_buffer *buf = (lisdex_buffer *)png_get_io_ptr(png);++ if (buf == NULL || buf->offset > buf->size ||+ count > buf->size - buf->offset) {+ png_error(png, "lisdex: read past end of buffer");+ return;+ }++ memcpy(out, buf->data + buf->offset, count);+ buf->offset += count;+}++static png_voidp lisdex_malloc(png_structp png, png_alloc_size_t size)+{+ (void)png;++ if (size == 0 || size > LISDEX_MAX_ALLOC) {+ return NULL;+ }++ return malloc((size_t)size);+}++static void lisdex_free(png_structp png, png_voidp ptr)+{+ (void)png;+ free(ptr);+}++int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)+{+ png_structp png = NULL;+ png_infop info = NULL;+ png_infop end_info = NULL;+ volatile png_bytep row = NULL;+ lisdex_buffer buf;+ png_uint_32 width = 0;+ png_uint_32 height = 0;+ png_uint_32 y = 0;+ int depth = 0;+ int color_type = 0;+ int interlace = 0;+ int passes = 1;+ int pass = 0;+ size_t rowbytes = 0;++ if (size < LISDEX_SIG_BYTES) {+ return 0;+ }++ if (png_sig_cmp((png_const_bytep)data, 0, LISDEX_SIG_BYTES) != 0) {+ return 0;+ }++ png = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL,+ NULL, lisdex_malloc, lisdex_free);+ if (png == NULL) {+ return 0;+ }++ info = png_create_info_struct(png);+ end_info = png_create_info_struct(png);+ if (info == NULL || end_info == NULL) {+ png_destroy_read_struct(&png, &info, &end_info);+ return 0;+ }++ if (setjmp(png_jmpbuf(png))) {+ free((png_bytep)row);+ png_destroy_read_struct(&png, &info, &end_info);+ return 0;+ }++ buf.data = data;+ buf.size = size;+ buf.offset = 0;++ png_set_read_fn(png, &buf, lisdex_read);+ png_set_crc_action(png, PNG_CRC_QUIET_USE, PNG_CRC_QUIET_USE);+#ifdef PNG_IGNORE_ADLER32+ png_set_option(png, PNG_IGNORE_ADLER32, PNG_OPTION_ON);+#endif++ png_read_info(png, info);++ if (png_get_IHDR(png, info, &width, &height, &depth, &color_type,+ &interlace, NULL, NULL) == 0) {+ png_destroy_read_struct(&png, &info, &end_info);+ return 0;+ }++ if (width == 0 || height > LISDEX_MAX_PIXELS / width) {+ png_destroy_read_struct(&png, &info, &end_info);+ return 0;+ }++ passes = png_set_interlace_handling(png);+ png_read_update_info(png, info);++ rowbytes = png_get_rowbytes(png, info);+ row = (png_bytep)malloc(rowbytes > 0 ? rowbytes : 1);+ if (row == NULL) {+ png_destroy_read_struct(&png, &info, &end_info);+ return 0;+ }++ for (pass = 0; pass < passes; pass++) {+ for (y = 0; y < height; y++) {+ png_read_row(png, (png_bytep)row, NULL);+ }+ }++ free((png_bytep)row);+ row = NULL;++ png_read_end(png, end_info);+ png_destroy_read_struct(&png, &info, &end_info);++ return 0;+}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/justfile b/PROJECTS/advanced/zero-day-vulnerability-scanner/justfileindex aabf6709..bfce85e6 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/justfile+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/justfile@@ -13,7 +13,7 @@ test:cargo test --workspaceclippy:- cargo clippy --workspace --all-targets+ cargo clippy --workspace --all-targets -- -D warningsfmt:cargo fmt@@ -24,3 +24,36 @@ fmt-check:lint: fmt-check clippycheck: lint test++dev-build:+ docker compose -f dev.compose.yml build++dev-up:+ docker compose -f dev.compose.yml up -d++dev-down:+ docker compose -f dev.compose.yml down++dev-nuke:+ docker compose -f dev.compose.yml down -v --remove-orphans++dev-sh:+ docker compose -f dev.compose.yml exec toolchain bash++dev-run CMD:+ docker compose -f dev.compose.yml exec toolchain bash -c {{quote(CMD)}}++dev-test:+ docker compose -f dev.compose.yml exec toolchain cargo test --workspace++dev-verify:+ docker compose -f dev.compose.yml exec toolchain bash scripts/verify-toolchain.sh++magma-libpng:+ docker compose -f dev.compose.yml exec toolchain bash scripts/build-magma-libpng.sh++magma-libpng-reset:+ docker compose -f dev.compose.yml exec toolchain bash scripts/build-magma-libpng.sh reset++m1-gate:+ docker compose -f dev.compose.yml exec toolchain bash scripts/m1-gate.shdiff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/build-magma-libpng.sh b/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/build-magma-libpng.shnew file mode 100755index 00000000..efcf45bc--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/build-magma-libpng.sh@@ -0,0 +1,209 @@+#!/usr/bin/env bash+# ©AngelaMos | 2026+# build-magma-libpng.sh++set -euo pipefail++MAGMA_SRC="${MAGMA_ROOT:-/opt/magma}"+MAGMA="$MAGMA_SRC/magma"+WORK="${MAGMA_WORK:-/opt/magma-work}"+TARGET="$WORK/libpng"+SHARED="$WORK/shared"+OUT_ROOT="$WORK/out/libpng"+HARNESS_SRC="${LISDEX_HARNESS:-/work/harnesses/libpng_read.c}"+DRIVER="${AFL_DRIVER:-/usr/local/lib/afl/libAFLDriver.a}"+HARNESS_BIN="lisdex_libpng_read"+PATCH_STAMP="$TARGET/.lisdex-patched"+MAGMA_STAMP="$WORK/.lisdex-magma-commit"+EXPECTED_LIBPNG_COMMIT="a37d4836519517bdce6cb9d956092321eca3e73b"+VARIANTS=(afl cmplog)+LISDEX_EXCLUDED_BUGS="${LISDEX_EXCLUDED_BUGS:-PNG005 PNG002}"++CANARY_FLAGS="-include $MAGMA/src/canary.h -DMAGMA_ENABLE_CANARIES -DMAGMA_FATAL_CANARIES -g -O0"++log() {+ printf '\n[lisdex] %s\n' "$1"+}++die() {+ printf '\n[lisdex] FATAL: %s\n' "$1" >&2+ exit 1+}++if [ "${1:-}" = "reset" ]; then+ log "resetting work tree $WORK"+ rm -rf "$TARGET" "$OUT_ROOT" "$SHARED" "$MAGMA_STAMP"+fi++[ -d "$MAGMA_SRC" ] || die "magma source missing at $MAGMA_SRC"+[ -f "$HARNESS_SRC" ] || die "hand-written harness missing at $HARNESS_SRC"+[ -f "$DRIVER" ] || die "libAFLDriver.a missing at $DRIVER"++log "stage 1/6: prepare work tree"+mkdir -p "$WORK" "$SHARED" "$OUT_ROOT"+if [ ! -d "$TARGET" ]; then+ cp -r "$MAGMA_SRC/targets/libpng" "$TARGET"+fi++for BUG in $LISDEX_EXCLUDED_BUGS; do+ if [ -f "$TARGET/patches/bugs/$BUG.patch" ]; then+ rm -f "$TARGET/patches/bugs/$BUG.patch"+ printf ' EXCLUDED %s: canary condition is trivially true on valid input;\n' "$BUG"+ printf ' see docs/research/08 "Canary fidelity"\n'+ fi+done+APPLIED_BUGS=""+for PATCH in "$TARGET"/patches/bugs/*.patch; do+ [ -f "$PATCH" ] || continue+ BUG_NAME="$(basename "$PATCH")"+ APPLIED_BUGS="$APPLIED_BUGS ${BUG_NAME%.patch}"+done+printf ' bug canaries selected:%s\n' "$APPLIED_BUGS"++MAGMA_COMMIT="$(git -C "$MAGMA_SRC" rev-parse HEAD)"+STAMPED_MAGMA=""+[ -f "$MAGMA_STAMP" ] && STAMPED_MAGMA="$(cat "$MAGMA_STAMP")"+if [ -n "$STAMPED_MAGMA" ] && [ "$STAMPED_MAGMA" != "$MAGMA_COMMIT" ]; then+ die "work tree was built from magma $STAMPED_MAGMA but the image ships $MAGMA_COMMIT - run: just magma-libpng-reset"+fi+printf '%s' "$MAGMA_COMMIT" > "$MAGMA_STAMP"+printf ' magma commit: %s\n' "$MAGMA_COMMIT"++log "stage 2/6: fetch libpng (pinned by magma)"+if [ ! -d "$TARGET/repo" ]; then+ TARGET="$TARGET" bash "$TARGET/fetch.sh"+else+ printf ' already fetched\n'+fi+LIBPNG_COMMIT="$(git -C "$TARGET/repo" rev-parse HEAD)"+printf ' libpng commit: %s\n' "$LIBPNG_COMMIT"+if [ "$LIBPNG_COMMIT" != "$EXPECTED_LIBPNG_COMMIT" ]; then+ die "libpng is at $LIBPNG_COMMIT, expected the magma-pinned $EXPECTED_LIBPNG_COMMIT"+fi++log "stage 3/6: apply magma setup + bug-canary patches"+if [ -f "$PATCH_STAMP" ]; then+ STAMPED="$(cat "$PATCH_STAMP")"+ printf ' already applied:%s\n' "$STAMPED"+ if [ "$STAMPED" != "$APPLIED_BUGS" ]; then+ die "canary selection changed (applied:$STAMPED wanted:$APPLIED_BUGS) - run: just magma-libpng-reset"+ fi+else+ TARGET="$TARGET" bash "$MAGMA/apply_patches.sh"+ printf '%s' "$APPLIED_BUGS" > "$PATCH_STAMP"+ printf ' applied:%s\n' "$APPLIED_BUGS"+fi+CANARY_SITES="$(grep -rho 'MAGMA_LOG' "$TARGET/repo"/*.c 2>/dev/null | wc -l || true)"+printf ' MAGMA_LOG call sites in libpng sources: %s\n' "$CANARY_SITES"+if [ "${CANARY_SITES:-0}" -eq 0 ]; then+ die "no canary call sites found; patches did not apply"+fi++log "stage 4/6: build magma monitor (uninstrumented)"+(+ export MAGMA SHARED+ export OUT="$OUT_ROOT"+ export CC=clang+ export CFLAGS=""+ export LDFLAGS=""+ export LIBS="-lrt"+ bash "$MAGMA/prebuild.sh"+)+[ -x "$OUT_ROOT/monitor" ] || die "magma monitor was not built"+printf ' monitor: %s\n' "$OUT_ROOT/monitor"++for VARIANT in "${VARIANTS[@]}"; do+ log "stage 5/6: canary runtime [$VARIANT]"+ (+ export MAGMA SHARED+ export OUT="$OUT_ROOT/$VARIANT"+ mkdir -p "$OUT"++ export CC=clang+ export LD=ld.lld+ export CFLAGS="-DMAGMA_FATAL_CANARIES -g -O0"+ export LDFLAGS=""++ bash "$MAGMA/build.sh"+ )+ [ -f "$OUT_ROOT/$VARIANT/magma.o" ] || die "magma.o not produced for $VARIANT"++ log "stage 5/6: instrumented target build [$VARIANT]"+ (+ export MAGMA SHARED TARGET+ export OUT="$OUT_ROOT/$VARIANT"+ mkdir -p "$OUT"++ export CC=afl-clang-lto+ export CXX=afl-clang-lto+++ export AR=llvm-ar+ export RANLIB=llvm-ranlib+ export AS=llvm-as+ export NM=llvm-nm+ export LD=ld.lld++ export AFL_USE_ASAN=1+ export AFL_USE_UBSAN=1+ export AFL_QUIET=1+ if [ "$VARIANT" = "cmplog" ]; then+ export AFL_LLVM_CMPLOG=1+ fi++ export CFLAGS="$CANARY_FLAGS"+ export CXXFLAGS="$CANARY_FLAGS"+ export LDFLAGS="-g"+ export LIBS=""++ cd "$TARGET/repo"+ autoreconf -f -i+ ./configure --with-libpng-prefix=MAGMA_ --disable-shared+ make -j"$(nproc)" clean+ make -j"$(nproc)" libpng16.la+ cp .libs/libpng16.a "$OUT/"++ $CC $CFLAGS -I. "$HARNESS_SRC" -o "$OUT/$HARNESS_BIN" \+ .libs/libpng16.a -L"$OUT" -l:magma.o -lrt "$DRIVER" -lz -g+ )+done++log "stage 6/6: verify instrumentation is actually present"+FAILURES=0+for VARIANT in "${VARIANTS[@]}"; do+ BIN="$OUT_ROOT/$VARIANT/$HARNESS_BIN"+ printf ' [%s] %s\n' "$VARIANT" "$BIN"+ if [ ! -x "$BIN" ]; then+ printf ' FAIL binary missing\n'+ FAILURES=$((FAILURES + 1))+ continue+ fi+ SYMS="$(nm "$BIN" 2>/dev/null || true)"+ ASAN_N="$(printf '%s' "$SYMS" | grep -c asan || true)"+ UBSAN_N="$(printf '%s' "$SYMS" | grep -c ubsan || true)"+ AFL_N="$(printf '%s' "$SYMS" | grep -cE '__afl_area_ptr|__sanitizer_cov' || true)"+ CANARY_N="$(printf '%s' "$SYMS" | grep -c magma_log || true)"+ CMPLOG_N="$(printf '%s' "$SYMS" | grep -c __cmplog || true)"++ [ "$ASAN_N" -gt 100 ] && printf ' PASS ASAN symbols: %s\n' "$ASAN_N" \+ || { printf ' FAIL ASAN symbols: %s\n' "$ASAN_N"; FAILURES=$((FAILURES + 1)); }+ [ "$UBSAN_N" -gt 0 ] && printf ' PASS UBSAN symbols: %s\n' "$UBSAN_N" \+ || { printf ' FAIL UBSAN symbols: %s\n' "$UBSAN_N"; FAILURES=$((FAILURES + 1)); }+ [ "$AFL_N" -gt 0 ] && printf ' PASS AFL coverage symbols: %s\n' "$AFL_N" \+ || { printf ' FAIL AFL coverage symbols: %s\n' "$AFL_N"; FAILURES=$((FAILURES + 1)); }+ [ "$CANARY_N" -gt 0 ] && printf ' PASS magma canary runtime linked (magma_log)\n' \+ || { printf ' FAIL magma canary runtime NOT linked\n'; FAILURES=$((FAILURES + 1)); }+ if [ "$VARIANT" = "cmplog" ]; then+ [ "$CMPLOG_N" -gt 0 ] && printf ' PASS cmplog instrumentation: %s symbols\n' "$CMPLOG_N" \+ || { printf ' FAIL cmplog instrumentation absent\n'; FAILURES=$((FAILURES + 1)); }+ fi+done++printf '\n'+if [ "$FAILURES" -eq 0 ]; then+ printf '[lisdex] MAGMA LIBPNG TARGET READY (canaries ON, fixes OFF, FATAL canaries ON)\n'+ printf '[lisdex] fuzz target : %s\n' "$OUT_ROOT/afl/$HARNESS_BIN"+ printf '[lisdex] cmplog : %s\n' "$OUT_ROOT/cmplog/$HARNESS_BIN"+ printf '[lisdex] monitor : %s\n' "$OUT_ROOT/monitor"+ exit 0+fi+printf '[lisdex] BUILD VERIFICATION FAILED: %d check(s)\n' "$FAILURES"+exit 1diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/m1-gate.sh b/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/m1-gate.shnew file mode 100755index 00000000..aeaa4372--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/m1-gate.sh@@ -0,0 +1,147 @@+#!/usr/bin/env bash+# ©AngelaMos | 2026+# m1-gate.sh++set -euo pipefail++WORK="${MAGMA_WORK:-/opt/magma-work}"+OUT_ROOT="$WORK/out/libpng"+REPO="$WORK/libpng/repo"+HARNESS_BIN="lisdex_libpng_read"+CORPUS="$WORK/gate/corpus"+FINDINGS="$WORK/gate/findings"+DB="$WORK/gate/lisdex.sqlite"+GATE_DURATION="${LISDEX_GATE_DURATION:-300}"+EXPECTED_FRAME_PREFIX="MAGMA_png_"+EXPECTED_BUG="${LISDEX_GATE_BUG:-PNG003}"+STACK_HASH_HEX_LEN=64+LISDEX_BIN="${CARGO_TARGET_DIR:-/cargo-target}/debug/lisdex"++log() {+ printf '\n[gate] %s\n' "$1"+}++die() {+ printf '\n[gate] FAIL: %s\n' "$1" >&2+ exit 1+}++[ -x "$OUT_ROOT/afl/$HARNESS_BIN" ] || die "target not built; run: just magma-libpng"+[ -x "$OUT_ROOT/cmplog/$HARNESS_BIN" ] || die "cmplog target not built; run: just magma-libpng"++log "stage 1/5: build lisdex CLI"+cargo build -p lisdex+[ -x "$LISDEX_BIN" ] || die "lisdex binary not found at $LISDEX_BIN"+"$LISDEX_BIN" --version++log "stage 2/5: seed corpus from the library's own test files"+rm -rf "$CORPUS" "$FINDINGS" "$DB"+mkdir -p "$CORPUS"+cp "$REPO"/contrib/pngsuite/*.png "$CORPUS/"+SEED_COUNT="$(find "$CORPUS" -name '*.png' | wc -l)"+printf ' seeds: %s\n' "$SEED_COUNT"++log "stage 2b/5: oracle baseline - every valid seed must run clean"+BASELINE_FAILED=0+BASELINE_BAD=""+for SEED in "$CORPUS"/*.png; do+ if ! ASAN_OPTIONS=detect_leaks=0 "$OUT_ROOT/afl/$HARNESS_BIN" "$SEED" >/dev/null 2>&1; then+ BASELINE_FAILED=$((BASELINE_FAILED + 1))+ BASELINE_BAD="$BASELINE_BAD $(basename "$SEED")"+ fi+done+if [ "$BASELINE_FAILED" -ne 0 ]; then+ printf ' %s of %s valid seeds CRASH the target:%s\n' \+ "$BASELINE_FAILED" "$SEED_COUNT" "$BASELINE_BAD"+ die "oracle is unsound - a canary fires on valid input, so any 'bug found' is meaningless"+fi+printf ' PASS %s/%s valid seeds run clean\n' "$SEED_COUNT" "$SEED_COUNT"++log "stage 3/5: lisdex drives the campaign"+"$LISDEX_BIN" fuzz \+ --target "$OUT_ROOT/afl/$HARNESS_BIN" \+ --cmplog "$OUT_ROOT/cmplog/$HARNESS_BIN" \+ --seeds "$CORPUS" \+ --findings "$FINDINGS" \+ --db "$DB" \+ --duration "$GATE_DURATION" \+ --until-crash \+ --label magma-libpng | tee "$WORK/gate/fuzz-summary.txt"++log "stage 4/5: read the crash back out of SQLite"+[ -f "$DB" ] || die "no database was created at $DB"+CRASH_LIST="$("$LISDEX_BIN" crashes --db "$DB" --campaign 1)"+printf '%s\n' "$CRASH_LIST"++log "stage 5/5: assert the gate"+FAILURES=0++CRASH_ROWS="$(sqlite3 "$DB" 'SELECT COUNT(*) FROM crashes;')"+if [ "${CRASH_ROWS:-0}" -ge 1 ]; then+ printf ' PASS crashes persisted in sqlite: %s\n' "$CRASH_ROWS"+else+ printf ' FAIL no crash rows in sqlite\n'+ FAILURES=$((FAILURES + 1))+fi++STATUS="$(sqlite3 "$DB" 'SELECT status FROM campaigns WHERE id = 1;')"+if [ "$STATUS" = "completed" ]; then+ printf ' PASS campaign reached terminal status: %s\n' "$STATUS"+else+ printf ' FAIL campaign status is %s, expected completed\n' "$STATUS"+ FAILURES=$((FAILURES + 1))+fi++ROW_SQL='SELECT %s FROM crashes WHERE id = (SELECT MIN(id) FROM crashes);'+HASH_LEN="$(sqlite3 "$DB" "$(printf "$ROW_SQL" 'LENGTH(stack_hash)')")"+if [ "${HASH_LEN:-0}" = "$STACK_HASH_HEX_LEN" ]; then+ printf ' PASS stack hash persisted (sha256, %s hex chars)\n' "$STACK_HASH_HEX_LEN"+else+ printf ' FAIL stack hash length is %s, expected %s\n' "${HASH_LEN:-none}" "$STACK_HASH_HEX_LEN"+ FAILURES=$((FAILURES + 1))+fi++INPUT_LEN="$(sqlite3 "$DB" "$(printf "$ROW_SQL" 'LENGTH(input)')")"+if [ "${INPUT_LEN:-0}" -gt 0 ]; then+ printf ' PASS crashing input bytes persisted: %s bytes\n' "$INPUT_LEN"+else+ printf ' FAIL crashing input is empty\n'+ FAILURES=$((FAILURES + 1))+fi++REPORT="$(sqlite3 "$DB" "$(printf "$ROW_SQL" 'sanitizer_report')")"++if printf '%s' "$REPORT" | grep -q "$EXPECTED_FRAME_PREFIX"; then+ FRAME="$(printf '%s' "$REPORT" | grep -o "${EXPECTED_FRAME_PREFIX}[a-zA-Z_]*" | head -1)"+ printf ' PASS crash attributed inside libpng: %s\n' "$FRAME"+else+ printf ' FAIL no %s frame in the crash stack\n' "$EXPECTED_FRAME_PREFIX"+ FAILURES=$((FAILURES + 1))+fi++CANARY_LOC="$(printf '%s\n' "$REPORT" | grep -A1 'in magma_log' | tail -1 \+ | grep -oE '/[^ ]+\.c:[0-9]+' | head -1 || true)"+if [ -n "$CANARY_LOC" ]; then+ CANARY_FILE="${CANARY_LOC%:*}"+ CANARY_LINE="${CANARY_LOC##*:}"+ BUG_ID="$(awk -v n="$CANARY_LINE" 'NR == n' "$CANARY_FILE" 2>/dev/null \+ | grep -oE 'MAGMA_LOG\("[A-Z0-9]+"' | grep -oE '[A-Z]+[0-9]+' | head -1 || true)"+ if [ "$BUG_ID" = "$EXPECTED_BUG" ]; then+ printf ' PASS canary resolved to bug id %s at %s\n' "$BUG_ID" "$CANARY_LOC"+ else+ printf ' FAIL canary at %s resolved to "%s", expected %s\n' \+ "$CANARY_LOC" "${BUG_ID:-unresolved}" "$EXPECTED_BUG"+ FAILURES=$((FAILURES + 1))+ fi+else+ printf ' FAIL no magma_log frame; crash is not an attributable canary trigger\n'+ FAILURES=$((FAILURES + 1))+fi++printf '\n'+if [ "$FAILURES" -eq 0 ]; then+ printf '[gate] M1 EXIT GATE PASSED\n'+ exit 0+fi+printf '[gate] M1 EXIT GATE FAILED: %d assertion(s)\n' "$FAILURES"+exit 1diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/verify-toolchain.sh b/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/verify-toolchain.shnew file mode 100755index 00000000..b6cbe2da--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/verify-toolchain.sh@@ -0,0 +1,219 @@+#!/usr/bin/env bash+# ©AngelaMos | 2026+# verify-toolchain.sh++set -uo pipefail++EXPECTED_MAGMA_COMMIT="75d1ae7b180443a778b8830c79176ca5f93642ac"+EXPECTED_RUST="1.97.0"+EXPECTED_AFL="5.02c"+EXPECTED_LIBPNG_CANARIES=7+MIN_ASAN_SYMBOLS=100+FUZZ_SMOKE_TIMEOUT_SECS=120+CORE_PATTERN_PATH=/proc/sys/kernel/core_pattern+FAILURES=0+WARNINGS=0++ok() {+ printf ' PASS %s\n' "$1"+}++fail() {+ printf ' FAIL %s\n' "$1"+ FAILURES=$((FAILURES + 1))+}++warn() {+ printf ' WARN %s\n' "$1"+ WARNINGS=$((WARNINGS + 1))+}++section() {+ printf '\n== %s ==\n' "$1"+}++require_cmd() {+ if command -v "$1" >/dev/null 2>&1; then+ ok "$1 -> $(command -v "$1")"+ else+ fail "$1 not on PATH"+ fi+}++section "Fuzzing engine (AFL++)"+for c in afl-fuzz afl-clang-lto afl-clang-lto++ afl-clang-fast afl-cmin afl-tmin afl-showmap; do+ require_cmd "$c"+done+AFL_BANNER="$(afl-fuzz -h 2>&1 || true)"+AFL_VERSION="$(printf '%s' "$AFL_BANNER" | grep -oE 'afl-fuzz\+\+[0-9][0-9.]*[a-z]*' | head -1)"+if [ "$AFL_VERSION" = "afl-fuzz++$EXPECTED_AFL" ]; then+ ok "afl-fuzz version pinned: $AFL_VERSION"+elif [ -n "$AFL_VERSION" ]; then+ fail "afl-fuzz is $AFL_VERSION, expected afl-fuzz++$EXPECTED_AFL"+else+ fail "afl-fuzz did not report a recognizable version banner"+fi++section "Host crash-reporting environment"+CORE_PATTERN="$(cat "$CORE_PATTERN_PATH" 2>/dev/null || true)"+printf ' INFO %s = %s\n' "$CORE_PATTERN_PATH" "${CORE_PATTERN:-unreadable}"+case "$CORE_PATTERN" in+ \|*)+ warn "core_pattern pipes cores to a userspace handler; afl-fuzz can mis-classify"+ warn "crashes as hangs and lose them. This container sets"+ warn "AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES=1, so the degradation is SILENT at runtime."+ warn "Remedy (host, needs root): echo core > $CORE_PATTERN_PATH"+ ;;+ *)+ ok "core_pattern is not piped to a userspace handler"+ ;;+esac++section "LLVM toolchain (afl-clang-lto requirements)"+require_cmd clang+require_cmd clang+++for c in llvm-ar llvm-ranlib llvm-as llvm-nm ld.lld; do+ require_cmd "$c"+done+printf ' INFO %s\n' "$(clang --version | head -1)"++section "AFL++ driver + libclang"+if [ -f "${AFL_DRIVER:-/usr/local/lib/afl/libAFLDriver.a}" ]; then+ ok "libAFLDriver.a present at ${AFL_DRIVER:-/usr/local/lib/afl/libAFLDriver.a}"+else+ fail "libAFLDriver.a missing"+fi+LIBCLANG="$(find /usr/lib -name 'libclang.so*' -o -name 'libclang-*.so*' 2>/dev/null | head -1)"+if [ -n "$LIBCLANG" ]; then+ ok "libclang present at $LIBCLANG"+else+ fail "libclang.so missing (clang-sys will not link in M3)"+fi++section "Rust toolchain"+require_cmd cargo+require_cmd rustc+if rustc --version | grep -q "$EXPECTED_RUST"; then+ ok "rustc pinned: $(rustc --version)"+else+ fail "rustc is $(rustc --version), expected $EXPECTED_RUST"+fi+if cargo clippy --version >/dev/null 2>&1; then+ ok "clippy: $(cargo clippy --version)"+else+ fail "clippy missing"+fi+if cargo fmt --version >/dev/null 2>&1; then+ ok "rustfmt: $(cargo fmt --version)"+else+ fail "rustfmt missing"+fi++section "Magma benchmark source"+MAGMA_ROOT="${MAGMA_ROOT:-/opt/magma}"+if [ -d "$MAGMA_ROOT" ]; then+ ACTUAL="$(git -C "$MAGMA_ROOT" rev-parse HEAD 2>/dev/null)"+ if [ "$ACTUAL" = "$EXPECTED_MAGMA_COMMIT" ]; then+ ok "magma pinned at $ACTUAL"+ else+ fail "magma at $ACTUAL, expected $EXPECTED_MAGMA_COMMIT"+ fi+ PNG_BUGS="$(ls "$MAGMA_ROOT/targets/libpng/patches/bugs/" 2>/dev/null | wc -l)"+ if [ "$PNG_BUGS" -eq 7 ]; then+ ok "libpng canary patches: $PNG_BUGS (PNG001-PNG007)"+ else+ fail "libpng canary patches: $PNG_BUGS, expected 7"+ fi+ for f in magma/src/canary.c magma/src/storage.c magma/build.sh magma/apply_patches.sh \+ targets/libpng/build.sh targets/libpng/fetch.sh; do+ if [ -f "$MAGMA_ROOT/$f" ]; then+ ok "magma file present: $f"+ else+ fail "magma file missing: $f"+ fi+ done+else+ fail "magma source tree missing at $MAGMA_ROOT"+fi++section "End-to-end spine: afl-clang-lto + ASAN + cmplog + afl-fuzz"+WORK="$(mktemp -d)"+trap 'rm -rf "$WORK"' EXIT+cat > "$WORK/planted.c" <<'EOF'+#include <stdint.h>+#include <stddef.h>+#include <string.h>+int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {+ char buf[8];+ if (size >= 4 && memcmp(data, "BOOM", 4) == 0) {+ memcpy(buf, data, size);+ return buf[0];+ }+ return 0;+}+EOF++export AR=llvm-ar RANLIB=llvm-ranlib AS=llvm-as NM=llvm-nm+DRIVER="${AFL_DRIVER:-/usr/local/lib/afl/libAFLDriver.a}"++if AFL_USE_ASAN=1 afl-clang-lto -O0 -g "$WORK/planted.c" "$DRIVER" \+ -o "$WORK/harness" >"$WORK/build.log" 2>&1; then+ ok "afl-clang-lto built ASAN harness"+else+ fail "afl-clang-lto ASAN build failed"+ tail -20 "$WORK/build.log"+fi++if AFL_USE_ASAN=1 AFL_LLVM_CMPLOG=1 afl-clang-lto -O0 -g "$WORK/planted.c" "$DRIVER" \+ -o "$WORK/harness_cmplog" >"$WORK/build_cmplog.log" 2>&1; then+ ok "afl-clang-lto built cmplog harness"+else+ fail "afl-clang-lto cmplog build failed"+ tail -20 "$WORK/build_cmplog.log"+fi++if [ -f "$WORK/harness" ]; then+ ASAN_SYMS="$(nm "$WORK/harness" 2>/dev/null | grep -c asan)"+ AFL_SYMS="$(nm "$WORK/harness" 2>/dev/null | grep -cE '__afl_area_ptr|__sanitizer_cov')"+ if [ "$ASAN_SYMS" -gt 100 ]; then+ ok "ASAN instrumentation present in binary ($ASAN_SYMS symbols)"+ else+ fail "ASAN instrumentation absent or thin ($ASAN_SYMS symbols)"+ fi+ if [ "$AFL_SYMS" -gt 0 ]; then+ ok "AFL coverage instrumentation present in binary ($AFL_SYMS symbols)"+ else+ fail "AFL coverage instrumentation absent ($AFL_SYMS symbols)"+ fi+fi++if [ -f "$WORK/harness" ] && [ -f "$WORK/harness_cmplog" ]; then+ mkdir -p "$WORK/in" "$WORK/out"+ printf 'AAAA' > "$WORK/in/seed"+ AFL_SKIP_CPUFREQ=1 AFL_NO_AFFINITY=1 AFL_NO_UI=1 AFL_BENCH_UNTIL_CRASH=1 \+ timeout 120 afl-fuzz -i "$WORK/in" -o "$WORK/out" -m none \+ -c "$WORK/harness_cmplog" -- "$WORK/harness" >"$WORK/fuzz.log" 2>&1+ CRASH="$(find "$WORK/out" -path '*/crashes/id:*' 2>/dev/null | head -1)"+ if [ -n "$CRASH" ]; then+ ok "afl-fuzz found the planted bug: $(basename "$CRASH")"+ REPRO_OUT="$("$WORK/harness" "$CRASH" 2>&1 || true)"+ SANI="$(printf '%s' "$REPRO_OUT" | grep -oE 'AddressSanitizer: [a-z-]+' | head -1)"+ if [ -n "$SANI" ]; then+ ok "crash reproduces under ASAN: $SANI"+ else+ fail "crash did not reproduce with an ASAN report"+ printf '%s\n' "$REPRO_OUT" | head -10+ fi+ else+ fail "afl-fuzz did not find the planted bug within the time budget"+ tail -25 "$WORK/fuzz.log"+ fi+fi++section "Result"+if [ "$FAILURES" -eq 0 ]; then+ printf 'TOOLCHAIN VERIFIED: all checks passed\n'+ exit 0+fi+printf 'TOOLCHAIN BROKEN: %d check(s) failed\n' "$FAILURES"+exit 1