use std::pin::Pin;
use tokio::task::JoinHandle;
use crate::config::ZondConfig;
use crate::detect::Detections;
use crate::journal::cursor::Checkpoint;
use crate::model::{
ip::set::{IpSet, Positions},
target::{TargetIndex, TargetMap},
};
#[cfg(feature = "journal-format")]
use crate::report::ScanPhase;
use crate::report::ScannerKind;
use crate::report::{ScanKind, ScanReport, TargetScope};
use crate::scanner::orchestrator::{
Enrichment, ScanCapabilities, finish_enrichment, live_addresses, probed_subset, run_port_phase,
};
use crate::scanner::recorder::PhaseRecorder;
use crate::scanner::session::{ScanContext, ScanSession, Stage};
use crate::system::interface;
use crate::system::privilege::Privilege;
use strategy::local::Scope;
pub mod handle;
pub mod recorder;
pub mod session;
pub mod pacing;
pub mod plan;
pub mod strategy;
pub mod audit;
#[cfg(feature = "journal-format")]
pub mod checkpoint;
pub mod detection;
pub mod dispatcher;
pub mod order;
pub mod payload;
pub mod pool;
pub mod rdns;
pub mod service;
mod orchestrator;
mod vantage;
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum ScanError {
#[error("the scan task {}: {detail}", if *.panicked { "panicked" } else { "was cancelled" })]
TaskFailed {
panicked: bool,
detail: String,
},
#[error("this journal records the other phase of a scan")]
WrongPhase,
#[cfg(feature = "journal-format")]
#[error("{0}")]
PlanChanged(#[from] crate::journal::manifest::PlanChanged),
#[error("{0}")]
Evasion(#[from] crate::evasion::EvasionError),
}
#[cfg(feature = "journal-format")]
fn under_the_recorded_policy(
journal: &crate::journal::Journal,
cfg: &ZondConfig,
) -> Result<(), ScanError> {
use crate::journal::manifest::Plan;
let manifest = journal.manifest();
let recorded = manifest.recorded();
let this_run = if let Some(addresses) = recorded.addresses() {
Plan::discovery(addresses, &cfg.exclusions, recorded.sweeps_the_segment())
} else if let Some(targets) = recorded.targets() {
Plan::port_scan(
targets,
&cfg.exclusions,
recorded.technique().unwrap_or_default(),
)
} else {
return Ok(());
};
manifest.covers(&this_run, manifest.privilege)?;
Ok(())
}
fn panic_or_cancellation(error: tokio::task::JoinError) -> ScanError {
if !error.is_panic() {
return ScanError::TaskFailed {
panicked: false,
detail: "the runtime shut down before the scan finished".to_string(),
};
}
let payload = error.into_panic();
let detail = payload
.downcast_ref::<&'static str>()
.map(|message| (*message).to_string())
.or_else(|| payload.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "a panic carrying no message".to_string());
ScanError::TaskFailed {
panicked: true,
detail,
}
}
pub struct ScanTask {
handle: JoinHandle<ScanReport>,
#[cfg(feature = "journal-format")]
journal: Option<checkpoint::Checkpointing>,
#[cfg(feature = "journal-format")]
earlier: Vec<ScanPhase>,
}
impl ScanTask {
fn new(handle: JoinHandle<ScanReport>) -> Self {
Self {
handle,
#[cfg(feature = "journal-format")]
journal: None,
#[cfg(feature = "journal-format")]
earlier: Vec::new(),
}
}
#[cfg(feature = "journal-format")]
fn journalling(
handle: JoinHandle<ScanReport>,
journal: checkpoint::Checkpointing,
earlier: Vec<ScanPhase>,
) -> Self {
Self {
handle,
journal: Some(journal),
earlier,
}
}
pub async fn join(self) -> Result<ScanReport, ScanError> {
let report = self.handle.await.map_err(panic_or_cancellation);
#[cfg(feature = "journal-format")]
if let Some(journal) = self.journal {
let phases = report.as_ref().map(ScanReport::phases).unwrap_or_default();
journal.finish(phases).await;
}
#[cfg(feature = "journal-format")]
if !self.earlier.is_empty() {
return report.map(|report| {
let mut whole = ScanReport::from_phases(self.earlier, []);
whole.merge(report);
whole
});
}
report
}
}
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(
targets: IpSet,
cfg: &ZondConfig,
) -> Result<(ScanSession, ScanTask), ScanError> {
cfg.evasion.validate()?;
let planned = planned_addresses(&Positions::of(&targets));
let (session, ctx) = ScanSession::builder()
.excluding(cfg.exclusions.clone())
.host_timeout(cfg.host_timeout)
.scan_timeout(cfg.scan_timeout)
.host_probe_interval(cfg.host_probe_interval)
.planning(Stage::Discovery, planned)
.staging(discovery_stages(cfg))
.ordering(Some(rand::random()))
.build();
let handle = spawn_discovery(targets, cfg, ctx);
Ok((session, ScanTask::new(handle)))
}
#[cfg(feature = "journal-format")]
pub async fn discover_with_journal(
targets: IpSet,
cfg: &ZondConfig,
journal: crate::journal::Journal,
) -> Result<(ScanSession, ScanTask), ScanError> {
cfg.evasion.validate()?;
let recorded = journal.manifest().recorded();
let Some(addresses) = recorded.addresses() else {
return Err(ScanError::WrongPhase);
};
under_the_recorded_policy(&journal, cfg)?;
let positions = addresses.positions();
let resume_point = journal.resume_point().clone();
let order_seed = journal.manifest().order_seed;
let sweep = if resume_point == Checkpoint::default() {
targets
} else {
resume_point.remaining_addresses(&positions)
};
let planned = planned_addresses(&positions);
let (session, ctx) = ScanSession::builder()
.excluding(cfg.exclusions.clone())
.host_timeout(cfg.host_timeout)
.scan_timeout(cfg.scan_timeout)
.host_probe_interval(cfg.host_probe_interval)
.resuming(&resume_point)
.counting(positions)
.planning(Stage::Discovery, planned)
.staging(discovery_stages(cfg))
.ordering(order_seed)
.build();
ctx.restore_hosts(journal.restored());
let earlier = journal.earlier_phases().to_vec();
let ticker = checkpoint::spawn_checkpoints(journal, ctx.progress());
let handle = spawn_discovery(sweep, cfg, ctx);
Ok((session, ScanTask::journalling(handle, ticker, earlier)))
}
fn planned_addresses(positions: &Positions) -> Option<u64> {
positions.unnumbered().is_empty().then(|| positions.total())
}
fn discovery_stages(cfg: &ZondConfig) -> Vec<Stage> {
let mut stages = vec![Stage::Discovery];
if cfg.os_detection.is_active() {
stages.push(Stage::Os);
}
if cfg.traceroute {
stages.push(Stage::Traceroute);
}
stages
}
fn scan_stages(cfg: &ZondConfig) -> Vec<Stage> {
let mut stages = Vec::new();
if !cfg.assume_up {
stages.push(Stage::Discovery);
}
stages.push(Stage::Ports);
if cfg.service_detection.connects() {
stages.push(Stage::Services);
}
if cfg.service_detection != crate::config::ServiceDetection::Off
&& cfg.detection.ceiling().is_some()
{
stages.push(Stage::Detections);
}
if cfg.tls_enumeration {
stages.push(Stage::Tls);
}
if cfg.os_detection.is_active() {
stages.push(Stage::Os);
}
if cfg.traceroute {
stages.push(Stage::Traceroute);
}
stages
}
fn planned_targets(map: &TargetMap) -> Option<u64> {
let index = TargetIndex::of(map);
index.is_complete().then(|| index.total())
}
fn spawn_discovery(
mut targets: IpSet,
cfg: &ZondConfig,
ctx: ScanContext,
) -> JoinHandle<ScanReport> {
let caps = ScanCapabilities::resolve(cfg);
let scope = TargetScope::from_ip_set(&mut targets, &cfg.exclusions);
let recorder = PhaseRecorder::start(ScanKind::Discovery, caps.privilege, scope, cfg);
let reach = if cfg.segment_sweep {
Scope::Sweep
} else {
Scope::Targeted
};
let cfg = cfg.clone();
tokio::spawn(async move {
ctx.enter_stage(Stage::Discovery, None);
run_discovery(targets, reach, caps, &cfg, &ctx, None).await;
orchestrator::run_active_os_probe(&ctx, cfg.os_detection, cfg.probe_tuning(), caps).await;
orchestrator::run_traceroute(&ctx, &cfg, caps).await;
ctx.enter_stage(Stage::Finishing, None);
orchestrator::run_characterise(&ctx, &cfg, caps).await;
orchestrator::run_ip_protocols(&ctx, &cfg).await;
vantage::attribute(&ctx);
orchestrator::run_correlation(&ctx, cfg.service_detection);
recorder.finish(&ctx)
})
}
async fn run_discovery(
targets: IpSet,
reach: Scope,
caps: ScanCapabilities,
cfg: &ZondConfig,
ctx: &ScanContext,
sctp_port: Option<u16>,
) {
if caps.privilege.is_raw() {
let unframed =
caps.beyond_frames(&targets, &cfg.send_source, interface::FrameSender::Sweep);
let mut plan =
plan::DiscoveryPlan::build(targets, reach, &cfg.exclusions, &cfg.send_source);
plan.connect_instead(&unframed.targets);
if let Some(port) = sctp_port {
plan.also_over_sctp(port);
}
for step in plan.steps() {
if let plan::DiscoveryStep::Connect { targets } = step {
ctx.record_reached_by_connect(targets);
}
}
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(), &cfg.evasion).await {
ctx.record_failure(ScannerKind::Connect, error.to_string());
}
finish_enrichment(None, caps, ctx).await;
}
orchestrator::run_passive_os_identification(ctx, cfg.os_detection);
}
#[must_use]
#[derive(Debug, Clone)]
pub struct ListenScope {
links: Vec<crate::model::ip::scoped::Zone>,
recording: strategy::passive::Recording,
until: Until,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Until {
#[default]
Stopped,
Elapsed(std::time::Duration),
}
impl ListenScope {
pub fn on(links: Vec<crate::model::ip::scoped::Zone>) -> Self {
Self {
links,
recording: strategy::passive::Recording::Attached,
until: Until::Stopped,
}
}
pub fn recording_everything(mut self) -> Self {
self.recording = strategy::passive::Recording::Everything;
self
}
pub fn recording_only(mut self, addresses: IpSet) -> Self {
self.recording = strategy::passive::Recording::Only(addresses);
self
}
pub fn for_at_most(mut self, span: std::time::Duration) -> Self {
self.until = Until::Elapsed(span);
self
}
pub fn links(&self) -> &[crate::model::ip::scoped::Zone] {
&self.links
}
pub fn until(&self) -> Until {
self.until
}
}
pub async fn listen(
scope: ListenScope,
cfg: &ZondConfig,
) -> Result<(ScanSession, ScanTask), ScanError> {
let (session, ctx) = ScanSession::builder()
.excluding(cfg.exclusions.clone())
.host_timeout(cfg.host_timeout)
.scan_timeout(cfg.scan_timeout)
.host_probe_interval(cfg.host_probe_interval)
.staging(vec![Stage::Listening])
.build();
let handle = spawn_listen(scope, cfg, ctx);
Ok((session, ScanTask::new(handle)))
}
#[cfg(feature = "journal-format")]
pub async fn listen_with_journal(
scope: ListenScope,
cfg: &ZondConfig,
journal: crate::journal::Journal,
) -> Result<(ScanSession, ScanTask), ScanError> {
let recorded = journal.manifest().recorded();
if recorded.kind() != ScanKind::Listen {
return Err(ScanError::WrongPhase);
}
let (session, ctx) = ScanSession::builder()
.excluding(cfg.exclusions.clone())
.host_timeout(cfg.host_timeout)
.scan_timeout(cfg.scan_timeout)
.host_probe_interval(cfg.host_probe_interval)
.staging(vec![Stage::Listening])
.build();
ctx.restore_hosts(journal.restored());
let earlier = journal.earlier_phases().to_vec();
let ticker = checkpoint::spawn_checkpoints(journal, ctx.progress());
let handle = spawn_listen(scope, cfg, ctx);
Ok((session, ScanTask::journalling(handle, ticker, earlier)))
}
fn spawn_listen(scope: ListenScope, cfg: &ZondConfig, ctx: ScanContext) -> JoinHandle<ScanReport> {
let cfg = cfg.clone();
tokio::spawn(async move {
ctx.enter_stage(Stage::Listening, None);
let opened =
strategy::passive::PassiveListener::open(&scope.links, scope.recording, ctx.clone());
let recorder = PhaseRecorder::start(
ScanKind::Listen,
Privilege::from_raw(opened.is_ok()),
TargetScope::listening_on(scope.links.clone(), &cfg.exclusions),
&cfg,
);
match opened {
Ok(listener) => {
let mut listener = listener.detecting_os(cfg.os_detection);
if let Until::Elapsed(span) = scope.until {
listener = listener.stopping_after(span);
}
if let Err(error) = listener.observe().await {
ctx.record_failure(ScannerKind::Passive, error.to_string());
}
}
Err(error) => ctx.record_failure(ScannerKind::Passive, error.to_string()),
}
vantage::attribute(&ctx);
orchestrator::run_correlation(&ctx, cfg.service_detection);
recorder.finish(&ctx)
})
}
pub async fn scan(
target_map: TargetMap,
cfg: &ZondConfig,
detections: Detections,
) -> Result<(ScanSession, ScanTask), ScanError> {
cfg.evasion.validate()?;
let planned = planned_targets(&target_map);
let (session, ctx) = ScanSession::builder()
.excluding(cfg.exclusions.clone())
.host_timeout(cfg.host_timeout)
.scan_timeout(cfg.scan_timeout)
.host_probe_interval(cfg.host_probe_interval)
.detections(detections)
.planning(Stage::Ports, planned)
.staging(scan_stages(cfg))
.ordering(Some(rand::random()))
.build();
let handle = spawn_scan(target_map, cfg, ctx, Checkpoint::default());
Ok((session, ScanTask::new(handle)))
}
#[cfg(feature = "journal-format")]
pub async fn scan_with_journal(
target_map: TargetMap,
cfg: &ZondConfig,
detections: Detections,
journal: crate::journal::Journal,
) -> Result<(ScanSession, ScanTask), ScanError> {
cfg.evasion.validate()?;
under_the_recorded_policy(&journal, cfg)?;
let (session, ctx) = ScanSession::builder()
.excluding(cfg.exclusions.clone())
.host_timeout(cfg.host_timeout)
.scan_timeout(cfg.scan_timeout)
.host_probe_interval(cfg.host_probe_interval)
.resuming(journal.resume_point())
.detections(detections)
.planning(Stage::Ports, planned_targets(&target_map))
.staging(scan_stages(cfg))
.ordering(journal.manifest().order_seed)
.build();
ctx.restore_hosts(journal.restored());
let earlier = journal.earlier_phases().to_vec();
let resume_point = journal.resume_point().clone();
let ticker = checkpoint::spawn_checkpoints(journal, ctx.progress());
let handle = spawn_scan(target_map, cfg, ctx, resume_point);
Ok((session, ScanTask::journalling(handle, ticker, earlier)))
}
fn spawn_scan(
mut target_map: TargetMap,
cfg: &ZondConfig,
ctx: ScanContext,
settled: Checkpoint,
) -> JoinHandle<ScanReport> {
let caps = ScanCapabilities::resolve(cfg);
let cfg = cfg.clone();
tokio::spawn(async move {
let (liveness, live) = if cfg.assume_up {
(None, None)
} else {
let mut ips = orchestrator::unsettled_ips(&target_map, &settled);
let scope = TargetScope::from_ip_set(&mut ips, &cfg.exclusions);
let recorder = PhaseRecorder::start(ScanKind::Discovery, caps.privilege, scope, &cfg);
ctx.enter_stage(Stage::Discovery, None);
let sctp = orchestrator::sctp_discovery_port(&target_map);
run_discovery(ips, Scope::Targeted, caps, &cfg, &ctx, sctp).await;
orchestrator::run_correlation(&ctx, cfg.service_detection);
let report = recorder.finish(&ctx);
(Some(report), Some(live_addresses(&ctx)))
};
let mut covered = match &live {
Some(live) => probed_subset(&target_map, live),
None => target_map.clone(),
};
let scope = TargetScope::from_target_map(&mut covered, &cfg.exclusions);
crate::model::exclusion::Exclusions::withhold_targets(&cfg.exclusions, &mut target_map);
let recorder = PhaseRecorder::start(ScanKind::PortScan, caps.privilege, scope, &cfg);
ctx.enter_stage(Stage::Ports, None);
run_port_phase(target_map, live, &ctx, caps, &cfg, settled).await;
orchestrator::run_tls_enumeration(&ctx, &cfg).await;
orchestrator::run_active_os_series(&ctx, cfg.os_detection, cfg.probe_tuning(), caps).await;
orchestrator::run_active_os_snmp(&ctx, cfg.os_detection).await;
orchestrator::run_active_os_mdns(&ctx, cfg.os_detection).await;
orchestrator::run_active_os_probe(&ctx, cfg.os_detection, cfg.probe_tuning(), caps).await;
orchestrator::run_traceroute(&ctx, &cfg, caps).await;
ctx.enter_stage(Stage::Finishing, None);
orchestrator::run_characterise(&ctx, &cfg, caps).await;
orchestrator::run_ip_protocols(&ctx, &cfg).await;
vantage::attribute(&ctx);
orchestrator::run_correlation(&ctx, cfg.service_detection);
orchestrator::run_cert_posture(&ctx);
let report = recorder.finish(&ctx);
match liveness {
Some(mut first) => {
first.merge(report);
first
}
None => report,
}
})
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn a_panicking_scan_reports_what_the_panic_said() {
for spawned in [
tokio::spawn(async { panic!("a literal message") }),
tokio::spawn(async { panic!("a formatted {}", "message") }),
] {
let error = panic_or_cancellation(spawned.await.expect_err("the task panicked"));
let ScanError::TaskFailed { panicked, detail } = error else {
unreachable!("a panic is a TaskFailed")
};
assert!(panicked);
assert!(detail.contains("message"), "the payload was lost: {detail}");
}
}
#[tokio::test]
async fn a_cancelled_scan_is_not_reported_as_a_panic() {
let spawned = tokio::spawn(std::future::pending::<()>());
spawned.abort();
let error = panic_or_cancellation(spawned.await.expect_err("the task was cancelled"));
let ScanError::TaskFailed { panicked, .. } = error else {
unreachable!("a cancellation is a TaskFailed")
};
assert!(!panicked);
}
}