pub mod diff;
pub mod redact;
pub mod schema;
#[cfg(any(
feature = "export-json",
feature = "export-jsonl",
feature = "export-html"
))]
pub(crate) mod write;
#[cfg(feature = "export-json")]
pub mod json;
#[cfg(feature = "export-jsonl")]
pub mod jsonl;
#[cfg(feature = "export-csv")]
pub mod csv;
#[cfg(feature = "export-html")]
pub mod html;
#[cfg(feature = "export-nmap")]
pub mod nmap;
#[cfg(test)]
pub(crate) mod fixture;
#[cfg(all(test, feature = "export-json"))]
mod conformance;
use std::borrow::Cow;
use std::fmt;
use std::io::Write;
use std::path::Path;
use crate::diff::HostDelta;
use crate::model::host::{Host, HostName};
use crate::model::mac::MacAddr;
use crate::report::ScanReport;
#[cfg(feature = "export-json")]
pub use json::JsonExporter;
#[cfg(feature = "export-jsonl")]
pub use jsonl::JsonLinesExporter;
#[cfg(feature = "export-csv")]
pub use csv::CsvExporter;
#[cfg(feature = "export-html")]
pub use html::HtmlExporter;
#[cfg(feature = "export-nmap")]
pub use nmap::NmapXmlExporter;
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum ExportError {
#[error("writing the report failed: {0}")]
Io(#[from] std::io::Error),
#[error("rendering the report as {format} failed: {message}")]
Render {
format: &'static str,
message: String,
},
}
pub trait Exporter {
fn export(&self, report: &ScanReport, out: &mut dyn Write) -> Result<(), ExportError>;
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum Redaction {
#[default]
None,
Standard,
}
impl Redaction {
pub fn hostname<'a>(self, name: &'a str) -> Cow<'a, str> {
match self {
Redaction::None => Cow::Borrowed(name),
Redaction::Standard => Cow::Owned(redact::hostname(name)),
}
}
pub fn mac(self, mac: &MacAddr) -> String {
match self {
Redaction::None => mac.to_string(),
Redaction::Standard => redact::mac_addr(mac),
}
}
pub fn is_active(self) -> bool {
!matches!(self, Redaction::None)
}
pub fn for_host(self, host: &Host) -> HostRedaction {
self.for_hosts([host])
}
pub fn for_delta(self, delta: &HostDelta) -> HostRedaction {
self.for_hosts(delta.baseline().into_iter().chain(delta.current()))
}
fn for_hosts<'h>(self, hosts: impl IntoIterator<Item = &'h Host>) -> HostRedaction {
HostRedaction {
redaction: self,
needles: if self.is_active() {
redact::Needle::for_names(hosts.into_iter().flat_map(host_names))
} else {
Vec::new()
},
}
}
}
#[derive(Debug, Clone, Default)]
pub struct HostRedaction {
redaction: Redaction,
needles: Vec<redact::Needle>,
}
impl HostRedaction {
pub fn redaction(&self) -> Redaction {
self.redaction
}
pub fn text<'a>(&self, text: &'a str) -> Cow<'a, str> {
redact::names_in(text, &self.needles)
}
pub fn excerpt<'a>(&self, excerpt: &'a str) -> Cow<'a, str> {
if self.redaction.is_active() && redact::is_binary(excerpt) {
Cow::Borrowed(redact::WITHHELD_EXCERPT)
} else {
self.text(excerpt)
}
}
}
fn host_names(host: &Host) -> impl Iterator<Item = &str> {
host.hostname()
.into_iter()
.chain(host.names().map(HostName::name))
.chain(host.set_aside_names())
}
#[must_use]
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct ExportOptions {
pub redaction: Redaction,
}
impl ExportOptions {
pub fn new() -> Self {
Self::default()
}
pub fn with_redaction(mut self, redaction: Redaction) -> Self {
self.redaction = redaction;
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ExportFormat {
#[cfg(feature = "export-json")]
Json,
#[cfg(feature = "export-jsonl")]
JsonLines,
#[cfg(feature = "export-csv")]
Csv,
#[cfg(feature = "export-html")]
Html,
#[cfg(feature = "export-nmap")]
NmapXml,
}
impl ExportFormat {
pub fn from_extension(extension: &str) -> Option<Self> {
match extension.to_ascii_lowercase().as_str() {
#[cfg(feature = "export-json")]
"json" => Some(ExportFormat::Json),
#[cfg(feature = "export-jsonl")]
"jsonl" | "ndjson" => Some(ExportFormat::JsonLines),
#[cfg(feature = "export-csv")]
"csv" => Some(ExportFormat::Csv),
#[cfg(feature = "export-html")]
"html" | "htm" => Some(ExportFormat::Html),
#[cfg(feature = "export-nmap")]
"xml" => Some(ExportFormat::NmapXml),
_ => None,
}
}
pub fn from_path(path: &Path) -> Option<Self> {
path.extension()
.and_then(|extension| extension.to_str())
.and_then(Self::from_extension)
}
pub fn extension(self) -> &'static str {
match self {
#[cfg(feature = "export-json")]
ExportFormat::Json => "json",
#[cfg(feature = "export-jsonl")]
ExportFormat::JsonLines => "jsonl",
#[cfg(feature = "export-csv")]
ExportFormat::Csv => "csv",
#[cfg(feature = "export-html")]
ExportFormat::Html => "html",
#[cfg(feature = "export-nmap")]
ExportFormat::NmapXml => "xml",
}
}
pub fn all() -> &'static [ExportFormat] {
&[
#[cfg(feature = "export-json")]
ExportFormat::Json,
#[cfg(feature = "export-jsonl")]
ExportFormat::JsonLines,
#[cfg(feature = "export-csv")]
ExportFormat::Csv,
#[cfg(feature = "export-html")]
ExportFormat::Html,
#[cfg(feature = "export-nmap")]
ExportFormat::NmapXml,
]
}
pub fn exporter(self, options: ExportOptions) -> Box<dyn Exporter> {
let _ = &options;
match self {
#[cfg(feature = "export-json")]
ExportFormat::Json => Box::new(JsonExporter::new(options)),
#[cfg(feature = "export-jsonl")]
ExportFormat::JsonLines => Box::new(JsonLinesExporter::new(options)),
#[cfg(feature = "export-csv")]
ExportFormat::Csv => Box::new(CsvExporter::new(options)),
#[cfg(feature = "export-html")]
ExportFormat::Html => Box::new(HtmlExporter::new(options)),
#[cfg(feature = "export-nmap")]
ExportFormat::NmapXml => Box::new(NmapXmlExporter::new(options)),
}
}
}
impl fmt::Display for ExportFormat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.extension())
}
}
pub fn export_to(
path: &Path,
report: &ScanReport,
out: &mut dyn Write,
options: ExportOptions,
) -> Option<Result<(), ExportError>> {
let format = ExportFormat::from_path(path)?;
Some(format.exporter(options).export(report, out))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn no_redaction_borrows_rather_than_copying() {
let borrowed = Redaction::None.hostname("workstation");
assert!(matches!(borrowed, Cow::Borrowed(_)));
assert_eq!(borrowed, "workstation");
assert!(!Redaction::None.is_active());
}
#[test]
fn standard_redaction_masks_but_keeps_records_apart() {
let workstation = Redaction::Standard.hostname("workstation");
let printer = Redaction::Standard.hostname("wifi-printer");
assert_eq!(workstation, "woXXXXXon");
assert_ne!(workstation, printer);
assert!(Redaction::Standard.is_active());
}
#[test]
fn standard_redaction_keeps_the_oui_and_drops_the_device() {
let mac = MacAddr::new(0x2c, 0xcf, 0x67, 0x00, 0x00, 0x01);
assert_eq!(Redaction::None.mac(&mac), "2c:cf:67:00:00:01");
assert_eq!(Redaction::Standard.mac(&mac), "2c:cf:67:XX:XX:XX");
}
#[test]
fn a_folded_record_masks_the_names_its_fold_did_not_keep() {
use crate::model::host::{NameKind, NameSource};
let address = "192.0.2.10".parse().expect("an address");
let mut kept = Host::new(address);
kept.set_hostname(Some("files.example".to_owned()));
let invented = |n: usize| {
HostName::new(NameKind::Host, NameSource::Ntlm, &format!("peer{n:03}")).expect("a name")
};
let mut n = 0;
while kept.record_name(invented(n)) {
n += 1;
}
let mut folded = Host::new(address);
folded.set_hostname(Some("archive.example".to_owned()));
folded.record_name(
HostName::new(NameKind::NetbiosHost, NameSource::Netbios, "VAULT").expect("a name"),
);
kept.merge(folded);
assert_eq!(kept.hostname(), Some("files.example"));
assert!(kept.names().all(|name| name.name() != "VAULT"));
let masked = Redaction::Standard
.for_host(&kept)
.text("archive.example is VAULT")
.to_lowercase();
assert!(
!masked.contains("archive") && !masked.contains("vault"),
"{masked}"
);
assert_eq!(
Redaction::None.for_host(&kept).text("VAULT"),
"VAULT",
"nothing is masked without a policy"
);
}
#[test]
fn a_format_is_resolved_from_a_path_case_insensitively() {
#[cfg(feature = "export-json")]
{
assert_eq!(
ExportFormat::from_path(Path::new("/tmp/scan.JSON")),
Some(ExportFormat::Json)
);
assert_eq!(ExportFormat::Json.extension(), "json");
assert_eq!(ExportFormat::Json.to_string(), "json");
}
assert_eq!(ExportFormat::from_path(Path::new("/tmp/scan")), None);
assert_eq!(ExportFormat::from_extension("pdf"), None);
}
#[test]
fn every_advertised_format_can_build_an_exporter() {
let report = super::fixture::report();
for format in ExportFormat::all() {
let mut sink = Vec::new();
format
.exporter(ExportOptions::new())
.export(&report, &mut sink)
.expect("an advertised format exports");
assert!(!sink.is_empty(), "{format} produced nothing at all");
assert_eq!(
ExportFormat::from_extension(format.extension()),
Some(*format),
"{format} does not resolve from its own extension"
);
}
}
#[test]
fn exporting_by_path_matches_exporting_by_format() {
let report = super::fixture::report();
for format in ExportFormat::all() {
let name = format!("scan.{}", format.extension());
let mut by_path = Vec::new();
export_to(
Path::new(&name),
&report,
&mut by_path,
ExportOptions::new(),
)
.expect("the extension names a format")
.expect("the export succeeds");
assert!(!by_path.is_empty());
}
let mut sink = Vec::new();
assert!(
export_to(
Path::new("scan.pdf"),
&report,
&mut sink,
ExportOptions::new()
)
.is_none(),
"an unsupported extension must not quietly produce a file"
);
assert!(sink.is_empty());
}
}