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},
port::PortSet,
target::{TargetIndex, TargetMap},
};
#[cfg(feature = "journal-format")]
use crate::report::ScanPhase;
use crate::report::ScannerKind;
use crate::report::{LivenessSkip, ScanKind, ScanReport, TargetScope};
use crate::scanner::orchestrator::{
Enrichment, ScanCapabilities, finish_enrichment, 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;
use strategy::routed::SynPorts;
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),
#[error("file descriptor limit {limit} is below the {needed} a scan needs")]
TooFewDescriptors {
limit: usize,
needed: usize,
},
}
fn enough_descriptors() -> Result<(), ScanError> {
match crate::system::descriptors::too_few() {
Some((limit, needed)) => Err(ScanError::TooFewDescriptors { limit, needed }),
None => Ok(()),
}
}
#[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()?;
enough_descriptors()?;
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)
.send_source(cfg.send_source.clone())
.listening_only_to(cfg.listen_only_ports.clone())
.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()?;
enough_descriptors()?;
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)
.send_source(cfg.send_source.clone())
.listening_only_to(cfg.listen_only_ports.clone())
.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, runs_liveness: bool) -> Vec<Stage> {
let cfg = &running_under(cfg);
let mut stages = Vec::new();
if runs_liveness {
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 asks_liveness(cfg: &ZondConfig) -> bool {
!cfg.assume_up && cfg.idle_scan.is_none()
}
fn liveness_earns_its_place(cfg: &ZondConfig, map: &TargetMap) -> bool {
use crate::model::port::Protocol;
if !asks_liveness(cfg) {
return false;
}
if !cfg.tcp_technique.has_connect_fallback() {
return true;
}
if map.names(Protocol::Udp) {
return true;
}
let asked = SynPorts::for_scan(&tcp_ports_of(map)).len()
+ usize::from(orchestrator::sctp_discovery_port(map).is_some());
let per_address = map
.units
.iter()
.map(crate::model::target::TargetSet::port_count)
.max()
.unwrap_or(0);
if per_address > asked {
return true;
}
reaches_a_local_segment(cfg, map)
}
fn liveness_skip(cfg: &ZondConfig, runs_liveness: bool) -> Option<LivenessSkip> {
if runs_liveness {
None
} else if cfg.idle_scan.is_some() {
Some(LivenessSkip::IdleScan)
} else if cfg.assume_up {
Some(LivenessSkip::AssumeUp)
} else {
Some(LivenessSkip::PortsNoDearer)
}
}
const ON_LINK_CHECK_CEILING: u128 = 1 << 13;
fn reaches_a_local_segment(cfg: &ZondConfig, map: &TargetMap) -> bool {
match map.gross_ips() {
Ok(count) if count <= ON_LINK_CHECK_CEILING => {}
_ => return false,
}
let mut ips = IpSet::new();
for unit in &map.units {
for range in unit.ips().v4() {
ips.push_v4_range(*range);
}
for range in unit.ips().v6() {
ips.push_v6_range(*range);
}
}
ips.canonicalize();
let plan = plan::DiscoveryPlan::build(ips, Scope::Targeted, &cfg.exclusions, &cfg.send_source);
plan.steps()
.iter()
.any(|step| matches!(step, plan::DiscoveryStep::Local { .. }))
}
fn running_under(cfg: &ZondConfig) -> ZondConfig {
if cfg.idle_scan.is_none() {
return cfg.clone();
}
let mut muted = cfg.clone();
muted.service_detection = crate::config::ServiceDetection::Off;
if muted.detection.ceiling() > Some(crate::model::finding::DetectionClass::Passive) {
muted.detection =
crate::config::DetectionEnvelope::up_to(crate::model::finding::DetectionClass::Passive);
}
if muted.os_detection.is_active() {
muted.os_detection = crate::config::OsDetection::Passive;
}
muted.traceroute = false;
muted.characterise = false;
muted.ip_protocols.clear();
muted.tls_enumeration = false;
muted
}
fn record_idle_refusals(cfg: &ZondConfig, ctx: &ScanContext) {
use crate::model::finding::DetectionClass;
use crate::report::ScannerKind;
use plan::RefusedStep;
if cfg.idle_scan.is_none() {
return;
}
if cfg.service_detection.connects() {
crate::info!(verbosity = 1, "service detection skipped (idle scan)");
}
if cfg.detection.ceiling() > Some(DetectionClass::Passive) {
ctx.record_refusal(
RefusedStep::pass_not_in_an_idle_scan(ScannerKind::Detection, "active detection")
.into(),
);
}
if cfg.os_detection.is_active() {
ctx.record_refusal(
RefusedStep::pass_not_in_an_idle_scan(
ScannerKind::OsSeries,
"active operating-system probing",
)
.into(),
);
}
if cfg.traceroute {
ctx.record_refusal(
RefusedStep::pass_not_in_an_idle_scan(ScannerKind::Routed, "the route trace").into(),
);
}
if cfg.characterise {
ctx.record_refusal(
RefusedStep::pass_not_in_an_idle_scan(
ScannerKind::Routed,
"the filter characterisation",
)
.into(),
);
}
if !cfg.ip_protocols.is_empty() {
ctx.record_refusal(
RefusedStep::pass_not_in_an_idle_scan(ScannerKind::Routed, "the IP-protocol probe")
.into(),
);
}
if cfg.tls_enumeration {
ctx.record_refusal(
RefusedStep::pass_not_in_an_idle_scan(ScannerKind::Service, "TLS enumeration").into(),
);
}
}
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, orchestrator::Probing::sweep());
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, SynPorts::common(), 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,
syn_ports: SynPorts,
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);
plan.asking_tcp(syn_ports);
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, rdns::Unheard::Skipped).await;
} else {
let targets = orchestrator::walkable(targets, ctx);
if let Err(error) =
strategy::connect::discover_on(targets, ctx.clone(), &cfg.evasion, syn_ports).await
{
ctx.record_failure(ScannerKind::Connect, error.to_string());
}
finish_enrichment(None, caps, ctx, rdns::Unheard::Skipped).await;
}
orchestrator::run_passive_os_identification(ctx, cfg.os_detection);
}
fn tcp_ports_of(map: &TargetMap) -> PortSet {
map.units
.iter()
.fold(PortSet::new(), |named, unit| named.union(unit.ports()))
}
#[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,
listening_privilege(opened.as_ref().err()),
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)
})
}
fn listening_privilege(refusal: Option<&strategy::StrategyError>) -> Privilege {
use crate::transport::capture::CaptureError;
match refusal {
None => Privilege::Raw,
Some(strategy::StrategyError::Capture(CaptureError::NoInterface { refused }))
if refused.is_empty() =>
{
Privilege::current()
}
Some(strategy::StrategyError::Capture(error)) if error.is_denied() => Privilege::Connect,
Some(strategy::StrategyError::Capture(_)) => Privilege::Raw,
Some(_) => Privilege::current(),
}
}
pub async fn scan(
target_map: TargetMap,
cfg: &ZondConfig,
detections: Detections,
) -> Result<(ScanSession, ScanTask), ScanError> {
cfg.evasion.validate()?;
enough_descriptors()?;
let planned = planned_targets(&target_map);
let runs_liveness = liveness_earns_its_place(cfg, &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)
.send_source(cfg.send_source.clone())
.listening_only_to(cfg.listen_only_ports.clone())
.detections(detections)
.planning(Stage::Ports, planned)
.staging(scan_stages(cfg, runs_liveness))
.ordering(Some(rand::random()))
.build();
let handle = spawn_scan(target_map, cfg, ctx, Checkpoint::default(), runs_liveness);
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()?;
enough_descriptors()?;
under_the_recorded_policy(&journal, cfg)?;
let runs_liveness = liveness_earns_its_place(cfg, &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)
.send_source(cfg.send_source.clone())
.listening_only_to(cfg.listen_only_ports.clone())
.resuming(journal.resume_point())
.detections(detections)
.planning(Stage::Ports, planned_targets(&target_map))
.staging(scan_stages(cfg, runs_liveness))
.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, runs_liveness);
Ok((session, ScanTask::journalling(handle, ticker, earlier)))
}
fn spawn_scan(
mut target_map: TargetMap,
cfg: &ZondConfig,
ctx: ScanContext,
settled: Checkpoint,
runs_liveness: bool,
) -> JoinHandle<ScanReport> {
let caps = ScanCapabilities::resolve(cfg, orchestrator::Probing::ports(cfg, &target_map));
let requested = cfg.clone();
let cfg = running_under(&requested);
tokio::spawn(async move {
let skipped = liveness_skip(&cfg, runs_liveness);
let (liveness, live) = if let Some(why) = skipped {
match why {
LivenessSkip::IdleScan => {
crate::info!(verbosity = 1, "liveness pass skipped (idle scan)");
}
LivenessSkip::PortsNoDearer => {
crate::info!(verbosity = 1, "liveness pass skipped (port scan no dearer)");
}
_ => {}
}
(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 syn_ports = SynPorts::for_scan(&tcp_ports_of(&target_map));
let sctp = orchestrator::sctp_discovery_port(&target_map);
run_discovery(ips, Scope::Targeted, caps, &cfg, &ctx, syn_ports, sctp).await;
orchestrator::run_correlation(&ctx, cfg.service_detection);
let (report, liveness) = recorder.close(&ctx);
(Some(report), liveness)
};
let mut covered = match &live {
Some(live) => probed_subset(&target_map, &live.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 mut recorder = PhaseRecorder::start(ScanKind::PortScan, caps.privilege, scope, &cfg);
if let Some(why) = skipped {
recorder = recorder.skipping_liveness(why);
}
ctx.enter_stage(Stage::Ports, None);
record_idle_refusals(&requested, &ctx);
let stands_in = skipped == Some(LivenessSkip::PortsNoDearer);
run_port_phase(target_map, live, &ctx, caps, &cfg, settled, stands_in).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::*;
#[test]
fn a_listener_is_recorded_unprivileged_only_where_privilege_refused_it() {
use crate::scanner::strategy::StrategyError;
use crate::transport::capture::CaptureError;
let denied = |link: &str| CaptureError::Denied {
interface: link.into(),
source: pcap::Error::PcapError("permission denied".into()),
};
let filter = CaptureError::Filter {
filter: "ip6 and ether proto 0x86dd".into(),
source: pcap::Error::PcapError("not an ethernet link".into()),
};
let refused = |refused| StrategyError::Capture(CaptureError::NoInterface { refused });
assert_eq!(
listening_privilege(Some(&refused(vec![("en0".into(), denied("en0"))]))),
Privilege::Connect,
"the platform refused this process"
);
assert_eq!(
listening_privilege(Some(&refused(vec![("utun4".into(), filter)]))),
Privilege::Raw,
"the link refused the filter, after the platform let it open"
);
assert_eq!(listening_privilege(None), Privilege::Raw, "it listened");
assert_eq!(
listening_privilege(Some(&refused(Vec::new()))),
Privilege::current(),
"no link was tried, so the process's own answer is all there is"
);
}
#[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);
}
}