use std::time::Duration;
use std::time::SystemTime;
use crate::diff::change::{Change, Coverage, Presence};
use crate::model::port::security::CertificateInfo;
use crate::model::port::{Port, PortState, Protocol, Security, Service};
#[derive(Debug, Clone, PartialEq)]
pub struct PortDelta {
number: u16,
protocol: Protocol,
presence: Presence,
baseline: Option<Port>,
current: Option<Port>,
changes: Vec<PortChange>,
}
impl PortDelta {
pub fn number(&self) -> u16 {
self.number
}
pub fn protocol(&self) -> Protocol {
self.protocol
}
pub fn presence(&self) -> Presence {
self.presence
}
pub fn baseline(&self) -> Option<&Port> {
self.baseline.as_ref()
}
pub fn current(&self) -> Option<&Port> {
self.current.as_ref()
}
pub fn changes(&self) -> &[PortChange] {
&self.changes
}
pub fn is_empty(&self) -> bool {
self.presence.is_in_both() && self.changes.is_empty()
}
pub fn is_opened(&self) -> bool {
self.state_of(self.current.as_ref()) == Some(PortState::Open)
&& self.state_of(self.baseline.as_ref()) != Some(PortState::Open)
}
pub fn is_closed(&self) -> bool {
self.state_of(self.baseline.as_ref()) == Some(PortState::Open)
&& self.state_of(self.current.as_ref()) != Some(PortState::Open)
}
fn state_of(&self, port: Option<&Port>) -> Option<PortState> {
port.map(Port::state)
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum PortChange {
State(Change<PortState>),
Service(ServiceChange),
Security(SecurityChange),
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum ServiceChange {
Identified(Service),
Unidentified(Service),
Name(Change<String>),
Product(Change<Option<String>>),
Vendor(Change<Option<String>>),
Version(Change<Option<String>>),
ExtraInfo(Change<Option<String>>),
Cpes {
gained: Vec<String>,
lost: Vec<String>,
},
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum SecurityChange {
TlsVersion(Change<Option<String>>),
CipherSuite(Change<Option<String>>),
Alpn {
gained: Vec<String>,
lost: Vec<String>,
},
Certificate(CertificateChange),
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum CertificateChange {
Presented(CertificateInfo),
Withdrawn(CertificateInfo),
Rotated {
before: Box<CertificateInfo>,
after: Box<CertificateInfo>,
},
Expiring {
certificate: Box<CertificateInfo>,
remaining: Duration,
},
Expired {
certificate: Box<CertificateInfo>,
since: Duration,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Validity {
Absent,
NotYetValid,
Valid,
Expiring,
Expired,
}
pub(crate) struct Clocks {
pub(crate) baseline: SystemTime,
pub(crate) current: SystemTime,
pub(crate) expiry_threshold: Duration,
}
pub(crate) fn compare(
baseline: &[&Port],
current: &[&Port],
presence: PresenceFor<'_>,
clocks: &Clocks,
) -> Vec<PortDelta> {
let mut keys: Vec<(u16, Protocol)> = baseline
.iter()
.chain(current.iter())
.map(|port| (port.number(), port.protocol()))
.collect();
keys.sort_unstable();
keys.dedup();
let mut deltas = Vec::new();
for (number, protocol) in keys {
let before = baseline
.iter()
.find(|port| port.number() == number && port.protocol() == protocol)
.copied();
let after = current
.iter()
.find(|port| port.number() == number && port.protocol() == protocol)
.copied();
let (presence, changes) = match (before, after) {
(Some(_), Some(_)) => (Presence::Both, changes_between(before, after, clocks)),
(Some(_), None) => (presence.removed(number, protocol), Vec::new()),
(None, Some(_)) => (presence.added(number, protocol), Vec::new()),
(None, None) => unreachable!("a key comes from one side or the other"),
};
if presence.is_in_both() && changes.is_empty() {
continue;
}
deltas.push(PortDelta {
number,
protocol,
presence,
baseline: before.cloned(),
current: after.cloned(),
changes,
});
}
deltas
}
pub(crate) struct PresenceFor<'a> {
pub(crate) baseline: &'a dyn Fn(u16, Protocol) -> Coverage,
pub(crate) current: &'a dyn Fn(u16, Protocol) -> Coverage,
}
impl PresenceFor<'_> {
fn added(&self, number: u16, protocol: Protocol) -> Presence {
Presence::Added {
before: (self.baseline)(number, protocol),
}
}
fn removed(&self, number: u16, protocol: Protocol) -> Presence {
Presence::Removed {
after: (self.current)(number, protocol),
}
}
}
fn changes_between(
before: Option<&Port>,
after: Option<&Port>,
clocks: &Clocks,
) -> Vec<PortChange> {
let (Some(before), Some(after)) = (before, after) else {
return Vec::new();
};
let mut changes = Vec::new();
if let Some(state) = Change::between(before.state(), after.state()) {
changes.push(PortChange::State(state));
}
changes.extend(
service_changes(before.service(), after.service())
.into_iter()
.map(PortChange::Service),
);
changes.extend(
security_changes(before.security(), after.security(), clocks)
.into_iter()
.map(PortChange::Security),
);
changes
}
fn service_changes(before: Option<&Service>, after: Option<&Service>) -> Vec<ServiceChange> {
let before = before.filter(|service| !service.is_inferred());
let after = after.filter(|service| !service.is_inferred());
match (before, after) {
(None, None) => Vec::new(),
(None, Some(after)) => vec![ServiceChange::Identified(after.clone())],
(Some(before), None) => vec![ServiceChange::Unidentified(before.clone())],
(Some(before), Some(after)) => {
let mut changes = Vec::new();
if let Some(name) = Change::between(before.name().to_owned(), after.name().to_owned()) {
changes.push(ServiceChange::Name(name));
}
if let Some(product) = optional(before.product(), after.product()) {
changes.push(ServiceChange::Product(product));
}
if let Some(vendor) = optional(before.vendor(), after.vendor()) {
changes.push(ServiceChange::Vendor(vendor));
}
if let Some(version) = optional(before.version(), after.version()) {
changes.push(ServiceChange::Version(version));
}
if let Some(extra) = optional(before.extrainfo(), after.extrainfo()) {
changes.push(ServiceChange::ExtraInfo(extra));
}
let (gained, lost) = set_change(
before.cpes().iter().map(|cpe| cpe.to_string()),
after.cpes().iter().map(|cpe| cpe.to_string()),
);
if !gained.is_empty() || !lost.is_empty() {
changes.push(ServiceChange::Cpes { gained, lost });
}
changes
}
}
}
fn security_changes(
before: Option<&Security>,
after: Option<&Security>,
clocks: &Clocks,
) -> Vec<SecurityChange> {
let mut changes = Vec::new();
let before_version = before.and_then(Security::tls_version);
let after_version = after.and_then(Security::tls_version);
if let Some(version) = optional(before_version, after_version) {
changes.push(SecurityChange::TlsVersion(version));
}
let before_cipher = before.and_then(Security::cipher_suite);
let after_cipher = after.and_then(Security::cipher_suite);
if let Some(cipher) = optional(before_cipher, after_cipher) {
changes.push(SecurityChange::CipherSuite(cipher));
}
let (gained, lost) = set_change(
before
.map(Security::alpn)
.unwrap_or_default()
.iter()
.map(|p| p.to_string()),
after
.map(Security::alpn)
.unwrap_or_default()
.iter()
.map(|p| p.to_string()),
);
if !gained.is_empty() || !lost.is_empty() {
changes.push(SecurityChange::Alpn { gained, lost });
}
changes.extend(
certificate_changes(before, after, clocks)
.into_iter()
.map(SecurityChange::Certificate),
);
changes
}
fn certificate_changes(
before: Option<&Security>,
after: Option<&Security>,
clocks: &Clocks,
) -> Vec<CertificateChange> {
let before_cert = before.and_then(Security::certificate);
let after_cert = after.and_then(Security::certificate);
let mut changes = Vec::new();
match (before_cert, after_cert) {
(None, None) => return changes,
(None, Some(after)) => changes.push(CertificateChange::Presented(after.clone())),
(Some(before), None) => {
changes.push(CertificateChange::Withdrawn(before.clone()));
return changes;
}
(Some(before), Some(after)) => {
if before.fingerprint_sha256() != after.fingerprint_sha256() {
changes.push(CertificateChange::Rotated {
before: Box::new(before.clone()),
after: Box::new(after.clone()),
});
}
}
}
let was = validity(before, clocks.expiry_threshold, clocks.baseline);
let is = validity(after, clocks.expiry_threshold, clocks.current);
if let Some(certificate) = after_cert {
match is {
Validity::Expiring if was != Validity::Expiring => {
let remaining = certificate
.validity_end()
.duration_since(clocks.current)
.unwrap_or_default();
changes.push(CertificateChange::Expiring {
certificate: Box::new(certificate.clone()),
remaining,
});
}
Validity::Expired if was != Validity::Expired => {
let since = clocks
.current
.duration_since(certificate.validity_end())
.unwrap_or_default();
changes.push(CertificateChange::Expired {
certificate: Box::new(certificate.clone()),
since,
});
}
_ => {}
}
}
changes
}
fn validity(security: Option<&Security>, threshold: Duration, at: SystemTime) -> Validity {
let Some(security) = security else {
return Validity::Absent;
};
let Some(certificate) = security.certificate() else {
return Validity::Absent;
};
if at < certificate.validity_start() {
Validity::NotYetValid
} else if at > certificate.validity_end() {
Validity::Expired
} else if security.is_cert_expiring_at(threshold, at) {
Validity::Expiring
} else {
Validity::Valid
}
}
fn optional(before: Option<&str>, after: Option<&str>) -> Option<Change<Option<String>>> {
Change::between(before.map(str::to_owned), after.map(str::to_owned))
}
fn set_change(
before: impl Iterator<Item = String>,
after: impl Iterator<Item = String>,
) -> (Vec<String>, Vec<String>) {
let before: std::collections::BTreeSet<String> = before.collect();
let after: std::collections::BTreeSet<String> = after.collect();
let gained = after.difference(&before).cloned().collect();
let lost = before.difference(&after).cloned().collect();
(gained, lost)
}