use std::net::IpAddr;
use std::pin::Pin;
use async_trait::async_trait;
use is_root::is_root;
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
use tokio::task::JoinHandle;
use crate::core::config::{SendMode, ZondConfig};
use crate::core::models::ip::range::IpRange;
use crate::core::models::{ip::set::IpSet, target::TargetMap};
use crate::core::session::{ScanContext, ScanEvent, ScanSession, ScannerKind};
use crate::scanner::resolver::HostnameResolver;
use crate::system::interface;
use crate::{error, info, success, warn};
use local::{LocalScanner, Scope};
use routed::RoutedScanner;
mod connect;
pub mod dispatcher;
mod local;
mod resolver;
mod routed;
mod service;
const PORT_SCAN_CONCURRENCY: usize = 50;
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum ScanError {
#[error("scan task terminated abnormally")]
TaskFailed,
}
pub struct ScanTask {
handle: JoinHandle<()>,
}
impl ScanTask {
fn new(handle: JoinHandle<()>) -> Self {
Self { handle }
}
pub async fn join(self) -> Result<(), ScanError> {
self.handle.await.map_err(|_| ScanError::TaskFailed)
}
}
impl IntoFuture for ScanTask {
type Output = Result<(), ScanError>;
type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(self.join())
}
}
#[async_trait]
trait NetworkExplorer {
async fn discover_hosts(&mut self) -> anyhow::Result<()>;
}
pub async fn scan(
mut target_map: TargetMap,
cfg: &ZondConfig,
) -> Result<(ScanSession, ScanTask), ScanError> {
let (session, ctx) = ScanSession::new();
let ips = target_ips(&target_map);
let target_count = target_map.gross_targets().unwrap_or(0) as usize;
let with_dns = !cfg.no_dns;
let syn_scanner = build_syn_scanner(ctx.clone(), target_count, cfg.send_mode);
let enrichment = if syn_scanner.is_some() {
Some(Enrichment::spawn(ips, &ctx, cfg, Scope::Targeted).await)
} else {
None
};
let handle = tokio::spawn(async move {
let dispatcher = dispatcher::Dispatcher::new(target_map);
let rx = dispatcher.run_shuffled(&ctx.handle);
let (kind, outcome) = match syn_scanner {
Some(mut scanner) => {
let outcome = scanner.scan(rx).await;
if outcome.is_ok() && !ctx.handle.should_stop() {
service::detect(&ctx).await;
}
(ScannerKind::Routed, outcome)
}
None => (
ScannerKind::Connect,
connect::scan(rx, PORT_SCAN_CONCURRENCY, ctx.clone()).await,
),
};
if let Err(e) = outcome {
report_scanner_failure(&ctx, kind, e.to_string());
}
match enrichment {
Some(enrichment) => enrichment.finish(&ctx).await,
None if with_dns => resolver::resolve_hosts_async(ctx.store.clone()).await,
None => {}
}
});
Ok((session, ScanTask::new(handle)))
}
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
}
fn build_syn_scanner(
ctx: ScanContext,
target_count: usize,
send_mode: SendMode,
) -> Option<routed::SynPortScanner> {
if not_root() {
return None;
}
let resolver = interface::SourceResolver::from_system();
if !resolver.has_sources() {
warn!("No usable network interface found; using TCP connect fallback");
return None;
}
match routed::SynPortScanner::new(resolver, ctx, target_count, send_mode) {
Ok(scanner) => Some(scanner),
Err(e) => {
error!("Failed to initialize SYN port scanner: {e}");
None
}
}
}
struct Enrichment {
scanners: Vec<(ScannerKind, JoinHandle<anyhow::Result<()>>)>,
resolver: Option<JoinHandle<Option<HostnameResolver>>>,
}
impl Enrichment {
async fn spawn(targets: IpSet, ctx: &ScanContext, cfg: &ZondConfig, scope: Scope) -> Self {
let (dns_tx, resolver) = if !cfg.no_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(targets, ctx, dns_tx, cfg.send_mode, scope).await;
Self { scanners, resolver }
}
async fn finish(self, ctx: &ScanContext) {
for (kind, handle) in self.scanners {
match handle.await {
Ok(Ok(())) => {}
Ok(Err(e)) => report_scanner_failure(ctx, kind, e.to_string()),
Err(e) => report_scanner_failure(ctx, kind, format!("panicked: {e}")),
}
}
if let Some(task) = self.resolver
&& let Ok(Some(mut resolver)) = task.await
{
resolver.resolve_hosts(ctx.store.clone());
}
}
}
pub async fn discover(
targets: IpSet,
cfg: &ZondConfig,
) -> Result<(ScanSession, ScanTask), ScanError> {
let with_dns: bool = !cfg.no_dns;
let (session, ctx) = ScanSession::new();
if not_root() {
let handle = tokio::spawn(async move {
if let Err(e) = connect::discover(targets, ctx.clone()).await {
report_scanner_failure(&ctx, ScannerKind::Connect, e.to_string());
}
if with_dns {
resolver::resolve_hosts_async(ctx.store).await;
}
});
return Ok((session, ScanTask::new(handle)));
}
let enrichment = Enrichment::spawn(targets, &ctx, cfg, Scope::Sweep).await;
let handle = tokio::spawn(async move {
enrichment.finish(&ctx).await;
});
Ok((session, ScanTask::new(handle)))
}
async fn spawn_explorers(
targets: IpSet,
ctx: &ScanContext,
dns_tx: Option<UnboundedSender<IpAddr>>,
send_mode: SendMode,
scope: Scope,
) -> Vec<(ScannerKind, JoinHandle<anyhow::Result<()>>)> {
let mut explorers: Vec<(ScannerKind, Box<dyn NetworkExplorer + Send>)> = Vec::new();
let interface::RoutedTargets {
local,
routed,
unmapped,
} = interface::map_ips_to_interfaces(targets);
for (intf, local_ips) in local {
if local_ips.is_empty() {
continue;
}
info!(verbosity = 1, "Spawning local scanner for {}", intf.name);
match LocalScanner::new(intf.clone(), local_ips, ctx.clone(), dns_tx.clone(), scope) {
Ok(scanner) => explorers.push((ScannerKind::Local, Box::new(scanner))),
Err(e) => {
report_scanner_failure(ctx, ScannerKind::Local, format!("{}: {e}", intf.name))
}
}
}
if !routed.is_empty() {
info!(
verbosity = 1,
"Spawning routed scanner for {} target(s)",
routed.len()
);
match RoutedScanner::new(routed, ctx.clone(), dns_tx.clone(), send_mode) {
Ok(scanner) => explorers.push((ScannerKind::Routed, Box::new(scanner))),
Err(e) => report_scanner_failure(ctx, ScannerKind::Routed, e.to_string()),
}
}
if !unmapped.is_empty() {
warn!(
verbosity = 1,
"Spawning fallback scanner for unmapped targets"
);
explorers.push((
ScannerKind::Connect,
Box::new(connect::ConnectScanner::new(unmapped, ctx.clone())),
));
}
explorers
.into_iter()
.map(|(kind, mut explorer)| {
(
kind,
tokio::spawn(async move { explorer.discover_hosts().await }),
)
})
.collect()
}
fn report_scanner_failure(ctx: &ScanContext, scanner: ScannerKind, reason: String) {
error!("Scanner {scanner:?} failed: {reason}");
let _ = ctx
.events_tx
.send(ScanEvent::ScannerFailed { scanner, reason });
}
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
}
}
})
}
fn not_root() -> bool {
if !is_root() {
warn!("Root privileges missing, defaulting to unprivileged TCP scan");
return true;
}
success!("Root privileges detected, raw socket scan enabled");
false
}