use std::pin::Pin;
use tokio::task::JoinHandle;
use crate::config::ZondConfig;
use std::net::IpAddr;
use crate::model::ip::range::{Ipv4Range, Ipv6Range};
use crate::model::ip::scoped::Zone;
use crate::model::{ip::set::IpSet, target::TargetMap, target::TargetSet};
use crate::scanner::orchestrator::{
Enrichment, ScanCapabilities, build_port_scanner, finish_enrichment, run_port_scan, target_ips,
};
use crate::scanner::report::{PhaseRecorder, ScanKind, ScanReport, TargetScope};
use crate::scanner::session::{ScanContext, ScanSession, ScannerKind};
use strategy::local::Scope;
pub mod handle;
pub mod report;
pub mod session;
pub mod pacing;
pub mod plan;
pub mod strategy;
pub mod audit;
pub mod dispatcher;
pub mod payload;
pub mod pool;
pub mod resolver;
pub mod service;
mod orchestrator;
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum ScanError {
#[error("scan task terminated abnormally")]
TaskFailed,
}
pub struct ScanTask {
handle: JoinHandle<ScanReport>,
}
impl ScanTask {
fn new(handle: JoinHandle<ScanReport>) -> Self {
Self { handle }
}
pub async fn join(self) -> Result<ScanReport, ScanError> {
self.handle.await.map_err(|_| ScanError::TaskFailed)
}
}
impl IntoFuture for ScanTask {
type Output = Result<ScanReport, ScanError>;
type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(self.join())
}
}
pub async fn discover(
mut targets: IpSet,
cfg: &ZondConfig,
) -> Result<(ScanSession, ScanTask), ScanError> {
let (session, ctx) = ScanSession::new();
let caps = ScanCapabilities::resolve(cfg);
let scope = TargetScope::from_ip_set(&mut targets);
let recorder = PhaseRecorder::start(ScanKind::Discovery, caps.privileged, scope, cfg);
let reach = if cfg.segment_sweep {
Scope::Sweep
} else {
Scope::Targeted
};
let cfg = cfg.clone();
let handle = tokio::spawn(async move {
run_discovery(targets, reach, caps, &cfg, &ctx).await;
recorder.finish(&ctx)
});
Ok((session, ScanTask::new(handle)))
}
async fn run_discovery(
targets: IpSet,
reach: Scope,
caps: ScanCapabilities,
cfg: &ZondConfig,
ctx: &ScanContext,
) {
if caps.privileged {
let plan = plan::DiscoveryPlan::build(targets, reach);
let enrichment = Enrichment::spawn(plan, ctx, caps, cfg.probe_tuning()).await;
finish_enrichment(Some(enrichment), caps, ctx).await;
} else {
let targets = orchestrator::walkable(targets, ctx);
if let Err(error) = strategy::connect::discover(targets, ctx.clone()).await {
ctx.record_failure(ScannerKind::Connect, error.to_string());
}
finish_enrichment(None, caps, ctx).await;
}
orchestrator::run_passive_os_identification(ctx, cfg.os_detection);
}
pub async fn scan(
target_map: TargetMap,
cfg: &ZondConfig,
) -> Result<(ScanSession, ScanTask), ScanError> {
let (session, ctx) = ScanSession::new();
let caps = ScanCapabilities::resolve(cfg);
let cfg = cfg.clone();
let handle = tokio::spawn(async move {
let (liveness, target_map) = if cfg.assume_up {
(None, target_map)
} else {
let mut ips = target_ips(&target_map);
let scope = TargetScope::from_ip_set(&mut ips);
let recorder = PhaseRecorder::start(ScanKind::Discovery, caps.privileged, scope, &cfg);
run_discovery(ips, Scope::Targeted, caps, &cfg, &ctx).await;
let report = recorder.finish(&ctx);
let live = only_live(&target_map, &ctx);
(Some(report), live)
};
let scope = TargetScope::from_target_map(&target_map);
let recorder = PhaseRecorder::start(ScanKind::PortScan, caps.privileged, scope, &cfg);
run_port_phase(target_map, &ctx, caps, &cfg).await;
orchestrator::run_active_os_probe(&ctx, cfg.os_detection, cfg.probe_tuning()).await;
let report = recorder.finish(&ctx);
match liveness {
Some(mut first) => {
first.merge(report);
first
}
None => report,
}
});
Ok((session, ScanTask::new(handle)))
}
async fn run_port_phase(
target_map: TargetMap,
ctx: &ScanContext,
caps: ScanCapabilities,
cfg: &ZondConfig,
) {
if target_map.is_empty() {
return;
}
let target_count = target_map.gross_targets().unwrap_or(0) as usize;
let built = build_port_scanner(
plan::PortScanPlan::build(cfg, caps.privileged),
ctx,
target_count,
cfg.probe_tuning(),
);
let enrichment = if cfg.assume_up && built.opened_raw() {
let plan = plan::DiscoveryPlan::build(target_ips(&target_map), Scope::Targeted);
Some(Enrichment::spawn(plan, ctx, caps, cfg.probe_tuning()).await)
} else {
None
};
let dispatcher = dispatcher::Dispatcher::new(target_map);
let rx = dispatcher.run_shuffled(&ctx.handle);
run_port_scan(built.scanner, rx, ctx).await;
finish_enrichment(enrichment, caps, ctx).await;
orchestrator::run_passive_os_identification(ctx, cfg.os_detection);
}
fn only_live(target_map: &TargetMap, ctx: &ScanContext) -> TargetMap {
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();
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
}
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::model::port::PortSet;
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
}
fn unit(ip: &str, ports: &str) -> TargetSet {
let mut ips = IpSet::new();
ips.insert(ip.parse().expect("an address"));
TargetSet::new(ips, PortSet::try_from(ports).expect("a port spec"))
}
fn map_of(units: Vec<TargetSet>) -> TargetMap {
let mut map = TargetMap::new();
for unit in units {
map.add_unit(unit);
}
map
}
#[test]
fn a_host_that_did_not_answer_is_dropped() {
for status in [HostStatus::Down, HostStatus::Unknown] {
let (_session, ctx) = store_holding(vec![host_at("10.0.0.1", status)]);
let kept = only_live(&map_of(vec![unit("10.0.0.1", "22")]), &ctx);
assert!(kept.is_empty(), "{status:?} was treated as alive");
}
}
#[test]
fn a_host_that_answered_is_kept() {
let (_session, ctx) = store_holding(vec![host_at("10.0.0.1", HostStatus::Up)]);
let kept = only_live(&map_of(vec![unit("10.0.0.1", "22")]), &ctx);
assert_eq!(kept.gross_ips().expect("countable"), 1);
assert_eq!(kept.gross_targets().expect("countable"), 1);
}
#[test]
fn a_host_filed_under_another_address_keeps_the_one_that_was_targeted() {
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 kept = only_live(&map_of(vec![unit("10.0.0.1", "22")]), &ctx);
assert!(
!kept.is_empty(),
"the targeted address was dropped because the host was filed elsewhere"
);
}
#[test]
fn each_unit_keeps_the_ports_it_was_given() {
let (_session, ctx) = store_holding(vec![host_at("10.0.0.1", HostStatus::Up)]);
let kept = only_live(
&map_of(vec![unit("10.0.0.1", "8080"), unit("10.0.0.1", "22,443")]),
&ctx,
);
let ports: Vec<usize> = kept.units.iter().map(|unit| unit.ports().len()).collect();
assert_eq!(ports, vec![1, 2], "a unit lost or gained ports at the gate");
}
#[test]
fn a_live_host_nobody_asked_about_is_not_scanned() {
let (_session, ctx) = store_holding(vec![
host_at("10.0.0.1", HostStatus::Up),
host_at("10.0.0.2", HostStatus::Up),
]);
let kept = only_live(&map_of(vec![unit("10.0.0.1", "22")]), &ctx);
assert_eq!(
kept.gross_ips().expect("countable"),
1,
"an address nobody named was added to the scan"
);
let named = |ip: &str| {
let wanted: IpAddr = ip.parse().expect("an address");
kept.units.iter().any(|unit| unit.ips().contains(&wanted))
};
assert!(named("10.0.0.1"));
assert!(
!named("10.0.0.2"),
"an address nobody named survived the gate"
);
}
#[test]
fn an_empty_store_keeps_nothing() {
let (_session, ctx) = store_holding(Vec::new());
let kept = only_live(&map_of(vec![unit("10.0.0.1", "22")]), &ctx);
assert!(kept.is_empty());
}
}