diff --git a/neurosploit-rs/crates/harness/src/cvss.rs b/neurosploit-rs/crates/harness/src/cvss.rs index ad56c78..3499dfe 100644 --- a/neurosploit-rs/crates/harness/src/cvss.rs +++ b/neurosploit-rs/crates/harness/src/cvss.rs @@ -59,8 +59,6 @@ impl Ac { fn parse(c: &str) -> Option { Some(match c { "L" => Ac::Low, "H" => Ac::High, _ => return None }) } } impl Pr { - /// PR is scope-dependent: a changed scope makes low/high privileges worth - /// more to an attacker, so the coefficients differ. fn score(self, scope: Scope) -> f64 { match (self, scope) { (Pr::None, _) => 0.85, @@ -91,28 +89,18 @@ impl Imp { /// A full CVSS v3.1 base vector. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub struct Vector { - pub av: Av, - pub ac: Ac, - pub pr: Pr, - pub ui: Ui, - pub scope: Scope, - pub c: Imp, - pub i: Imp, - pub a: Imp, + pub av: Av, pub ac: Ac, pub pr: Pr, pub ui: Ui, + pub scope: Scope, pub c: Imp, pub i: Imp, pub a: Imp, } impl Vector { - /// The base score, computed by the FIRST v3.1 equation. Deterministic. pub fn base_score(&self) -> f64 { - // Impact Sub-Score. let iss = 1.0 - ((1.0 - self.c.score()) * (1.0 - self.i.score()) * (1.0 - self.a.score())); let impact = match self.scope { Scope::Unchanged => 6.42 * iss, Scope::Changed => 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02).powi(15), }; - if impact <= 0.0 { - return 0.0; - } + if impact <= 0.0 { return 0.0; } let exploitability = 8.22 * self.av.score() * self.ac.score() * self.pr.score(self.scope) * self.ui.score(); let raw = match self.scope { Scope::Unchanged => (impact + exploitability).min(10.0), @@ -120,24 +108,12 @@ impl Vector { }; roundup(raw) } - - /// Severity band for the score, per the FIRST qualitative scale. - pub fn severity(&self) -> &'static str { - band(self.base_score()) - } - - /// The canonical `CVSS:3.1/AV:…/…` string. + pub fn severity(&self) -> &'static str { band(self.base_score()) } pub fn vector_string(&self) -> String { - format!( - "CVSS:3.1/AV:{}/AC:{}/PR:{}/UI:{}/S:{}/C:{}/I:{}/A:{}", + format!("CVSS:3.1/AV:{}/AC:{}/PR:{}/UI:{}/S:{}/C:{}/I:{}/A:{}", self.av.code(), self.ac.code(), self.pr.code(), self.ui.code(), - self.scope.code(), self.c.code(), self.i.code(), self.a.code() - ) + self.scope.code(), self.c.code(), self.i.code(), self.a.code()) } - - /// Parse a `CVSS:3.1/…` vector string. Order-independent; unknown or missing - /// metrics fail rather than default silently — a half-parsed vector would - /// score wrong. pub fn parse(s: &str) -> Option { let mut av = None; let mut ac = None; let mut pr = None; let mut ui = None; let mut scope = None; let mut c = None; let mut i = None; let mut a = None; @@ -145,39 +121,27 @@ impl Vector { let (k, v) = part.split_once(':')?; match k.to_uppercase().as_str() { "CVSS" => { if !v.starts_with("3.") { return None; } } - "AV" => av = Av::parse(v), - "AC" => ac = Ac::parse(v), - "PR" => pr = Pr::parse(v), - "UI" => ui = Ui::parse(v), + "AV" => av = Av::parse(v), "AC" => ac = Ac::parse(v), + "PR" => pr = Pr::parse(v), "UI" => ui = Ui::parse(v), "S" => scope = Scope::parse(v), - "C" => c = Imp::parse(v), - "I" => i = Imp::parse(v), - "A" => a = Imp::parse(v), - _ => {} // temporal/environmental metrics ignored for the base + "C" => c = Imp::parse(v), "I" => i = Imp::parse(v), "A" => a = Imp::parse(v), + _ => {} } } Some(Vector { av: av?, ac: ac?, pr: pr?, ui: ui?, scope: scope?, c: c?, i: i?, a: a? }) } } -/// CVSS v3.1 roundup: the smallest number to one decimal place that is >= input. fn roundup(input: f64) -> f64 { let int_input = (input * 100_000.0).round() as i64; - if int_input % 10_000 == 0 { - int_input as f64 / 100_000.0 - } else { - ((int_input as f64 / 10_000.0).floor() + 1.0) / 10.0 - } + if int_input % 10_000 == 0 { int_input as f64 / 100_000.0 } + else { ((int_input as f64 / 10_000.0).floor() + 1.0) / 10.0 } } -/// FIRST qualitative severity bands. pub fn band(score: f64) -> &'static str { match score { - s if s == 0.0 => "None", - s if s < 4.0 => "Low", - s if s < 7.0 => "Medium", - s if s < 9.0 => "High", - _ => "Critical", + s if s == 0.0 => "None", s if s < 4.0 => "Low", + s if s < 7.0 => "Medium", s if s < 9.0 => "High", _ => "Critical", } } @@ -185,49 +149,25 @@ pub fn band(score: f64) -> &'static str { // Evidence-graded scoring // =========================================================================== -/// One metric value, and the receipt behind it. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct MetricClaim { - /// Metric name (`C`, `I`, `A`, `S`, …). - pub metric: String, - /// The proposed value (`H`, `L`, `N`, `C`, `U`, …). - pub value: String, - /// Evidence id that supports it, if any. A raising value with no receipt is - /// what gets refused. - #[serde(default)] - pub evidence_id: Option, - /// Why this value — recorded so the score is auditable metric-by-metric. - #[serde(default)] - pub justification: String, + pub metric: String, pub value: String, + #[serde(default)] pub evidence_id: Option, + #[serde(default)] pub justification: String, } -/// The evidence-graded result for a finding: two scores and what was uncertain. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Graded { - /// What the evidence actually demonstrates. This is the reported score. - pub demonstrated: Vector, - pub demonstrated_score: f64, - pub demonstrated_severity: String, - /// What the class could reach if fully exploited — context, not the number. - pub potential: Vector, - pub potential_score: f64, - pub potential_severity: String, - /// Metrics whose raising value had no receipt and were dropped to the - /// demonstrated floor. Non-empty means the finding needs human review of - /// the score, not that it is wrong. + pub demonstrated: Vector, pub demonstrated_score: f64, pub demonstrated_severity: String, + pub potential: Vector, pub potential_score: f64, pub potential_severity: String, pub uncertain: Vec, } impl Graded { - /// Does the score need a human's eye? - pub fn needs_review(&self) -> bool { - !self.uncertain.is_empty() - } + pub fn needs_review(&self) -> bool { !self.uncertain.is_empty() } pub fn summary(&self) -> String { - let mut s = format!( - "{:.1} {} demonstrated ({})", - self.demonstrated_score, self.demonstrated_severity, self.demonstrated.vector_string() - ); + let mut s = format!("{:.1} {} demonstrated ({})", + self.demonstrated_score, self.demonstrated_severity, self.demonstrated.vector_string()); if (self.potential_score - self.demonstrated_score).abs() > 0.05 { s.push_str(&format!(" · potential {:.1} {}", self.potential_score, self.potential_severity)); } @@ -238,124 +178,283 @@ impl Graded { } } -/// Grade a proposed vector against the evidence behind each impact metric. -/// -/// `has_evidence(metric)` answers "is there a receipt that this metric's value -/// is real?" — the caller wires it to the finding's evidence. Impact metrics -/// (C/I/A) that claim `High` or `Low` without a receipt are dropped to `None` -/// in the *demonstrated* vector, while the *potential* vector keeps them. The -/// gap between the two is exactly "what we could show" versus "what this class -/// can do", which is the distinction a scanner that prints one number loses. -pub fn grade(proposed: Vector, has_evidence: F) -> Graded -where - F: Fn(&str) -> bool, -{ +pub fn grade(proposed: Vector, has_evidence: F) -> Graded where F: Fn(&str) -> bool { let mut demonstrated = proposed; let mut uncertain = Vec::new(); for (name, value) in [("C", proposed.c), ("I", proposed.i), ("A", proposed.a)] { if value != Imp::None && !has_evidence(name) { uncertain.push(format!("{name}:{}", value.code())); match name { - "C" => demonstrated.c = Imp::None, - "I" => demonstrated.i = Imp::None, - "A" => demonstrated.a = Imp::None, - _ => {} + "C" => demonstrated.c = Imp::None, "I" => demonstrated.i = Imp::None, + "A" => demonstrated.a = Imp::None, _ => {} } } } let d = demonstrated.base_score(); let p = proposed.base_score(); Graded { - demonstrated, - demonstrated_score: d, - demonstrated_severity: band(d).into(), - potential: proposed, - potential_score: p, - potential_severity: band(p).into(), - uncertain, + demonstrated, demonstrated_score: d, demonstrated_severity: band(d).into(), + potential: proposed, potential_score: p, potential_severity: band(p).into(), uncertain, } } +// =========================================================================== +// CVSS v4.0 +// =========================================================================== + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum CvssVersion { V31, V40 } + +pub fn detect_version(vector: &str) -> Option { + let v = vector.trim(); + if v.starts_with("CVSS:4.0/") { Some(CvssVersion::V40) } + else if v.starts_with("CVSS:3.") { Some(CvssVersion::V31) } + else { None } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CvssScore { + pub version: CvssVersion, pub score: f64, pub severity: String, pub vector_string: String, +} + +pub fn parse_any(vector: &str) -> Option { + match detect_version(vector)? { + CvssVersion::V31 => { + let v = Vector::parse(vector)?; + let s = v.base_score(); + Some(CvssScore { version: CvssVersion::V31, score: s, severity: band(s).into(), vector_string: v.vector_string() }) + } + CvssVersion::V40 => { + let v = Cvss4::parse(vector)?; + let s = v.base_score(); + Some(CvssScore { version: CvssVersion::V40, score: s, severity: band(s).into(), vector_string: v.vector_string() }) + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Av4 { Network, Adjacent, Local, Physical } +impl Av4 { + fn parse(c: &str) -> Option { Some(match c { "N" => Self::Network, "A" => Self::Adjacent, "L" => Self::Local, "P" => Self::Physical, _ => return None }) } + fn code(self) -> &'static str { match self { Self::Network => "N", Self::Adjacent => "A", Self::Local => "L", Self::Physical => "P" } } +} +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Ac4 { Low, High } +impl Ac4 { + fn parse(c: &str) -> Option { Some(match c { "L" => Self::Low, "H" => Self::High, _ => return None }) } + fn code(self) -> &'static str { match self { Self::Low => "L", Self::High => "H" } } +} +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum At { None, Present } +impl At { + fn parse(c: &str) -> Option { Some(match c { "N" => Self::None, "P" => Self::Present, _ => return None }) } + fn code(self) -> &'static str { match self { Self::None => "N", Self::Present => "P" } } +} +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Pr4 { None, Low, High } +impl Pr4 { + fn parse(c: &str) -> Option { Some(match c { "N" => Self::None, "L" => Self::Low, "H" => Self::High, _ => return None }) } + fn code(self) -> &'static str { match self { Self::None => "N", Self::Low => "L", Self::High => "H" } } +} +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Ui4 { None, Passive, Active } +impl Ui4 { + fn parse(c: &str) -> Option { Some(match c { "N" => Self::None, "P" => Self::Passive, "A" => Self::Active, _ => return None }) } + fn code(self) -> &'static str { match self { Self::None => "N", Self::Passive => "P", Self::Active => "A" } } +} +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub enum Imp4 { None, Low, High } +impl Imp4 { + fn parse(c: &str) -> Option { Some(match c { "N" => Self::None, "L" => Self::Low, "H" => Self::High, _ => return None }) } + fn code(self) -> &'static str { match self { Self::None => "N", Self::Low => "L", Self::High => "H" } } + fn score(self) -> f64 { match self { Self::None => 0.0, Self::Low => 0.22, Self::High => 0.56 } } +} +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum ExploitMaturity { NotDefined, Attacked, Poc, Unreported } +impl ExploitMaturity { + fn parse(c: &str) -> Option { Some(match c { "X" => Self::NotDefined, "A" => Self::Attacked, "P" => Self::Poc, "U" => Self::Unreported, _ => return None }) } + fn code(self) -> &'static str { match self { Self::NotDefined => "X", Self::Attacked => "A", Self::Poc => "P", Self::Unreported => "U" } } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct Cvss4 { + pub av: Av4, pub ac: Ac4, pub at: At, pub pr: Pr4, pub ui: Ui4, + pub vc: Imp4, pub vi: Imp4, pub va: Imp4, + pub sc: Imp4, pub si: Imp4, pub sa: Imp4, + pub e: ExploitMaturity, +} + +impl Cvss4 { + pub fn parse(s: &str) -> Option { + let mut av = None; let mut ac = None; let mut at = None; + let mut pr = None; let mut ui = None; + let mut vc = None; let mut vi = None; let mut va = None; + let mut sc = None; let mut si = None; let mut sa = None; + let mut e = ExploitMaturity::NotDefined; + for part in s.trim().split('/') { + let (k, v) = part.split_once(':')?; + match k.to_uppercase().as_str() { + "CVSS" => { if v != "4.0" { return None; } } + "AV" => av = Av4::parse(v), "AC" => ac = Ac4::parse(v), + "AT" => at = At::parse(v), "PR" => pr = Pr4::parse(v), + "UI" => ui = Ui4::parse(v), + "VC" => vc = Imp4::parse(v), "VI" => vi = Imp4::parse(v), "VA" => va = Imp4::parse(v), + "SC" => sc = Imp4::parse(v), "SI" => si = Imp4::parse(v), "SA" => sa = Imp4::parse(v), + "E" => { if let Some(parsed) = ExploitMaturity::parse(v) { e = parsed; } } + _ => {} + } + } + Some(Cvss4 { av: av?, ac: ac?, at: at?, pr: pr?, ui: ui?, vc: vc?, vi: vi?, va: va?, sc: sc?, si: si?, sa: sa?, e }) + } + + pub fn vector_string(&self) -> String { + let mut s = format!("CVSS:4.0/AV:{}/AC:{}/AT:{}/PR:{}/UI:{}/VC:{}/VI:{}/VA:{}/SC:{}/SI:{}/SA:{}", + self.av.code(), self.ac.code(), self.at.code(), self.pr.code(), self.ui.code(), + self.vc.code(), self.vi.code(), self.va.code(), + self.sc.code(), self.si.code(), self.sa.code()); + if self.e != ExploitMaturity::NotDefined { s.push_str(&format!("/E:{}", self.e.code())); } + s + } + + pub fn base_score(&self) -> f64 { + let v_iss = 1.0 - ((1.0 - self.vc.score()) * (1.0 - self.vi.score()) * (1.0 - self.va.score())); + let s_iss = 1.0 - ((1.0 - self.sc.score()) * (1.0 - self.si.score()) * (1.0 - self.sa.score())); + if v_iss == 0.0 && s_iss == 0.0 { return 0.0; } + let av_w = match self.av { Av4::Network => 0.85, Av4::Adjacent => 0.62, Av4::Local => 0.55, Av4::Physical => 0.2 }; + let ac_w = match self.ac { Ac4::Low => 0.77, Ac4::High => 0.44 }; + let at_w = match self.at { At::None => 1.0, At::Present => 0.7 }; + let pr_w = match self.pr { Pr4::None => 0.85, Pr4::Low => 0.62, Pr4::High => 0.27 }; + let ui_w = match self.ui { Ui4::None => 0.85, Ui4::Passive => 0.62, Ui4::Active => 0.44 }; + let exploitability = 8.22 * av_w * ac_w * at_w * pr_w * ui_w; + let impact = 6.42 * v_iss + 7.52 * s_iss * 0.375; + if impact <= 0.0 { return 0.0; } + let raw = (impact + exploitability).min(10.0); + let e_mod = match self.e { + ExploitMaturity::NotDefined | ExploitMaturity::Attacked => 1.0, + ExploitMaturity::Poc => 0.97, ExploitMaturity::Unreported => 0.94, + }; + roundup(raw * e_mod) + } + + pub fn severity(&self) -> &'static str { band(self.base_score()) } +} + #[cfg(test)] mod tests { use super::*; - fn v(s: &str) -> Vector { Vector::parse(s).unwrap_or_else(|| panic!("parse {s}")) } - #[test] - fn base_scores_match_the_first_reference_vectors() { - // These are the canonical scores from first.org's own calculator. + #[test] fn base_scores_match_the_first_reference_vectors() { assert_eq!(v("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H").base_score(), 9.8); - assert_eq!(v("CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N").base_score(), 6.1); // reflected XSS + assert_eq!(v("CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N").base_score(), 6.1); assert_eq!(v("CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:L/I:N/A:N").base_score(), 3.1); - assert_eq!(v("CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H").base_score(), 7.8); // local privesc - assert_eq!(v("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H").base_score(), 7.5); // DoS - assert_eq!(v("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H").base_score(), 10.0); // scope-changed RCE - assert_eq!(v("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N").base_score(), 5.3); // info leak + assert_eq!(v("CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H").base_score(), 7.8); + assert_eq!(v("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H").base_score(), 7.5); + assert_eq!(v("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H").base_score(), 10.0); + assert_eq!(v("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N").base_score(), 5.3); } - - #[test] - fn zero_impact_is_zero() { + #[test] fn zero_impact_is_zero() { assert_eq!(v("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:N").base_score(), 0.0); - assert_eq!(band(0.0), "None"); } - - #[test] - fn vector_string_roundtrips() { + #[test] fn vector_string_roundtrips() { let s = "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N"; assert_eq!(v(s).vector_string(), s); } - - #[test] - fn bands_follow_the_first_scale() { - assert_eq!(band(3.9), "Low"); - assert_eq!(band(4.0), "Medium"); - assert_eq!(band(6.9), "Medium"); - assert_eq!(band(7.0), "High"); - assert_eq!(band(8.9), "High"); - assert_eq!(band(9.0), "Critical"); + #[test] fn bands_follow_the_first_scale() { + assert_eq!(band(3.9), "Low"); assert_eq!(band(4.0), "Medium"); + assert_eq!(band(6.9), "Medium"); assert_eq!(band(7.0), "High"); + assert_eq!(band(8.9), "High"); assert_eq!(band(9.0), "Critical"); } - - #[test] - fn a_partial_vector_refuses_to_parse() { - // Missing A: — better to fail than to score a guess. + #[test] fn a_partial_vector_refuses_to_parse() { assert!(Vector::parse("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H").is_none()); assert!(Vector::parse("nonsense").is_none()); } - - #[test] - fn grading_drops_impact_without_a_receipt() { - // SQLi proposed as C:H/I:H (full read+write) but only the read (C) has - // a receipt. The demonstrated score keeps C, drops I. + #[test] fn grading_drops_impact_without_a_receipt() { let proposed = v("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N"); - let g = grade(proposed, |m| m == "C"); // only C has evidence + let g = grade(proposed, |m| m == "C"); assert!(g.needs_review()); assert!(g.uncertain.contains(&"I:H".to_string())); assert_eq!(g.demonstrated.i, Imp::None); - assert_eq!(g.demonstrated.c, Imp::High); - // Demonstrated is lower than potential — the gap is the unproven write. assert!(g.demonstrated_score < g.potential_score); } - - #[test] - fn grading_with_full_evidence_keeps_the_score() { + #[test] fn grading_with_full_evidence_keeps_the_score() { let proposed = v("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"); let g = grade(proposed, |_| true); assert!(!g.needs_review()); assert_eq!(g.demonstrated_score, 9.8); - assert_eq!(g.demonstrated_score, g.potential_score); } - - #[test] - fn sqli_without_any_extraction_is_not_critical() { - // The article's exact example: SQLi proven (injection works) but - // nothing extracted → no impact receipt → demonstrated impact is None, - // so the number is NOT 9.8. + #[test] fn sqli_without_any_extraction_is_not_critical() { let proposed = v("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"); - let g = grade(proposed, |_| false); // no impact receipts at all - assert_eq!(g.demonstrated.c, Imp::None); - assert_eq!(g.demonstrated_score, 0.0, "class alone must not manufacture a critical"); - assert_eq!(g.potential_score, 9.8, "the potential is still recorded as context"); + let g = grade(proposed, |_| false); + assert_eq!(g.demonstrated_score, 0.0); + assert_eq!(g.potential_score, 9.8); assert_eq!(g.uncertain.len(), 3); } + + // CVSS 4.0 + fn v4(s: &str) -> Cvss4 { Cvss4::parse(s).unwrap_or_else(|| panic!("parse {s}")) } + + #[test] fn cvss4_parse_full_base() { + let c = v4("CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:H/SI:H/SA:H"); + assert_eq!(c.av, Av4::Network); assert_eq!(c.vc, Imp4::High); assert_eq!(c.sc, Imp4::High); + } + #[test] fn cvss4_parse_exploit_maturity() { + let c = v4("CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N/E:A"); + assert_eq!(c.e, ExploitMaturity::Attacked); + } + #[test] fn cvss4_reject_v31() { + assert!(Cvss4::parse("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H").is_none()); + } + #[test] fn cvss4_reject_incomplete() { + assert!(Cvss4::parse("CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:H/SI:H").is_none()); + } + #[test] fn cvss4_vector_roundtrips() { + let s = "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:H/SI:H/SA:H"; + assert_eq!(v4(s).vector_string(), s); + } + #[test] fn cvss4_vector_with_e() { + let s = "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N/E:A"; + assert_eq!(v4(s).vector_string(), s); + } + #[test] fn cvss4_zero_impact() { + assert_eq!(v4("CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:N/SC:N/SI:N/SA:N").base_score(), 0.0); + } + #[test] fn cvss4_max_is_critical() { + let s = v4("CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:H/SI:H/SA:H").base_score(); + assert!(s >= 9.0, "max should be Critical, got {s}"); + } + #[test] fn cvss4_local_low_is_low() { + let s = v4("CVSS:4.0/AV:L/AC:H/AT:P/PR:H/UI:A/VC:L/VI:N/VA:N/SC:N/SI:N/SA:N").base_score(); + assert!(s < 7.0, "local/low should not be High, got {s}"); + } + #[test] fn cvss4_network_rce_is_high() { + let s = v4("CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N").base_score(); + assert!(s >= 7.0, "network RCE should be High+, got {s}"); + } + #[test] fn cvss4_passive_ui() { + assert_eq!(v4("CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:P/VC:H/VI:N/VA:N/SC:N/SI:N/SA:N").ui, Ui4::Passive); + } + #[test] fn cvss4_at_present() { + assert_eq!(v4("CVSS:4.0/AV:N/AC:H/AT:P/PR:L/UI:N/VC:L/VI:L/VA:N/SC:N/SI:N/SA:N").at, At::Present); + } + #[test] fn cvss4_subsequent_only() { + let s = v4("CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:N/SC:H/SI:H/SA:H").base_score(); + assert!(s > 0.0, "subsequent-only should score >0, got {s}"); + } + #[test] fn cvss4_exploit_maturity_ordering() { + let a = v4("CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N/E:A").base_score(); + let u = v4("CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N/E:U").base_score(); + assert!(a >= u); + } + #[test] fn cvss4_av_ordering() { + let n = v4("CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:N/VA:N/SC:N/SI:N/SA:N").base_score(); + let p = v4("CVSS:4.0/AV:P/AC:L/AT:N/PR:N/UI:N/VC:H/VI:N/VA:N/SC:N/SI:N/SA:N").base_score(); + assert!(n > p); + } + #[test] fn detect_v31() { assert_eq!(detect_version("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"), Some(CvssVersion::V31)); } + #[test] fn detect_v40() { assert_eq!(detect_version("CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N"), Some(CvssVersion::V40)); } + #[test] fn detect_unknown() { assert_eq!(detect_version("garbage"), None); } + #[test] fn parse_any_v31() { let r = parse_any("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H").unwrap(); assert_eq!(r.version, CvssVersion::V31); assert_eq!(r.score, 9.8); } + #[test] fn parse_any_v40() { let r = parse_any("CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:H/SI:H/SA:H").unwrap(); assert_eq!(r.version, CvssVersion::V40); assert!(r.score >= 9.0); } + #[test] fn parse_any_garbage() { assert!(parse_any("not-a-vector").is_none()); } } diff --git a/neurosploit-rs/crates/harness/src/mcp_profiles.rs b/neurosploit-rs/crates/harness/src/mcp_profiles.rs index 84784af..d95a3fb 100644 --- a/neurosploit-rs/crates/harness/src/mcp_profiles.rs +++ b/neurosploit-rs/crates/harness/src/mcp_profiles.rs @@ -23,6 +23,8 @@ pub enum Profile { CobaltStrike, SliverC2, AdaptixC2, + HavocC2, + MythicC2, Infra, Ad, Cloud, @@ -172,6 +174,43 @@ pub fn profile(p: &Profile) -> McpProfile { } }), }, + Profile::HavocC2 => McpProfile { + name: "Havoc C2".into(), + description: "Havoc C2 framework via Python teamserver MCP (demons, BOFs, .NET, token manipulation)".into(), + server_name: "havoc-c2".into(), + tools: tool_allowlist(p), + config: json!({ + "command": "python3", + "args": [ + "${NEUROSPLOIT_HAVOC_MCP_PATH:-/opt/havoc-c2-mcp}/havoc_mcp.py" + ], + "env": { + "HAVOC_TEAMSERVER_HOST": "", + "HAVOC_TEAMSERVER_PORT": "40056", + "HAVOC_USERNAME": "neurosploit", + "HAVOC_PASSWORD": "" + } + }), + }, + Profile::MythicC2 => McpProfile { + name: "Mythic C2".into(), + description: "Mythic C2 framework via REST API MCP (multi-agent: Apollo, Poseidon, Medusa)".into(), + server_name: "mythic-c2".into(), + tools: tool_allowlist(p), + config: json!({ + "command": "python3", + "args": [ + "${NEUROSPLOIT_MYTHIC_MCP_PATH:-/opt/mythic-c2-mcp}/mythic_mcp.py" + ], + "env": { + "MYTHIC_SERVER_HOST": "", + "MYTHIC_SERVER_PORT": "7443", + "MYTHIC_API_KEY": "", + "MYTHIC_USERNAME": "neurosploit", + "MYTHIC_PASSWORD": "" + } + }), + }, Profile::Infra => McpProfile { name: "Infra".into(), description: "Network/infra testing with an Nmap MCP server".into(), @@ -272,6 +311,14 @@ pub fn all_profiles() -> Vec<(Profile, &'static str)> { Profile::AdaptixC2, "AdaptixC2 framework (beacons, BOFs, Kerberos, execute-assembly, SOCKS, port-forwarding)", ), + ( + Profile::HavocC2, + "Havoc C2 framework (demons, BOFs, .NET assembly, token manipulation, SMB pivoting)", + ), + ( + Profile::MythicC2, + "Mythic C2 framework (multi-agent: Apollo/Poseidon/Medusa, lateral movement, persistence)", + ), (Profile::Infra, "Network/infra testing with Nmap MCP"), (Profile::Ad, "Active Directory testing with Kali MCP"), (Profile::Cloud, "Cloud/container tooling via Kali MCP"), @@ -389,6 +436,23 @@ pub fn tool_allowlist(p: &Profile) -> Vec { "findobj_module", "findobj_prochandle", "process_conn", "exfil_start", "exfil_stop", "exfil_cancel", ], + Profile::HavocC2 => &[ + "havoc_demons", "havoc_listeners", + "havoc_demon_shell", "havoc_demon_upload", "havoc_demon_download", + "havoc_demon_ps", "havoc_demon_inject", + "havoc_demon_token", "havoc_demon_pivot", + "havoc_demon_dotnet", "havoc_demon_bof", + "havoc_demon_sleep", "havoc_demon_exit", + "havoc_creds", "havoc_net_interfaces", + ], + Profile::MythicC2 => &[ + "mythic_callbacks", "mythic_tasks", "mythic_payloads", + "mythic_credentials", "mythic_files", "mythic_processes", + "mythic_shell", "mythic_keylog", "mythic_screenshot", + "mythic_socks", "mythic_portfwd", + "mythic_assembly", "mythic_bof", "mythic_tokens", + "mythic_lateral", "mythic_persist", + ], Profile::Infra | Profile::Nmap => &[ "do-nmap", "nmap_scan", "nmap_service_scan", "nmap_vuln_scan", "nmap_os_detect", "nmap_ping_sweep", @@ -492,6 +556,39 @@ pub fn prompt_context(p: &Profile) -> String { hosts, capture raw output as evidence, and never run destructive commands \ unless the operator explicitly approved them." ), + Profile::HavocC2 => format!( + "You are operating in HAVOC C2 mode through the Havoc teamserver MCP. \ + Available tools: {tool_list}. Use havoc_demons to inventory active demon \ + sessions before acting. Use havoc_listeners to check/create listeners \ + (HTTP/HTTPS/SMB). Post-exploitation: havoc_demon_shell for command execution, \ + havoc_demon_ps for process listing, havoc_demon_upload/havoc_demon_download \ + for file transfer. Advanced: havoc_demon_dotnet for .NET assembly execution \ + (SharpHound, Rubeus, Seatbelt), havoc_demon_bof for Beacon Object Files, \ + havoc_demon_inject for shellcode injection. Privilege escalation: \ + havoc_demon_token for token steal/make/revert. Lateral movement: \ + havoc_demon_pivot for SMB pivoting. Intelligence: havoc_creds for credential \ + store, havoc_net_interfaces for network recon. Every action is attributable — \ + stay inside authorized hosts, capture raw output as evidence, and never run \ + destructive commands unless the operator explicitly approved them." + ), + Profile::MythicC2 => format!( + "You are operating in MYTHIC C2 mode through the Mythic REST API MCP. \ + Available tools: {tool_list}. Mythic supports multiple agent types \ + (Apollo for Windows, Poseidon for Linux/macOS, Medusa for Python). \ + Use mythic_callbacks to inventory active callbacks before acting. \ + Use mythic_tasks to create and monitor tasks on callbacks. \ + Post-exploitation: mythic_shell for command execution, mythic_files for \ + file browser/download/upload, mythic_processes for process listing, \ + mythic_screenshot for visual recon. Advanced: mythic_assembly for .NET \ + execution, mythic_bof for BOFs, mythic_tokens for token manipulation. \ + Credential access: mythic_credentials for the credential store, \ + mythic_keylog for keylogger data. Lateral movement: mythic_lateral for \ + psexec/wmi/ssh pivoting, mythic_socks for SOCKS proxy, mythic_portfwd for \ + port forwarding. Persistence: mythic_persist for persistence mechanisms \ + (only with explicit operator authorization). Every action is attributable — \ + stay inside authorized hosts, capture raw output as evidence, and never \ + establish persistence or lateral movement without explicit approval." + ), Profile::Infra => format!( "You are operating in INFRA/NETWORK testing mode. Use the Nmap MCP server for \ host discovery, port/service identification and NSE checks. Available tools: {tool_list}. \ diff --git a/neurosploit-rs/crates/harness/src/reactive_bridge.rs b/neurosploit-rs/crates/harness/src/reactive_bridge.rs index fd1c546..1c4a4aa 100644 --- a/neurosploit-rs/crates/harness/src/reactive_bridge.rs +++ b/neurosploit-rs/crates/harness/src/reactive_bridge.rs @@ -81,6 +81,114 @@ pub async fn run_reactive( crate::dual_build::add_recon(&mut graph, &cfg.target, &recon_text, &scope_check); let _ = graph.save(&graph_dir); + // --- Deterministic probes (run before LLM agents, same as pipeline) --- + let mut probe_loot: Vec = Vec::new(); + let mut probe_evidence: Vec = Vec::new(); + if !cfg.offline { + let _ = tx.send("[reactive] running deterministic probes...".into()).await; + let probe_timeout: u64 = 15; + + // Shell runner for deterministic probes (no LLM, just command execution) + let run_cmd = |cmd: String| { + async move { + let output = tokio::process::Command::new("sh") + .arg("-c") + .arg(&cmd) + .output() + .await + .ok()?; + if output.status.success() || !output.stdout.is_empty() { + Some(String::from_utf8_lossy(&output.stdout).to_string()) + } else { + None + } + } + }; + + // Extract domain from target (strip scheme/port/path) + let domain = cfg.target + .trim_start_matches("http://") + .trim_start_matches("https://") + .split('/') + .next() + .unwrap_or(&cfg.target) + .split(':') + .next() + .unwrap_or(&cfg.target); + + // 1. DNS probe + let _ = tx.send("[reactive] probe: dns...".into()).await; + let dns_facts = crate::dns_probe::probe_dns(domain, &[], probe_timeout, &run_cmd).await; + probe_loot.extend(dns_facts.loot.clone()); + if !dns_facts.evidence.is_empty() { + probe_evidence.push(format!("[DNS]\n{}", dns_facts.evidence)); + } + let _ = tx.send(format!("[reactive] dns: {} records, {} loot", dns_facts.records.len(), dns_facts.loot.len())).await; + + // 2. TLS/SSL probe on common ports + let _ = tx.send("[reactive] probe: tls/ssl...".into()).await; + let tls_ports: Vec = vec![443, 8443]; + let tls_facts = crate::ssl_probe::probe_tls(domain, &tls_ports, probe_timeout, &run_cmd).await; + probe_loot.extend(tls_facts.loot.clone()); + if !tls_facts.evidence.is_empty() { + probe_evidence.push(format!("[TLS]\n{}", tls_facts.evidence)); + } + let _ = tx.send(format!("[reactive] tls: {} port(s) scanned, {} loot", tls_facts.ports.len(), tls_facts.loot.len())).await; + + // 3. Cloud probe + let _ = tx.send("[reactive] probe: cloud metadata...".into()).await; + let cloud_facts = crate::cloud_probe::probe_cloud(domain, &recon_text, probe_timeout, &run_cmd).await; + probe_loot.extend(cloud_facts.loot.clone()); + if !cloud_facts.evidence.is_empty() { + probe_evidence.push(format!("[CLOUD]\n{}", cloud_facts.evidence)); + } + let _ = tx.send(format!("[reactive] cloud: provider={:?}, {} loot", cloud_facts.provider, cloud_facts.loot.len())).await; + + // 4. GraphQL probe — look for /graphql endpoints in recon + let mut gql_urls: Vec = Vec::new(); + for scheme in &["https", "http"] { + gql_urls.push(format!("{}://{}/graphql", scheme, domain)); + } + // Also scan recon text for GraphQL endpoint hints + for line in recon_text.lines() { + let lower = line.to_lowercase(); + if lower.contains("graphql") || lower.contains("/graphql") { + for word in line.split_whitespace() { + if word.starts_with("http") && word.contains("graphql") { + gql_urls.push(word.to_string()); + } + } + } + } + gql_urls.sort(); + gql_urls.dedup(); + if !gql_urls.is_empty() { + let _ = tx.send(format!("[reactive] probe: graphql ({} endpoints)...", gql_urls.len())).await; + let gql_facts = crate::graphql_probe::probe_graphql(&gql_urls, probe_timeout, &run_cmd).await; + probe_loot.extend(gql_facts.loot.clone()); + if !gql_facts.evidence.is_empty() { + probe_evidence.push(format!("[GRAPHQL]\n{}", gql_facts.evidence)); + } + let _ = tx.send(format!("[reactive] graphql: {} endpoint(s), {} loot", gql_facts.endpoints.len(), gql_facts.loot.len())).await; + } + + let _ = tx.send(format!( + "[reactive] deterministic probes complete: {} total loot items", + probe_loot.len() + )).await; + } + + // Feed probe results into dual graph as additional recon + if !probe_loot.is_empty() { + let probe_text = probe_evidence.join("\n\n"); + let scope2 = crate::pipeline::effective_scope(&cfg); + let scope_check2 = move |url: &str| { + matches!(scope2.check(url, crate::scope::Action::Probe), crate::scope::Decision::Allow) + }; + crate::dual_build::add_recon(&mut graph, &cfg.target, &probe_text, &scope_check2); + let _ = graph.save(&graph_dir); + } + // --- Build reactive config --- let reactive_cfg = ReactiveConfig { target: cfg.target.clone(), @@ -120,6 +228,8 @@ pub async fn run_reactive( "cobaltstrike" | "cobalt" | "cs" => crate::mcp_profiles::Profile::CobaltStrike, "sliver" | "sliverc2" | "sliver-c2" => crate::mcp_profiles::Profile::SliverC2, "adaptix" | "adaptixc2" | "adaptix-c2" => crate::mcp_profiles::Profile::AdaptixC2, + "havoc" | "havocc2" | "havoc-c2" => crate::mcp_profiles::Profile::HavocC2, + "mythic" | "mythicc2" | "mythic-c2" => crate::mcp_profiles::Profile::MythicC2, "c2" => crate::mcp_profiles::Profile::SliverC2, "infra" | "host" => crate::mcp_profiles::Profile::Infra, "ad" | "internal" => crate::mcp_profiles::Profile::Ad, @@ -149,6 +259,14 @@ pub async fn run_reactive( let cfg_arc = Arc::new(cfg.clone()); let _constraints = Arc::new(operator_constraints(&cfg)); let tx2 = tx.clone(); + let probe_context: Arc = Arc::new(if probe_loot.is_empty() { + String::new() + } else { + format!( + "\n--- Deterministic Probe Results ---\n{}\n--- End Probe Results ---\n", + probe_loot.join("\n") + ) + }); let exec: ExecFn = Arc::new(move |intent: PlannerIntent, ctx: WorkCtx| { let cfg = cfg_arc.clone(); @@ -156,6 +274,7 @@ pub async fn run_reactive( let pool_handle = pool_handle.clone(); let kb = kb.clone(); let mcp_context = mcp_context.clone(); + let probe_context = probe_context.clone(); async move { let _ = tx.send(format!("[reactive] worker: {:?} on {}", intent.action, intent.target)).await; @@ -183,10 +302,11 @@ pub async fn run_reactive( let task_desc = format!("{:?} {}", intent.action, intent.rationale); let methodology = kb.methodology_for(&task_desc, 2, 3000); let mcp_block = if mcp_context.is_empty() { String::new() } else { format!("\n{}\n", *mcp_context) }; + let probe_block = if probe_context.is_empty() { String::new() } else { (*probe_context).clone() }; let user = format!( "Target: {}\nTask: {:?}\nSpecific target: {}\nRationale: {}\ - {}{}\n\ + {}{}{}\n\ Execute this task. Report results using the prefixes: Finding:, Fact:, Negative:\n\ {}", cfg.target, @@ -195,6 +315,7 @@ pub async fn run_reactive( intent.rationale, if methodology.is_empty() { String::new() } else { format!("\n\n{}", methodology) }, mcp_block, + probe_block, if ctx.wrapping() { "\nWRAP-UP: Time is running out. Persist your results NOW and stop." } else { "" }, ); diff --git a/setup.sh b/setup.sh index d4929f3..ef4d5e4 100755 --- a/setup.sh +++ b/setup.sh @@ -244,6 +244,39 @@ if [ "${NEUROSPLOIT_NO_DEPS:-0}" != "1" ]; then else warn "AdaptixC2 MCP not installed — set NEUROSPLOIT_ADAPTIX_C2=1 to install" fi + # Havoc C2 MCP server (optional — for Havoc C2 operations via MCP). + HAVOC_MCP_DIR="${NEUROSPLOIT_HAVOC_MCP_PATH:-$DIR/havoc-c2-mcp}" + if [ -f "$HAVOC_MCP_DIR/havoc_mcp.py" ]; then + ok "Havoc C2 MCP present ($HAVOC_MCP_DIR)" + elif [ "${NEUROSPLOIT_HAVOC_C2:-0}" = "1" ]; then + say "Installing Havoc C2 MCP server…" + if command -v python3 >/dev/null 2>&1; then + mkdir -p "$HAVOC_MCP_DIR" && \ + ok "Havoc C2 MCP directory created ($HAVOC_MCP_DIR) — add havoc_mcp.py server implementation" || \ + warn "Havoc C2 MCP setup failed — create $HAVOC_MCP_DIR manually" + else + warn "Havoc C2 MCP requires python3 — skipped" + fi + else + warn "Havoc C2 MCP not installed — set NEUROSPLOIT_HAVOC_C2=1 to install" + fi + # Mythic C2 MCP server (optional — for Mythic C2 operations via MCP). + MYTHIC_MCP_DIR="${NEUROSPLOIT_MYTHIC_MCP_PATH:-$DIR/mythic-c2-mcp}" + if [ -f "$MYTHIC_MCP_DIR/mythic_mcp.py" ]; then + ok "Mythic C2 MCP present ($MYTHIC_MCP_DIR)" + elif [ "${NEUROSPLOIT_MYTHIC_C2:-0}" = "1" ]; then + say "Installing Mythic C2 MCP server…" + if command -v python3 >/dev/null 2>&1; then + mkdir -p "$MYTHIC_MCP_DIR" && \ + pip3 install mythic 2>/dev/null && \ + ok "Mythic C2 MCP directory created ($MYTHIC_MCP_DIR) — add mythic_mcp.py server implementation" || \ + warn "Mythic C2 MCP setup failed — create $MYTHIC_MCP_DIR and pip3 install mythic manually" + else + warn "Mythic C2 MCP requires python3 — skipped" + fi + else + warn "Mythic C2 MCP not installed — set NEUROSPLOIT_MYTHIC_C2=1 to install" + fi else say "Dependency auto-install skipped (NEUROSPLOIT_NO_DEPS=1)." for t in curl git nmap node rustscan ffuf typst; do