use std::net::IpAddr;
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
use tokio::task::JoinHandle;
use crate::config::{OsDetection, ProbeTuning, ServiceDetection, ZondConfig};
use crate::fingerprint::os;
use crate::journal::cursor::Checkpoint;
use crate::model::ip::range::{IpRange, Ipv4Range, Ipv6Range};
use crate::model::ip::scoped::Zone;
use crate::model::{
ip::set::IpSet,
port::{Discovery as PortDiscovery, Port, PortState, Protocol, ScanResponse},
target::{PlannedTarget, TargetMap, TargetSet},
technique::TcpScanTechnique,
};
use crate::scanner::pacing::limits::CONNECT_CONCURRENCY;
use crate::scanner::pool::ProbePool;
use crate::scanner::resolver::HostnameResolver;
use crate::scanner::session::{ScanContext, ScannerKind};
use crate::scanner::strategy::local::Scope;
use crate::scanner::strategy::{HostScanner, PortScanner, StrategyError};
use crate::scanner::{pacing, plan, resolver, strategy};
use crate::system::interface;
use crate::system::privilege::is_elevated;
use crate::{error, info, success, warn};
pub(super) fn walkable(targets: IpSet, ctx: &ScanContext) -> IpSet {
let refused: Vec<_> = targets
.v6()
.iter()
.filter(|range| !interface::is_enumerable(range))
.copied()
.collect();
if refused.is_empty() {
return targets;
}
let mut kept = IpSet::new();
for range in targets.v4() {
kept.push_v4_range(*range);
}
for range in targets.v6() {
if interface::is_enumerable(range) {
kept.push_v6_range(*range);
}
}
kept.canonicalize();
for range in &refused {
let refusal = plan::Refusal::unprivileged_range_not_enumerable(range);
ctx.record_failure(refusal.scanner, refusal.reason);
}
kept
}
#[derive(Clone, Copy)]
pub(super) struct ScanCapabilities {
pub(super) privileged: bool,
dns: bool,
}
impl ScanCapabilities {
pub(super) fn resolve(cfg: &ZondConfig) -> Self {
let privileged = is_elevated();
if privileged {
success!("raw sockets available: probing with ARP, ICMPv6 and SYN");
} else {
warn!("no raw sockets: probing with TCP connect only");
}
Self {
privileged,
dns: !cfg.no_dns,
}
}
}
pub(super) struct Enrichment {
scanners: Vec<(ScannerKind, JoinHandle<Result<(), StrategyError>>)>,
resolver: Option<JoinHandle<Option<HostnameResolver>>>,
}
impl Enrichment {
pub(super) async fn spawn(
plan: plan::DiscoveryPlan,
ctx: &ScanContext,
caps: ScanCapabilities,
tuning: ProbeTuning,
) -> Self {
let (dns_tx, resolver) = if caps.dns {
let (tx, rx) = mpsc::unbounded_channel();
(Some(tx), Some(spawn_resolver(rx).await))
} else {
info!("DNS resolution skipped by user flag");
(None, None)
};
let scanners = spawn_explorers(plan, ctx, dns_tx, tuning).await;
Self { scanners, resolver }
}
async fn finish(self, ctx: &ScanContext) {
for (kind, handle) in self.scanners {
match handle.await {
Ok(Ok(())) => {}
Ok(Err(e)) => ctx.record_failure(kind, e.to_string()),
Err(e) => ctx.record_failure(kind, format!("panicked: {e}")),
}
}
if let Some(task) = self.resolver
&& let Ok(Some(mut resolver)) = task.await
{
resolver.resolve_hosts(ctx);
}
}
}
pub(super) async fn spawn_explorers(
plan: plan::DiscoveryPlan,
ctx: &ScanContext,
dns_tx: Option<UnboundedSender<IpAddr>>,
tuning: ProbeTuning,
) -> Vec<(ScannerKind, JoinHandle<Result<(), StrategyError>>)> {
for refusal in plan.refusals() {
ctx.record_failure(refusal.scanner, refusal.reason.clone());
}
let mut explorers: Vec<Box<dyn HostScanner>> = Vec::new();
for step in plan.into_steps() {
let kind = step.kind();
info!(
verbosity = 1,
"spawning {:?} scanner for {} target(s)",
kind,
step.target_count()
);
match step.into_scanner(ctx.clone(), dns_tx.clone(), tuning) {
Ok(scanner) => explorers.push(scanner),
Err(e) => ctx.record_failure(kind, e.to_string()),
}
}
explorers
.into_iter()
.map(|mut explorer| {
let kind = explorer.kind();
(
kind,
tokio::spawn(async move { explorer.discover_hosts().await }),
)
})
.collect()
}
pub(super) fn build_port_scanner(
plan: plan::PortScanPlan,
ctx: &ScanContext,
target_count: usize,
tuning: ProbeTuning,
) -> BuiltPortScan {
for refusal in plan.refusals() {
ctx.record_failure(refusal.scanner, refusal.reason.clone());
}
let technique = plan.technique();
let intended: Vec<Protocol> = [Protocol::Tcp, Protocol::Udp]
.into_iter()
.filter(|protocol| plan.covers(*protocol))
.collect();
let mut scanners: Vec<Box<dyn PortScanner>> = Vec::new();
let mut opened = Vec::new();
for step in plan.into_steps() {
match step.into_scanner(ctx.clone(), target_count, tuning) {
Ok(scanner) => {
opened.push(step);
scanners.push(scanner);
}
Err(e) => ctx.record_failure(step.kind(), e.to_string()),
}
}
BuiltPortScan {
scanner: Box::new(strategy::composite::CompositePortScanner::new(
ensure_coverage(
scanners,
ctx,
technique,
&intended,
tuning.service_detection,
),
ctx.clone(),
)),
opened,
}
}
pub(super) fn ensure_coverage(
mut scanners: Vec<Box<dyn PortScanner>>,
ctx: &ScanContext,
technique: TcpScanTechnique,
intended: &[Protocol],
detection: ServiceDetection,
) -> Vec<Box<dyn PortScanner>> {
let covered: Vec<Protocol> = scanners
.iter()
.flat_map(|scanner| scanner.supported_protocols())
.collect();
let missing = |protocol: Protocol| intended.contains(&protocol) && !covered.contains(&protocol);
if missing(Protocol::Tcp) {
if technique.finds_open_ports() {
scanners.push(Box::new(strategy::connect::ConnectPortScanner::new(
ctx.clone(),
pacing::limits::CONNECT_CONCURRENCY,
detection,
)));
} else {
let refusal = plan::Refusal::technique_needs_raw_sockets(technique);
ctx.record_failure(refusal.scanner, refusal.reason);
}
}
if missing(Protocol::Udp) {
scanners.push(Box::new(strategy::connect::ConnectUdpPortScanner::new(
ctx.clone(),
pacing::limits::CONNECT_CONCURRENCY,
)));
}
scanners
}
pub(super) struct BuiltPortScan {
pub(super) scanner: Box<dyn PortScanner>,
opened: Vec<plan::PortScanStep>,
}
impl BuiltPortScan {
pub(super) fn opened_raw(&self) -> bool {
self.opened.iter().any(plan::PortScanStep::is_raw)
}
}
pub(super) async fn run_port_scan(
mut scanner: Box<dyn PortScanner>,
rx: mpsc::Receiver<PlannedTarget>,
ctx: &ScanContext,
) {
let kind = scanner.kind();
match scanner.scan(rx).await {
Ok(()) => {
if !ctx.handle.should_stop() {
scanner.detect_services(ctx).await;
}
}
Err(e) => ctx.record_failure(kind, e.to_string()),
}
}
pub(super) async fn finish_enrichment(
enrichment: Option<Enrichment>,
caps: ScanCapabilities,
ctx: &ScanContext,
) {
match enrichment {
Some(enrichment) => enrichment.finish(ctx).await,
None if caps.dns => resolver::resolve_hosts_async(ctx).await,
None => {}
}
}
pub(super) fn run_passive_os_identification(ctx: &ScanContext, os_detection: OsDetection) {
if matches!(os_detection, OsDetection::Off) {
return;
}
let mut named = 0usize;
for ip in ctx.host_addresses() {
let mut identified = false;
ctx.write_host(ip, |host| {
identified = os::identify(host, []);
identified
});
if identified {
named += 1;
}
}
if named > 0 {
info!(
verbosity = 1,
"named {named} host(s) from what the sweep already knew"
);
}
}
pub(super) async fn run_active_os_series(
ctx: &ScanContext,
os_detection: OsDetection,
tuning: ProbeTuning,
) {
if !os_detection.is_active() {
return;
}
let thorough = matches!(os_detection, OsDetection::Aggressive);
let targets: Vec<strategy::routed::SeriesTarget> = ctx
.host_addresses()
.into_iter()
.filter_map(|ip| {
ctx.read_host(&ip, |host| {
if !host.status().is_up() {
return None;
}
let settled = host.os().is_some_and(|os| os.accuracy() >= 85);
if settled && !thorough {
return None;
}
strategy::routed::SeriesTarget::for_host(ip, host)
})
.flatten()
})
.collect();
if targets.is_empty() {
return;
}
let samples = if thorough {
strategy::routed::AGGRESSIVE_SAMPLES
} else {
strategy::routed::ACTIVE_SAMPLES
};
info!("following {} host(s) over {samples} samples", targets.len());
match strategy::routed::OsSeriesScanner::new(ctx.clone(), targets, samples, tuning.send_mode) {
Ok(mut scanner) => {
if let Err(e) = scanner.discover_hosts().await {
ctx.record_failure(ScannerKind::OsSeries, e.to_string());
}
}
Err(e) => ctx.record_failure(
ScannerKind::OsSeries,
format!("the active series probe could not open its transport: {e}"),
),
}
}
pub(super) async fn run_active_os_snmp(ctx: &ScanContext, os_detection: OsDetection) {
if !os_detection.is_active() {
return;
}
let targets: Vec<crate::model::ip::scoped::ScopedIp> = ctx
.host_addresses()
.into_iter()
.filter_map(|ip| {
ctx.read_host(&ip, |host| {
let known = host.os().is_some_and(|os| os.kernel().is_some());
(host.status().is_up() && !known).then(|| host.scoped_ip())
})
.flatten()
})
.collect();
if targets.is_empty() {
return;
}
info!("asking {} host(s) for their kernel", targets.len());
let mut named = 0usize;
let mut pool = ProbePool::new(
CONNECT_CONCURRENCY,
ctx.clone(),
ScannerKind::OsSnmp,
|found: Option<(IpAddr, Port, Vec<os::OsEvidence>)>, _audit| {
if let Some((ip, port, evidence)) = found {
ctx.update_host(ip, |host| {
host.add_port(port);
if os::identify(host, evidence) {
named += 1;
}
});
}
},
);
for target in targets {
if ctx.handle.should_stop() {
break;
}
pool.admit(ask_for_kernel(target)).await;
}
pool.drain().await;
if named > 0 {
info!(verbosity = 1, "named {named} host(s) by SNMP");
}
}
const SNMP_PORT: u16 = 161;
async fn ask_for_kernel(
target: crate::model::ip::scoped::ScopedIp,
) -> Option<(IpAddr, Port, Vec<os::OsEvidence>)> {
let addr = target.to_socket_addr(SNMP_PORT)?;
let port = crate::fingerprint::baseline_port(SNMP_PORT, Protocol::Udp, PortState::Open);
let (port, evidence) = crate::fingerprint::fingerprint_udp_detailed(addr, port).await?;
let port = port.with_discovery(PortDiscovery::new(ScanResponse::UdpResponse));
Some((target.addr(), port, evidence))
}
pub(super) async fn run_traceroute(ctx: &ScanContext, cfg: &crate::config::ZondConfig) {
if !cfg.traceroute {
return;
}
let mut alive: Vec<IpAddr> = ctx
.host_addresses()
.into_iter()
.filter(|ip| {
ctx.read_host(ip, |host| host.status().is_up())
.unwrap_or(false)
})
.collect();
alive.sort_unstable();
alive.dedup();
if alive.is_empty() {
return;
}
info!("measuring the route to {} host(s)", alive.len());
strategy::routed::traceroute::trace(ctx, alive).await;
}
pub(super) async fn run_active_os_probe(
ctx: &ScanContext,
os_detection: crate::config::OsDetection,
tuning: ProbeTuning,
) {
if !os_detection.is_active() {
return;
}
let mut unnamed: Vec<IpAddr> = ctx
.host_addresses()
.into_iter()
.filter(|ip| {
ctx.read_host(ip, |host| {
host.status().is_up() && host.os().is_none_or(|os| os.accuracy() < 85)
})
.unwrap_or(false)
})
.collect();
unnamed.sort_unstable();
unnamed.dedup();
if unnamed.is_empty() {
return;
}
info!(
"probing {} host(s) the passive sources could not name, by echo",
unnamed.len()
);
match strategy::routed::OsEchoScanner::new(ctx.clone(), unnamed, tuning) {
Ok(mut scanner) => {
if let Err(e) = scanner.discover_hosts().await {
ctx.record_failure(ScannerKind::OsEcho, e.to_string());
}
}
Err(e) => ctx.record_failure(
ScannerKind::OsEcho,
format!("the active echo probe could not open its transport: {e}"),
),
}
}
pub(super) fn target_ips(target_map: &TargetMap) -> IpSet {
let mut ips = IpSet::new();
for unit in &target_map.units {
for range in unit.ips().v4() {
ips.insert_range(IpRange::V4(*range));
}
for range in unit.ips().v6() {
ips.insert_range(IpRange::V6(*range));
}
}
ips.canonicalize();
ips
}
pub(super) async fn spawn_resolver(
dns_rx: UnboundedReceiver<IpAddr>,
) -> JoinHandle<Option<HostnameResolver>> {
tokio::spawn(async move {
match HostnameResolver::new(dns_rx) {
Ok(resolver) => {
success!("successfully initialized hostname resolver");
Some(resolver.run().await)
}
Err(e) => {
error!("resolver failed to start: {e}");
None
}
}
})
}
pub(super) async fn run_port_phase(
target_map: TargetMap,
live: Option<IpSet>,
ctx: &ScanContext,
caps: ScanCapabilities,
cfg: &ZondConfig,
settled: Checkpoint,
) {
if target_map.is_empty() {
return;
}
let target_count = target_map.gross_targets().unwrap_or(0) as usize;
let built = build_port_scanner(
super::plan::PortScanPlan::build(cfg, caps.privileged),
ctx,
target_count,
cfg.probe_tuning(),
);
let enrichment = if cfg.assume_up && built.opened_raw() {
let plan = super::plan::DiscoveryPlan::build(target_ips(&target_map), Scope::Targeted);
Some(Enrichment::spawn(plan, ctx, caps, cfg.probe_tuning()).await)
} else {
None
};
let mut dispatcher = super::dispatcher::Dispatcher::new(target_map).resuming(settled);
if let Some(live) = live {
dispatcher = dispatcher.only_live(live);
}
let rx = dispatcher.run_shuffled(ctx);
run_port_scan(built.scanner, rx, ctx).await;
finish_enrichment(enrichment, caps, ctx).await;
run_passive_os_identification(ctx, cfg.os_detection);
}
pub(super) fn probed_subset(target_map: &TargetMap, live: &IpSet) -> TargetMap {
let mut kept = TargetMap::new();
for unit in &target_map.units {
let mut ips = IpSet::new();
for ip in live.iter() {
if unit.ips().contains(&ip) {
push_single(&mut ips, ip, None);
}
}
ips.canonicalize();
if !ips.is_empty() {
kept.add_unit(TargetSet::new(ips, unit.ports().clone()));
}
}
kept
}
pub(super) fn live_addresses(ctx: &ScanContext) -> IpSet {
let mut live = IpSet::new();
for entry in ctx.store.iter() {
let host = entry.value();
if !host.is_alive() {
continue;
}
for ip in host.ips() {
push_single(&mut live, *ip, host.zone().and_then(Zone::index));
}
}
live.canonicalize();
live
}
fn push_single(set: &mut IpSet, ip: IpAddr, zone: Option<u32>) {
match ip {
IpAddr::V4(v4) => {
if let Ok(range) = Ipv4Range::new(v4, v4) {
set.push_v4_range(range);
}
}
IpAddr::V6(v6) => {
let zone = v6.is_unicast_link_local().then_some(zone).flatten();
if let Ok(range) = Ipv6Range::scoped(v6, v6, zone) {
set.push_v6_range(range);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::host::{Host, HostStatus};
use crate::scanner::report::ScannerFailure;
use crate::scanner::session::ScanSession;
use tokio::sync::mpsc;
struct StubScanner(Vec<Protocol>);
#[async_trait::async_trait]
impl PortScanner for StubScanner {
fn kind(&self) -> ScannerKind {
ScannerKind::SynPort
}
fn supported_protocols(&self) -> Vec<Protocol> {
self.0.clone()
}
async fn scan(
&mut self,
_targets: mpsc::Receiver<PlannedTarget>,
) -> Result<(), StrategyError> {
Ok(())
}
}
const BOTH: &[Protocol] = &[Protocol::Tcp, Protocol::Udp];
fn ip_set(exprs: &[&str]) -> IpSet {
crate::model::parse::ip::to_set(exprs, None, None).expect("hand-written targets parse")
}
#[test]
fn a_range_too_large_to_walk_is_refused_rather_than_started() {
let (_session, ctx) = ScanSession::new();
let kept = walkable(ip_set(&["2001:db8::/64"]), &ctx);
assert!(kept.is_empty(), "nothing here can be walked");
let failures = ctx.failures_snapshot();
assert_eq!(failures.len(), 1);
assert_eq!(failures[0].scanner(), ScannerKind::Connect);
assert!(
failures[0].reason().contains("18446744073709551616"),
"the refusal quotes the size it is refusing: {}",
failures[0].reason()
);
}
#[test]
fn the_walkable_part_of_a_mixed_set_survives() {
let (_session, ctx) = ScanSession::new();
let kept = walkable(
ip_set(&["2001:db8::/64", "10.0.0.0/30", "2001:db8:1::/126"]),
&ctx,
);
assert_eq!(kept.len(), 8);
assert_eq!(ctx.failures_snapshot().len(), 1);
}
#[test]
fn a_set_that_can_be_walked_is_left_alone_and_files_nothing() {
let (_session, ctx) = ScanSession::new();
let kept = walkable(ip_set(&["10.0.0.0/24", "2001:db8::/120"]), &ctx);
assert_eq!(kept.len(), 512);
assert!(ctx.failures_snapshot().is_empty());
}
#[test]
fn a_large_ipv4_range_is_not_this_functions_business() {
let (_session, ctx) = ScanSession::new();
let kept = walkable(ip_set(&["10.0.0.0/8"]), &ctx);
assert_eq!(kept.len(), 1 << 24);
assert!(ctx.failures_snapshot().is_empty());
}
fn covered(scanners: Vec<Box<dyn PortScanner>>) -> Vec<Protocol> {
let (_session, ctx) = ScanSession::new();
ensure_coverage(
scanners,
&ctx,
TcpScanTechnique::Syn,
BOTH,
ServiceDetection::default(),
)
.iter()
.flat_map(|scanner| scanner.supported_protocols())
.collect()
}
#[test]
fn a_refusal_the_plan_already_made_is_not_recorded_again() {
let cfg = ZondConfig {
tcp_technique: TcpScanTechnique::Fin,
..ZondConfig::default()
};
let (_session, ctx) = ScanSession::new();
let _built = build_port_scanner(
plan::PortScanPlan::build(&cfg, false),
&ctx,
0,
cfg.probe_tuning(),
);
let failures = ctx.take_failures();
assert_eq!(
failures.len(),
1,
"one cause, one entry: {:?}",
failures
.iter()
.map(ScannerFailure::reason)
.collect::<Vec<_>>()
);
assert_eq!(failures[0].scanner(), ScannerKind::TcpPort);
assert!(failures[0].reason().contains("fin"));
}
#[test]
fn a_raw_scan_earns_enrichment_whichever_technique_it_carries() {
for technique in TcpScanTechnique::ALL {
let built = BuiltPortScan {
scanner: Box::new(StubScanner(vec![Protocol::Tcp])),
opened: vec![plan::PortScanStep::RawTcp { technique }],
};
assert!(built.opened_raw(), "a raw {technique} scan is still raw");
}
let unprivileged = BuiltPortScan {
scanner: Box::new(StubScanner(vec![Protocol::Tcp])),
opened: vec![
plan::PortScanStep::ConnectTcp,
plan::PortScanStep::ConnectUdp,
],
};
assert!(
!unprivileged.opened_raw(),
"a connect scan has no MAC or round trip to offer"
);
}
#[test]
fn an_unprivileged_scan_covers_both_protocols() {
let protocols = covered(Vec::new());
assert!(protocols.contains(&Protocol::Tcp));
assert!(protocols.contains(&Protocol::Udp));
}
#[test]
fn a_protocol_without_a_privileged_scanner_still_gets_a_fallback() {
let protocols = covered(vec![Box::new(StubScanner(vec![Protocol::Udp]))]);
assert!(
protocols.contains(&Protocol::Tcp),
"TCP targets would be silently dropped"
);
assert!(protocols.contains(&Protocol::Udp));
}
#[test]
fn a_technique_the_fallback_cannot_express_is_reported_rather_than_substituted() {
let (_session, ctx) = ScanSession::new();
let scanners = ensure_coverage(
Vec::new(),
&ctx,
TcpScanTechnique::Fin,
BOTH,
ServiceDetection::default(),
);
let protocols: Vec<Protocol> = scanners
.iter()
.flat_map(|scanner| scanner.supported_protocols())
.collect();
assert!(
!protocols.contains(&Protocol::Tcp),
"a connect scan cannot send a FIN and must not pretend to"
);
let failures = ctx.take_failures();
assert_eq!(failures.len(), 1, "the caller has to be told");
assert_eq!(failures[0].scanner(), ScannerKind::TcpPort);
assert!(
failures[0].reason().contains("fin"),
"the failure has to name the technique: {}",
failures[0].reason()
);
}
#[test]
fn a_privileged_tcp_only_scan_falls_back_for_udp() {
let protocols = covered(vec![Box::new(StubScanner(vec![Protocol::Tcp]))]);
assert!(protocols.contains(&Protocol::Tcp));
assert!(
protocols.contains(&Protocol::Udp),
"UDP targets would be silently dropped"
);
}
#[test]
fn fully_covered_protocols_gain_no_fallback() {
let (_session, ctx) = ScanSession::new();
let scanners = ensure_coverage(
vec![
Box::new(StubScanner(vec![Protocol::Tcp])),
Box::new(StubScanner(vec![Protocol::Udp])),
],
&ctx,
TcpScanTechnique::Syn,
BOTH,
ServiceDetection::default(),
);
assert_eq!(scanners.len(), 2);
}
#[test]
fn a_protocol_the_plan_left_out_gains_no_fallback_and_no_second_refusal() {
let (_session, ctx) = ScanSession::new();
let scanners = ensure_coverage(
Vec::new(),
&ctx,
TcpScanTechnique::Fin,
&[Protocol::Udp],
ServiceDetection::default(),
);
let protocols: Vec<Protocol> = scanners
.iter()
.flat_map(|scanner| scanner.supported_protocols())
.collect();
assert_eq!(protocols, vec![Protocol::Udp]);
assert!(
ctx.take_failures().is_empty(),
"the plan already said why, in the same words"
);
}
#[test]
fn a_discovery_sweep_now_names_what_its_own_findings_imply() {
let (_session, ctx) = ScanSession::new();
let ip: IpAddr = "192.0.2.1".parse().expect("a valid address");
ctx.update_host(ip, |host| {
host.record_mac("a4:83:e7:00:00:01".parse().expect("an Apple address"));
host.set_hostname(Some("MacBook-Pro".to_owned()));
});
run_passive_os_identification(&ctx, OsDetection::Passive);
let named = ctx
.read_host(&ip, |host| host.os().map(ToString::to_string))
.expect("the host is in the store");
assert!(
named.as_deref().is_some_and(|os| os.contains("macOS")),
"{named:?}"
);
}
#[test]
fn detection_turned_off_identifies_nothing() {
let (_session, ctx) = ScanSession::new();
let ip: IpAddr = "192.0.2.1".parse().expect("a valid address");
ctx.update_host(ip, |host| {
host.record_mac("a4:83:e7:00:00:01".parse().expect("an Apple address"));
host.set_hostname(Some("MacBook-Pro".to_owned()));
});
run_passive_os_identification(&ctx, OsDetection::Off);
let named = ctx
.read_host(&ip, |host| host.os().is_some())
.expect("the host is in the store");
assert!(!named);
}
#[tokio::test(flavor = "current_thread")]
async fn the_kernel_probe_skips_only_hosts_whose_kernel_is_known() {
use crate::model::host::{HostStatus, OsFingerprint, StatusProtocol, StatusReason};
let up = |host: &mut crate::model::host::Host| {
host.record_evidence(
HostStatus::Up,
StatusReason::new(StatusProtocol::Arp, "an address resolution reply"),
);
};
let (_session, ctx) = ScanSession::new();
let named: IpAddr = "192.0.2.10".parse().expect("a valid address");
ctx.update_host(named, |host| {
up(host);
host.set_os(OsFingerprint::new("Debian", 84).with_family("Linux"));
});
let known: IpAddr = "192.0.2.11".parse().expect("a valid address");
ctx.update_host(known, |host| {
up(host);
host.set_os(
OsFingerprint::new("Debian", 84)
.with_family("Linux")
.with_kernel("6.1.0"),
);
});
run_active_os_snmp(&ctx, OsDetection::Active).await;
assert!(ctx.take_failures().is_empty(), "declining is not failing");
assert!(
ctx.read_host(&known, |host| host
.os()
.and_then(|os| os.kernel().map(ToOwned::to_owned)))
.flatten()
.as_deref()
== Some("6.1.0"),
"a kernel already on record is left as it was"
);
}
#[test]
fn a_port_the_kernel_probe_found_is_recorded_with_what_found_it() {
let port = crate::fingerprint::baseline_port(161, Protocol::Udp, PortState::Open)
.with_discovery(PortDiscovery::new(ScanResponse::UdpResponse));
assert_eq!(port.number(), 161);
assert_eq!(port.protocol(), Protocol::Udp);
assert_eq!(port.state(), PortState::Open);
assert_eq!(
port.discovery().map(|found| found.reason().clone()),
Some(ScanResponse::UdpResponse),
"a report has to be able to tell this from a port the scan established"
);
}
#[tokio::test(flavor = "current_thread")]
async fn the_kernel_probe_sends_nothing_below_the_active_level() {
for level in [OsDetection::Off, OsDetection::Passive] {
let (_session, ctx) = ScanSession::new();
let ip: IpAddr = "192.0.2.12".parse().expect("a valid address");
ctx.update_host(ip, |host| {
host.record_evidence(
crate::model::host::HostStatus::Up,
crate::model::host::StatusReason::new(
crate::model::host::StatusProtocol::Arp,
"an address resolution reply",
),
);
});
run_active_os_snmp(&ctx, level).await;
assert!(
ctx.take_probe_stats().is_empty(),
"{level} put a probe on the wire"
);
}
}
#[tokio::test(flavor = "current_thread")]
async fn the_series_probe_declines_when_no_host_has_a_port_to_ask_again() {
let (_session, ctx) = ScanSession::new();
let ip: IpAddr = "192.0.2.3".parse().expect("a valid address");
ctx.update_host(ip, |host| {
host.record_evidence(
crate::model::host::HostStatus::Up,
crate::model::host::StatusReason::new(
crate::model::host::StatusProtocol::Arp,
"an address resolution reply",
),
);
});
run_active_os_series(&ctx, OsDetection::Active, ProbeTuning::default()).await;
assert!(
ctx.take_failures().is_empty(),
"declining is not failing: there was nothing to follow, so nothing \
should have been opened"
);
assert!(
ctx.read_host(&ip, |host| host.os().is_none())
.expect("the host is in the store"),
"and nothing may be concluded from probes that were never sent"
);
}
#[tokio::test(flavor = "current_thread")]
async fn the_series_probe_sends_nothing_below_the_active_level() {
use crate::model::port::{Port, PortState, Protocol};
for level in [OsDetection::Off, OsDetection::Passive] {
let (_session, ctx) = ScanSession::new();
let ip: IpAddr = "192.0.2.4".parse().expect("a valid address");
ctx.update_host(ip, |host| {
host.add_port(Port::new(22, Protocol::Tcp, PortState::Open));
});
run_active_os_series(&ctx, level, ProbeTuning::default()).await;
assert!(
ctx.take_probe_stats().is_empty(),
"{level} put a scanner on the wire"
);
}
}
#[test]
fn a_host_with_nothing_to_go_on_is_left_as_it_was() {
let (_session, ctx) = ScanSession::new();
let ip: IpAddr = "192.0.2.2".parse().expect("a valid address");
ctx.update_host(ip, |host| {
host.record_mac(
"02:00:5e:00:53:04"
.parse()
.expect("a locally administered address"),
);
});
run_passive_os_identification(&ctx, OsDetection::Passive);
let named = ctx
.read_host(&ip, |host| host.os().is_some())
.expect("the host is in the store");
assert!(!named);
}
fn store_holding(hosts: Vec<Host>) -> (ScanSession, ScanContext) {
let (session, ctx) = ScanSession::new();
for host in hosts {
ctx.store.insert(host.primary_ip(), host);
}
(session, ctx)
}
fn host_at(ip: &str, status: HostStatus) -> Host {
let mut host = Host::new(ip.parse().expect("an address"));
host.set_status(status);
host
}
#[test]
fn a_host_that_did_not_answer_is_not_live() {
for status in [HostStatus::Down, HostStatus::Unknown] {
let (_session, ctx) = store_holding(vec![host_at("10.0.0.1", status)]);
assert!(
live_addresses(&ctx).is_empty(),
"{status:?} was treated as alive"
);
}
}
#[test]
fn a_host_that_answered_is_live() {
let (_session, ctx) = store_holding(vec![host_at("10.0.0.1", HostStatus::Up)]);
let live = live_addresses(&ctx);
assert!(live.contains(&"10.0.0.1".parse::<IpAddr>().expect("an address")));
assert_eq!(live.len(), 1);
}
#[test]
fn every_address_of_a_live_host_is_live() {
let mut host = host_at("2001:db8::1", HostStatus::Up);
host.add_ip("10.0.0.1".parse().expect("an address"));
let (_session, ctx) = store_holding(vec![host]);
let live = live_addresses(&ctx);
assert!(
live.contains(&"10.0.0.1".parse::<IpAddr>().expect("an address")),
"the targeted address was lost because the host was filed elsewhere"
);
assert!(live.contains(&"2001:db8::1".parse::<IpAddr>().expect("an address")));
}
#[test]
fn an_empty_store_has_nothing_live() {
let (_session, ctx) = store_holding(Vec::new());
assert!(live_addresses(&ctx).is_empty());
}
}