mirror of
https://github.com/CyberSecurityUP/NeuroSploit.git
synced 2026-12-05 02:24:17 +01:00
feat(harness): add coverage tracking ledger
Track tested endpoints × vulnerability classes to identify attack surface gaps: - 55+ web vuln classes, 30+ infra, 17 cloud, 20 mobile, 17 binary - CWE-to-class mapping for 40+ CWE IDs - Agent name inference when CWE is missing - Technology-aware filtering (e.g., GraphQL classes only when detected) - Gap analysis with priority ranking - Persistence to coverage.json for cross-run accumulation - Integrated into exploration loop for all modes Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
77aadf5ed1
commit
53c547d4fb
1 file changed
+697
@@ -0,0 +1,697 @@
|
||||
//! Coverage ledger — tracks tested attack surfaces and identifies gaps.
|
||||
//!
|
||||
//! Every finding written by an agent (or the exploration loop) is logged here
|
||||
//! with its endpoint and CWE/vuln-class. At the end of a run the ledger
|
||||
//! reports which endpoints still have untested vulnerability classes, ranked
|
||||
//! by priority so the exploration loop (or a human operator) knows where to
|
||||
//! look next.
|
||||
//!
|
||||
//! Persistence: the ledger is saved to `<workdir>/coverage.json` and loaded
|
||||
//! on the next run against the same target so progress accumulates.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::path::Path;
|
||||
|
||||
// ── Vulnerability class taxonomy ────────────────────────────────────────────
|
||||
|
||||
/// Canonical vulnerability classes grouped by domain.
|
||||
/// Every agent finding's CWE is mapped to one of these for coverage tracking.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub enum VulnDomain {
|
||||
Web,
|
||||
Infra,
|
||||
Cloud,
|
||||
Mobile,
|
||||
Binary,
|
||||
}
|
||||
|
||||
impl VulnDomain {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
VulnDomain::Web => "web",
|
||||
VulnDomain::Infra => "infra",
|
||||
VulnDomain::Cloud => "cloud",
|
||||
VulnDomain::Mobile => "mobile",
|
||||
VulnDomain::Binary => "binary",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn classes(&self) -> &'static [&'static str] {
|
||||
match self {
|
||||
VulnDomain::Web => &[
|
||||
"xss-reflected", "xss-stored", "xss-dom",
|
||||
"sqli-union", "sqli-blind", "sqli-error", "sqli-time",
|
||||
"ssrf", "ssti", "xxe",
|
||||
"lfi", "rfi", "path-traversal",
|
||||
"command-injection", "code-injection",
|
||||
"cors-misconfig", "csrf",
|
||||
"idor", "bola", "bfla",
|
||||
"auth-bypass", "session-fixation", "session-hijack",
|
||||
"jwt-attack", "oauth-misconfig",
|
||||
"file-upload", "unrestricted-upload",
|
||||
"deserialization",
|
||||
"graphql-introspection", "graphql-injection",
|
||||
"websocket-hijack",
|
||||
"race-condition", "toctou",
|
||||
"cache-poisoning", "web-cache-deception",
|
||||
"http-smuggling", "request-splitting",
|
||||
"open-redirect", "header-injection",
|
||||
"clickjacking",
|
||||
"business-logic", "mass-assignment",
|
||||
"api-abuse", "rate-limit-bypass",
|
||||
"info-disclosure", "verbose-error",
|
||||
"insecure-direct-object",
|
||||
"subdomain-takeover",
|
||||
"crlf-injection",
|
||||
"nosql-injection",
|
||||
"ldap-injection",
|
||||
"xpath-injection",
|
||||
"prototype-pollution",
|
||||
"regex-dos",
|
||||
"secret-exposure",
|
||||
],
|
||||
VulnDomain::Infra => &[
|
||||
"port-scan", "service-enum", "banner-grab",
|
||||
"cve-known", "nday-exploit",
|
||||
"privesc-linux", "privesc-windows",
|
||||
"lateral-movement", "pivot",
|
||||
"credential-reuse", "credential-spray", "credential-brute",
|
||||
"ad-enum", "ad-kerberoast", "ad-asreproast", "ad-dcsync",
|
||||
"ad-delegation-abuse", "ad-gpo-abuse", "ad-acl-abuse",
|
||||
"ad-certificate-abuse",
|
||||
"kerberos-attack",
|
||||
"ldap-enum", "ldap-relay",
|
||||
"smb-relay", "smb-signing",
|
||||
"rdp-attack",
|
||||
"ssh-attack", "ssh-key-reuse",
|
||||
"dns-zone-transfer", "dns-poisoning",
|
||||
"snmp-enum",
|
||||
"nfs-exposure",
|
||||
"default-creds",
|
||||
"weak-cipher", "weak-protocol",
|
||||
"mitm",
|
||||
"c2-establish", "persistence",
|
||||
],
|
||||
VulnDomain::Cloud => &[
|
||||
"iam-misconfig", "iam-escalation",
|
||||
"storage-exposure", "s3-public", "blob-public",
|
||||
"metadata-abuse", "imds-ssrf",
|
||||
"network-misconfig", "security-group-open",
|
||||
"logging-gap", "cloudtrail-disabled",
|
||||
"lambda-abuse", "serverless-injection",
|
||||
"container-escape", "k8s-misconfig",
|
||||
"secret-manager-exposure",
|
||||
"cross-account-access",
|
||||
"resource-policy-abuse",
|
||||
],
|
||||
VulnDomain::Mobile => &[
|
||||
"static-analysis", "dynamic-analysis",
|
||||
"ssl-pinning-bypass", "certificate-validation",
|
||||
"root-jailbreak-detection", "root-bypass",
|
||||
"hardcoded-secrets", "api-key-exposure",
|
||||
"insecure-storage", "shared-preferences",
|
||||
"insecure-ipc", "content-provider-leak",
|
||||
"webview-attack", "deep-link-abuse",
|
||||
"binary-protection", "code-obfuscation",
|
||||
"runtime-manipulation", "frida-hook",
|
||||
"clipboard-leak", "screenshot-leak",
|
||||
"biometric-bypass",
|
||||
],
|
||||
VulnDomain::Binary => &[
|
||||
"buffer-overflow", "stack-overflow", "heap-overflow",
|
||||
"format-string",
|
||||
"use-after-free", "double-free",
|
||||
"integer-overflow",
|
||||
"rop-chain", "ret2libc",
|
||||
"type-confusion",
|
||||
"null-deref",
|
||||
"race-condition-binary",
|
||||
"aslr-bypass", "dep-bypass", "canary-bypass",
|
||||
"firmware-analysis",
|
||||
"symbol-analysis", "string-analysis",
|
||||
"control-flow-hijack",
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── CWE → VulnClass mapping ────────────────────────────────────────────────
|
||||
|
||||
/// Map a CWE id (e.g. "79", "CWE-79") to a canonical vuln class.
|
||||
pub fn cwe_to_class(cwe: &str) -> Option<(&'static str, VulnDomain)> {
|
||||
let num: u32 = cwe.trim_start_matches("CWE-")
|
||||
.trim_start_matches("cwe-")
|
||||
.parse()
|
||||
.ok()?;
|
||||
Some(match num {
|
||||
// Web — XSS
|
||||
79 => ("xss-reflected", VulnDomain::Web),
|
||||
// Web — SQLi
|
||||
89 => ("sqli-union", VulnDomain::Web),
|
||||
564 => ("sqli-blind", VulnDomain::Web),
|
||||
// Web — SSRF
|
||||
918 => ("ssrf", VulnDomain::Web),
|
||||
// Web — SSTI
|
||||
1336 => ("ssti", VulnDomain::Web),
|
||||
// Web — XXE
|
||||
611 => ("xxe", VulnDomain::Web),
|
||||
// Web — LFI/path traversal
|
||||
22 | 23 => ("path-traversal", VulnDomain::Web),
|
||||
98 => ("rfi", VulnDomain::Web),
|
||||
// Web — Command injection
|
||||
78 | 77 => ("command-injection", VulnDomain::Web),
|
||||
94 => ("code-injection", VulnDomain::Web),
|
||||
// Web — CORS
|
||||
942 => ("cors-misconfig", VulnDomain::Web),
|
||||
// Web — CSRF
|
||||
352 => ("csrf", VulnDomain::Web),
|
||||
// Web — IDOR/BOLA
|
||||
639 => ("idor", VulnDomain::Web),
|
||||
// Web — Auth
|
||||
287 | 306 => ("auth-bypass", VulnDomain::Web),
|
||||
384 => ("session-fixation", VulnDomain::Web),
|
||||
// Web — JWT
|
||||
347 => ("jwt-attack", VulnDomain::Web),
|
||||
// Web — File upload
|
||||
434 => ("file-upload", VulnDomain::Web),
|
||||
// Web — Deserialization
|
||||
502 => ("deserialization", VulnDomain::Web),
|
||||
// Web — Open redirect
|
||||
601 => ("open-redirect", VulnDomain::Web),
|
||||
// Web — Clickjacking
|
||||
1021 => ("clickjacking", VulnDomain::Web),
|
||||
// Web — CRLF
|
||||
113 => ("crlf-injection", VulnDomain::Web),
|
||||
// Web — Header injection
|
||||
644 => ("header-injection", VulnDomain::Web),
|
||||
// Web — NoSQL injection
|
||||
943 => ("nosql-injection", VulnDomain::Web),
|
||||
// Web — LDAP injection
|
||||
90 => ("ldap-injection", VulnDomain::Web),
|
||||
// Web — XPath
|
||||
643 => ("xpath-injection", VulnDomain::Web),
|
||||
// Web — Prototype pollution
|
||||
1321 => ("prototype-pollution", VulnDomain::Web),
|
||||
// Web — Mass assignment
|
||||
915 => ("mass-assignment", VulnDomain::Web),
|
||||
// Web — Race condition
|
||||
362 => ("race-condition", VulnDomain::Web),
|
||||
// Web — HTTP smuggling
|
||||
444 => ("http-smuggling", VulnDomain::Web),
|
||||
// Web — Info disclosure
|
||||
200 | 209 => ("info-disclosure", VulnDomain::Web),
|
||||
// Web — Secret exposure
|
||||
798 => ("secret-exposure", VulnDomain::Web),
|
||||
// Web — Business logic
|
||||
840 => ("business-logic", VulnDomain::Web),
|
||||
// Web — GraphQL
|
||||
// No official CWE; map introspection to info-disclosure
|
||||
// Web — Subdomain takeover
|
||||
// No official CWE; handled by agent name
|
||||
// Infra — Default creds
|
||||
1392 | 521 => ("default-creds", VulnDomain::Infra),
|
||||
// Infra — Privesc
|
||||
269 => ("privesc-linux", VulnDomain::Infra),
|
||||
250 => ("privesc-windows", VulnDomain::Infra),
|
||||
// Cloud — IAM
|
||||
732 => ("iam-misconfig", VulnDomain::Cloud),
|
||||
// Binary — Buffer overflow
|
||||
120 | 121 | 122 => ("buffer-overflow", VulnDomain::Binary),
|
||||
// Binary — Format string
|
||||
134 => ("format-string", VulnDomain::Binary),
|
||||
// Binary — Use after free
|
||||
416 => ("use-after-free", VulnDomain::Binary),
|
||||
// Binary — Double free
|
||||
415 => ("double-free", VulnDomain::Binary),
|
||||
// Binary — Integer overflow
|
||||
190 => ("integer-overflow", VulnDomain::Binary),
|
||||
// Binary — Null deref
|
||||
476 => ("null-deref", VulnDomain::Binary),
|
||||
// Mobile — Insecure storage
|
||||
312 | 922 => ("insecure-storage", VulnDomain::Mobile),
|
||||
// Mobile — Hardcoded secrets
|
||||
259 => ("hardcoded-secrets", VulnDomain::Mobile),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Infer vuln class from an agent name when CWE is missing or unmapped.
|
||||
pub fn agent_to_class(agent: &str) -> Option<(&'static str, VulnDomain)> {
|
||||
let low = agent.to_ascii_lowercase();
|
||||
// Web agents
|
||||
if low.contains("xss") { return Some(("xss-reflected", VulnDomain::Web)); }
|
||||
if low.contains("sqli") || low.contains("sql_injection") || low.contains("sql-injection") { return Some(("sqli-union", VulnDomain::Web)); }
|
||||
if low.contains("ssrf") { return Some(("ssrf", VulnDomain::Web)); }
|
||||
if low.contains("ssti") { return Some(("ssti", VulnDomain::Web)); }
|
||||
if low.contains("xxe") { return Some(("xxe", VulnDomain::Web)); }
|
||||
if low.contains("lfi") || low.contains("path_traversal") || low.contains("path-traversal") { return Some(("path-traversal", VulnDomain::Web)); }
|
||||
if low.contains("rfi") { return Some(("rfi", VulnDomain::Web)); }
|
||||
if low.contains("command_injection") || low.contains("cmd_injection") || low.contains("os_command") { return Some(("command-injection", VulnDomain::Web)); }
|
||||
if low.contains("cors") { return Some(("cors-misconfig", VulnDomain::Web)); }
|
||||
if low.contains("csrf") { return Some(("csrf", VulnDomain::Web)); }
|
||||
if low.contains("idor") || low.contains("bola") { return Some(("idor", VulnDomain::Web)); }
|
||||
if low.contains("auth_bypass") || low.contains("auth-bypass") || low.contains("broken_auth") { return Some(("auth-bypass", VulnDomain::Web)); }
|
||||
if low.contains("jwt") { return Some(("jwt-attack", VulnDomain::Web)); }
|
||||
if low.contains("file_upload") || low.contains("upload") { return Some(("file-upload", VulnDomain::Web)); }
|
||||
if low.contains("deseriali") { return Some(("deserialization", VulnDomain::Web)); }
|
||||
if low.contains("graphql") { return Some(("graphql-introspection", VulnDomain::Web)); }
|
||||
if low.contains("websocket") { return Some(("websocket-hijack", VulnDomain::Web)); }
|
||||
if low.contains("race_condition") || low.contains("race-condition") { return Some(("race-condition", VulnDomain::Web)); }
|
||||
if low.contains("cache_poison") || low.contains("cache-poison") { return Some(("cache-poisoning", VulnDomain::Web)); }
|
||||
if low.contains("http_smuggl") || low.contains("smuggling") { return Some(("http-smuggling", VulnDomain::Web)); }
|
||||
if low.contains("open_redirect") || low.contains("redirect") { return Some(("open-redirect", VulnDomain::Web)); }
|
||||
if low.contains("clickjack") { return Some(("clickjacking", VulnDomain::Web)); }
|
||||
if low.contains("business_logic") || low.contains("biz_logic") { return Some(("business-logic", VulnDomain::Web)); }
|
||||
if low.contains("nosql") { return Some(("nosql-injection", VulnDomain::Web)); }
|
||||
if low.contains("prototype_pollution") || low.contains("proto-pollution") { return Some(("prototype-pollution", VulnDomain::Web)); }
|
||||
if low.contains("crlf") { return Some(("crlf-injection", VulnDomain::Web)); }
|
||||
if low.contains("subdomain_takeover") || low.contains("subdomain-takeover") { return Some(("subdomain-takeover", VulnDomain::Web)); }
|
||||
if low.contains("mass_assignment") { return Some(("mass-assignment", VulnDomain::Web)); }
|
||||
if low.contains("secret") || low.contains("hardcoded_key") { return Some(("secret-exposure", VulnDomain::Web)); }
|
||||
// Infra agents
|
||||
if low.contains("privesc") || low.contains("privilege_escalation") { return Some(("privesc-linux", VulnDomain::Infra)); }
|
||||
if low.contains("lateral") || low.contains("pivot") { return Some(("lateral-movement", VulnDomain::Infra)); }
|
||||
if low.contains("active_directory") || low.contains("ad_") { return Some(("ad-enum", VulnDomain::Infra)); }
|
||||
if low.contains("kerberos") || low.contains("kerberoast") { return Some(("ad-kerberoast", VulnDomain::Infra)); }
|
||||
if low.contains("credential") || low.contains("cred_") { return Some(("credential-reuse", VulnDomain::Infra)); }
|
||||
if low.contains("c2") || low.contains("command_and_control") { return Some(("c2-establish", VulnDomain::Infra)); }
|
||||
if low.contains("persistence") { return Some(("persistence", VulnDomain::Infra)); }
|
||||
if low.contains("nday") || low.contains("cve") { return Some(("cve-known", VulnDomain::Infra)); }
|
||||
if low.contains("smb") { return Some(("smb-relay", VulnDomain::Infra)); }
|
||||
if low.contains("dns") { return Some(("dns-zone-transfer", VulnDomain::Infra)); }
|
||||
// Cloud agents
|
||||
if low.contains("cloud") || low.contains("aws") || low.contains("azure") || low.contains("gcp") { return Some(("iam-misconfig", VulnDomain::Cloud)); }
|
||||
if low.contains("container") || low.contains("k8s") || low.contains("kubernetes") { return Some(("k8s-misconfig", VulnDomain::Cloud)); }
|
||||
if low.contains("s3") || low.contains("storage") { return Some(("storage-exposure", VulnDomain::Cloud)); }
|
||||
// Mobile agents
|
||||
if low.contains("ssl_pinning") || low.contains("ssl-pinning") { return Some(("ssl-pinning-bypass", VulnDomain::Mobile)); }
|
||||
if low.contains("root_detect") || low.contains("jailbreak") { return Some(("root-jailbreak-detection", VulnDomain::Mobile)); }
|
||||
if low.contains("apk") || low.contains("ipa") || low.contains("static_analysis") { return Some(("static-analysis", VulnDomain::Mobile)); }
|
||||
// Binary agents
|
||||
if low.contains("binary") || low.contains("pwn") || low.contains("bof") { return Some(("buffer-overflow", VulnDomain::Binary)); }
|
||||
if low.contains("reverse") || low.contains("ghidra") { return Some(("symbol-analysis", VulnDomain::Binary)); }
|
||||
None
|
||||
}
|
||||
|
||||
// ── Coverage ledger ─────────────────────────────────────────────────────────
|
||||
|
||||
/// A gap in test coverage: an endpoint that has untested vuln classes.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct CoverageGap {
|
||||
pub endpoint: String,
|
||||
pub domain: VulnDomain,
|
||||
pub missing_tests: Vec<String>,
|
||||
pub priority: f32,
|
||||
}
|
||||
|
||||
/// Record of a single test executed against an endpoint.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TestRecord {
|
||||
pub vuln_class: String,
|
||||
pub domain: VulnDomain,
|
||||
pub agent: String,
|
||||
pub found_vuln: bool,
|
||||
#[serde(default)]
|
||||
pub timestamp: u64,
|
||||
}
|
||||
|
||||
/// Tracks what has been tested and what remains.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct CoverageLedger {
|
||||
/// endpoint → set of tested vuln classes
|
||||
tested: BTreeMap<String, Vec<TestRecord>>,
|
||||
/// All endpoints discovered during the engagement
|
||||
known_endpoints: BTreeSet<String>,
|
||||
/// Technologies detected (affects which classes are relevant)
|
||||
technologies: BTreeSet<String>,
|
||||
/// Run mode: web, host, whitebox, greybox, container, mobile, cloud, ai
|
||||
#[serde(default)]
|
||||
mode: String,
|
||||
}
|
||||
|
||||
impl CoverageLedger {
|
||||
pub fn new(mode: &str) -> Self {
|
||||
CoverageLedger {
|
||||
mode: mode.to_string(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Register a discovered endpoint (from recon, findings, or intel extraction).
|
||||
pub fn register_endpoint(&mut self, endpoint: &str) {
|
||||
let normalized = normalize_endpoint(endpoint);
|
||||
if !normalized.is_empty() {
|
||||
self.known_endpoints.insert(normalized);
|
||||
}
|
||||
}
|
||||
|
||||
/// Register a detected technology (affects relevant vuln classes).
|
||||
pub fn register_technology(&mut self, tech: &str) {
|
||||
self.technologies.insert(tech.to_lowercase());
|
||||
}
|
||||
|
||||
/// Mark a vuln class as tested for a given endpoint.
|
||||
pub fn mark_tested(&mut self, endpoint: &str, vuln_class: &str, domain: &VulnDomain, agent: &str, found: bool) {
|
||||
let normalized = normalize_endpoint(endpoint);
|
||||
if normalized.is_empty() { return; }
|
||||
self.known_endpoints.insert(normalized.clone());
|
||||
let record = TestRecord {
|
||||
vuln_class: vuln_class.to_string(),
|
||||
domain: domain.clone(),
|
||||
agent: agent.to_string(),
|
||||
found_vuln: found,
|
||||
timestamp: std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0),
|
||||
};
|
||||
self.tested.entry(normalized).or_default().push(record);
|
||||
}
|
||||
|
||||
/// Record findings from an agent run, mapping CWE/agent name to coverage.
|
||||
pub fn record_findings(&mut self, findings: &[crate::types::Finding]) {
|
||||
for f in findings {
|
||||
let endpoint = if f.endpoint.is_empty() { "_target_" } else { &f.endpoint };
|
||||
let found = f.validated || f.confidence >= 0.5;
|
||||
|
||||
// Try CWE mapping first, fall back to agent name
|
||||
if let Some((class, domain)) = cwe_to_class(&f.cwe) {
|
||||
self.mark_tested(endpoint, class, &domain, &f.agent, found);
|
||||
} else if let Some((class, domain)) = agent_to_class(&f.agent) {
|
||||
self.mark_tested(endpoint, class, &domain, &f.agent, found);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Record agents that ran (even those that found nothing — they still tested).
|
||||
pub fn record_agents_ran(&mut self, agents: &[String], target: &str) {
|
||||
for agent in agents {
|
||||
if let Some((class, domain)) = agent_to_class(agent) {
|
||||
self.mark_tested(target, class, &domain, agent, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get tested vuln classes for an endpoint.
|
||||
pub fn tested_classes(&self, endpoint: &str) -> HashSet<String> {
|
||||
let normalized = normalize_endpoint(endpoint);
|
||||
self.tested.get(&normalized)
|
||||
.map(|records| records.iter().map(|r| r.vuln_class.clone()).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Relevant domains for this engagement mode.
|
||||
fn relevant_domains(&self) -> Vec<VulnDomain> {
|
||||
match self.mode.as_str() {
|
||||
"web" | "greybox" => vec![VulnDomain::Web],
|
||||
"whitebox" => vec![VulnDomain::Web, VulnDomain::Binary],
|
||||
"host" => vec![VulnDomain::Infra],
|
||||
"container" => vec![VulnDomain::Cloud, VulnDomain::Infra],
|
||||
"mobile" => vec![VulnDomain::Mobile, VulnDomain::Binary],
|
||||
"cloud" => vec![VulnDomain::Cloud],
|
||||
"ai" => vec![VulnDomain::Web],
|
||||
_ => vec![VulnDomain::Web, VulnDomain::Infra, VulnDomain::Cloud],
|
||||
}
|
||||
}
|
||||
|
||||
/// Relevant vuln classes given detected technologies and engagement mode.
|
||||
fn relevant_classes(&self) -> Vec<(&'static str, VulnDomain)> {
|
||||
let domains = self.relevant_domains();
|
||||
let mut classes = Vec::new();
|
||||
for domain in &domains {
|
||||
for &class in domain.classes() {
|
||||
// Filter by technology relevance
|
||||
if self.is_class_relevant(class) {
|
||||
classes.push((class, domain.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
classes
|
||||
}
|
||||
|
||||
fn is_class_relevant(&self, class: &str) -> bool {
|
||||
// If no technologies known, all classes are potentially relevant
|
||||
if self.technologies.is_empty() { return true; }
|
||||
match class {
|
||||
"graphql-introspection" | "graphql-injection" => self.technologies.iter().any(|t| t.contains("graphql")),
|
||||
"websocket-hijack" => self.technologies.iter().any(|t| t.contains("websocket") || t.contains("ws")),
|
||||
"nosql-injection" => self.technologies.iter().any(|t| t.contains("mongo") || t.contains("nosql") || t.contains("couchdb") || t.contains("redis")),
|
||||
"prototype-pollution" => self.technologies.iter().any(|t| t.contains("node") || t.contains("javascript") || t.contains("express")),
|
||||
// AD classes only relevant when AD is in scope
|
||||
c if c.starts_with("ad-") => self.technologies.iter().any(|t| t.contains("active directory") || t.contains("windows") || t.contains("domain")),
|
||||
// K8s classes
|
||||
"k8s-misconfig" | "container-escape" => self.technologies.iter().any(|t| t.contains("kubernetes") || t.contains("docker") || t.contains("container")),
|
||||
// Most classes are relevant regardless of technology
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Compute coverage gaps, ranked by priority.
|
||||
pub fn gaps(&self) -> Vec<CoverageGap> {
|
||||
let relevant = self.relevant_classes();
|
||||
let mut gaps: Vec<CoverageGap> = Vec::new();
|
||||
|
||||
// For each known endpoint, check which relevant classes haven't been tested
|
||||
for endpoint in &self.known_endpoints {
|
||||
let tested = self.tested_classes(endpoint);
|
||||
for domain in &self.relevant_domains() {
|
||||
let missing: Vec<String> = domain.classes().iter()
|
||||
.filter(|&&c| self.is_class_relevant(c) && !tested.contains(c))
|
||||
.map(|&s| s.to_string())
|
||||
.collect();
|
||||
if !missing.is_empty() {
|
||||
let total_relevant = domain.classes().iter()
|
||||
.filter(|&&c| self.is_class_relevant(c))
|
||||
.count() as f32;
|
||||
let coverage_pct = 1.0 - (missing.len() as f32 / total_relevant);
|
||||
// Priority: endpoints with SOME coverage but big gaps rank highest
|
||||
// (we already started testing there, finish the job)
|
||||
let priority = if tested.is_empty() {
|
||||
0.3 // untouched — lower priority than partially tested
|
||||
} else {
|
||||
0.5 + (0.5 * (1.0 - coverage_pct)) // 0.5..1.0
|
||||
};
|
||||
gaps.push(CoverageGap {
|
||||
endpoint: endpoint.clone(),
|
||||
domain: domain.clone(),
|
||||
missing_tests: missing,
|
||||
priority,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Also check for domains with zero endpoint coverage
|
||||
for (class, domain) in &relevant {
|
||||
let any_tested = self.tested.values().any(|records| {
|
||||
records.iter().any(|r| r.vuln_class == *class)
|
||||
});
|
||||
if !any_tested {
|
||||
// Check if we already have a gap entry for this class
|
||||
let already_listed = gaps.iter().any(|g| {
|
||||
g.domain == *domain && g.missing_tests.contains(&class.to_string())
|
||||
});
|
||||
if !already_listed && self.known_endpoints.is_empty() {
|
||||
gaps.push(CoverageGap {
|
||||
endpoint: "_target_".to_string(),
|
||||
domain: domain.clone(),
|
||||
missing_tests: vec![class.to_string()],
|
||||
priority: 0.2,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
gaps.sort_by(|a, b| b.priority.partial_cmp(&a.priority).unwrap_or(std::cmp::Ordering::Equal));
|
||||
gaps
|
||||
}
|
||||
|
||||
/// Total coverage percentage across all endpoints and relevant classes.
|
||||
pub fn coverage_pct(&self) -> f32 {
|
||||
let relevant = self.relevant_classes();
|
||||
if relevant.is_empty() || self.known_endpoints.is_empty() { return 0.0; }
|
||||
let total_cells = relevant.len() * self.known_endpoints.len();
|
||||
if total_cells == 0 { return 0.0; }
|
||||
let mut tested_cells = 0usize;
|
||||
for endpoint in &self.known_endpoints {
|
||||
let tested = self.tested_classes(endpoint);
|
||||
for (class, _) in &relevant {
|
||||
if tested.contains(*class) {
|
||||
tested_cells += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
tested_cells as f32 / total_cells as f32
|
||||
}
|
||||
|
||||
/// Human-readable summary.
|
||||
pub fn summary(&self) -> String {
|
||||
let pct = self.coverage_pct() * 100.0;
|
||||
let gaps = self.gaps();
|
||||
let total_missing: usize = gaps.iter().map(|g| g.missing_tests.len()).sum();
|
||||
let total_tested: usize = self.tested.values().map(|v| v.len()).sum();
|
||||
let vulns_found: usize = self.tested.values()
|
||||
.flat_map(|v| v.iter())
|
||||
.filter(|r| r.found_vuln)
|
||||
.count();
|
||||
format!(
|
||||
"coverage: {pct:.0}% · {total_tested} test(s) across {} endpoint(s) · {vulns_found} vuln(s) found · {total_missing} untested class(es) in {} gap(s)",
|
||||
self.known_endpoints.len(),
|
||||
gaps.len(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Top N gaps formatted for log output.
|
||||
pub fn top_gaps(&self, n: usize) -> String {
|
||||
let gaps = self.gaps();
|
||||
if gaps.is_empty() { return "no coverage gaps detected".to_string(); }
|
||||
let mut out = String::new();
|
||||
for (i, gap) in gaps.iter().take(n).enumerate() {
|
||||
let top3: Vec<&str> = gap.missing_tests.iter().take(3).map(|s| s.as_str()).collect();
|
||||
let more = if gap.missing_tests.len() > 3 {
|
||||
format!(" +{} more", gap.missing_tests.len() - 3)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
out.push_str(&format!(
|
||||
" {}. [{}] {} — missing: {}{} (priority {:.1})\n",
|
||||
i + 1, gap.domain.as_str(), gap.endpoint, top3.join(", "), more, gap.priority
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ── Persistence ─────────────────────────────────────────────────────────
|
||||
|
||||
pub fn save(&self, workdir: &Path) {
|
||||
let path = workdir.join("coverage.json");
|
||||
if let Ok(json) = serde_json::to_string_pretty(self) {
|
||||
let _ = std::fs::write(&path, json);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load(workdir: &Path) -> Option<Self> {
|
||||
let path = workdir.join("coverage.json");
|
||||
let data = std::fs::read_to_string(&path).ok()?;
|
||||
serde_json::from_str(&data).ok()
|
||||
}
|
||||
|
||||
/// Load existing coverage or create new for the given mode.
|
||||
pub fn load_or_new(workdir: Option<&Path>, mode: &str) -> Self {
|
||||
workdir
|
||||
.and_then(Self::load)
|
||||
.unwrap_or_else(|| Self::new(mode))
|
||||
}
|
||||
|
||||
pub fn total_tests(&self) -> usize {
|
||||
self.tested.values().map(|v| v.len()).sum()
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
fn normalize_endpoint(endpoint: &str) -> String {
|
||||
let ep = endpoint.trim();
|
||||
if ep.is_empty() { return String::new(); }
|
||||
// Collapse path parameters
|
||||
crate::budget::route_family(
|
||||
ep.split(['?', '#']).next().unwrap_or(ep)
|
||||
)
|
||||
}
|
||||
|
||||
// ── Tests ───────────────────────────────────────────────────────────────────
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cwe_mapping_covers_owasp_top_10() {
|
||||
assert_eq!(cwe_to_class("79").unwrap().0, "xss-reflected");
|
||||
assert_eq!(cwe_to_class("CWE-89").unwrap().0, "sqli-union");
|
||||
assert_eq!(cwe_to_class("918").unwrap().0, "ssrf");
|
||||
assert_eq!(cwe_to_class("78").unwrap().0, "command-injection");
|
||||
assert_eq!(cwe_to_class("502").unwrap().0, "deserialization");
|
||||
assert_eq!(cwe_to_class("639").unwrap().0, "idor");
|
||||
assert_eq!(cwe_to_class("611").unwrap().0, "xxe");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_name_mapping() {
|
||||
assert_eq!(agent_to_class("xss_all_variants").unwrap().0, "xss-reflected");
|
||||
assert_eq!(agent_to_class("sql_injection_deep").unwrap().0, "sqli-union");
|
||||
assert_eq!(agent_to_class("active_directory_attacks").unwrap().0, "ad-enum");
|
||||
assert!(agent_to_class("unknown_agent_xyz").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coverage_tracking_and_gaps() {
|
||||
let mut ledger = CoverageLedger::new("web");
|
||||
ledger.register_endpoint("https://example.com/api/users");
|
||||
ledger.mark_tested(
|
||||
"https://example.com/api/users", "sqli-union", &VulnDomain::Web,
|
||||
"sqli_agent", true,
|
||||
);
|
||||
ledger.mark_tested(
|
||||
"https://example.com/api/users", "xss-reflected", &VulnDomain::Web,
|
||||
"xss_agent", false,
|
||||
);
|
||||
let tested = ledger.tested_classes("https://example.com/api/users");
|
||||
assert!(tested.contains("sqli-union"));
|
||||
assert!(tested.contains("xss-reflected"));
|
||||
|
||||
let gaps = ledger.gaps();
|
||||
assert!(!gaps.is_empty());
|
||||
// Should still have many untested classes
|
||||
let total_missing: usize = gaps.iter().map(|g| g.missing_tests.len()).sum();
|
||||
assert!(total_missing > 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coverage_percentage() {
|
||||
let mut ledger = CoverageLedger::new("web");
|
||||
// No endpoints = 0%
|
||||
assert_eq!(ledger.coverage_pct(), 0.0);
|
||||
|
||||
ledger.register_endpoint("https://example.com/");
|
||||
// One endpoint, nothing tested = 0%
|
||||
assert_eq!(ledger.coverage_pct(), 0.0);
|
||||
|
||||
// Test one class
|
||||
ledger.mark_tested("https://example.com/", "xss-reflected", &VulnDomain::Web, "xss", false);
|
||||
let pct = ledger.coverage_pct();
|
||||
assert!(pct > 0.0 && pct < 0.1); // 1 out of ~50 classes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn technology_filtering() {
|
||||
let mut ledger = CoverageLedger::new("web");
|
||||
// Without tech, GraphQL is relevant
|
||||
assert!(ledger.is_class_relevant("graphql-introspection"));
|
||||
|
||||
// With non-GraphQL tech, it's not
|
||||
ledger.register_technology("PHP");
|
||||
assert!(!ledger.is_class_relevant("graphql-introspection"));
|
||||
|
||||
// With GraphQL tech, it is
|
||||
ledger.register_technology("GraphQL");
|
||||
assert!(ledger.is_class_relevant("graphql-introspection"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistence_round_trip() {
|
||||
let dir = std::env::temp_dir().join("neurosploit_coverage_test");
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
|
||||
let mut ledger = CoverageLedger::new("web");
|
||||
ledger.register_endpoint("https://example.com/");
|
||||
ledger.mark_tested("https://example.com/", "xss-reflected", &VulnDomain::Web, "xss", true);
|
||||
ledger.save(&dir);
|
||||
|
||||
let loaded = CoverageLedger::load(&dir).expect("should load");
|
||||
assert_eq!(loaded.tested_classes("https://example.com/").len(), 1);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user