use std::collections::BTreeMap;
use std::fmt;
use std::net::IpAddr;
use std::time::{Duration, Instant, SystemTime};
use crate::core::config::{SendMode, ZondConfig};
use crate::core::models::host::{Host, HostStatus};
use crate::core::models::ip::range::IpRange;
use crate::core::models::ip::set::IpSet;
use crate::core::models::port::{PortState, Protocol};
use crate::core::models::retry::RetryConfig;
use crate::core::models::target::TargetMap;
use crate::core::session::{ScanContext, ScannerKind};
use crate::network::capture::CaptureCounts;
pub const ENGINE_VERSION: &str = env!("CARGO_PKG_VERSION");
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ScanKind {
Discovery,
PortScan,
}
impl fmt::Display for ScanKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ScanKind::Discovery => write!(f, "discovery"),
ScanKind::PortScan => write!(f, "port scan"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TargetScope {
ranges: Vec<IpRange>,
addresses: u128,
probes: Option<u128>,
protocols: Vec<Protocol>,
}
impl TargetScope {
pub fn from_ip_set(ips: &mut IpSet) -> Self {
ips.canonicalize();
let ranges = ip_set_ranges(ips);
let addresses = ips.len();
Self {
ranges,
addresses,
probes: None,
protocols: Vec::new(),
}
}
pub fn from_target_map(targets: &mut TargetMap) -> Self {
targets.canonicalize();
let mut ranges = Vec::new();
let mut protocols = Vec::new();
for unit in &targets.units {
ranges.extend(ip_set_ranges(unit.ips()));
for (_, protocol) in unit.ports().iter() {
if !protocols.contains(&protocol) {
protocols.push(protocol);
}
}
}
ranges.sort_by_key(|range| (range.start_addr(), range.end_addr()));
ranges.dedup();
protocols.sort();
let addresses = targets.gross_ips().unwrap_or(0);
let probes = targets.gross_targets().ok();
Self {
ranges,
addresses,
probes,
protocols,
}
}
pub fn ranges(&self) -> &[IpRange] {
&self.ranges
}
pub fn addresses(&self) -> u128 {
self.addresses
}
pub fn probes(&self) -> Option<u128> {
self.probes
}
pub fn protocols(&self) -> &[Protocol] {
&self.protocols
}
}
fn ip_set_ranges(ips: &IpSet) -> Vec<IpRange> {
let v4 = ips.v4().iter().copied().map(IpRange::V4);
let v6 = ips.v6().iter().copied().map(IpRange::V6);
v4.chain(v6).collect()
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ScanSettings {
pub send_mode: SendMode,
pub retry: RetryConfig,
pub max_probe_rate: Option<u32>,
pub dns_enabled: bool,
pub redact: bool,
}
impl From<&ZondConfig> for ScanSettings {
fn from(cfg: &ZondConfig) -> Self {
Self {
send_mode: cfg.send_mode,
retry: cfg.retry,
max_probe_rate: cfg.max_probe_rate,
dns_enabled: !cfg.no_dns,
redact: cfg.redact,
}
}
}
pub const BUCKET_BOUNDS_MS: [u64; 9] = [1, 2, 5, 10, 25, 50, 100, 250, 1_000];
pub const ATTEMPTS_COUNTED: usize = 6;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StopReason {
Aborted,
AllResponded,
AttemptsSpent,
DeadlineExpired,
StreamClosed,
}
impl StopReason {
pub fn is_complete(&self) -> bool {
matches!(self, StopReason::AllResponded | StopReason::AttemptsSpent)
}
}
impl fmt::Display for StopReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let text = match self {
StopReason::Aborted => "aborted by the caller",
StopReason::AllResponded => "every target answered",
StopReason::AttemptsSpent => "attempts spent",
StopReason::DeadlineExpired => "deadline expired",
StopReason::StreamClosed => "capture stream closed",
};
f.write_str(text)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProbeStats {
pub(crate) scanner: ScannerKind,
pub(crate) targets: u128,
pub(crate) stop_reason: StopReason,
pub(crate) elapsed: Duration,
pub(crate) sends_attempted: u64,
pub(crate) sends_failed: u64,
pub(crate) segments_seen: u64,
pub(crate) segments_off_target: u64,
pub(crate) replies_without_rtt: u64,
pub(crate) hosts_found: u64,
pub(crate) answered_on: [u64; ATTEMPTS_COUNTED],
pub(crate) answered_unattributed: u64,
pub(crate) first_reply: Option<Duration>,
pub(crate) last_reply: Option<Duration>,
pub(crate) found_at: [u64; BUCKET_BOUNDS_MS.len() + 1],
pub(crate) capture: Option<CaptureCounts>,
}
impl ProbeStats {
pub fn scanner(&self) -> ScannerKind {
self.scanner
}
pub fn targets(&self) -> u128 {
self.targets
}
pub fn stop_reason(&self) -> StopReason {
self.stop_reason
}
pub fn elapsed(&self) -> Duration {
self.elapsed
}
pub fn sends_attempted(&self) -> u64 {
self.sends_attempted
}
pub fn sends_failed(&self) -> u64 {
self.sends_failed
}
pub fn segments_seen(&self) -> u64 {
self.segments_seen
}
pub fn segments_off_target(&self) -> u64 {
self.segments_off_target
}
pub fn replies_without_rtt(&self) -> u64 {
self.replies_without_rtt
}
pub fn hosts_found(&self) -> u64 {
self.hosts_found
}
pub fn answered_on(&self) -> &[u64] {
&self.answered_on
}
pub fn answered_unattributed(&self) -> u64 {
self.answered_unattributed
}
pub fn first_reply(&self) -> Option<Duration> {
self.first_reply
}
pub fn last_reply(&self) -> Option<Duration> {
self.last_reply
}
pub fn found_at(&self) -> &[u64] {
&self.found_at
}
pub fn capture(&self) -> Option<CaptureCounts> {
self.capture
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScannerFailure {
scanner: ScannerKind,
reason: String,
at: SystemTime,
}
impl ScannerFailure {
pub fn new(scanner: ScannerKind, reason: impl Into<String>) -> Self {
Self {
scanner,
reason: reason.into(),
at: SystemTime::now(),
}
}
pub fn scanner(&self) -> ScannerKind {
self.scanner
}
pub fn reason(&self) -> &str {
&self.reason
}
pub fn at(&self) -> SystemTime {
self.at
}
}
impl fmt::Display for ScannerFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?} scanner failed: {}", self.scanner, self.reason)
}
}
#[derive(Debug, Clone)]
pub struct ScanPhase {
kind: ScanKind,
started_at: SystemTime,
elapsed: Duration,
privileged: bool,
targets: TargetScope,
settings: ScanSettings,
failures: Vec<ScannerFailure>,
probes: Vec<ProbeStats>,
}
impl ScanPhase {
pub fn kind(&self) -> ScanKind {
self.kind
}
pub fn started_at(&self) -> SystemTime {
self.started_at
}
pub fn elapsed(&self) -> Duration {
self.elapsed
}
pub fn privileged(&self) -> bool {
self.privileged
}
pub fn targets(&self) -> &TargetScope {
&self.targets
}
pub fn settings(&self) -> &ScanSettings {
&self.settings
}
pub fn failures(&self) -> &[ScannerFailure] {
&self.failures
}
pub fn probe_stats(&self) -> &[ProbeStats] {
&self.probes
}
}
pub(crate) struct PhaseRecorder {
kind: ScanKind,
started_at: SystemTime,
started: Instant,
privileged: bool,
targets: TargetScope,
settings: ScanSettings,
}
impl PhaseRecorder {
pub(crate) fn start(
kind: ScanKind,
privileged: bool,
targets: TargetScope,
cfg: &ZondConfig,
) -> Self {
Self {
kind,
started_at: SystemTime::now(),
started: Instant::now(),
privileged,
targets,
settings: ScanSettings::from(cfg),
}
}
pub(crate) fn finish(self, ctx: &ScanContext) -> ScanReport {
let phase = ScanPhase {
kind: self.kind,
started_at: self.started_at,
elapsed: self.started.elapsed(),
privileged: self.privileged,
targets: self.targets,
settings: self.settings,
failures: ctx.take_failures(),
probes: ctx.take_probe_stats(),
};
let hosts = ctx.store.iter().map(|entry| entry.value().clone());
ScanReport::new(phase, hosts)
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ScanSummary {
pub hosts_total: usize,
pub hosts_alive: usize,
pub hosts_by_status: BTreeMap<HostStatus, usize>,
pub ports_total: usize,
pub ports_open: usize,
pub ports_by_state: BTreeMap<PortState, usize>,
pub services_identified: usize,
}
#[derive(Debug, Clone)]
#[must_use = "a report is the record of the scan that just ran; dropping it discards it"]
pub struct ScanReport {
engine_version: &'static str,
phases: Vec<ScanPhase>,
hosts: BTreeMap<IpAddr, Host>,
}
impl ScanReport {
pub fn new(phase: ScanPhase, hosts: impl IntoIterator<Item = Host>) -> Self {
let hosts = hosts
.into_iter()
.map(|host| (host.primary_ip(), host))
.collect();
Self {
engine_version: ENGINE_VERSION,
phases: vec![phase],
hosts,
}
}
pub fn engine_version(&self) -> &'static str {
self.engine_version
}
pub fn phases(&self) -> &[ScanPhase] {
&self.phases
}
pub fn hosts(&self) -> impl Iterator<Item = &Host> {
self.hosts.values()
}
pub fn host_count(&self) -> usize {
self.hosts.len()
}
pub fn host(&self, ip: &IpAddr) -> Option<&Host> {
self.hosts.get(ip)
}
pub fn started_at(&self) -> SystemTime {
self.phases
.iter()
.map(ScanPhase::started_at)
.min()
.unwrap_or_else(SystemTime::now)
}
pub fn elapsed(&self) -> Duration {
self.phases.iter().map(ScanPhase::elapsed).sum()
}
pub fn failures(&self) -> impl Iterator<Item = &ScannerFailure> {
self.phases.iter().flat_map(ScanPhase::failures)
}
pub fn probe_stats(&self) -> impl Iterator<Item = &ProbeStats> {
self.phases.iter().flat_map(ScanPhase::probe_stats)
}
pub fn is_partial(&self) -> bool {
self.phases.iter().any(|phase| !phase.failures.is_empty())
}
pub fn summary(&self) -> ScanSummary {
let mut summary = ScanSummary::default();
for host in self.hosts.values() {
summary.hosts_total += 1;
if host.is_alive() {
summary.hosts_alive += 1;
}
*summary.hosts_by_status.entry(host.status()).or_default() += 1;
for port in host.ports() {
summary.ports_total += 1;
if port.state() == PortState::Open {
summary.ports_open += 1;
}
*summary.ports_by_state.entry(port.state()).or_default() += 1;
if port.service().is_some() {
summary.services_identified += 1;
}
}
}
summary
}
pub fn merge(&mut self, other: ScanReport) {
self.phases.extend(other.phases);
for (ip, host) in other.hosts {
match self.hosts.get_mut(&ip) {
Some(existing) => existing.merge(host),
None => {
self.hosts.insert(ip, host);
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::models::ip::range::Ipv4Range;
use crate::core::models::port::{Port, PortSet, Service};
use crate::core::models::target::TargetSet;
use std::net::Ipv4Addr;
use std::str::FromStr;
fn ip(last: u8) -> IpAddr {
IpAddr::V4(Ipv4Addr::new(192, 168, 0, last))
}
fn phase(kind: ScanKind) -> ScanPhase {
ScanPhase {
kind,
started_at: SystemTime::UNIX_EPOCH,
elapsed: Duration::from_millis(500),
privileged: true,
targets: TargetScope::from_ip_set(&mut IpSet::new()),
settings: ScanSettings::from(&ZondConfig::default()),
failures: Vec::new(),
probes: Vec::new(),
}
}
fn ip_set(spec: &str) -> IpSet {
let mut set = IpSet::new();
set.insert_range(IpRange::from_str(spec).expect("valid range"));
set
}
#[test]
fn scope_merges_overlapping_ranges_before_counting() {
let mut ips = ip_set("192.168.0.0/24");
ips.insert_range(IpRange::from_str("192.168.0.128/25").expect("valid range"));
let scope = TargetScope::from_ip_set(&mut ips);
assert_eq!(scope.ranges().len(), 1);
assert_eq!(scope.addresses(), 256);
assert_eq!(scope.probes(), None);
assert!(scope.protocols().is_empty());
}
#[test]
fn port_scan_scope_counts_probes_not_addresses() {
let ports = PortSet::from_iter([
(80, Protocol::Tcp),
(443, Protocol::Tcp),
(53, Protocol::Udp),
]);
let mut targets = TargetMap::new();
targets.add_unit(TargetSet::new(ip_set("10.0.0.1-10.0.0.4"), ports));
let scope = TargetScope::from_target_map(&mut targets);
assert_eq!(scope.addresses(), 4);
assert_eq!(scope.probes(), Some(12));
assert_eq!(scope.protocols(), &[Protocol::Tcp, Protocol::Udp]);
}
#[test]
fn settings_ignore_presentation_config() {
let scanning = ZondConfig {
no_dns: true,
..Default::default()
};
let presentation = ZondConfig {
no_banner: true,
quiet: 2,
disable_input: true,
..Default::default()
};
assert_eq!(
ScanSettings::from(&presentation),
ScanSettings::from(&ZondConfig::default())
);
assert_ne!(
ScanSettings::from(&scanning),
ScanSettings::from(&ZondConfig::default())
);
}
#[test]
fn summary_counts_states_and_services() {
let mut up = Host::new(ip(1));
up.set_status(HostStatus::Up);
up.add_port(
Port::new(22, Protocol::Tcp, PortState::Open).with_service(Service::new("ssh", 90)),
);
up.add_port(Port::new(80, Protocol::Tcp, PortState::Open));
up.add_port(Port::new(81, Protocol::Tcp, PortState::Filtered));
let mut filtered = Host::new(ip(2));
filtered.set_status(HostStatus::Filtered);
let mut down = Host::new(ip(3));
down.set_status(HostStatus::Down);
let report = ScanReport::new(phase(ScanKind::PortScan), [up, filtered, down]);
let summary = report.summary();
assert_eq!(summary.hosts_total, 3);
assert_eq!(summary.hosts_alive, 2);
assert_eq!(summary.hosts_by_status[&HostStatus::Up], 1);
assert_eq!(summary.hosts_by_status[&HostStatus::Down], 1);
assert_eq!(summary.ports_total, 3);
assert_eq!(summary.ports_open, 2);
assert_eq!(summary.ports_by_state[&PortState::Filtered], 1);
assert_eq!(summary.services_identified, 1);
}
#[test]
fn hosts_are_ordered_by_ip_regardless_of_discovery_order() {
let scrambled = [Host::new(ip(30)), Host::new(ip(2)), Host::new(ip(17))];
let report = ScanReport::new(phase(ScanKind::Discovery), scrambled);
let order: Vec<IpAddr> = report.hosts().map(Host::primary_ip).collect();
assert_eq!(order, vec![ip(2), ip(17), ip(30)]);
}
#[test]
fn merge_combines_hosts_and_keeps_phase_order() {
let mut discovered = Host::new(ip(1));
discovered.set_status(HostStatus::Up);
discovered.add_rtt(Duration::from_millis(3));
let mut first = ScanReport::new(phase(ScanKind::Discovery), [discovered]);
let mut scanned = Host::new(ip(1));
scanned.add_port(Port::new(443, Protocol::Tcp, PortState::Open));
let second = ScanReport::new(phase(ScanKind::PortScan), [scanned, Host::new(ip(9))]);
first.merge(second);
let host = first.host(&ip(1)).expect("host survives the merge");
assert_eq!(host.status(), HostStatus::Up);
assert_eq!(host.port_count(), 1);
assert!(host.min_rtt().is_some());
assert_eq!(first.host_count(), 2);
assert_eq!(
first
.phases()
.iter()
.map(ScanPhase::kind)
.collect::<Vec<_>>(),
vec![ScanKind::Discovery, ScanKind::PortScan]
);
assert_eq!(first.elapsed(), Duration::from_secs(1));
}
#[test]
fn failures_are_visible_across_phases() {
let mut failed = phase(ScanKind::Discovery);
failed.failures.push(ScannerFailure::new(
ScannerKind::Routed,
"raw socket unavailable",
));
let clean = ScanReport::new(phase(ScanKind::PortScan), []);
let mut report = ScanReport::new(failed, []);
report.merge(clean);
assert!(report.is_partial());
assert_eq!(report.failures().count(), 1);
}
#[test]
fn probe_stats_filed_during_a_scan_land_in_its_phase() {
let (_session, ctx) = crate::core::session::ScanSession::new();
let recorder = PhaseRecorder::start(
ScanKind::Discovery,
true,
TargetScope::from_ip_set(&mut IpSet::new()),
&ZondConfig::default(),
);
ctx.record_probe_stats(ProbeStats {
scanner: ScannerKind::Routed,
targets: 256,
stop_reason: StopReason::AllResponded,
elapsed: Duration::from_millis(40),
sends_attempted: 300,
sends_failed: 0,
segments_seen: 250,
segments_off_target: 1,
replies_without_rtt: 2,
hosts_found: 9,
answered_on: [7, 2, 0, 0, 0, 0],
answered_unattributed: 0,
first_reply: Some(Duration::from_millis(1)),
last_reply: Some(Duration::from_millis(30)),
found_at: [0; BUCKET_BOUNDS_MS.len() + 1],
capture: None,
});
let report = recorder.finish(&ctx);
let stats = report.phases()[0].probe_stats();
assert_eq!(stats.len(), 1);
assert_eq!(stats[0].scanner(), ScannerKind::Routed);
assert_eq!(stats[0].hosts_found(), 9);
assert_eq!(stats[0].answered_on()[1], 2);
assert_eq!(report.probe_stats().count(), 1);
assert!(ctx.take_probe_stats().is_empty());
}
#[test]
fn an_uninstrumented_phase_reports_no_probe_stats() {
let report = ScanReport::new(phase(ScanKind::PortScan), []);
assert!(report.phases()[0].probe_stats().is_empty());
assert_eq!(report.probe_stats().count(), 0);
}
#[test]
fn a_stop_reason_knows_whether_the_run_finished() {
assert!(StopReason::AllResponded.is_complete());
assert!(StopReason::AttemptsSpent.is_complete());
assert!(!StopReason::DeadlineExpired.is_complete());
assert!(!StopReason::Aborted.is_complete());
assert!(!StopReason::StreamClosed.is_complete());
}
#[test]
fn a_clean_report_is_not_partial() {
let report = ScanReport::new(phase(ScanKind::Discovery), []);
assert!(!report.is_partial());
assert_eq!(report.failures().count(), 0);
assert_eq!(report.engine_version(), ENGINE_VERSION);
}
#[test]
fn scope_ranges_cover_both_families() {
let mut ips = ip_set("10.0.0.0/30");
ips.insert_range(IpRange::from_str("fe80::/126").expect("valid range"));
let scope = TargetScope::from_ip_set(&mut ips);
assert_eq!(scope.addresses(), 8);
assert!(matches!(scope.ranges()[0], IpRange::V4(_)));
assert!(matches!(scope.ranges()[1], IpRange::V6(_)));
}
#[test]
fn ipv4_range_scope_reports_its_own_bounds() {
let mut ips = IpSet::new();
ips.push_v4_range(
Ipv4Range::new(Ipv4Addr::new(10, 0, 0, 5), Ipv4Addr::new(10, 0, 0, 9))
.expect("valid range"),
);
let scope = TargetScope::from_ip_set(&mut ips);
assert_eq!(scope.addresses(), 5);
assert_eq!(
scope.ranges()[0].start_addr(),
IpAddr::V4(Ipv4Addr::new(10, 0, 0, 5))
);
}
}