zond-engine 0.9.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
// 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/.

//! # Unprivileged TCP Connect Scanning
//!
//! The fallback strategy for when raw sockets are not available, whether because
//! the process is not root, no usable interface exists, or the OS could not route
//! a target. Everything here is built on ordinary [`TcpStream`] connects, so it
//! needs no special privileges and works anywhere the async runtime does.
//!
//! It answers both scan phases. [`discover`] establishes host presence by probing
//! a small set of common infrastructure ports and treating any TCP-layer response,
//! an accept or even a refusal, as proof the host is alive. [`scan`] takes known
//! targets and classifies each port from a full connect handshake. Both consume a
//! randomized [`Dispatcher`] stream and cap their in-flight connections with a
//! [`ProbePool`](super::pool::ProbePool) to avoid exhausting OS sockets, and both
//! record findings through the shared [`ScanContext`] like every other strategy.

use super::dispatcher::Dispatcher;
use super::pool::ProbePool;
use super::{NetworkExplorer, PortScanner, tuning};
use crate::core::models::host::Host;
use crate::core::models::ip::set::IpSet;
use crate::core::models::port::{Port, PortSet, PortState, Protocol};
use crate::core::models::target::{Target, TargetMap, TargetSet};
use crate::core::session::{ScanContext, ScannerKind};
use async_trait::async_trait;
use dashmap::DashSet;
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::time::Instant;
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use tokio::time::timeout;

/// Most common ports across Linux, Windows, and Networking gear.
const DISCOVERY_PORTS: &[u16] = &[22, 80, 443, 445, 3389];

/// Adapts the unprivileged [`discover`] strategy to [`NetworkExplorer`], so it can
/// be spawned alongside [`LocalScanner`](super::local::LocalScanner) and
/// [`RoutedScanner`](super::routed::RoutedScanner) from a single explorer list.
pub struct ConnectScanner {
    /// The addresses being probed for aliveness.
    ips: IpSet,
    /// Shared state (host store, event channel, abort signal) for the scan
    /// this explorer is part of.
    ctx: ScanContext,
}

impl ConnectScanner {
    pub fn new(ips: IpSet, ctx: ScanContext) -> Self {
        Self { ips, ctx }
    }
}

#[async_trait]
impl NetworkExplorer for ConnectScanner {
    async fn discover_hosts(self: Box<Self>) -> anyhow::Result<()> {
        // A discovery run is single-shot, so it consumes the scanner: `ips` and
        // `ctx` move straight into `discover`, no `mem::take` placeholder needed.
        discover(self.ips, self.ctx).await
    }
}

/// The outcome of one finished [`port_prober`] task: the port it classified, or
/// `None` when the port was closed or the target was not probed at all. A probe
/// never fails, since every network outcome maps to a port state or to `None`, so
/// this is a plain [`Option`] rather than a `Result`.
type ProbedPort = Option<(IpAddr, Port)>;

/// Adapts the unprivileged [`scan`] engine to [`PortScanner`], so
/// [`crate::scanner::scan`] can drive it through the same path as the privileged
/// [`SynPortScanner`](super::routed::SynPortScanner).
///
/// It carries no [`detect_services`](PortScanner::detect_services) override,
/// because the connect engine fingerprints each port inline over the live stream
/// it already holds (see [`port_prober`]), so a second identification pass would
/// be wasted work. This is the reason service detection lives on the trait rather
/// than in the caller: the fact that connect needs no second pass is expressed
/// here by its absence, instead of as a branch at the call site.
pub struct ConnectPortScanner {
    /// Shared state (host store, event channel, abort signal) for the scan this
    /// strategy is part of.
    ctx: ScanContext,
    /// The ceiling on in-flight connect probes.
    concurrency: usize,
}

impl ConnectPortScanner {
    pub fn new(ctx: ScanContext, concurrency: usize) -> Self {
        Self { ctx, concurrency }
    }
}

#[async_trait]
impl PortScanner for ConnectPortScanner {
    fn kind(&self) -> ScannerKind {
        ScannerKind::Connect
    }

    fn supported_protocols(&self) -> Vec<Protocol> {
        vec![Protocol::Tcp]
    }

    async fn scan(&mut self, rx: mpsc::Receiver<Target>) -> anyhow::Result<()> {
        scan(rx, self.concurrency, self.ctx.clone()).await
    }
}

/// Unprivileged UDP port scanner.
pub struct ConnectUdpPortScanner {
    ctx: ScanContext,
    concurrency: usize,
}

impl ConnectUdpPortScanner {
    pub fn new(ctx: ScanContext, concurrency: usize) -> Self {
        Self { ctx, concurrency }
    }
}

#[async_trait]
impl PortScanner for ConnectUdpPortScanner {
    fn kind(&self) -> ScannerKind {
        ScannerKind::Connect // or add a new one if preferred, but Connect covers unprivileged
    }

    fn supported_protocols(&self) -> Vec<Protocol> {
        vec![Protocol::Udp]
    }

