use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt;
use std::net::IpAddr;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use crate::config::DetectionEnvelope;
use crate::config::RetryConfig;
use crate::config::{IdleScan, OsDetection, ServiceDetection, ZondConfig};
use crate::evasion::EvasionProfile;
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::{ScopedIp, Zone};
use crate::model::ip::set::IpSet;
use crate::model::mac::MacAddr;
use crate::model::port::{PortSet, PortState, Protocol};
use crate::model::target::{TargetMap, TargetSet};
use crate::model::technique::{SctpScanTechnique, TcpScanTechnique};
use crate::system::privilege::Privilege;
use crate::transport::probe::SendMode;
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,
Listen,
}
impl ScanKind {
pub const ALL: [ScanKind; 3] = [Self::Discovery, Self::PortScan, Self::Listen];
}
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"),
ScanKind::Listen => write!(f, "listen"),
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LivenessSkip {
AssumeUp,
IdleScan,
PortsNoDearer,
}
impl LivenessSkip {
pub const ALL: [LivenessSkip; 3] = [Self::AssumeUp, Self::IdleScan, Self::PortsNoDearer];
}
#[non_exhaustive]
#[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>,
listened: 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 {
listened: Vec::new(),
ranges,
links: Vec::new(),
addresses,
probes: None,
ports: PortScope::NoPorts,
protocols: Vec::new(),
excluded: exclusions.ranges(),
withheld,
}
}
pub fn listening_on(links: Vec<Zone>, exclusions: &Exclusions) -> Self {
Self {
ranges: Vec::new(),
links: Vec::new(),
listened: links,
addresses: 0,
probes: None,
ports: PortScope::NoPorts,
protocols: Vec::new(),
excluded: exclusions.ranges(),
withheld: 0,
}
}
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 {
listened: Vec::new(),
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 listened(&self) -> &[Zone] {
&self.listened
}
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, PartialEq, Eq)]
pub struct EvasionRecord {
pub source_port: Option<u16>,
pub ttl: Option<u8>,
pub padding: Option<u16>,
pub bad_tcp_checksum: bool,
pub spoof_mac: Option<MacAddr>,
pub fragment: Option<u16>,
pub decoys: Vec<IpAddr>,
pub flags: Option<u8>,
}
impl EvasionRecord {
#[must_use]
pub fn from_profile(profile: &EvasionProfile) -> Option<Self> {
profile.is_active().then(|| Self {
source_port: profile.source_port,
ttl: profile.ttl,
padding: profile.padding,
bad_tcp_checksum: profile.bad_tcp_checksum,
spoof_mac: profile.spoof_mac,
fragment: profile.fragment,
decoys: profile.decoys.clone(),
flags: profile.flags,
})
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ScanSettings {
pub send_mode: SendMode,
pub tcp_technique: TcpScanTechnique,
pub sctp_technique: SctpScanTechnique,
pub retry: RetryConfig,
pub max_probe_rate: Option<std::num::NonZeroU32>,
pub min_probe_rate: Option<std::num::NonZeroU32>,
pub host_probe_interval: Option<Duration>,
pub host_timeout: Option<Duration>,
pub scan_timeout: Option<Duration>,
pub dns_enabled: bool,
pub redact: bool,
pub os_detection: OsDetection,
pub service_detection: ServiceDetection,
pub detection: DetectionEnvelope,
pub traceroute: bool,
pub characterise: bool,
pub ip_protocols: Vec<u8>,
pub tls_enumeration: bool,
pub listen_only_ports: Vec<u16>,
pub evasion: Option<EvasionRecord>,
pub idle_scan: Option<IdleScan>,
pub icmp_evidence: bool,
}
impl ScanSettings {
#[must_use]
pub fn listened_only_to(&self, number: u16, protocol: Protocol) -> bool {
protocol == Protocol::Tcp && self.listen_only_ports.contains(&number)
}
}
impl From<&ZondConfig> for ScanSettings {
fn from(cfg: &ZondConfig) -> Self {
let ZondConfig {
send_mode,
tcp_technique,
sctp_technique,
retry,
max_probe_rate,
min_probe_rate,
host_probe_interval,
host_timeout,
scan_timeout,
no_dns,
redact,
os_detection,
service_detection,
detection,
traceroute,
characterise,
ip_protocols,
tls_enumeration,
listen_only_ports,
evasion,
idle_scan,
icmp_evidence,
exclusions: _,
segment_sweep: _,
assume_up: _,
send_source: _,
} = cfg;
Self {
send_mode: *send_mode,
tcp_technique: *tcp_technique,
sctp_technique: *sctp_technique,
retry: *retry,
max_probe_rate: *max_probe_rate,
min_probe_rate: *min_probe_rate,
host_probe_interval: *host_probe_interval,
host_timeout: *host_timeout,
scan_timeout: *scan_timeout,
dns_enabled: !no_dns,
redact: *redact,
os_detection: *os_detection,
service_detection: *service_detection,
detection: *detection,
traceroute: *traceroute,
characterise: *characterise,
ip_protocols: ip_protocols.iter().copied().collect(),
tls_enumeration: *tls_enumeration,
listen_only_ports: listen_only_ports.iter().copied().collect(),
evasion: EvasionRecord::from_profile(evasion),
idle_scan: *idle_scan,
icmp_evidence: *icmp_evidence,
}
}
}
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,
TimedOut,
}
impl StopReason {
pub const ALL: [StopReason; 6] = [
Self::Aborted,
Self::AllResponded,
Self::AttemptsSpent,
Self::DeadlineExpired,
Self::StreamClosed,
Self::TimedOut,
];
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",
StopReason::TimedOut => "scan budget spent",
};
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) sends_witnessed: 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 sends_witnessed(&self) -> u64 {
self.sends_witnessed
}
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
}
}
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refusal {
scanner: ScannerKind,
reason: String,
}
impl Refusal {
pub fn new(scanner: ScannerKind, reason: impl Into<String>) -> Self {
Self {
scanner,
reason: reason.into(),
}
}
pub fn scanner(&self) -> ScannerKind {
self.scanner
}
pub fn reason(&self) -> &str {
&self.reason
}
}
#[must_use]
#[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 listened: 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 {
listened: parts.listened,
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 sends_witnessed: 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,
sends_witnessed: parts.sends_witnessed,
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,
}
}
}
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attachment {
link: Zone,
source: AttachmentSource,
device_mac: Option<MacAddr>,
device_name: Option<String>,
port: Option<String>,
native_vlan: Option<u16>,
management: Option<IpAddr>,
observed_at: SystemTime,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum AttachmentSource {
Lldp,
Cdp,
}
impl AttachmentSource {
pub const ALL: [AttachmentSource; 2] = [Self::Lldp, Self::Cdp];
}
impl Attachment {
pub fn new(link: Zone, source: AttachmentSource, observed_at: SystemTime) -> Self {
Self {
link,
source,
device_mac: None,
device_name: None,
port: None,
native_vlan: None,
management: None,
observed_at,
}
}
pub fn with_device_mac(mut self, mac: MacAddr) -> Self {
self.device_mac = Some(mac);
self
}
pub fn with_device_name(mut self, name: impl Into<String>) -> Self {
self.device_name = Some(name.into());
self
}
pub fn with_port(mut self, port: impl Into<String>) -> Self {
self.port = Some(port.into());
self
}
pub fn with_native_vlan(mut self, vlan: u16) -> Self {
self.native_vlan = Some(vlan);
self
}
pub fn with_management_address(mut self, address: IpAddr) -> Self {
self.management = Some(address);
self
}
pub fn link(&self) -> &Zone {
&self.link
}
pub fn source(&self) -> AttachmentSource {
self.source
}
pub fn device_mac(&self) -> Option<MacAddr> {
self.device_mac
}
pub fn device_name(&self) -> Option<&str> {
self.device_name.as_deref()
}
pub fn port(&self) -> Option<&str> {
self.port.as_deref()
}
pub fn native_vlan(&self) -> Option<u16> {
self.native_vlan
}
pub fn management_address(&self) -> Option<IpAddr> {
self.management
}
pub fn observed_at(&self) -> SystemTime {
self.observed_at
}
}
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PhaseOrigin {
label: Option<Arc<str>>,
engine_version: Arc<str>,
}
impl PhaseOrigin {
pub fn new(engine_version: impl Into<Arc<str>>) -> Self {
Self {
label: None,
engine_version: engine_version.into(),
}
}
pub fn with_label(mut self, label: impl Into<Arc<str>>) -> Self {
self.label = Some(label.into());
self
}
pub fn label(&self) -> Option<&str> {
self.label.as_deref()
}
pub fn engine_version(&self) -> &str {
&self.engine_version
}
}
#[derive(Debug, Clone)]
pub struct PhaseParts {
pub kind: ScanKind,
pub started_at: SystemTime,
pub elapsed: Duration,
pub privilege: Option<Privilege>,
pub targets: TargetScope,
pub settings: ScanSettings,
pub failures: Vec<ScannerFailure>,
pub refusals: Vec<Refusal>,
pub unroutable: Vec<IpAddr>,
pub timed_out: Vec<IpAddr>,
pub icmp_rate_limited: Vec<IpAddr>,
pub reached_by_connect: Vec<IpRange>,
pub undecided: Vec<IpRange>,
pub liveness_skipped: Option<LivenessSkip>,
pub silent: Vec<IpRange>,
pub probes: Vec<ProbeStats>,
pub origin: Option<PhaseOrigin>,
pub attachments: Vec<Attachment>,
}
impl ScanPhase {
pub fn from_parts(parts: PhaseParts) -> Self {
Self {
kind: parts.kind,
started_at: parts.started_at,
elapsed: parts.elapsed,
privilege: parts.privilege,
targets: parts.targets,
settings: parts.settings,
failures: parts.failures,
refusals: parts.refusals,
unroutable: parts.unroutable,
timed_out: parts.timed_out,
icmp_rate_limited: parts.icmp_rate_limited,
reached_by_connect: parts.reached_by_connect,
undecided: parts.undecided,
liveness_skipped: parts.liveness_skipped,
silent: parts.silent,
probes: parts.probes,
origin: parts.origin,
attachments: parts.attachments,
}
}
pub fn attribute(&mut self, origin: PhaseOrigin) {
self.origin = Some(origin);
}
}
#[derive(Debug, Clone)]
pub struct ScanPhase {
kind: ScanKind,
started_at: SystemTime,
elapsed: Duration,
privilege: Option<Privilege>,
targets: TargetScope,
settings: ScanSettings,
failures: Vec<ScannerFailure>,
unroutable: Vec<IpAddr>,
refusals: Vec<Refusal>,
timed_out: Vec<IpAddr>,
icmp_rate_limited: Vec<IpAddr>,
reached_by_connect: Vec<IpRange>,
undecided: Vec<IpRange>,
liveness_skipped: Option<LivenessSkip>,
silent: Vec<IpRange>,
probes: Vec<ProbeStats>,
origin: Option<PhaseOrigin>,
attachments: Vec<Attachment>,
}
impl ScanPhase {
pub fn origin(&self) -> Option<&PhaseOrigin> {
self.origin.as_ref()
}
pub fn attachments(&self) -> &[Attachment] {
&self.attachments
}
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 privilege(&self) -> Option<Privilege> {
self.privilege
}
pub fn targets(&self) -> &TargetScope {
&self.targets
}
pub fn settings(&self) -> &ScanSettings {
&self.settings
}
pub fn unroutable(&self) -> &[IpAddr] {
&self.unroutable
}
pub fn timed_out(&self) -> &[IpAddr] {
&self.timed_out
}
pub fn icmp_rate_limited(&self) -> &[IpAddr] {
&self.icmp_rate_limited
}
pub fn reached_by_connect(&self) -> &[IpRange] {
&self.reached_by_connect
}
pub fn undecided(&self) -> &[IpRange] {
&self.undecided
}
pub fn liveness_skipped(&self) -> Option<LivenessSkip> {
self.liveness_skipped
}
pub fn silent(&self) -> &[IpRange] {
&self.silent
}
pub fn failures(&self) -> &[ScannerFailure] {
&self.failures
}
pub fn refusals(&self) -> &[Refusal] {
&self.refusals
}
pub fn probe_stats(&self) -> &[ProbeStats] {
&self.probes
}
}
#[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<ScopedIp, Host>,
}
impl ScanReport {
pub fn new(phase: ScanPhase, hosts: impl IntoIterator<Item = Host>) -> Self {
let mut report = Self {
engine_version: Cow::Borrowed(ENGINE_VERSION),
phases: vec![phase],
hosts: index(hosts),
};
report.forget_the_silent();
report
}
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 mut report = Self {
engine_version,
phases,
hosts: index(hosts),
};
report.forget_the_silent();
report
}
pub fn engine_version(&self) -> &str {
&self.engine_version
}
pub fn phases(&self) -> &[ScanPhase] {
&self.phases
}
pub fn is_merged(&self) -> bool {
self.phases.iter().any(|phase| phase.origin().is_some())
}
pub fn hosts(&self) -> impl Iterator<Item = &Host> {
self.hosts.values()
}
pub(crate) fn hosts_mut(&mut self) -> impl Iterator<Item = &mut Host> {
self.hosts.values_mut()
}
pub fn host_count(&self) -> usize {
self.hosts.len()
}
pub fn host(&self, ip: &IpAddr) -> Option<&Host> {
self.hosts
.range(ScopedIp::unscoped(*ip)..)
.next()
.filter(|(key, _)| key.addr() == *ip)
.map(|(_, host)| host)
}
pub fn host_scoped(&self, ip: &ScopedIp) -> Option<&Host> {
self.hosts.get(ip)
}
pub fn into_phases(self) -> Vec<ScanPhase> {
self.phases
}
pub fn started_at(&self) -> SystemTime {
self.phases
.iter()
.map(ScanPhase::started_at)
.min()
.unwrap_or_else(SystemTime::now)
}
pub fn finished_at(&self) -> SystemTime {
self.phases
.iter()
.map(|phase| {
phase
.started_at()
.checked_add(phase.elapsed())
.unwrap_or_else(|| phase.started_at())
})
.max()
.unwrap_or_else(SystemTime::now)
}
pub fn observed_at(&self) -> SystemTime {
if !self.phases.is_empty() {
return self.finished_at();
}
self.hosts()
.map(Host::last_seen)
.max()
.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 refusals(&self) -> impl Iterator<Item = &Refusal> {
self.phases.iter().flat_map(ScanPhase::refusals)
}
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() || !phase.refusals.is_empty())
|| !self.timed_out().is_empty()
|| !self.undecided().is_empty()
|| self.left_ports_unasked()
}
pub fn undecided(&self) -> Vec<IpRange> {
let mut open = IpSet::new();
let mut decided = IpSet::new();
for phase in &self.phases {
let mut left = IpSet::new();
for range in &phase.undecided {
left.insert_range(*range);
}
let mut walked = IpSet::new();
for range in phase.targets.ranges() {
walked.insert_range(*range);
}
walked.subtract(&left);
append(&mut open, &left);
append(&mut decided, &walked);
for address in &phase.unroutable {
decided.insert(*address);
}
}
if open.is_empty() {
return Vec::new();
}
for host in self.hosts.values().filter(|host| host.is_alive()) {
for address in host.ips() {
decided.insert(*address);
}
}
open.subtract(&decided);
open.canonicalize();
let v4 = open.v4().iter().copied().map(IpRange::V4);
let v6 = open.v6().iter().copied().map(IpRange::V6);
v4.chain(v6).collect()
}
pub fn timed_out(&self) -> Vec<IpAddr> {
let walked: Vec<IpSet> = self
.phases
.iter()
.map(|phase| {
let mut walked = IpSet::new();
for range in phase.targets.ranges() {
walked.insert_range(*range);
}
walked.canonicalize();
walked
})
.collect();
let mut left: Vec<IpAddr> = self
.phases
.iter()
.flat_map(|phase| phase.timed_out.iter().map(move |ip| (phase.kind, *ip)))
.filter(|(kind, ip)| {
!self.phases.iter().zip(&walked).any(|(other, walked)| {
other.kind == *kind && walked.contains(ip) && !other.timed_out.contains(ip)
})
})
.map(|(_, ip)| ip)
.collect();
left.sort_unstable();
left.dedup();
left
}
pub(crate) fn left_ports_unasked(&self) -> bool {
let unroutable: std::collections::BTreeSet<&IpAddr> = self
.phases
.iter()
.flat_map(|phase| phase.unroutable.iter())
.collect();
self.hosts.values().any(|host| {
host.ips().iter().any(|ip| !unroutable.contains(ip))
&& host
.ports()
.any(|port| port.state() == crate::model::port::PortState::Unasked)
})
}
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 (key, host) in other.hosts {
match self.hosts.get_mut(&key) {
Some(existing) => existing.merge(host),
None => {
self.hosts.insert(key, host);
}
}
}
self.forget_the_silent();
}
fn forget_the_silent(&mut self) {
let mut silent = IpSet::new();
for phase in &self.phases {
for range in &phase.silent {
silent.insert_range(*range);
}
if phase.kind == ScanKind::PortScan {
for range in &phase.undecided {
silent.insert_range(*range);
}
}
}
if silent.is_empty() {
return;
}
silent.canonicalize();
self.hosts.retain(|_, host| {
host.status() != HostStatus::Unknown || !host.ips().iter().any(|ip| silent.contains(ip))
});
}
}
fn append(into: &mut IpSet, from: &IpSet) {
for range in from.v4() {
into.push_v4_range(*range);
}
for range in from.v6() {
into.push_v6_range(*range);
}
}
fn index(hosts: impl IntoIterator<Item = Host>) -> BTreeMap<ScopedIp, Host> {
let mut indexed: BTreeMap<ScopedIp, Host> = BTreeMap::new();
for host in hosts {
match indexed.get_mut(&host.scoped_ip()) {
Some(existing) => existing.merge(host),
None => {
indexed.insert(host.scoped_ip(), host);
}
}
}
indexed
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScannerKind {
Local,
Passive,
Routed,
RoutedSctp,
SynPort,
TcpPort,
Connect,
ConnectUdp,
UdpPort,
SctpPort,
OsEcho,
OsSeries,
OsSnmp,
Idle,
Composite,
Service,
Detection,
Journal,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WindowSummary {
pub capacity: usize,
pub peak: usize,
pub reductions: u32,
pub adaptive: bool,
pub at_floor: bool,
}
impl ScannerKind {
pub const ALL: [ScannerKind; 18] = [
Self::Local,
Self::Passive,
Self::Routed,
Self::RoutedSctp,
Self::SynPort,
Self::TcpPort,
Self::Connect,
Self::ConnectUdp,
Self::UdpPort,
Self::SctpPort,
Self::OsEcho,
Self::OsSeries,
Self::OsSnmp,
Self::Idle,
Self::Composite,
Self::Service,
Self::Detection,
Self::Journal,
];
pub const fn for_raw_tcp(technique: TcpScanTechnique) -> Self {
match technique {
TcpScanTechnique::Syn => Self::SynPort,
_ => Self::TcpPort,
}
}
}
impl fmt::Display for WindowSummary {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if !self.adaptive {
return write!(f, "fixed {}", self.capacity);
}
write!(
f,
"{} (peak {}, cut {}x){}",
self.capacity,
self.peak,
self.reductions,
if self.at_floor { " at floor" } else { "" }
)
}
}
#[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("192.0.2.0/30", "80,443"));
same.add_unit(unit("198.51.100.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("192.0.2.0/30", "80,443"));
differing.add_unit(unit("198.51.100.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(&["192.0.2.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(203, 0, 113, last))
}
fn phase(kind: ScanKind) -> ScanPhase {
ScanPhase {
attachments: Vec::new(),
kind,
started_at: SystemTime::UNIX_EPOCH,
elapsed: Duration::from_millis(500),
privilege: Some(Privilege::Raw),
targets: TargetScope::from_ip_set(&mut IpSet::new(), &Exclusions::none()),
settings: ScanSettings::from(&ZondConfig::default()),
failures: Vec::new(),
refusals: Vec::new(),
unroutable: Vec::new(),
timed_out: Vec::new(),
icmp_rate_limited: Vec::new(),
reached_by_connect: Vec::new(),
undecided: Vec::new(),
liveness_skipped: None,
silent: Vec::new(),
probes: Vec::new(),
origin: None,
}
}
fn standing_in(silent: &[u8]) -> ScanPhase {
let mut phase = phase(ScanKind::PortScan);
phase.liveness_skipped = Some(LivenessSkip::PortsNoDearer);
phase.silent = silent
.iter()
.map(|&last| {
let v4 = Ipv4Addr::new(203, 0, 113, last);
IpRange::V4(Ipv4Range::new(v4, v4).expect("a range"))
})
.collect();
phase
}
fn unheard(last: u8) -> Host {
let mut host = Host::new(ip(last));
host.add_port(Port::new(443, Protocol::Tcp, PortState::Filtered));
host
}
#[test]
fn a_host_nothing_answered_at_an_undecided_address_is_not_a_host() {
let mut ports = standing_in(&[]);
let mut sweep = phase(ScanKind::Discovery);
for (phase, last) in [(&mut ports, 5), (&mut sweep, 9)] {
let v4 = Ipv4Addr::new(203, 0, 113, last);
phase
.undecided
.push(IpRange::V4(Ipv4Range::new(v4, v4).expect("a range")));
}
let report = ScanReport::new(ports, [unheard(5)]);
assert!(
report.host(&ip(5)).is_none(),
"an undecided address is no host"
);
let report = ScanReport::new(sweep, [unheard(9)]);
assert!(report.host(&ip(9)).is_some());
}
#[test]
fn a_host_nothing_answered_at_a_silent_address_is_not_a_host() {
let mut up = Host::new(ip(1));
up.set_status(HostStatus::Up);
let report = ScanReport::new(standing_in(&[5]), [up, unheard(5), unheard(9)]);
assert!(report.host(&ip(5)).is_none(), "a silent address is no host");
assert!(
report.host(&ip(1)).is_some(),
"a host that answered is kept"
);
assert!(
report.host(&ip(9)).is_some(),
"an address the phase does not name silent keeps its record"
);
}
#[test]
fn a_journalled_record_at_a_silent_address_is_dropped_on_read_back() {
let resumed = ScanReport::from_phases(vec![standing_in(&[5])], [unheard(5)]);
assert!(resumed.host(&ip(5)).is_none());
let recorded = ScanReport::recorded("0.17.0", vec![standing_in(&[5])], [unheard(5)]);
assert!(recorded.host(&ip(5)).is_none());
}
#[test]
fn a_host_heard_elsewhere_survives_a_phase_that_found_it_silent() {
let mut up = Host::new(ip(5));
up.set_status(HostStatus::Up);
let mut earlier = ScanReport::new(phase(ScanKind::Discovery), [up]);
earlier.merge(ScanReport::new(standing_in(&[5]), [unheard(5)]));
assert!(
earlier
.host(&ip(5))
.is_some_and(|host| host.status() == HostStatus::Up),
"the merge kept the host an earlier phase heard"
);
}
#[test]
fn a_phase_claiming_more_time_than_a_clock_holds_does_not_end_the_process() {
let mut absurd = phase(ScanKind::PortScan);
absurd.started_at = SystemTime::UNIX_EPOCH;
absurd.elapsed = Duration::from_secs(u64::MAX);
let ordinary = phase(ScanKind::Discovery);
let ends_at = ordinary.started_at + ordinary.elapsed;
let report = ScanReport::recorded("zond", vec![absurd, ordinary], Vec::new());
assert_eq!(
report.finished_at(),
ends_at,
"the phase that could be placed is the one that should place the report"
);
assert!(crate::diff::ScanDiff::between(&report, &report).is_empty());
}
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("203.0.113.0/24");
ips.insert_range(IpRange::from_str("203.0.113.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("192.0.2.1-192.0.2.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_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());
assert!(!StopReason::TimedOut.is_complete());
}
#[test]
fn a_run_that_left_a_host_early_is_partial() {
let mut left = phase(ScanKind::PortScan);
left.timed_out.push(ip(1));
assert!(ScanReport::new(left, [Host::new(ip(1))]).is_partial());
}
fn walked(at: u64, walked: &str, left: &[IpAddr]) -> ScanPhase {
let mut ips: IpSet = walked.parse().expect("a range");
ScanPhase {
started_at: SystemTime::UNIX_EPOCH + Duration::from_secs(at),
targets: TargetScope::from_ip_set(&mut ips, &Exclusions::none()),
timed_out: left.to_vec(),
..phase(ScanKind::PortScan)
}
}
#[test]
fn a_host_a_later_sitting_finished_is_not_left_early() {
let mut report = ScanReport::new(walked(1, "203.0.113.1", &[ip(1)]), []);
report.merge(ScanReport::new(walked(2, "203.0.113.1", &[]), []));
assert!(report.timed_out().is_empty());
assert!(!report.is_partial());
let mut again = ScanReport::new(walked(1, "203.0.113.1", &[ip(1)]), []);
again.merge(ScanReport::new(walked(2, "203.0.113.1", &[ip(1)]), []));
assert_eq!(again.timed_out(), [ip(1)], "left early both times");
assert!(again.is_partial());
}
#[test]
fn every_recorded_shortfall_is_partial_and_an_unreachable_address_is_not() {
let refused = {
let mut phase = phase(ScanKind::Discovery);
phase
.refusals
.push(Refusal::new(ScannerKind::Connect, "too large to sweep"));
ScanReport::new(phase, [])
};
assert!(
refused.is_partial(),
"ground declined is ground not covered"
);
let undecided = {
let mut phase = phase(ScanKind::Discovery);
phase.undecided.push(IpRange::V4(
Ipv4Range::new(Ipv4Addr::new(192, 0, 2, 4), Ipv4Addr::new(192, 0, 2, 7))
.expect("a range"),
));
ScanReport::new(phase, [])
};
assert!(undecided.is_partial(), "an address nobody decided");
let mut unasked = Host::new(ip(1));
unasked.add_port(Port::new(443, Protocol::Tcp, PortState::Unasked));
let cut_short = ScanReport::new(phase(ScanKind::PortScan), [unasked.clone()]);
assert!(cut_short.is_partial(), "a port named and never asked");
let mut no_route = phase(ScanKind::PortScan);
no_route.unroutable.push(ip(1));
let unreachable = ScanReport::new(no_route, [unasked]);
assert!(
!unreachable.is_partial(),
"a port unasked because nothing could reach its address was never coverable"
);
}
#[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("192.0.2.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(192, 0, 2, 5), Ipv4Addr::new(192, 0, 2, 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(192, 0, 2, 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);
}
}