use std::net::IpAddr;
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
use tokio::task::JoinHandle;
use crate::config::{OsDetection, ProbeTuning, ZondConfig};
use crate::fingerprint::os;
use crate::model::ip::range::IpRange;
use crate::model::{
ip::set::IpSet,
port::Protocol,
target::{Target, TargetMap},
technique::TcpScanTechnique,
};
use crate::scanner::resolver::HostnameResolver;
use crate::scanner::session::{ScanContext, ScannerKind};
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!("Root privileges detected, raw socket scan enabled");
} else {
warn!("Root privileges missing, defaulting to unprivileged TCP scan");
}
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),
ctx.clone(),
)),
opened,
}
}
pub(super) fn ensure_coverage(
mut scanners: Vec<Box<dyn PortScanner>>,
ctx: &ScanContext,
technique: TcpScanTechnique,
intended: &[Protocol],
) -> 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,
)));
} 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<Target>,
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_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
}
}
})
}
#[cfg(test)]
mod tests {
use super::*;
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<Target>) -> 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)
.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);
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,
);
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]);
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);
}
#[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);
}
}