    async fn scan(&mut self, mut rx: mpsc::Receiver<Target>) -> anyhow::Result<()> {
        let mut pool = ProbePool::new(self.concurrency, |probed| absorb_probe(&self.ctx, probed));

        while let Some(target) = rx.recv().await {
            if self.ctx.handle.should_stop() {
                break;
            }
            pool.admit(udp_port_prober(target)).await;
        }

        pool.drain().await;
        Ok(())
    }
}

/// Performs a high-concurrency, unprivileged port scan.
///
/// This is the primary scanning strategy for callers without root privileges. It
/// consumes a randomized stream of [`Target`]s from a [`Dispatcher`], holding the
/// number of in-flight connections at or below `concurrency_limit` to avoid
/// exhausting OS sockets, and records every non-closed port it finds into the
/// shared [`ScanContext`] store.
pub async fn scan(
    mut rx: mpsc::Receiver<Target>,
    concurrency_limit: usize,
    ctx: ScanContext,
) -> anyhow::Result<()> {
    let mut pool = ProbePool::new(concurrency_limit, |probed| absorb_probe(&ctx, probed));

    while let Some(target) = rx.recv().await {
        if ctx.handle.should_stop() {
            break;
        }
        pool.admit(port_prober(target)).await;
    }

    // Every target dispatched; wait out the probes still in flight.
    pool.drain().await;
    Ok(())
}

/// Folds one finished probe into the store, if it classified a non-closed port.
fn absorb_probe(ctx: &ScanContext, probed: ProbedPort) {
    if let Some((ip, port)) = probed {
        ctx.update_host(ip, |host| host.add_port(port));
    }
}

/// Probes a single [`Target`] over a full TCP connect handshake and classifies
/// its port. Returns `Some(..)` for a non-closed port and `None` for a closed
/// port or a target this strategy doesn't handle.
///
/// An accepted connection is `Open` and gets fingerprinted over the live stream,
/// and a refusal is `Closed`. Anything else is `Filtered`, including a timeout,
/// which is the usual signature of a firewall drop. Only TCP is supported, so UDP
/// targets are skipped.
async fn port_prober(target: Target) -> ProbedPort {
    if target.protocol == Protocol::Udp {
        // UDP can't be probed through a TCP stream; skip rather than misreport.
        return None;
    }

    let socket_addr = SocketAddr::new(target.ip, target.port);

    match timeout(
        tuning::CONNECT_PROBE_TIMEOUT,
        TcpStream::connect(socket_addr),
    )
    .await
    {
        Ok(Ok(stream)) => {
            let port =
                crate::fingerprinting::baseline_port(target.port, Protocol::Tcp, PortState::Open);
            let port = crate::fingerprinting::fingerprint_tcp(stream, port).await;
            Some((target.ip, port))
        }
        Ok(Err(e)) => {
            use std::io::ErrorKind;
            match e.kind() {
                // A refusal is a definite "closed"; report nothing to record.
                ErrorKind::ConnectionRefused => None,
                // Anything else reached the host but didn't complete: filtered.
                _ => Some((
                    target.ip,
                    crate::fingerprinting::baseline_port(
                        target.port,
                        Protocol::Tcp,
                        PortState::Filtered,
                    ),
                )),
            }
        }
        // Timeout: the probe was silently dropped, the classic firewall signature.
        Err(_) => Some((
            target.ip,
            crate::fingerprinting::baseline_port(target.port, Protocol::Tcp, PortState::Filtered),
        )),
    }
}

/// Probes a single [`Target`] for UDP using a standard OS `UdpSocket`.
async fn udp_port_prober(target: Target) -> ProbedPort {
    if target.protocol != Protocol::Udp {
        return None;
    }

    let socket_addr = SocketAddr::new(target.ip, target.port);
    let socket = match tokio::net::UdpSocket::bind("0.0.0.0:0").await {
        Ok(s) => s,
        Err(_) => return None,
    };

    if socket.connect(socket_addr).await.is_err() {
        return None;
    }

    // Send an empty UDP packet (or could be customized for specific payloads like DNS)
    if socket.send(b"").await.is_err() {
        return None; // Could be blocked locally
    }

    let mut buf = [0u8; 1024];
    match timeout(tuning::CONNECT_PROBE_TIMEOUT, socket.recv(&mut buf)).await {
        Ok(Ok(_)) => {
            // Valid response received, port is open
            Some((
                target.ip,
                crate::fingerprinting::baseline_port(target.port, Protocol::Udp, PortState::Open),
            ))
        }
        Ok(Err(e)) => {
            use std::io::ErrorKind;
            // ConnectionRefused on UDP usually means we received an ICMP Port Unreachable
            if e.kind() == ErrorKind::ConnectionRefused {
                Some((
                    target.ip,
                    crate::fingerprinting::baseline_port(
                        target.port,
                        Protocol::Udp,
                        PortState::Closed,
                    ),
                ))
            } else {
                // Any other error means it's likely OpenFiltered
                Some((
                    target.ip,
                    crate::fingerprinting::baseline_port(
                        target.port,
                        Protocol::Udp,
                        PortState::OpenFiltered,
                    ),
                ))
            }
        }
        Err(_) => {
            // Timeout means no ICMP unreachable and no valid response
            Some((
                target.ip,
                crate::fingerprinting::baseline_port(
                    target.port,
                    Protocol::Udp,
                    PortState::OpenFiltered,
                ),
            ))
        }
    }
}

