use std::borrow::Cow;
use std::net::IpAddr;
use std::time::{Duration, SystemTime};
use serde::Serialize;
use serde::ser::{SerializeSeq, Serializer};
use crate::config::SendMode;
use crate::config::{RetryConfig, ScanEffort};
use crate::export::ExportOptions;
use crate::export::time::rfc3339;
use crate::model::capture::CaptureCounts;
use crate::model::host::{
HardwareInfo, Host, HostStatus, HostTelemetry, NetworkRole, OsFingerprint, StatusProtocol,
StatusReason,
};
use crate::model::ip::range::IpRange;
use crate::model::port::{
CertificateInfo, Discovery, Port, PortState, Protocol, ScanResponse, Security, Service,
};
use crate::scanner::report::{
ATTEMPTS_COUNTED, BUCKET_BOUNDS_MS, ProbeStats, ScanKind, ScanPhase, ScanReport, ScanSettings,
ScanSummary, ScannerFailure, StopReason, TargetScope,
};
use crate::scanner::session::ScannerKind;
pub use crate::format::{ENGINE_NAME, SCHEMA_VERSION};
pub fn scan_kind_name(kind: ScanKind) -> &'static str {
match kind {
ScanKind::Discovery => "discovery",
ScanKind::PortScan => "port_scan",
}
}
pub fn scanner_kind_name(kind: ScannerKind) -> &'static str {
match kind {
ScannerKind::Local => "local",
ScannerKind::Routed => "routed",
ScannerKind::SynPort => "syn_port",
ScannerKind::TcpPort => "tcp_port",
ScannerKind::Connect => "connect",
ScannerKind::ConnectUdp => "connect_udp",
ScannerKind::UdpPort => "udp_port",
ScannerKind::OsEcho => "os_echo",
ScannerKind::Composite => "composite",
}
}
pub fn host_status_name(status: HostStatus) -> &'static str {
match status {
HostStatus::Unknown => "unknown",
HostStatus::Down => "down",
HostStatus::Filtered => "filtered",
HostStatus::Up => "up",
}
}
pub fn port_state_name(state: PortState) -> &'static str {
match state {
PortState::ClosedFiltered => "closed_filtered",
PortState::Filtered => "filtered",
PortState::Unfiltered => "unfiltered",
PortState::Closed => "closed",
PortState::OpenFiltered => "open_filtered",
PortState::Open => "open",
}
}
pub fn protocol_name(protocol: Protocol) -> &'static str {
match protocol {
Protocol::Tcp => "tcp",
Protocol::Udp => "udp",
}
}
pub fn network_role_name(role: NetworkRole) -> &'static str {
match role {
NetworkRole::Tarpit => "tarpit",
}
}
pub fn stop_reason_name(reason: StopReason) -> &'static str {
match reason {
StopReason::Aborted => "aborted",
StopReason::AllResponded => "all_responded",
StopReason::AttemptsSpent => "attempts_spent",
StopReason::DeadlineExpired => "deadline_expired",
StopReason::StreamClosed => "stream_closed",
}
}
pub fn send_mode_name(mode: SendMode) -> &'static str {
match mode {
SendMode::Auto => "auto",
SendMode::RawSocket => "raw_socket",
SendMode::Ethernet => "ethernet",
}
}
pub fn scan_effort_name(effort: ScanEffort) -> &'static str {
match effort {
ScanEffort::Single => "single",
ScanEffort::Fast => "fast",
ScanEffort::Balanced => "balanced",
ScanEffort::Thorough => "thorough",
}
}
pub fn status_protocol_name(protocol: &StatusProtocol) -> Cow<'_, str> {
match protocol {
StatusProtocol::Arp => Cow::Borrowed("arp"),
StatusProtocol::Ndp => Cow::Borrowed("ndp"),
StatusProtocol::IcmpEcho => Cow::Borrowed("icmp_echo"),
StatusProtocol::IcmpUnreachable => Cow::Borrowed("icmp_unreachable"),
StatusProtocol::TcpSyn => Cow::Borrowed("tcp_syn"),
StatusProtocol::Tcp => Cow::Borrowed("tcp"),
StatusProtocol::Udp => Cow::Borrowed("udp"),
StatusProtocol::Custom(name) => Cow::Owned(format!("custom:{name}")),
}
}
pub fn scan_response_name(response: &ScanResponse) -> Cow<'_, str> {
match response {
ScanResponse::TcpSynAck => Cow::Borrowed("tcp_syn_ack"),
ScanResponse::TcpRst => Cow::Borrowed("tcp_rst"),
ScanResponse::UdpResponse => Cow::Borrowed("udp_response"),
ScanResponse::NoResponse => Cow::Borrowed("no_response"),
ScanResponse::IcmpUnreachable => Cow::Borrowed("icmp_unreachable"),
ScanResponse::IcmpProhibited => Cow::Borrowed("icmp_prohibited"),
ScanResponse::Custom(name) => Cow::Owned(format!("custom:{name}")),
}
}
fn micros(duration: Duration) -> u64 {
u64::try_from(duration.as_micros()).unwrap_or(u64::MAX)
}
fn micros_opt(duration: Option<Duration>) -> Option<u64> {
duration.map(micros)
}
#[derive(Debug)]
pub struct ReportDto<'a> {
report: &'a ScanReport,
options: &'a ExportOptions,
generated_at: SystemTime,
}
impl<'a> ReportDto<'a> {
pub fn new(report: &'a ScanReport, options: &'a ExportOptions) -> Self {
Self::generated_at(report, options, SystemTime::now())
}
pub fn generated_at(
report: &'a ScanReport,
options: &'a ExportOptions,
generated_at: SystemTime,
) -> Self {
Self {
report,
options,
generated_at,
}
}
pub fn report(&self) -> &'a ScanReport {
self.report
}
pub fn options(&self) -> &'a ExportOptions {
self.options
}
}
impl Serialize for ReportDto<'_> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut doc = serializer.serialize_struct("Report", HEADER_FIELDS + 1)?;
write_header(&mut doc, self.report, self.generated_at)?;
doc.serialize_field(
"hosts",
&HostsDto {
report: self.report,
options: self.options,
},
)?;
doc.end()
}
}
#[derive(Debug)]
pub struct ReportHeaderDto<'a> {
report: &'a ScanReport,
generated_at: SystemTime,
}
impl<'a> ReportHeaderDto<'a> {
pub fn new(report: &'a ScanReport) -> Self {
Self::generated_at(report, SystemTime::now())
}
pub fn generated_at(report: &'a ScanReport, generated_at: SystemTime) -> Self {
Self {
report,
generated_at,
}
}
}
impl Serialize for ReportHeaderDto<'_> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut doc = serializer.serialize_struct("ReportHeader", HEADER_FIELDS)?;
write_header(&mut doc, self.report, self.generated_at)?;
doc.end()
}
}
pub fn total_elapsed_us(phases: &[PhaseDto<'_>]) -> u64 {
phases
.iter()
.fold(0u64, |total, phase| total.saturating_add(phase.elapsed_us))
}
const HEADER_FIELDS: usize = 8;
fn write_header<S: serde::ser::SerializeStruct>(
doc: &mut S,
report: &ScanReport,
generated_at: SystemTime,
) -> Result<(), S::Error> {
let phases: Vec<PhaseDto<'_>> = report.phases().iter().map(PhaseDto::new).collect();
let elapsed_us = total_elapsed_us(&phases);
doc.serialize_field("schema_version", &SCHEMA_VERSION)?;
doc.serialize_field(
"engine",
&EngineDto {
name: ENGINE_NAME,
version: report.engine_version(),
},
)?;
doc.serialize_field("generated_at", &rfc3339(generated_at))?;
doc.serialize_field("started_at", &rfc3339(report.started_at()))?;
doc.serialize_field("elapsed_us", &elapsed_us)?;
doc.serialize_field("partial", &report.is_partial())?;
doc.serialize_field("summary", &SummaryDto::new(&report.summary()))?;
doc.serialize_field("phases", &phases)?;
Ok(())
}
struct HostsDto<'a> {
report: &'a ScanReport,
options: &'a ExportOptions,
}
impl Serialize for HostsDto<'_> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut seq = serializer.serialize_seq(Some(self.report.host_count()))?;
for host in self.report.hosts() {
seq.serialize_element(&HostDto::new(host, self.options))?;
}
seq.end()
}
}
#[derive(Debug, Clone, Serialize)]
pub struct EngineDto {
pub name: &'static str,
pub version: &'static str,
}
#[derive(Debug, Clone, Serialize)]
pub struct SummaryDto {
pub hosts_total: usize,
pub hosts_alive: usize,
pub hosts_by_status: HostStatusCounts,
pub ports_total: usize,
pub ports_open: usize,
pub ports_by_state: PortStateCounts,
pub services_identified: usize,
pub hosts_by_family: FamilyCounts,
}
#[derive(Debug, Clone, Copy, Serialize)]
pub struct FamilyCounts {
pub ipv4: usize,
pub ipv6: usize,
pub dual_stack: usize,
}
impl SummaryDto {
pub fn new(summary: &ScanSummary) -> Self {
let status = |status: HostStatus| {
summary
.hosts_by_status
.get(&status)
.copied()
.unwrap_or_default()
};
let state = |state: PortState| {
summary
.ports_by_state
.get(&state)
.copied()
.unwrap_or_default()
};
Self {
hosts_total: summary.hosts_total,
hosts_alive: summary.hosts_alive,
hosts_by_status: HostStatusCounts {
up: status(HostStatus::Up),
filtered: status(HostStatus::Filtered),
down: status(HostStatus::Down),
unknown: status(HostStatus::Unknown),
},
ports_total: summary.ports_total,
ports_open: summary.ports_open,
ports_by_state: PortStateCounts {
open: state(PortState::Open),
open_filtered: state(PortState::OpenFiltered),
closed: state(PortState::Closed),
unfiltered: state(PortState::Unfiltered),
filtered: state(PortState::Filtered),
closed_filtered: state(PortState::ClosedFiltered),
},
services_identified: summary.services_identified,
hosts_by_family: FamilyCounts {
ipv4: summary.hosts_by_family.ipv4,
ipv6: summary.hosts_by_family.ipv6,
dual_stack: summary.hosts_by_family.dual_stack,
},
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct HostStatusCounts {
pub up: usize,
pub filtered: usize,
pub down: usize,
pub unknown: usize,
}
#[derive(Debug, Clone, Serialize)]
pub struct PortStateCounts {
pub open: usize,
pub open_filtered: usize,
pub closed: usize,
pub unfiltered: usize,
pub filtered: usize,
pub closed_filtered: usize,
}
#[derive(Debug, Clone, Serialize)]
pub struct PhaseDto<'a> {
pub kind: &'static str,
pub started_at: String,
pub elapsed_us: u64,
pub privileged: bool,
pub targets: ScopeDto,
pub settings: SettingsDto,
pub failures: Vec<FailureDto<'a>>,
pub probe_stats: Vec<ProbeStatsDto>,
}
impl<'a> PhaseDto<'a> {
pub fn new(phase: &'a ScanPhase) -> Self {
Self {
kind: scan_kind_name(phase.kind()),
started_at: rfc3339(phase.started_at()),
elapsed_us: micros(phase.elapsed()),
privileged: phase.privileged(),
targets: ScopeDto::new(phase.targets()),
settings: SettingsDto::new(phase.settings()),
failures: phase.failures().iter().map(FailureDto::new).collect(),
probe_stats: phase.probe_stats().iter().map(ProbeStatsDto::new).collect(),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ScopeDto {
pub ranges: Vec<RangeDto>,
pub addresses: String,
pub probes: Option<String>,
pub protocols: Vec<&'static str>,
}
impl ScopeDto {
pub fn new(scope: &TargetScope) -> Self {
Self {
ranges: scope.ranges().iter().map(RangeDto::new).collect(),
addresses: scope.addresses().to_string(),
probes: scope.probes().map(|count| count.to_string()),
protocols: scope
.protocols()
.iter()
.copied()
.map(protocol_name)
.collect(),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct RangeDto {
pub family: &'static str,
pub start: String,
pub end: String,
}
impl RangeDto {
pub fn new(range: &IpRange) -> Self {
Self {
family: match range {
IpRange::V4(_) => "ipv4",
IpRange::V6(_) => "ipv6",
},
start: range.start_addr().to_string(),
end: range.end_addr().to_string(),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct SettingsDto {
pub send_mode: &'static str,
pub tcp_technique: &'static str,
pub retry: RetryDto,
pub max_probe_rate: Option<u32>,
pub dns_enabled: bool,
pub redact: bool,
pub os_detection: &'static str,
}
impl SettingsDto {
pub fn new(settings: &ScanSettings) -> Self {
Self {
send_mode: send_mode_name(settings.send_mode),
tcp_technique: settings.tcp_technique.name(),
retry: RetryDto::new(&settings.retry),
max_probe_rate: settings.max_probe_rate,
dns_enabled: settings.dns_enabled,
redact: settings.redact,
os_detection: settings.os_detection.name(),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct RetryDto {
pub effort: &'static str,
pub max_attempts: Option<u8>,
pub timeout_scale: Option<f64>,
pub dampen_silent_hosts: bool,
}
impl RetryDto {
pub fn new(retry: &RetryConfig) -> Self {
Self {
effort: scan_effort_name(retry.effort),
max_attempts: retry.max_attempts,
timeout_scale: retry.timeout_scale.filter(|scale| scale.is_finite()),
dampen_silent_hosts: retry.dampen_silent_hosts,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct FailureDto<'a> {
pub scanner: &'static str,
pub reason: &'a str,
pub at: String,
}
impl<'a> FailureDto<'a> {
pub fn new(failure: &'a ScannerFailure) -> Self {
Self {
scanner: scanner_kind_name(failure.scanner()),
reason: failure.reason(),
at: rfc3339(failure.at()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ProbeStatsDto {
pub scanner: &'static str,
pub targets: String,
pub stop_reason: &'static str,
pub complete: bool,
pub elapsed_us: u64,
pub sends_attempted: u64,
pub sends_failed: u64,
pub segments_seen: u64,
pub segments_off_target: u64,
pub replies_without_rtt: u64,
pub hosts_found: u64,
pub answered_on: Vec<AttemptCountDto>,
pub answered_unattributed: u64,
pub first_reply_us: Option<u64>,
pub last_reply_us: Option<u64>,
pub found_at: Vec<BucketDto>,
pub capture: Option<CaptureDto>,
}
impl ProbeStatsDto {
pub fn new(stats: &ProbeStats) -> Self {
let answered_on = stats
.answered_on()
.iter()
.enumerate()
.map(|(index, &count)| AttemptCountDto {
attempt: index as u32 + 1,
or_later: index + 1 == ATTEMPTS_COUNTED,
count,
})
.collect();
let found_at = stats
.found_at()
.iter()
.enumerate()
.map(|(index, &count)| BucketDto {
le_ms: BUCKET_BOUNDS_MS.get(index).copied(),
count,
})
.collect();
Self {
scanner: scanner_kind_name(stats.scanner()),
targets: stats.targets().to_string(),
stop_reason: stop_reason_name(stats.stop_reason()),
complete: stats.stop_reason().is_complete(),
elapsed_us: micros(stats.elapsed()),
sends_attempted: stats.sends_attempted(),
sends_failed: stats.sends_failed(),
segments_seen: stats.segments_seen(),
segments_off_target: stats.segments_off_target(),
replies_without_rtt: stats.replies_without_rtt(),
hosts_found: stats.hosts_found(),
answered_on,
answered_unattributed: stats.answered_unattributed(),
first_reply_us: micros_opt(stats.first_reply()),
last_reply_us: micros_opt(stats.last_reply()),
found_at,
capture: stats.capture().map(CaptureDto::new),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct AttemptCountDto {
pub attempt: u32,
pub or_later: bool,
pub count: u64,
}
#[derive(Debug, Clone, Serialize)]
pub struct BucketDto {
pub le_ms: Option<u64>,
pub count: u64,
}
#[derive(Debug, Clone, Serialize)]
pub struct CaptureDto {
pub received: u64,
pub dropped: u64,
pub if_dropped: u64,
}
impl CaptureDto {
pub fn new(counts: CaptureCounts) -> Self {
Self {
received: counts.received,
dropped: counts.dropped,
if_dropped: counts.if_dropped,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct HostDto<'a> {
pub primary_ip: String,
pub ips: Vec<String>,
pub zone: Option<&'a str>,
pub families: Vec<&'static str>,
pub hostname: Option<Cow<'a, str>>,
pub status: &'static str,
pub alive: bool,
pub reasons: Vec<ReasonDto<'a>>,
pub roles: Vec<&'static str>,
pub os: Option<OsDto<'a>>,
pub hardware: Option<HardwareDto<'a>>,
pub telemetry: TelemetryDto,
pub ports: Vec<PortDto<'a>>,
pub first_seen: String,
pub last_seen: String,
}
impl<'a> HostDto<'a> {
pub fn new(host: &'a Host, options: &ExportOptions) -> Self {
let redaction = options.redaction;
let mut families: Vec<&'static str> = Vec::with_capacity(2);
if host.ips().iter().any(std::net::IpAddr::is_ipv4) {
families.push("ipv4");
}
if host.ips().iter().any(std::net::IpAddr::is_ipv6) {
families.push("ipv6");
}
let mut reasons: Vec<ReasonDto<'a>> = host.reasons().iter().map(ReasonDto::new).collect();
reasons.sort_by(|a, b| {
a.protocol
.cmp(&b.protocol)
.then(a.source_ip.cmp(&b.source_ip))
.then(a.details.cmp(&b.details))
});
let mut roles: Vec<&'static str> = host
.network_roles()
.iter()
.copied()
.map(network_role_name)
.collect();
roles.sort_unstable();
Self {
primary_ip: host.primary_ip().to_string(),
ips: host.ips().iter().map(IpAddr::to_string).collect(),
zone: host.zone().map(|zone| zone.name()),
families,
hostname: host.hostname().map(|name| redaction.hostname(name)),
status: host_status_name(host.status()),
alive: host.is_alive(),
reasons,
roles,
os: host.os().map(OsDto::new),
hardware: host
.hardware()
.map(|hardware| HardwareDto::new(hardware, options)),
telemetry: TelemetryDto::new(host.telemetry()),
ports: host
.ports()
.map(|port| PortDto::new(port, options))
.collect(),
first_seen: rfc3339(host.first_seen()),
last_seen: rfc3339(host.last_seen()),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ReasonDto<'a> {
pub protocol: Cow<'a, str>,
pub source_ip: Option<String>,
pub details: Option<&'a str>,
}
impl<'a> ReasonDto<'a> {
pub fn new(reason: &'a StatusReason) -> Self {
Self {
protocol: status_protocol_name(&reason.protocol),
source_ip: reason.source.map(|ip| ip.to_string()),
details: reason.details.as_deref(),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct OsDto<'a> {
pub name: &'a str,
pub family: Option<&'a str>,
pub generation: Option<&'a str>,
pub vendor: Option<&'a str>,
pub accuracy: u8,
pub cpe: Vec<&'a str>,
pub evidence: Option<&'a str>,
}
impl<'a> OsDto<'a> {
pub fn new(os: &'a OsFingerprint) -> Self {
Self {
name: os.name(),
family: os.family(),
generation: os.generation(),
vendor: os.vendor(),
accuracy: os.accuracy(),
cpe: os.cpes().iter().map(|cpe| &**cpe).collect(),
evidence: os.evidence(),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct HardwareDto<'a> {
pub mac: Option<String>,
pub macs: Vec<String>,
pub vendor: Option<&'a str>,
}
impl<'a> HardwareDto<'a> {
pub fn new(hardware: &'a HardwareInfo, options: &ExportOptions) -> Self {
let redaction = options.redaction;
let mut macs: Vec<String> = hardware
.macs()
.keys()
.map(|mac| redaction.mac(mac))
.collect();
macs.dedup();
Self {
mac: hardware.most_recent_mac().map(|mac| redaction.mac(&mac)),
macs,
vendor: hardware.vendor(),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct TelemetryDto {
pub rtt_min_us: Option<u64>,
pub rtt_median_us: Option<u64>,
pub rtt_avg_us: Option<u64>,
pub rtt_max_us: Option<u64>,
pub jitter_us: Option<u64>,
pub samples: usize,
}
impl TelemetryDto {
pub fn new(telemetry: &HostTelemetry) -> Self {
Self {
rtt_min_us: micros_opt(telemetry.min_rtt()),
rtt_median_us: micros_opt(telemetry.median_rtt()),
rtt_avg_us: micros_opt(telemetry.average_rtt()),
rtt_max_us: micros_opt(telemetry.max_rtt()),
jitter_us: micros_opt(telemetry.jitter()),
samples: telemetry.history().len(),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PortDto<'a> {
pub port: u16,
pub protocol: &'static str,
pub state: &'static str,
pub service: Option<ServiceDto<'a>>,
pub security: Option<SecurityDto<'a>>,
pub discovery: Option<DiscoveryDto<'a>>,
}
impl<'a> PortDto<'a> {
pub fn new(port: &'a Port, options: &ExportOptions) -> Self {
Self {
port: port.number(),
protocol: protocol_name(port.protocol()),
state: port_state_name(port.state()),
service: port.service().map(ServiceDto::new),
security: port
.security()
.map(|security| SecurityDto::new(security, options)),
discovery: port.discovery().map(DiscoveryDto::new),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ServiceDto<'a> {
pub name: &'a str,
pub confidence: u8,
pub product: Option<&'a str>,
pub vendor: Option<&'a str>,
pub version: Option<&'a str>,
pub extrainfo: Option<&'a str>,
pub cpe: Vec<&'a str>,
}
impl<'a> ServiceDto<'a> {
pub fn new(service: &'a Service) -> Self {
Self {
name: service.name(),
confidence: service.confidence(),
product: service.product(),
vendor: service.vendor(),
version: service.version(),
extrainfo: service.extrainfo(),
cpe: service.cpes().iter().map(AsRef::as_ref).collect(),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct SecurityDto<'a> {
pub tls_version: Option<&'a str>,
pub cipher_suite: Option<&'a str>,
pub alpn: Vec<&'a str>,
pub certificate: Option<CertificateDto<'a>>,
}
impl<'a> SecurityDto<'a> {
pub fn new(security: &'a Security, options: &ExportOptions) -> Self {
Self {
tls_version: security.tls_version(),
cipher_suite: security.cipher_suite(),
alpn: security.alpn().iter().map(AsRef::as_ref).collect(),
certificate: security
.certificate()
.map(|cert| CertificateDto::new(cert, options)),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct CertificateDto<'a> {
pub common_name: Cow<'a, str>,
pub sans: Vec<Cow<'a, str>>,
pub issuer: &'a str,
pub validity_start: String,
pub validity_end: String,
pub pubkey_type: &'a str,
pub pubkey_bits: u32,
pub fingerprint_sha256: &'a str,
}
impl<'a> CertificateDto<'a> {
pub fn new(cert: &'a CertificateInfo, options: &ExportOptions) -> Self {
let redaction = options.redaction;
Self {
common_name: redaction.hostname(cert.common_name()),
sans: cert
.sans()
.iter()
.map(|san| redaction.hostname(san))
.collect(),
issuer: cert.issuer(),
validity_start: rfc3339(cert.validity_start()),
validity_end: rfc3339(cert.validity_end()),
pubkey_type: cert.pubkey_type(),
pubkey_bits: cert.pubkey_bits(),
fingerprint_sha256: cert.fingerprint_sha256(),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct DiscoveryDto<'a> {
pub reason: Cow<'a, str>,
pub timestamp: String,
pub rtt_us: Option<u64>,
pub ttl: Option<u8>,
pub source_ip: Option<String>,
}
impl<'a> DiscoveryDto<'a> {
pub fn new(discovery: &'a Discovery) -> Self {
Self {
reason: scan_response_name(discovery.reason()),
timestamp: rfc3339(discovery.timestamp()),
rtt_us: micros_opt(discovery.rtt()),
ttl: discovery.ttl(),
source_ip: discovery.source_ip().map(|ip| ip.to_string()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::ip::set::IpSet;
use crate::model::port::PortSet;
use crate::model::target::{TargetMap, TargetSet};
#[test]
fn wire_names_are_pinned() {
assert_eq!(scan_kind_name(ScanKind::PortScan), "port_scan");
assert_eq!(scanner_kind_name(ScannerKind::SynPort), "syn_port");
assert_eq!(host_status_name(HostStatus::Filtered), "filtered");
assert_eq!(port_state_name(PortState::OpenFiltered), "open_filtered");
assert_eq!(protocol_name(Protocol::Udp), "udp");
assert_eq!(network_role_name(NetworkRole::Tarpit), "tarpit");
assert_eq!(
stop_reason_name(StopReason::AttemptsSpent),
"attempts_spent"
);
assert_eq!(send_mode_name(SendMode::RawSocket), "raw_socket");
assert_eq!(scan_effort_name(ScanEffort::Thorough), "thorough");
}
#[test]
fn a_custom_name_can_never_collide_with_a_builtin() {
let impostor = StatusProtocol::Custom("arp".into());
assert_eq!(status_protocol_name(&StatusProtocol::Arp), "arp");
assert_eq!(status_protocol_name(&impostor), "custom:arp");
let response = ScanResponse::Custom("tcp_rst".into());
assert_eq!(scan_response_name(&ScanResponse::TcpRst), "tcp_rst");
assert_eq!(scan_response_name(&response), "custom:tcp_rst");
}
#[test]
fn the_summary_reports_categories_that_saw_nothing() {
let summary = SummaryDto::new(&ScanSummary::default());
assert_eq!(summary.hosts_by_status.up, 0);
assert_eq!(summary.hosts_by_status.unknown, 0);
assert_eq!(summary.ports_by_state.open, 0);
assert_eq!(summary.ports_by_state.closed_filtered, 0);
}
#[test]
fn oversized_counts_are_rendered_as_exact_strings() {
let mut ips = IpSet::new();
ips.insert_range("2001:db8::/32".parse().expect("a valid range"));
let scope = ScopeDto::new(&TargetScope::from_ip_set(&mut ips));
assert_eq!(scope.addresses, "79228162514264337593543950336");
assert!(scope.addresses.parse::<u128>().expect("exact") > (1u128 << 53));
}
#[test]
fn a_discovery_scope_has_no_probe_count() {
let mut ips = IpSet::new();
ips.insert_range("192.168.0.0/24".parse().expect("a valid range"));
let scope = ScopeDto::new(&TargetScope::from_ip_set(&mut ips));
assert_eq!(scope.addresses, "256");
assert_eq!(scope.probes, None);
assert!(scope.protocols.is_empty());
assert_eq!(scope.ranges.len(), 1);
assert_eq!(scope.ranges[0].family, "ipv4");
assert_eq!(scope.ranges[0].start, "192.168.0.0");
assert_eq!(scope.ranges[0].end, "192.168.0.255");
}
#[test]
fn a_port_scan_scope_carries_the_probe_count() {
let mut ips = IpSet::new();
ips.insert_range("10.0.0.1-10.0.0.4".parse().expect("a valid range"));
let mut targets = TargetMap::new();
targets.add_unit(TargetSet::new(
ips,
PortSet::from_iter([(80, Protocol::Tcp), (53, Protocol::Udp)]),
));
let scope = ScopeDto::new(&TargetScope::from_target_map(&targets));
assert_eq!(scope.addresses, "4");
assert_eq!(scope.probes.as_deref(), Some("8"));
assert_eq!(scope.protocols, vec!["tcp", "udp"]);
}
#[cfg(feature = "export-json")]
#[test]
fn the_total_duration_is_exactly_the_sum_of_the_phases() {
let mut report = crate::export::fixture::report();
report.merge(crate::export::fixture::report());
let document = serde_json::to_value(ReportDto::new(&report, &ExportOptions::new()))
.expect("the report serializes");
let summed: u64 = document["phases"]
.as_array()
.expect("a phase array")
.iter()
.map(|phase| phase["elapsed_us"].as_u64().expect("a phase duration"))
.sum();
assert_eq!(document["elapsed_us"].as_u64(), Some(summed));
}
#[test]
fn a_non_finite_timeout_scale_is_dropped() {
let retry = RetryConfig {
timeout_scale: Some(f64::NAN),
..Default::default()
};
assert_eq!(RetryDto::new(&retry).timeout_scale, None);
let retry = RetryConfig {
timeout_scale: Some(2.5),
..Default::default()
};
assert_eq!(RetryDto::new(&retry).timeout_scale, Some(2.5));
}
}