use serde::Serialize;
use serde::ser::{SerializeSeq, Serializer};
use crate::diff::host::Reassessment;
use crate::diff::{
CertificateChange, Confirmed, Coverage, DiffSummary, HostChange, HostDelta, PortChange,
PortDelta, Presence, ScanDiff, SecurityChange, ServiceChange, Significance,
};
use crate::export::ExportOptions;
use crate::export::schema::{EngineDto, HostDto};
use crate::format::time::rfc3339;
use crate::model::finding::Finding;
use crate::model::host::os::OsFingerprint;
use crate::model::host::{IpProtocolState, ip_protocol_name};
use crate::record::wire::{
host_status_name, ip_protocol_state_name, port_state_name, protocol_name, scan_kind_name,
};
pub use crate::format::{DIFF_SCHEMA_VERSION, ENGINE_NAME};
pub fn presence_name(presence: Presence) -> &'static str {
match presence {
Presence::Both => "both",
Presence::Added { .. } => "added",
Presence::Removed { .. } => "removed",
}
}
pub fn coverage_name(coverage: Coverage) -> &'static str {
match coverage {
Coverage::Covered => "covered",
Coverage::Withheld => "withheld",
Coverage::OutOfScope => "out_of_scope",
Coverage::Unreached => "unreached",
Coverage::Unstated => "unstated",
}
}
pub fn significance_name(significance: Significance) -> &'static str {
match significance {
Significance::Routine => "routine",
Significance::Notable => "notable",
Significance::Urgent => "urgent",
}
}
#[non_exhaustive]
#[derive(Debug, Serialize)]
pub struct DiffDto<'a> {
pub schema_version: u32,
pub engine: EngineDto,
pub generated_at: String,
pub baseline: ProvenanceDto,
pub current: ProvenanceDto,
pub unchanged: bool,
pub significance: &'static str,
pub summary: SummaryDto,
pub hosts: HostDeltasDto<'a>,
}
#[non_exhaustive]
#[derive(Debug)]
pub struct HostDeltasDto<'a> {
deltas: &'a [HostDelta],
options: &'a ExportOptions,
}
impl<'a> HostDeltasDto<'a> {
pub fn deltas(&self) -> &'a [HostDelta] {
self.deltas
}
pub fn len(&self) -> usize {
self.deltas.len()
}
pub fn is_empty(&self) -> bool {
self.deltas.is_empty()
}
}
impl Serialize for HostDeltasDto<'_> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut seq = serializer.serialize_seq(Some(self.deltas.len()))?;
for delta in self.deltas {
seq.serialize_element(&HostDeltaDto::new(delta, self.options))?;
}
seq.end()
}
}
impl<'a> DiffDto<'a> {
pub fn new(diff: &'a ScanDiff, options: &'a ExportOptions) -> Self {
Self {
schema_version: DIFF_SCHEMA_VERSION,
engine: EngineDto {
name: ENGINE_NAME,
version: crate::report::ENGINE_VERSION,
},
generated_at: rfc3339(std::time::SystemTime::now()),
baseline: ProvenanceDto::new(diff.baseline()),
current: ProvenanceDto::new(diff.current()),
unchanged: diff.is_empty(),
significance: significance_name(diff.significance()),
summary: SummaryDto::new(&diff.summary()),
hosts: HostDeltasDto {
deltas: diff.hosts(),
options,
},
}
}
}
#[non_exhaustive]
#[derive(Debug, Serialize)]
pub struct ProvenanceDto {
pub engine_version: String,
pub at: String,
pub hosts: usize,
pub kinds: Vec<&'static str>,
pub states_scope: bool,
}
impl ProvenanceDto {
pub fn new(provenance: &crate::diff::Provenance) -> Self {
Self {
engine_version: provenance.engine_version().to_owned(),
at: rfc3339(provenance.at()),
hosts: provenance.hosts(),
kinds: provenance
.kinds()
.iter()
.copied()
.map(scan_kind_name)
.collect(),
states_scope: provenance.states_scope(),
}
}
}
#[non_exhaustive]
#[derive(Debug, Serialize)]
pub struct ConfirmedDto {
pub total: usize,
pub confirmed: usize,
}
impl ConfirmedDto {
pub fn new(count: Confirmed) -> Self {
Self {
total: count.total,
confirmed: count.confirmed,
}
}
}
#[non_exhaustive]
#[derive(Debug, Serialize)]
pub struct SummaryDto {
pub hosts_added: ConfirmedDto,
pub hosts_removed: ConfirmedDto,
pub hosts_changed: usize,
pub ports_opened: ConfirmedDto,
pub ports_closed: ConfirmedDto,
pub ports_changed: usize,
pub services_changed: usize,
pub certificates_rotated: usize,
pub certificates_expiring: usize,
pub certificates_expired: usize,
}
impl SummaryDto {
pub fn new(summary: &DiffSummary) -> Self {
Self {
hosts_added: ConfirmedDto::new(summary.hosts_added),
hosts_removed: ConfirmedDto::new(summary.hosts_removed),
hosts_changed: summary.hosts_changed,
ports_opened: ConfirmedDto::new(summary.ports_opened),
ports_closed: ConfirmedDto::new(summary.ports_closed),
ports_changed: summary.ports_changed,
services_changed: summary.services_changed,
certificates_rotated: summary.certificates_rotated,
certificates_expiring: summary.certificates_expiring,
certificates_expired: summary.certificates_expired,
}
}
}
#[non_exhaustive]
#[derive(Debug, Serialize)]
pub struct HostDeltaDto<'a> {
pub address: String,
pub presence: &'static str,
pub coverage: Option<&'static str>,
pub confirmed: bool,
pub significance: &'static str,
pub records: RecordsDto,
pub regrouped: bool,
pub changes: Vec<ChangeDto>,
pub ports: Vec<PortDeltaDto>,
pub baseline: Option<HostDto<'a>>,
pub current: Option<HostDto<'a>>,
}
impl<'a> HostDeltaDto<'a> {
pub fn new(delta: &'a HostDelta, options: &ExportOptions) -> Self {
let (baseline_records, current_records) = delta.records();
Self {
address: delta.address().to_string(),
presence: presence_name(delta.presence()),
coverage: delta.presence().counterpart_coverage().map(coverage_name),
confirmed: delta.presence().is_confirmed(),
significance: significance_name(delta.significance()),
records: RecordsDto {
baseline: baseline_records,
current: current_records,
},
regrouped: delta.is_regrouped(),
changes: delta
.changes()
.iter()
.flat_map(|change| ChangeDto::of_host(change, options))
.collect(),
ports: delta
.ports()
.iter()
.map(|port| PortDeltaDto::new(port, options))
.collect(),
baseline: delta.baseline().map(|host| HostDto::new(host, options)),
current: delta.current().map(|host| HostDto::new(host, options)),
}
}
}
#[non_exhaustive]
#[derive(Debug, Serialize)]
pub struct RecordsDto {
pub baseline: usize,
pub current: usize,
}
#[non_exhaustive]
#[derive(Debug, Serialize)]
pub struct PortDeltaDto {
pub port: u16,
pub protocol: &'static str,
pub presence: &'static str,
pub coverage: Option<&'static str>,
pub confirmed: bool,
pub significance: &'static str,
pub opened: bool,
pub closed: bool,
pub changes: Vec<ChangeDto>,
}
impl PortDeltaDto {
pub fn new(delta: &PortDelta, options: &ExportOptions) -> Self {
Self {
port: delta.number(),
protocol: protocol_name(delta.protocol()),
presence: presence_name(delta.presence()),
coverage: delta.presence().counterpart_coverage().map(coverage_name),
confirmed: delta.presence().is_confirmed(),
significance: significance_name(delta.significance()),
opened: delta.is_opened(),
closed: delta.is_closed(),
changes: delta
.changes()
.iter()
.flat_map(|change| ChangeDto::of_port(change, options))
.collect(),
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ChangeDto {
pub kind: &'static str,
pub before: Option<String>,
pub after: Option<String>,
}
impl ChangeDto {
fn between(kind: &'static str, before: impl Into<String>, after: impl Into<String>) -> Self {
Self {
kind,
before: Some(before.into()),
after: Some(after.into()),
}
}
fn gained(kind: &'static str, after: impl Into<String>) -> Self {
Self {
kind,
before: None,
after: Some(after.into()),
}
}
fn lost(kind: &'static str, before: impl Into<String>) -> Self {
Self {
kind,
before: Some(before.into()),
after: None,
}
}
fn optional(kind: &'static str, before: Option<&str>, after: Option<&str>) -> Vec<Self> {
match (before, after) {
(None, None) => Vec::new(),
(None, Some(after)) => vec![Self::gained(kind, after)],
(Some(before), None) => vec![Self::lost(kind, before)],
(Some(before), Some(after)) => vec![Self::between(kind, before, after)],
}
}
fn set<T: ToString>(
gained_kind: &'static str,
lost_kind: &'static str,
gained: &[T],
lost: &[T],
) -> Vec<Self> {
gained
.iter()
.map(|value| Self::gained(gained_kind, value.to_string()))
.chain(
lost.iter()
.map(|value| Self::lost(lost_kind, value.to_string())),
)
.collect()
}
pub fn of_host(change: &HostChange, options: &ExportOptions) -> Vec<Self> {
let redaction = options.redaction;
match change {
HostChange::Status(status) => vec![Self::between(
"status",
host_status_name(status.before),
host_status_name(status.after),
)],
HostChange::Hostname(name) => Self::optional(
"hostname",
name.before
.as_deref()
.map(|n| redaction.hostname(n))
.as_deref(),
name.after
.as_deref()
.map(|n| redaction.hostname(n))
.as_deref(),
),
HostChange::Addresses { gained, lost } => {
Self::set("address_gained", "address_lost", gained, lost)
}
HostChange::Os(os) => Self::optional(
"os",
os.before.as_ref().map(identify).as_deref(),
os.after.as_ref().map(identify).as_deref(),
),
HostChange::Macs { gained, lost } => {
let gained: Vec<String> = gained.iter().map(|mac| redaction.mac(mac)).collect();
let lost: Vec<String> = lost.iter().map(|mac| redaction.mac(mac)).collect();
Self::set("mac_gained", "mac_lost", &gained, &lost)
}
HostChange::Vendor(vendor) => {
Self::optional("vendor", vendor.before.as_deref(), vendor.after.as_deref())
}
HostChange::Roles { gained, lost } => {
let name = crate::record::wire::network_role_name;
let gained: Vec<&'static str> = gained.iter().copied().map(name).collect();
let lost: Vec<&'static str> = lost.iter().copied().map(name).collect();
Self::set("role_gained", "role_lost", &gained, &lost)
}
HostChange::Filtering { gained, lost } => {
let name = crate::record::wire::filtering_name;
let gained: Vec<&'static str> = gained.iter().copied().map(name).collect();
let lost: Vec<&'static str> = lost.iter().copied().map(name).collect();
Self::set("filtering_gained", "filtering_lost", &gained, &lost)
}
HostChange::IpProtocols { changed } => changed
.iter()
.map(|moved| {
Self::between(
"ip_protocol",
Self::describe_ip_protocol(moved.protocol, moved.state.before),
Self::describe_ip_protocol(moved.protocol, moved.state.after),
)
})
.collect(),
HostChange::Findings {
appeared,
resolved,
reassessed,
} => Self::findings(appeared, resolved, reassessed),
}
}
fn describe_ip_protocol(number: u8, state: IpProtocolState) -> String {
let verdict = ip_protocol_state_name(state);
match ip_protocol_name(number) {
Some(name) => format!("{number} {name}: {verdict}"),
None => format!("{number}: {verdict}"),
}
}
fn findings(
appeared: &[Finding],
resolved: &[Finding],
reassessed: &[Reassessment],
) -> Vec<Self> {
let name = crate::record::wire::severity_name;
let describe =
|finding: &Finding| format!("{}: {}", name(finding.severity()), finding.title());
let gained: Vec<String> = appeared.iter().map(describe).collect();
let lost: Vec<String> = resolved.iter().map(describe).collect();
let mut entries = Self::set("finding_appeared", "finding_resolved", &gained, &lost);
entries.extend(reassessed.iter().map(|shift| {
Self::between(
"finding_reassessed",
format!("{}: {}", name(shift.severity.before), shift.finding.title()),
format!("{}: {}", name(shift.severity.after), shift.finding.title()),
)
}));
entries
}
pub fn of_port(change: &PortChange, _options: &ExportOptions) -> Vec<Self> {
match change {
PortChange::State(state) => vec![Self::between(
"port_state",
port_state_name(state.before),
port_state_name(state.after),
)],
PortChange::Service(service) => Self::of_service(service),
PortChange::Security(security) => Self::of_security(security),
PortChange::Findings {
appeared,
resolved,
reassessed,
} => Self::findings(appeared, resolved, reassessed),
}
}
fn of_service(change: &ServiceChange) -> Vec<Self> {
match change {
ServiceChange::Identified(service) => {
vec![Self::gained("service_identified", describe(service))]
}
ServiceChange::Unidentified(service) => {
vec![Self::lost("service_lost", describe(service))]
}
ServiceChange::Name(name) => {
vec![Self::between("service_name", &name.before, &name.after)]
}
ServiceChange::Product(value) => Self::optional(
"service_product",
value.before.as_deref(),
value.after.as_deref(),
),
ServiceChange::Vendor(value) => Self::optional(
"service_vendor",
value.before.as_deref(),
value.after.as_deref(),
),
ServiceChange::Version(value) => Self::optional(
"service_version",
value.before.as_deref(),
value.after.as_deref(),
),
ServiceChange::ExtraInfo(value) => Self::optional(
"service_extrainfo",
value.before.as_deref(),
value.after.as_deref(),
),
ServiceChange::Cpes { gained, lost } => {
Self::set("cpe_gained", "cpe_lost", gained, lost)
}
}
}
fn of_security(change: &SecurityChange) -> Vec<Self> {
match change {
SecurityChange::TlsVersion(value) => Self::optional(
"tls_version",
value.before.as_deref(),
value.after.as_deref(),
),
SecurityChange::CipherSuite(value) => Self::optional(
"cipher_suite",
value.before.as_deref(),
value.after.as_deref(),
),
SecurityChange::Alpn { gained, lost } => {
Self::set("alpn_gained", "alpn_lost", gained, lost)
}
SecurityChange::Certificate(certificate) => Self::of_certificate(certificate),
}
}
fn of_certificate(change: &CertificateChange) -> Vec<Self> {
match change {
CertificateChange::Presented(certificate) => vec![Self::gained(
"certificate_presented",
certificate.fingerprint_sha256(),
)],
CertificateChange::Withdrawn(certificate) => vec![Self::lost(
"certificate_withdrawn",
certificate.fingerprint_sha256(),
)],
CertificateChange::Rotated { before, after } => vec![Self::between(
"certificate_rotated",
before.fingerprint_sha256(),
after.fingerprint_sha256(),
)],
CertificateChange::Expiring { certificate, .. } => vec![Self::gained(
"certificate_expiring",
rfc3339(certificate.validity_end()),
)],
CertificateChange::Expired { certificate, .. } => vec![Self::gained(
"certificate_expired",
rfc3339(certificate.validity_end()),
)],
}
}
}
fn identify(os: &OsFingerprint) -> String {
match os.generation() {
Some(generation)
if !os.name().contains(generation)
&& !os.name().contains(|c: char| c.is_ascii_digit()) =>
{
format!("{} {generation}", os.name())
}
_ => os.name().to_owned(),
}
}
fn describe(service: &crate::model::port::Service) -> String {
let mut described = service.name().to_owned();
if let Some(product) = service
.product()
.filter(|p| !p.eq_ignore_ascii_case(&described))
{
described.push(' ');
described.push_str(product);
}
if let Some(version) = service.version() {
described.push(' ');
described.push_str(version);
}
described
}