zond-engine 0.8.0

A lightweight, fast, and highly concurrent networking backend for packet crafting, protocol fingerprinting, and host discovery.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
// If a copy of the MPL was not distributed with this file, You can obtain one at
// https://mozilla.org/MPL/2.0/.

//! # Network Scanning
//!
//! Orchestration for turning a set of target addresses into scan results.
//!
//! A scan happens in two independent phases, exposed here as the two entry
//! points [`discover`] and [`scan`]. `discover` finds out which hosts in a
//! target range are actually alive; `scan` takes a set of targets - usually
//! ones `discover` already confirmed - and finds out which of their ports
//! are open. Splitting them this way lets a caller run a cheap discovery
//! sweep first and spend the more expensive port-scanning work only on
//! hosts that are actually there.
//!
//! Both phases adapt to whether the process has root privileges. With root,
//! `discover` partitions targets by network interface and scans each one
//! with a raw-socket strategy suited to it - [`LocalScanner`] (in the
//! [`local`] module) for hosts on the same physical segment, using
//! ARP/ICMP, and [`RoutedScanner`] (in [`routed`]) for anything reached
//! through a gateway, using TCP SYN. `scan` takes the same approach for
//! ports: privileged callers get [`routed::SynPortScanner`], which
//! classifies each port from a single raw SYN probe instead of completing
//! a full handshake. Either way, targets that can't be mapped to a usable
//! interface, along with every target when running unprivileged, fall back
//! to plain TCP connect attempts via the [`connect`] module.
//!
//! Every scanning strategy implements [`NetworkExplorer`], which is what
//! lets [`discover`] spawn several unrelated scanners - the per-interface
//! local ones, the routed one, and the fallback - and run them all through
//! the same loop rather than special-casing each one. Discovered hosts land
//! in a shared, thread-safe
//! store as they're found, and each update fires a lightweight event so a
//! caller can watch a scan in progress instead of waiting for it to finish.
//! If DNS resolution is enabled, hostnames for discovered hosts are looked
//! up in the background, via the [`resolver`] module, without blocking
//! discovery itself.

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;

/// How many TCP connect probes [`scan`] runs at once.
const PORT_SCAN_CONCURRENCY: usize = 50;

/// An error from a scan.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum ScanError {
    /// The scan did not run to completion because its task panicked or was
    /// aborted.
    #[error("scan task terminated abnormally")]
    TaskFailed,
}

/// A handle to a running scan.
///
/// Discovered hosts arrive live through the paired [`ScanSession`]. Await this
/// handle, or call [`ScanTask::join`], to wait for the whole scan to finish.
/// To stop a scan early, call
/// [`ScanHandle::abort`](crate::core::handle::ScanHandle::abort) on the
/// session's handle.
pub struct ScanTask {
    handle: JoinHandle<()>,
}

impl ScanTask {
    fn new(handle: JoinHandle<()>) -> Self {
        Self { handle }
    }

    /// Waits for the scan to finish, failing only if it did not run to
    /// completion. Per-target scan failures are reported through the
    /// [`ScanSession`] event stream, not here.
    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())
    }
}

/// A scanning strategy that finds which hosts, among a set of targets it
/// already owns, are actually reachable.
///
/// Implementations don't return what they find - they write discovered
/// hosts directly into the shared [`ScanContext`] they were built with, and
/// `discover_hosts` only reports whether the attempt itself succeeded. That
/// makes very different strategies (raw ARP/ICMP, raw TCP SYN, plain TCP
/// connect) interchangeable from the caller's point of view: build one, run
/// it, move on. [`spawn_explorers`] relies on exactly that to drive a
/// handful of unrelated scanner types through one shared loop.
#[async_trait]
trait NetworkExplorer {
    async fn discover_hosts(&mut self) -> anyhow::Result<()>;
}

/// Probes a known set of targets for open ports.
///
/// This is the second phase of a scan: given targets and the ports to check
/// on each, find out which of those ports are open. It does no host
/// discovery of its own - a target that isn't actually alive just comes
/// back with every port closed or filtered, at the cost of a wasted probe.
/// Call [`discover`] first if you don't already know which targets exist.
///
/// With root privileges, every probe is a raw TCP SYN sent from the source
/// address the host would route each target through, classified by
/// [`routed::SynPortScanner`] from a single reply rather than a completed
/// handshake. Without root, or if the host has no address to probe from,
/// probes fall back to a plain TCP connect attempt per target via the
/// [`connect`] module.
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);

    // A privileged scan enriches hosts exactly as `discover` does - ARP/ICMPv6
    // for MAC and RTT, TCP SYN for RTT, passive DNS/mDNS for hostnames and
    // extra IPs - running concurrently with the port scan and writing into the
    // same store, so a scanned host carries the same detail a discovered one
    // does. The unprivileged fallback can't ARP, so it settles for active
    // reverse DNS.
    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)))
}

/// Collects every target address from a [`TargetMap`] into an [`IpSet`], so
/// the host-enrichment phase knows which addresses to identify.
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
}

