use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt;
use std::net::IpAddr;
use std::time::{Duration, Instant, SystemTime};
use crate::config::RetryConfig;
use crate::config::{OsDetection, SendMode, ServiceDetection, ZondConfig};
use crate::model::capture::CaptureCounts;
use crate::model::exclusion::Exclusions;
use crate::model::host::{Host, HostStatus};
use crate::model::ip::range::{IpRange, Ipv4Range, Ipv6Range};
use crate::model::ip::scoped::Zone;
use crate::model::ip::set::IpSet;
use crate::model::port::{PortSet, PortState, Protocol};
use crate::model::target::{TargetMap, TargetSet};
use crate::model::technique::TcpScanTechnique;
use crate::scanner::pacing::congestion::WindowSummary;
use crate::scanner::session::{ScanContext, ScannerKind};
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, Default)]
pub enum PortScope {
#[default]
Unstated,
NoPorts,
Every(PortSet),
Mixed(PortSet),
}
impl PortScope {
pub fn ports(&self) -> Option<&PortSet> {
match self {
PortScope::Unstated | PortScope::NoPorts => None,
PortScope::Every(ports) | PortScope::Mixed(ports) => Some(ports),
}
}
pub fn covers(&self, port: u16, protocol: Protocol) -> Option<bool> {
match self {
PortScope::Unstated => None,
PortScope::NoPorts => Some(false),
PortScope::Every(ports) => Some(ports.contains(port, protocol)),
PortScope::Mixed(ports) => {
if ports.contains(port, protocol) {
None
} else {
Some(false)
}
}
}
}
fn of<'a>(units: impl Iterator<Item = &'a PortSet>) -> Self {
let mut units = units;
let Some(first) = units.next().cloned() else {
return PortScope::NoPorts;
};
let mut united = first.clone();
let mut agreed = true;
for ports in units {
agreed &= *ports == first;
united = united.union(ports);
}
if united.is_empty() {
PortScope::NoPorts
} else if agreed {
PortScope::Every(united)
} else {
PortScope::Mixed(united)
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TargetScope {
ranges: Vec<IpRange>,
links: Vec<Zone>,
addresses: u128,
probes: Option<u128>,
ports: PortScope,
protocols: Vec<Protocol>,
excluded: Vec<IpRange>,
withheld: u128,
}
impl TargetScope {
pub fn from_ip_set(ips: &mut IpSet, exclusions: &Exclusions) -> Self {
let withheld = exclusions.withhold(ips);
ips.canonicalize();
let ranges = ip_set_ranges(ips);
let addresses = ips.len();
Self {
ranges,
links: Vec::new(),
addresses,
probes: None,
ports: PortScope::NoPorts,
protocols: Vec::new(),
excluded: exclusions.ranges(),
withheld,
}
}
pub fn from_target_map(targets: &mut TargetMap, exclusions: &Exclusions) -> Self {
let withheld = exclusions.withhold_targets(targets);
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();
let ports = PortScope::of(targets.units.iter().map(TargetSet::ports));
Self {
ranges,
links: Vec::new(),
addresses,
probes,
ports,
protocols,
excluded: exclusions.ranges(),
withheld,
}
}
pub fn ranges(&self) -> &[IpRange] {
&self.ranges
}
pub fn addresses(&self) -> u128 {
self.addresses
}
pub fn probes(&self) -> Option<u128> {
self.probes
}
pub fn links(&self) -> &[Zone] {
&self.links
}
pub fn swept(&self, zone: Option<&Zone>) -> bool {
let Some(zone) = zone else {
return false;
};
self.links.iter().any(|link| link.name() == zone.name())
}
pub(crate) fn record_sweeps(&mut self, links: Vec<Zone>) {
for link in links {
if !self.links.iter().any(|held| held.name() == link.name()) {
self.links.push(link);
}
}
}
pub fn ports(&self) -> &PortScope {
&self.ports
}
pub fn protocols(&self) -> &[Protocol] {
&self.protocols
}
pub fn excluded(&self) -> &[IpRange] {
&self.excluded
}
pub fn withheld(&self) -> u128 {
self.withheld
}
}
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 tcp_technique: TcpScanTechnique,
pub retry: RetryConfig,
pub max_probe_rate: Option<u32>,
pub dns_enabled: bool,
pub redact: bool,
pub os_detection: OsDetection,
pub service_detection: ServiceDetection,
pub traceroute: bool,
}
impl From<&ZondConfig> for ScanSettings {
fn from(cfg: &ZondConfig) -> Self {
Self {
send_mode: cfg.send_mode,
tcp_technique: cfg.tcp_technique,
retry: cfg.retry,
max_probe_rate: cfg.max_probe_rate,
dns_enabled: !cfg.no_dns,
redact: cfg.redact,
os_detection: cfg.os_detection,
service_detection: cfg.service_detection,
traceroute: cfg.traceroute,
}
}
}
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>,
pub(crate) window: Option<WindowSummary>,
}
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 window(&self) -> Option<WindowSummary> {
self.window
}
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 recorded_at(mut self, at: SystemTime) -> Self {
self.at = at;
self
}
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, PartialEq, Eq)]
pub struct ScopeParts {
pub ranges: Vec<IpRange>,
pub links: Vec<Zone>,
pub addresses: u128,
pub probes: Option<u128>,
pub ports: PortScope,
pub protocols: Vec<Protocol>,
pub excluded: Vec<IpRange>,
pub withheld: u128,
}
impl TargetScope {
pub fn from_parts(parts: ScopeParts) -> Self {
Self {
ranges: parts.ranges,
links: parts.links,
addresses: parts.addresses,
probes: parts.probes,
ports: parts.ports,
protocols: parts.protocols,
excluded: parts.excluded,
withheld: parts.withheld,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProbeStatsParts {
pub scanner: ScannerKind,
pub targets: u128,
pub stop_reason: StopReason,
pub elapsed: Duration,
pub sends_attempted: u64,
pub sends_failed: u64,
pub segments_seen: u64,
pub window: Option<WindowSummary>,
pub segments_off_target: u64,
pub replies_without_rtt: u64,
pub hosts_found: u64,
pub answered_on: [u64; ATTEMPTS_COUNTED],
pub answered_unattributed: u64,
pub first_reply: Option<Duration>,
pub last_reply: Option<Duration>,
pub found_at: [u64; BUCKET_BOUNDS_MS.len() + 1],
pub capture: Option<CaptureCounts>,
}
impl ProbeStats {
pub fn from_parts(parts: ProbeStatsParts) -> Self {
Self {
scanner: parts.scanner,
targets: parts.targets,
stop_reason: parts.stop_reason,
elapsed: parts.elapsed,
sends_attempted: parts.sends_attempted,
sends_failed: parts.sends_failed,
segments_seen: parts.segments_seen,
window: parts.window,
segments_off_target: parts.segments_off_target,
replies_without_rtt: parts.replies_without_rtt,
hosts_found: parts.hosts_found,
answered_on: parts.answered_on,
answered_unattributed: parts.answered_unattributed,
first_reply: parts.first_reply,
last_reply: parts.last_reply,
found_at: parts.found_at,
capture: parts.capture,
}
}
}
#[derive(Debug, Clone)]
pub struct PhaseParts {
pub kind: ScanKind,
pub started_at: SystemTime,
pub elapsed: Duration,
pub privileged: bool,
pub targets: TargetScope,
pub settings: ScanSettings,
pub failures: Vec<ScannerFailure>,
pub unroutable: Vec<IpAddr>,
pub probes: Vec<ProbeStats>,
}
impl ScanPhase {
pub fn from_parts(parts: PhaseParts) -> Self {
Self {
kind: parts.kind,
started_at: parts.started_at,
elapsed: parts.elapsed,
privileged: parts.privileged,
targets: parts.targets,
settings: parts.settings,
failures: parts.failures,
unroutable: parts.unroutable,
probes: parts.probes,
}
}
}
#[derive(Debug, Clone)]
pub struct ScanPhase {
kind: ScanKind,
started_at: SystemTime,
elapsed: Duration,
privileged: bool,
targets: TargetScope,
settings: ScanSettings,
failures: Vec<ScannerFailure>,
unroutable: Vec<IpAddr>,
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 unroutable(&self) -> &[IpAddr] {
&self.unroutable
}
pub fn failures(&self) -> &[ScannerFailure] {
&self.failures
}
pub fn probe_stats(&self) -> &[ProbeStats] {
&self.probes
}
}
pub struct PhaseRecorder {
kind: ScanKind,
started_at: SystemTime,
started: Instant,
privileged: bool,
targets: TargetScope,
settings: ScanSettings,
}
impl PhaseRecorder {
pub 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 fn finish(self, ctx: &ScanContext) -> ScanReport {
let mut targets = self.targets;
targets.record_sweeps(ctx.take_swept_links());
let phase = ScanPhase {
kind: self.kind,
started_at: self.started_at,
elapsed: self.started.elapsed(),
privileged: self.privileged,
targets,
settings: self.settings,
failures: ctx.take_failures(),
unroutable: ctx.take_unroutable(),
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,
pub hosts_by_family: FamilyCounts,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FamilyCounts {
pub ipv4: usize,
pub ipv6: usize,
pub dual_stack: 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: Cow<'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: Cow::Borrowed(ENGINE_VERSION),
phases: vec![phase],
hosts,
}
}
pub fn from_phases(phases: Vec<ScanPhase>, hosts: impl IntoIterator<Item = Host>) -> Self {
Self::attributed(Cow::Borrowed(ENGINE_VERSION), phases, hosts)
}
pub fn recorded(
engine_version: impl Into<String>,
phases: Vec<ScanPhase>,
hosts: impl IntoIterator<Item = Host>,
) -> Self {
Self::attributed(Cow::Owned(engine_version.into()), phases, hosts)
}
fn attributed(
engine_version: Cow<'static, str>,
phases: Vec<ScanPhase>,
hosts: impl IntoIterator<Item = Host>,
) -> Self {
let hosts = hosts
.into_iter()
.map(|host| (host.primary_ip(), host))
.collect();
Self {
engine_version,
phases,
hosts,
}
}
pub fn engine_version(&self) -> &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;
let v4 = host.ips().iter().any(IpAddr::is_ipv4);
let v6 = host.ips().iter().any(IpAddr::is_ipv6);
summary.hosts_by_family.ipv4 += usize::from(v4);
summary.hosts_by_family.ipv6 += usize::from(v6);
summary.hosts_by_family.dual_stack += usize::from(v4 && v6);
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 alive_targets(&self, ports: PortSet) -> TargetMap {
let mut ips = IpSet::new();
for host in self.hosts.values().filter(|host| host.is_alive()) {
match host.primary_ip() {
IpAddr::V4(v4) => {
if let Ok(range) = Ipv4Range::new(v4, v4) {
ips.push_v4_range(range);
}
}
IpAddr::V6(v6) => {
let zone = v6
.is_unicast_link_local()
.then(|| host.zone().and_then(Zone::index))
.flatten();
if let Ok(range) = Ipv6Range::scoped(v6, v6, zone) {
ips.push_v6_range(range);
}
}
}
}
ips.canonicalize();
let mut targets = TargetMap::new();
if !ips.is_empty() {
targets.add_unit(TargetSet::new(ips, ports));
}
targets
}
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 {
#[test]
fn a_scope_says_whether_its_addresses_agree_about_ports() {
use crate::model::parse::ip::to_set;
use crate::model::port::PortSet;
use crate::model::target::TargetSet;
let unit = |cidr: &str, ports: &str| {
TargetSet::new(
to_set(&[cidr], None, None).expect("a range"),
PortSet::try_from(ports).expect("a port specification"),
)
};
let mut same = TargetMap::new();
same.add_unit(unit("10.0.0.0/30", "80,443"));
same.add_unit(unit("10.0.1.0/30", "80,443"));
let scope = TargetScope::from_target_map(&mut same, &Exclusions::none());
assert_eq!(
scope.ports().covers(443, Protocol::Tcp),
Some(true),
"every address was walked for it"
);
assert_eq!(scope.ports().covers(8080, Protocol::Tcp), Some(false));
let mut differing = TargetMap::new();
differing.add_unit(unit("10.0.0.0/30", "80,443"));
differing.add_unit(unit("10.0.1.0/30", "8080"));
let scope = TargetScope::from_target_map(&mut differing, &Exclusions::none());
assert_eq!(
scope.ports().covers(8080, Protocol::Tcp),
None,
"walked for one unit and not the other, so the scope cannot say"
);
assert_eq!(
scope.ports().covers(9999, Protocol::Tcp),
Some(false),
"absent from the union means walked for no address at all"
);
}
#[test]
fn a_discovery_sweep_walked_no_ports_and_says_so() {
let mut ips = crate::model::parse::ip::to_set(&["10.0.0.0/30"], None, None).unwrap();
let scope = TargetScope::from_ip_set(&mut ips, &Exclusions::none());
assert_eq!(*scope.ports(), PortScope::NoPorts);
assert_eq!(scope.ports().covers(80, Protocol::Tcp), Some(false));
}
use super::*;
use crate::model::ip::range::Ipv4Range;
use crate::model::port::{Port, PortSet, Service};
use crate::model::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(), &Exclusions::none()),
settings: ScanSettings::from(&ZondConfig::default()),
failures: Vec::new(),
unroutable: 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, &Exclusions::none());
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, &Exclusions::none());
assert_eq!(scope.addresses(), 4);
assert_eq!(scope.probes(), Some(12));
assert_eq!(scope.protocols(), &[Protocol::Tcp, Protocol::Udp]);
}
#[test]
fn settings_record_what_changed_the_scan() {
let scanning = ZondConfig {
no_dns: true,
..Default::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 only_hosts_that_answered_become_port_scan_targets() {
let mut up = Host::new(ip(1));
up.set_status(HostStatus::Up);
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 unknown = Host::new(ip(4));
let report = ScanReport::new(phase(ScanKind::Discovery), [up, filtered, down, unknown]);
let targets = report.alive_targets(PortSet::from_iter([(80, Protocol::Tcp)]));
assert_eq!(targets.gross_ips().expect("countable"), 2);
assert_eq!(targets.gross_targets().expect("countable"), 2);
}
#[test]
fn a_dual_stack_host_is_scanned_once() {
let mut dual = Host::new(ip(1));
dual.set_status(HostStatus::Up);
dual.add_ip(IpAddr::from_str("2001:db8::1").unwrap());
let report = ScanReport::new(phase(ScanKind::Discovery), [dual]);
let targets = report.alive_targets(PortSet::from_iter([(80, Protocol::Tcp)]));
assert_eq!(targets.gross_ips().expect("countable"), 1);
}
#[test]
fn a_link_local_target_keeps_the_interface_it_was_found_on() {
let lla: IpAddr = "fe80::10".parse().unwrap();
let mut host = Host::new(lla);
host.set_status(HostStatus::Up);
host.set_zone(Zone::new(7, "en0"));
let report = ScanReport::new(phase(ScanKind::Discovery), [host]);
let targets = report.alive_targets(PortSet::from_iter([(80, Protocol::Tcp)]));
let zones: Vec<Option<u32>> = targets
.units
.iter()
.flat_map(|unit| unit.ips().v6().iter().map(|range| range.zone()))
.collect();
assert_eq!(zones, vec![Some(7)]);
}
#[test]
fn a_sweep_that_found_nothing_yields_no_targets() {
let report = ScanReport::new(phase(ScanKind::Discovery), [Host::new(ip(1))]);
let targets = report.alive_targets(PortSet::from_iter([(80, Protocol::Tcp)]));
assert!(targets.is_empty());
assert!(targets.units.is_empty());
}
#[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 an_unroutable_address_is_recorded_without_making_the_scan_partial() {
let cfg = ZondConfig::default();
let (_session, ctx) = crate::scanner::session::ScanSession::new();
let mut targets = IpSet::from_str("192.168.0.1-192.168.0.2").expect("a valid range");
let scope = TargetScope::from_ip_set(&mut targets, &Exclusions::none());
let recorder = PhaseRecorder::start(ScanKind::Discovery, false, scope, &cfg);
let unreachable: IpAddr = "2001:db8::1".parse().expect("literal");
ctx.record_unroutable(unreachable);
ctx.record_unroutable(unreachable);
let report = recorder.finish(&ctx);
assert_eq!(report.phases()[0].unroutable(), [unreachable]);
assert!(
!report.is_partial(),
"no strategy failed; that address is simply not reachable from here"
);
assert_eq!(report.failures().count(), 0);
}
#[test]
fn a_self_orchestrated_scan_can_close_its_own_phase() {
let cfg = ZondConfig::default();
let (_session, ctx) = crate::scanner::session::ScanSession::new();
let mut targets = IpSet::from_str("192.168.0.1-192.168.0.4").expect("a valid range");
let scope = TargetScope::from_ip_set(&mut targets, &Exclusions::none());
let recorder = PhaseRecorder::start(ScanKind::Discovery, false, scope, &cfg);
ctx.update_host(ip(1), |host| host.set_status(HostStatus::Up));
ctx.record_failure(ScannerKind::Local, "eth0: no address".into());
let report = recorder.finish(&ctx);
assert_eq!(report.host_count(), 1);
assert_eq!(report.phases()[0].targets().addresses(), 4);
assert!(report.is_partial(), "the failure has to reach the record");
assert_eq!(report.failures().count(), 1);
}
#[test]
fn probe_stats_filed_during_a_scan_land_in_its_phase() {
let (_session, ctx) = crate::scanner::session::ScanSession::new();
let recorder = PhaseRecorder::start(
ScanKind::Discovery,
true,
TargetScope::from_ip_set(&mut IpSet::new(), &Exclusions::none()),
&ZondConfig::default(),
);
ctx.record_probe_stats(ProbeStats {
window: None,
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, &Exclusions::none());
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, &Exclusions::none());
assert_eq!(scope.addresses(), 5);
assert_eq!(
scope.ranges()[0].start_addr(),
IpAddr::V4(Ipv4Addr::new(10, 0, 0, 5))
);
}
#[test]
fn family_counts_record_a_dual_stack_host_under_both() {
let mut dual = Host::new(ip(1));
dual.add_ip(IpAddr::from_str("2001:db8::1").unwrap());
let v6_only = Host::new(IpAddr::from_str("2001:db8::2").unwrap());
let report = ScanReport::new(
phase(ScanKind::Discovery),
[dual, Host::new(ip(2)), v6_only],
);
let summary = report.summary();
assert_eq!(summary.hosts_total, 3);
assert_eq!(summary.hosts_by_family.ipv4, 2);
assert_eq!(summary.hosts_by_family.ipv6, 2);
assert_eq!(summary.hosts_by_family.dual_stack, 1);
}
}