pub mod file;
pub mod network;
pub mod triage;
pub const RULES: &[(&str, &str)] = &[
(
"file.became_unreadable",
"a watched file was readable at baseline and is not now",
),
("file.created", "a watched path now exists where it did not"),
("file.deleted", "a watched file no longer exists"),
("file.modified", "a watched file's contents changed"),
(
"file.unbaselined",
"a watched file has no baseline entry to compare against",
),
("file.unreadable", "a watched file could not be read"),
(
"net.listener_gone",
"a port in the baseline is no longer listening",
),
(
"net.new_listener",
"a port is listening that was not in the baseline",
),
(
"net.notable_port",
"a port conventionally used by remote-access tooling is listening",
),
];
use serde::{Deserialize, Serialize};
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Confidence {
Possible,
Probable,
Certain,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Severity {
Info,
Low,
Medium,
High,
Critical,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Evidence {
pub kind: String,
pub observed: String,
pub expected: Option<String>,
}
impl Evidence {
pub fn observed(kind: impl Into<String>, observed: impl Into<String>) -> Self {
Self {
kind: kind.into(),
observed: observed.into(),
expected: None,
}
}
pub fn differs(
kind: impl Into<String>,
observed: impl Into<String>,
expected: impl Into<String>,
) -> Self {
Self {
kind: kind.into(),
observed: observed.into(),
expected: Some(expected.into()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "subject")]
pub enum Subject {
File {
path: String,
},
Network {
local_port: u16,
remote: Option<String>,
process: Option<String>,
pid: Option<u32>,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Finding {
pub rule: String,
pub title: String,
pub severity: Severity,
pub confidence: Confidence,
pub subject: Subject,
pub evidence: Vec<Evidence>,
pub observed_at: u64,
}
impl Finding {
pub fn new(
rule: impl Into<String>,
title: impl Into<String>,
severity: Severity,
confidence: Confidence,
subject: Subject,
evidence: Vec<Evidence>,
) -> Option<Self> {
if evidence.is_empty() {
return None;
}
Some(Self {
rule: rule.into(),
title: title.into(),
severity,
confidence,
subject,
evidence,
observed_at: now_secs(),
})
}
}
pub(crate) fn now_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "status")]
pub enum ScanStatus {
NoBaseline {
recorded: usize,
reason: String,
},
Clean {
checked: usize,
},
Findings {
checked: usize,
findings: Vec<Finding>,
},
Failed {
reason: String,
},
}
impl ScanStatus {
pub fn findings(&self) -> &[Finding] {
match self {
ScanStatus::Findings { findings, .. } => findings,
_ => &[],
}
}
pub fn is_conclusive(&self) -> bool {
matches!(self, ScanStatus::Clean { .. } | ScanStatus::Findings { .. })
}
}
#[cfg(test)]
mod tests {
use super::*;
fn subject() -> Subject {
Subject::File {
path: "/etc/passwd".into(),
}
}
#[test]
fn a_finding_without_evidence_cannot_be_built() {
assert!(
Finding::new(
"file.modified",
"something happened",
Severity::Critical,
Confidence::Certain,
subject(),
vec![],
)
.is_none(),
"a finding with no evidence is an opinion, and this is the only \
constructor, so there is no way around it"
);
}
#[test]
fn a_finding_with_evidence_is_built_and_timestamped() {
let f = Finding::new(
"file.modified",
"hash differs",
Severity::High,
Confidence::Certain,
subject(),
vec![Evidence::differs("file.hash", "abc", "def")],
)
.expect("evidence supplied");
assert_eq!(f.evidence.len(), 1);
assert_eq!(f.evidence[0].expected.as_deref(), Some("def"));
}
#[test]
fn no_baseline_is_not_clean_and_neither_is_a_failure() {
let none = ScanStatus::NoBaseline {
recorded: 12,
reason: "first run".into(),
};
let clean = ScanStatus::Clean { checked: 12 };
let failed = ScanStatus::Failed {
reason: "permission denied".into(),
};
assert_ne!(none, clean);
assert!(
!none.is_conclusive(),
"a first run has not established that a machine is uncompromised; \
reporting it as clean is the most dangerous sentence this module \
could emit"
);
assert!(!failed.is_conclusive());
assert!(clean.is_conclusive());
let a = serde_json::to_string(&none).unwrap();
let b = serde_json::to_string(&clean).unwrap();
let c = serde_json::to_string(&failed).unwrap();
assert!(a.contains("\"status\":\"no_baseline\""), "{a}");
assert!(b.contains("\"status\":\"clean\""), "{b}");
assert!(c.contains("\"status\":\"failed\""), "{c}");
assert_ne!(a, b);
assert_ne!(b, c);
}
#[test]
fn findings_is_empty_for_two_unrelated_reasons() {
let none = ScanStatus::NoBaseline {
recorded: 0,
reason: "first run".into(),
};
let clean = ScanStatus::Clean { checked: 500 };
assert!(none.findings().is_empty());
assert!(clean.findings().is_empty());
assert!(
!none.is_conclusive() && clean.is_conclusive(),
"an empty findings list is not a result on its own — the variant is"
);
}
#[test]
fn severity_and_confidence_order_the_way_a_reader_expects() {
assert!(Severity::Critical > Severity::High);
assert!(Severity::Info < Severity::Low);
assert!(Confidence::Certain > Confidence::Probable);
assert!(Confidence::Probable > Confidence::Possible);
}
#[test]
fn a_high_severity_finding_may_be_low_confidence() {
let f = Finding::new(
"net.suspicious_port",
"outbound connection to an unusual port",
Severity::High,
Confidence::Possible,
Subject::Network {
local_port: 51234,
remote: Some("203.0.113.5:4444".into()),
process: None,
pid: None,
},
vec![Evidence::observed("net.remote_port", "4444")],
)
.unwrap();
assert_eq!(f.severity, Severity::High);
assert_eq!(f.confidence, Confidence::Possible);
}
#[test]
fn an_unknown_process_is_none_rather_than_a_placeholder_string() {
let s = Subject::Network {
local_port: 22,
remote: None,
process: None,
pid: None,
};
let json = serde_json::to_string(&s).unwrap();
assert!(json.contains("\"process\":null"), "{json}");
assert!(
!json.contains("unknown"),
"a placeholder string would be an absence dressed as a reading: {json}"
);
}
}