/// Attempts to build a privileged, raw-socket SYN port scanner, resolving
/// each probe's source address per target across all of the host's
/// interfaces and its routing table.
///
/// Returns `None` - meaning [`scan`] should fall back to TCP connect
/// probes - when running unprivileged, when the host has no address to probe
/// from, or when the scanner fails to initialize (for instance, because raw
/// sockets couldn't be opened); each of these is logged at its call site
/// rather than treated as a hard failure, since the unprivileged path is
/// always a working substitute.
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
        }
    }
}

/// The privileged host-identification phase, shared by [`discover`] and
/// [`scan`].
///
/// It spawns the same strategies discovery uses - per-interface
/// [`LocalScanner`]s (ARP/ICMPv6, yielding MAC and RTT), a [`RoutedScanner`]
/// for off-link targets (RTT), and the passive DNS/mDNS
/// [`HostnameResolver`] - all writing into the shared store. `discover` runs
/// this alone; `scan` runs it alongside the port scan. Keeping it in one place
/// is what lets both surface identical host detail without duplicating the
/// orchestration.
struct Enrichment {
    scanners: Vec<(ScannerKind, JoinHandle<anyhow::Result<()>>)>,
    resolver: Option<JoinHandle<Option<HostnameResolver>>>,
}

impl Enrichment {
    /// Spawns every enrichment strategy for `targets`; they begin running
    /// immediately and concurrently. Call [`Enrichment::finish`] to await them.
    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 }
    }

    /// Awaits every enrichment strategy, reporting any that failed, then folds
    /// the resolver's collected hostnames and extra IPs into the store.
    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());
        }
    }
}

/// Finds which hosts, among a set of target addresses, are actually alive.
///
/// This is the first phase of a scan: it establishes presence, not open
/// ports. With root privileges, targets are grouped by the network
/// interface that would reach them, and scanned with a raw-socket strategy
/// suited to each: [`LocalScanner`] (ARP/ICMP) for hosts on the same
/// physical segment, [`RoutedScanner`] (TCP SYN) for anything reached
/// through a gateway. Targets that can't be mapped to an interface at all -
/// a loopback address, for instance - along with every target when running
/// without root, fall back to plain TCP connect attempts against a handful
/// of common ports.
///
/// Hosts are written into the returned [`ScanSession`]'s store as they're
/// found, and each write fires a [`crate::core::session::ScanEvent`], so a
/// caller can watch a scan in progress rather than only seeing the final
/// result. Unless `cfg.no_dns` is set, discovered hosts are also resolved
/// to hostnames in the background - via passive DNS/mDNS sniffing when
/// privileged, or active reverse lookups otherwise - without blocking or
/// slowing down discovery itself.
///
/// The returned [`ScanTask`] resolves once every scanning strategy, and the
/// resolver if one was started, has finished. To stop a scan early, call
/// [`crate::core::handle::ScanHandle::abort`] on the session's handle; both
/// phases check for that signal regularly rather than only between targets.
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)))
}

/// Builds a scanning strategy for each way a target can be reached, and runs
/// them all concurrently.
///
/// [`interface::map_ips_to_interfaces`] classifies the targets into three
/// groups: those on-link to an interface's segment become a per-interface
/// [`LocalScanner`]; those reached through a gateway, each already paired
/// with the source address to probe it from, are covered by a single
/// [`RoutedScanner`]; and those with no resolvable route go to a
/// [`connect::ConnectScanner`]. If constructing a particular scanner fails -
/// a capture socket that couldn't be opened, for instance - that one scanner
/// is skipped and logged; the rest of the scan proceeds without it.
///
/// Every constructed scanner is spawned as its own task, tagged with its
/// [`ScannerKind`] and returned, so the caller can wait on all of them and
/// react to failures individually rather than one bad scanner aborting the
/// whole scan. A scanner that fails to start is reported via
/// [`ScanEvent::ScannerFailed`] and skipped.
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);

    // Local Scanner (ARP/ICMP)
    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))
            }
        }
    }

    // Routed Scanner (TCP SYN)
    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()),
        }
    }

    // Fallback Scanner (Unprivileged TCP Handshake) for unmapped IPs (e.g. localhost,
    // or targets the OS couldn't resolve a route/interface for).
    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()
}

/// Logs a scanner failure and announces it on the event stream, so a consumer
/// watching a scan can tell it ran degraded rather than clean.
fn report_scanner_failure(ctx: &ScanContext, scanner: ScannerKind, reason: String) {
    error!("Scanner {scanner:?} failed: {reason}");
    let _ = ctx
        .events_tx
        .send(ScanEvent::ScannerFailed { scanner, reason });
}

/// Starts the background hostname resolver as its own task.
///
/// The resolver listens for raw DNS and mDNS traffic and answers reverse
/// lookups for any IP sent down `dns_rx`, independent of and concurrent
/// with whatever scanning strategies are running. If it fails to start -
/// most likely because no usable network socket could be opened - that
/// failure is logged and `None` is returned rather than propagated, since a
/// scan without hostname resolution is still a useful scan.
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
            }
        }
    })
}

/// Checks for root privileges, logging which scanning mode this implies.
///
/// Returns `true` when *not* running as root, i.e. when the caller should
/// fall back to unprivileged, TCP-connect-based scanning rather than raw
/// sockets. The inverted name reads more sensibly at the call site -
/// `if not_root() { /* fall back */ }` - than mirroring `is_root` would.
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
}