use std::fmt;
use std::str::FromStr;
use thiserror::Error;
use crate::model::confidence::Confidence;
pub const MAX_EXCERPT_BYTES: usize = 2048;
pub const MAX_FINDINGS_PER_SUBJECT: usize = 256;
#[non_exhaustive]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub enum Severity {
Info,
Low,
Medium,
High,
Critical,
}
impl Severity {
pub const fn label(self) -> &'static str {
match self {
Self::Info => "Info",
Self::Low => "Low",
Self::Medium => "Medium",
Self::High => "High",
Self::Critical => "Critical",
}
}
pub const fn as_score(self) -> u8 {
match self {
Self::Info => 0,
Self::Low => 25,
Self::Medium => 50,
Self::High => 75,
Self::Critical => 100,
}
}
pub const ALL: [Severity; 5] = [
Self::Info,
Self::Low,
Self::Medium,
Self::High,
Self::Critical,
];
}
#[non_exhaustive]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub enum DetectionClass {
Passive,
ActiveBenign,
ActiveMutating,
Exploit,
Dos,
}
impl DetectionClass {
pub const fn label(self) -> &'static str {
match self {
Self::Passive => "passive",
Self::ActiveBenign => "active-benign",
Self::ActiveMutating => "active-mutating",
Self::Exploit => "exploit",
Self::Dos => "DoS",
}
}
pub const ALL: [DetectionClass; 5] = [
Self::Passive,
Self::ActiveBenign,
Self::ActiveMutating,
Self::Exploit,
Self::Dos,
];
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Version {
pub major: u16,
pub minor: u16,
pub patch: u16,
}
impl Version {
pub const fn new(major: u16, minor: u16, patch: u16) -> Self {
Self {
major,
minor,
patch,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("'{input}' is not a version: expected three dot-separated numbers, as in `1.2.3`")]
pub struct VersionParseError {
pub input: String,
}
impl FromStr for Version {
type Err = VersionParseError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let fail = || VersionParseError {
input: text.to_string(),
};
let mut parts = text.split('.');
let mut number = || parts.next().ok_or_else(fail)?.parse().map_err(|_| fail());
let major = number()?;
let minor = number()?;
let patch = number()?;
if parts.next().is_some() {
return Err(fail());
}
Ok(Self::new(major, minor, patch))
}
}
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Reference {
Cve(String),
Cwe(u32),
Url(String),
}
impl Reference {
pub fn cve(id: impl Into<String>) -> Option<Self> {
let id = id.into();
is_cve_shaped(&id).then_some(Self::Cve(id))
}
pub const fn cwe(number: u32) -> Self {
Self::Cwe(number)
}
pub fn url(url: impl Into<String>) -> Self {
Self::Url(url.into())
}
}
fn is_cve_shaped(id: &str) -> bool {
let Some(rest) = id.strip_prefix("CVE-") else {
return false;
};
let Some((year, seq)) = rest.split_once('-') else {
return false;
};
year.len() == 4
&& year.bytes().all(|b| b.is_ascii_digit())
&& !seq.is_empty()
&& seq.bytes().all(|b| b.is_ascii_digit())
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct Excerpt(String);
impl Excerpt {
pub fn new(text: impl Into<String>) -> Self {
let mut text = text.into();
if text.len() > MAX_EXCERPT_BYTES {
let mut end = MAX_EXCERPT_BYTES;
while !text.is_char_boundary(end) {
end -= 1;
}
text.truncate(end);
}
Self(text)
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DetectionId {
id: String,
version: Version,
content_hash: String,
}
impl DetectionId {
pub fn new(
id: impl Into<String>,
version: Version,
content_hash: impl Into<String>,
) -> Result<Self, FindingError> {
let id = id.into();
if id.trim().is_empty() {
return Err(FindingError::EmptyId);
}
Ok(Self {
id,
version,
content_hash: content_hash.into(),
})
}
pub fn id(&self) -> &str {
&self.id
}
pub fn version(&self) -> Version {
self.version
}
pub fn content_hash(&self) -> &str {
&self.content_hash
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ClaimId {
detection: String,
subject: String,
}
impl ClaimId {
pub fn detection(&self) -> &str {
&self.detection
}
pub fn subject(&self) -> &str {
&self.subject
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
detection: DetectionId,
title: String,
severity: Severity,
confidence: Confidence,
class: DetectionClass,
excerpt: Excerpt,
references: Vec<Reference>,
remediation: Option<String>,
}
impl Finding {
pub fn new(
detection: DetectionId,
title: impl Into<String>,
severity: Severity,
confidence: Confidence,
class: DetectionClass,
) -> Result<Self, FindingError> {
let title = title.into();
if title.trim().is_empty() {
return Err(FindingError::EmptyTitle);
}
Ok(Self {
detection,
title,
severity,
confidence,
class,
excerpt: Excerpt::default(),
references: Vec::new(),
remediation: None,
})
}
#[must_use]
pub fn with_reference(mut self, reference: Reference) -> Self {
if !self.references.contains(&reference) {
self.references.push(reference);
}
self
}
#[must_use]
pub fn with_excerpt(mut self, excerpt: Excerpt) -> Self {
self.excerpt = excerpt;
self
}
#[must_use]
pub fn with_remediation(mut self, remediation: impl Into<String>) -> Self {
self.remediation = Some(remediation.into());
self
}
pub fn detection(&self) -> &DetectionId {
&self.detection
}
pub fn title(&self) -> &str {
&self.title
}
pub fn severity(&self) -> Severity {
self.severity
}
pub fn confidence(&self) -> Confidence {
self.confidence
}
pub fn class(&self) -> DetectionClass {
self.class
}
pub fn excerpt(&self) -> &Excerpt {
&self.excerpt
}
pub fn references(&self) -> impl Iterator<Item = &Reference> {
self.references.iter()
}
pub fn remediation(&self) -> Option<&str> {
self.remediation.as_deref()
}
pub fn claim_id(&self) -> ClaimId {
let subject = self
.references
.iter()
.filter_map(|r| match r {
Reference::Cve(id) => Some(id.clone()),
_ => None,
})
.min()
.unwrap_or_else(|| self.title.clone());
ClaimId {
detection: self.detection.id.clone(),
subject,
}
}
pub fn corroborate(&mut self, other: Finding) -> bool {
let Finding {
detection,
title,
severity,
confidence,
class,
excerpt,
references,
remediation,
} = other;
let mut changed = false;
let stronger = self.confidence.max(confidence);
if stronger != self.confidence {
self.confidence = stronger;
changed = true;
}
if detection.version >= self.detection.version {
if detection.version > self.detection.version {
self.detection = detection;
changed = true;
}
if severity != self.severity {
self.severity = severity;
changed = true;
}
if title != self.title {
self.title = title;
changed = true;
}
if class != self.class {
self.class = class;
changed = true;
}
if !excerpt.is_empty() && excerpt != self.excerpt {
self.excerpt = excerpt;
changed = true;
}
if remediation.is_some() && remediation != self.remediation {
self.remediation = remediation;
changed = true;
}
} else {
if self.excerpt.is_empty() && !excerpt.is_empty() {
self.excerpt = excerpt;
changed = true;
}
if self.remediation.is_none() && remediation.is_some() {
self.remediation = remediation;
changed = true;
}
}
for reference in references {
if !self.references.contains(&reference) {
self.references.push(reference);
changed = true;
}
}
changed
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Standing {
Upheld,
Overturned,
Unsettled,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum FindingError {
#[error("a detection id cannot be empty")]
EmptyId,
#[error("a finding title cannot be empty")]
EmptyTitle,
}
#[cfg(test)]
mod tests {
use super::*;
fn detection() -> DetectionId {
DetectionId::new("redis-unauth-access", Version::new(1, 0, 0), "abc123").unwrap()
}
fn finding() -> Finding {
Finding::new(
detection(),
"Unauthenticated Redis access",
Severity::High,
Confidence::Certain,
DetectionClass::ActiveBenign,
)
.unwrap()
}
#[test]
fn severity_orders_weakest_to_strongest() {
assert!(Severity::Info < Severity::Low);
assert!(Severity::Low < Severity::Medium);
assert!(Severity::Medium < Severity::High);
assert!(Severity::High < Severity::Critical);
assert_eq!(Severity::ALL.iter().max(), Some(&Severity::Critical));
assert_eq!(Severity::Critical.as_score(), 100);
assert_eq!(Severity::Info.as_score(), 0);
}
#[test]
fn an_empty_title_is_refused() {
let err = Finding::new(
detection(),
" ",
Severity::High,
Confidence::Certain,
DetectionClass::ActiveBenign,
);
assert_eq!(err, Err(FindingError::EmptyTitle));
}
#[test]
fn an_empty_detection_id_is_refused() {
let err = DetectionId::new("", Version::new(1, 0, 0), "hash");
assert_eq!(err, Err(FindingError::EmptyId));
}
#[test]
fn an_over_length_excerpt_is_truncated_on_a_char_boundary() {
let big = "é".repeat(MAX_EXCERPT_BYTES); let excerpt = Excerpt::new(big);
assert!(excerpt.as_str().len() <= MAX_EXCERPT_BYTES);
assert!(excerpt.as_str().chars().all(|c| c == 'é'));
}
#[test]
fn a_short_excerpt_is_kept_verbatim() {
let excerpt = Excerpt::new("redis_version:7.2.4");
assert_eq!(excerpt.as_str(), "redis_version:7.2.4");
}
#[test]
fn references_dedup_and_keep_the_order_they_were_added_in() {
let worst = Reference::cve("CVE-2024-6387").expect("a CVE");
let older = Reference::cve("CVE-2015-5600").expect("a CVE");
let f = finding()
.with_reference(Reference::cwe(306))
.with_reference(Reference::cwe(306))
.with_reference(worst.clone())
.with_reference(older.clone());
let refs: Vec<_> = f.references().cloned().collect();
assert_eq!(refs.len(), 3, "the duplicate CWE must fold away");
assert_eq!(refs, vec![Reference::cwe(306), worst, older]);
}
#[test]
fn a_claim_is_keyed_on_the_lowest_cve_however_they_were_ordered() {
let ranked = finding()
.with_reference(Reference::cve("CVE-2024-6387").expect("a CVE"))
.with_reference(Reference::cve("CVE-2015-5600").expect("a CVE"));
let reordered = finding()
.with_reference(Reference::cve("CVE-2015-5600").expect("a CVE"))
.with_reference(Reference::cve("CVE-2024-6387").expect("a CVE"));
assert_eq!(ranked.claim_id(), reordered.claim_id());
assert_eq!(ranked.claim_id().subject(), "CVE-2015-5600");
}
#[test]
fn a_malformed_cve_is_not_a_reference() {
assert!(Reference::cve("CVE-2021-44228").is_some());
assert!(Reference::cve("not-a-cve").is_none());
assert!(Reference::cve("CVE-21-44228").is_none()); assert!(Reference::cve("CVE-2021-").is_none()); }
#[test]
fn version_parses_and_orders_numerically() {
assert_eq!("8.3.1".parse(), Ok(Version::new(8, 3, 1)));
assert!("8.3".parse::<Version>().is_err());
assert!("8.3.1.0".parse::<Version>().is_err());
assert!("8.x.1".parse::<Version>().is_err());
assert!(Version::new(8, 10, 0) > Version::new(8, 3, 1));
}
#[test]
fn claim_id_keys_on_cve_when_present_else_title() {
let v1 = finding().with_reference(Reference::cve("CVE-2021-44228").unwrap());
let newer = Finding::new(
DetectionId::new("redis-unauth-access", Version::new(2, 0, 0), "def456").unwrap(),
"A reworded title",
Severity::Critical,
Confidence::Strong,
DetectionClass::ActiveBenign,
)
.unwrap()
.with_reference(Reference::cve("CVE-2021-44228").unwrap());
assert_eq!(v1.claim_id(), newer.claim_id());
let by_title = finding();
assert_eq!(
by_title.claim_id(),
ClaimId {
detection: "redis-unauth-access".to_string(),
subject: "Unauthenticated Redis access".to_string(),
}
);
}
#[test]
fn corroborate_takes_the_stronger_and_newer_reading() {
let mut base = finding() .with_reference(Reference::cve("CVE-2022-0543").unwrap());
let newer = Finding::new(
DetectionId::new("redis-unauth-access", Version::new(1, 1, 0), "newhash").unwrap(),
"Unauthenticated Redis access",
Severity::Critical, Confidence::Strong, DetectionClass::ActiveBenign,
)
.unwrap()
.with_reference(Reference::cve("CVE-2022-0543").unwrap()) .with_reference(Reference::cwe(306))
.with_remediation("Require a password.");
assert_eq!(base.claim_id(), newer.claim_id());
assert!(base.corroborate(newer));
assert_eq!(base.severity(), Severity::Critical, "newer severity wins");
assert_eq!(
base.confidence(),
Confidence::Certain,
"confidence only rises"
);
assert_eq!(base.detection().version(), Version::new(1, 1, 0));
assert_eq!(base.remediation(), Some("Require a password."));
let refs: Vec<_> = base.references().cloned().collect();
assert_eq!(refs.len(), 2, "references union, not replace");
assert!(refs.contains(&Reference::Cwe(306)));
}
#[test]
fn an_older_account_does_not_supply_a_newer_versions_verdict() {
let account = |version: Version, severity: Severity, title: &str| {
Finding::new(
DetectionId::new("redis-unauth-access", version, "hash").unwrap(),
title,
severity,
Confidence::Probable,
DetectionClass::ActiveBenign,
)
.unwrap()
};
let mut current = account(
Version::new(2, 0, 0),
Severity::Critical,
"Redis, wide open",
);
let superseded = account(Version::new(1, 0, 0), Severity::Low, "Redis reachable");
current.corroborate(superseded);
assert_eq!(current.detection().version(), Version::new(2, 0, 0));
assert_eq!(
current.severity(),
Severity::Critical,
"the stamp and the verdict have to name one version"
);
assert_eq!(current.title(), "Redis, wide open");
}
#[test]
fn an_account_at_the_same_version_supplies_the_current_reading() {
let account = |severity: Severity| {
Finding::new(
DetectionId::new("tls-weak-cipher", Version::new(1, 0, 0), "hash").unwrap(),
"a weak cipher is offered",
severity,
Confidence::Probable,
DetectionClass::Passive,
)
.unwrap()
};
let mut january = account(Severity::Low);
assert!(january.corroborate(account(Severity::Critical)));
assert_eq!(january.severity(), Severity::Critical);
let mut worse_before = account(Severity::Critical);
assert!(worse_before.corroborate(account(Severity::Low)));
assert_eq!(worse_before.severity(), Severity::Low);
assert_eq!(january.detection().version(), Version::new(1, 0, 0));
}
#[test]
fn an_older_account_fills_a_gap_it_cannot_overwrite() {
let account = |version: Version| {
Finding::new(
DetectionId::new("redis-unauth-access", version, "hash").unwrap(),
"Unauthenticated Redis access",
Severity::High,
Confidence::Probable,
DetectionClass::ActiveBenign,
)
.unwrap()
};
let mut current = account(Version::new(2, 0, 0));
let older = account(Version::new(1, 0, 0))
.with_excerpt(Excerpt::new("-ERR unknown command"))
.with_remediation("Require a password.");
assert!(current.corroborate(older), "a gap was filled");
assert_eq!(current.excerpt().as_str(), "-ERR unknown command");
assert_eq!(current.remediation(), Some("Require a password."));
let mut carrying = account(Version::new(2, 0, 0)).with_excerpt(Excerpt::new("READONLY"));
carrying.corroborate(account(Version::new(1, 0, 0)).with_excerpt(Excerpt::new("older")));
assert_eq!(carrying.excerpt().as_str(), "READONLY");
}
#[test]
fn corroborate_reports_no_change_for_an_identical_refiring() {
let mut base = finding();
assert!(!base.corroborate(finding()));
}
}