/// Multi-port host discovery for unprivileged environments.
///
/// Sweeps the target networks by probing a small set of common infrastructure
/// ports: SSH (22), HTTP (80), HTTPS (443), SMB (445), and RDP (3389). Spreading
/// the probe across several ports catches hosts that only expose one of them,
/// which improves the odds of finding Linux, Windows, and embedded targets alike.
///
/// Once any port confirms a host is alive, the remaining probes for that IP are
/// skipped, so a host is recorded once rather than once per open port. Targets
/// are drawn from a shuffling [`Dispatcher`] to spread load across the network
/// instead of hammering one subnet at a time, and each probe waits out the
/// [`CONNECT_PROBE_TIMEOUT`](tuning::CONNECT_PROBE_TIMEOUT) so that hosts on slow
/// or distant links still register.
pub async fn discover(ips: IpSet, ctx: ScanContext) -> anyhow::Result<()> {
    let mut target_map = TargetMap::new();
    let port_set = PortSet::try_from(
        DISCOVERY_PORTS
            .iter()
            .map(|p| p.to_string())
            .collect::<Vec<_>>()
            .join(",")
            .as_str(),
    )?;
    target_map.add_unit(TargetSet::new(ips, port_set));

    let dispatcher = Dispatcher::new(target_map).with_batch_size(1024);
    let mut rx = dispatcher.run_shuffled(&ctx.handle);
    let found_hosts = Arc::new(DashSet::new());
    let mut pool = ProbePool::new(tuning::DISCOVERY_CONCURRENCY, |probed| {
        absorb_host(&ctx, probed)
    });

    while let Some(target) = rx.recv().await {
        if ctx.handle.should_stop() {
            break;
        }
        let found = Arc::clone(&found_hosts);
        pool.admit(prober(target, found)).await;
    }

    // Every target dispatched; wait out the probes still in flight.
    pool.drain().await;
    Ok(())
}

/// The outcome of one finished [`prober`] task: a live [`Host`], or `None` when
/// the target stayed silent or was already claimed by a parallel probe. A probe
/// never fails, so this is a plain [`Option`] rather than a `Result`.
type ProbedHost = Option<Host>;

/// Merges one finished discovery probe's host into the store. A freshly created
/// entry starts from [`Host::new`] and absorbs the probe's findings (RTT, any
/// extra IPs), so the recorded result is the same whether or not the host was
/// seen before.
fn absorb_host(ctx: &ScanContext, probed: ProbedHost) {
    if let Some(host) = probed {
        let ip = host.primary_ip();
        ctx.update_host(ip, |existing| existing.merge(host));
    }
}

/// Probes a single [`Target`] for host presence over a TCP connect.
///
/// To avoid needless traffic and wasted sockets, it exits early when the host has
/// already been identified by a parallel probe, for example when SSH responded
/// before HTTP finished.
///
/// `found_set` is a sharded [`DashSet`] rather than a `Mutex<HashSet>`, so the
/// many concurrent probes contend per shard instead of on one global lock.
/// `insert` returning `false` is what makes exactly the first prober to reach a
/// host emit it, while the rest fold to `None`.
async fn prober(target: Target, found_set: Arc<DashSet<IpAddr>>) -> ProbedHost {
    // Skip the connect entirely if another probe already found this host.
    if found_set.contains(&target.ip) {
        return None;
    }

    let socket_addr: SocketAddr = SocketAddr::new(target.ip, target.port);

    let start: Instant = Instant::now();
    let alive = match timeout(
        tuning::CONNECT_PROBE_TIMEOUT,
        TcpStream::connect(socket_addr),
    )
    .await
    {
        // A completed handshake means the host is alive.
        Ok(Ok(_)) => true,
        // Only these TCP errors imply the host answered at the IP/TCP layer. Any
        // other error (no route, permission denied, timeout) says nothing.
        Ok(Err(e)) => {
            use std::io::ErrorKind;
            matches!(
                e.kind(),
                ErrorKind::ConnectionRefused
                    | ErrorKind::ConnectionReset
                    | ErrorKind::ConnectionAborted
            )
        }
        Err(_elapsed) => false,
    };

    // `insert` returns false if a parallel probe already claimed this host, so
    // exactly the first prober to reach it emits the record; the rest fold to None.
    if alive && found_set.insert(target.ip) {
        Some(Host::new(target.ip).with_rtt(start.elapsed()))
    } else {
        None
    }
}