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
// 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/.

//! # SYN Port Probing
//!
//! Implements the privileged half of [`crate::scanner::scan`]: probing
//! specific `(address, port)` pairs with raw TCP SYN packets and
//! classifying each one by how - or whether - it responds, rather than
//! completing a full TCP handshake per port the way the unprivileged
//! fallback in [`crate::scanner::connect`] has to.
//!
//! A SYN+ACK means the port is open; a RST means it's closed; silence
//! until the scan's deadline means it's filtered - most likely a firewall
//! dropping the probe rather than responding to it.

use std::collections::HashMap;
use std::net::IpAddr;
use std::time::{Duration, Instant};

use pnet::packet::tcp::TcpPacket;
use tokio::sync::mpsc;

use crate::core::config::SendMode;
use crate::core::models::deadline::{AdaptiveDeadline, AdaptiveDeadlineConfig};
use crate::core::models::host::Host;
use crate::core::models::port::{Port, PortState, Protocol, Service};
use crate::core::models::target::Target;
use crate::core::models::timer::ScanBudget;
use crate::core::session::{ScanContext, ScanEvent};
use crate::error;
use crate::network::probe::{ProbeKind, ProbeTransport};
use crate::protocols::tcp::{self, ProbeResponse};
use crate::system::interface::SourceResolver;

use super::{SeqNum, send_syn};

/// How long a port scan runs, and how it adapts. Uses the same bounds as
/// [`super::DEADLINE_CONFIG`], since both send raw TCP SYN probes over the
/// same kind of network path.
const DEADLINE_CONFIG: AdaptiveDeadlineConfig = AdaptiveDeadlineConfig::new(
    ScanBudget::new(
        Duration::from_millis(200),
        Duration::from_micros(500),
        Duration::from_millis(3_000),
    ),
    ScanBudget::new(
        Duration::from_millis(70),
        Duration::from_micros(175),
        Duration::from_millis(1_000),
    ),
    Duration::from_millis(150),
    Duration::from_millis(1_500),
    4.0,
    20,
);

/// Outstanding probes, keyed by the target they were sent to, recording the
/// sequence number they were sent with and when.
type PendingProbes = HashMap<(IpAddr, u16), (SeqNum, Instant)>;

/// Probes specific `(address, port)` pairs with raw TCP SYN packets.
///
/// Unlike [`RoutedScanner`](super::RoutedScanner), which sends one SYN per
/// host purely to check for a pulse, this sends one per `(address, port)`
/// pair it's given and reports back what each one revealed.
pub struct SynPortScanner {
    /// Resolves, per target, the source address to send its probe from -
    /// consulting on-link subnets and the kernel routing table, and caching
    /// each answer so the many ports probed on one host cost a single lookup.
    resolver: SourceResolver,
    /// Shared state (host store, event channel, abort signal) for the scan
    /// this prober is part of.
    ctx: ScanContext,
    /// Transport used to send SYN probes and receive replies.
    transport: ProbeTransport,
    /// Governs how long this scan keeps running, adapting to observed
    /// round-trip times.
    deadline: AdaptiveDeadline,
    /// Probes sent but not yet resolved into an open/closed classification.
    pending: PendingProbes,
}

impl SynPortScanner {
    /// Builds a scanner that selects each probe's source via `resolver`, sized
    /// for a scan covering `target_count` `(address, port)` pairs.
    pub fn new(
        resolver: SourceResolver,
        ctx: ScanContext,
        target_count: usize,
        send_mode: SendMode,
    ) -> anyhow::Result<Self> {
        let transport = ProbeTransport::open_with(ProbeKind::TcpSyn, send_mode)?;
        let deadline = AdaptiveDeadline::new(DEADLINE_CONFIG, target_count);

        Ok(Self {
            resolver,
            ctx,
            transport,
            deadline,
            pending: PendingProbes::new(),
        })
    }

    /// Builds a scanner around an already-constructed transport, opening no
    /// sockets. The seam that lets tests drive probe/reply correlation with a
    /// mock sender and synthesized replies.
    #[cfg(test)]
    pub(crate) fn with_transport(
        resolver: SourceResolver,
        ctx: ScanContext,
        transport: ProbeTransport,
        target_count: usize,
    ) -> Self {
        Self {
            resolver,
            ctx,
            transport,
            deadline: AdaptiveDeadline::new(DEADLINE_CONFIG, target_count),
            pending: PendingProbes::new(),
        }
    }

    /// Consumes `targets`, sending a SYN probe for each TCP one - this
    /// scanner doesn't support UDP or SCTP yet, so those are skipped - and
    /// classifying every reply, until every probe has been resolved or the
    /// scan's deadline expires. Anything still outstanding at that point is
    /// reported as filtered.
    pub async fn scan(&mut self, mut targets: mpsc::Receiver<Target>) -> anyhow::Result<()> {
        let mut sending_finished = false;

        loop {
            if self.ctx.handle.should_stop() || self.deadline.has_expired() {
                break;
            }
            if sending_finished && self.pending.is_empty() {
                break;
            }

            tokio::select! {
                target = targets.recv(), if !sending_finished => {
                    match target {
                        Some(target) => self.send_probe(target),
                        None => sending_finished = true,
                    }
                }

                res = self.transport.rx.recv() => {
                    match res {
                        Some((bytes, ip)) => self.handle_reply(ip, &bytes),
                        None => break,
                    }
                }

                // Wakes periodically so the checks above are re-evaluated
                // even when no further replies arrive.
                _ = tokio::time::sleep(self.deadline.time_until_next_tick()) => {}
            }
        }

        self.resolve_remaining_as_filtered();
        Ok(())
    }

    fn send_probe(&mut self, target: Target) {
        if target.protocol != Protocol::Tcp {
            return;
        }

        let Some(src_addr) = self.resolver.resolve(target.ip) else {
            error!(
                verbosity = 2,
                "No route to {}; skipping {}:{}", target.ip, target.ip, target.port
            );
            return;
        };

        if let Some(seq_num) =
            send_syn(self.transport.tx.as_ref(), src_addr, target.ip, target.port)
        {
            self.pending
                .insert((target.ip, target.port), (seq_num, Instant::now()));
        }
    }

    /// Matches a reply against an outstanding probe and, if it is one,
    /// classifies it and records the port's state.
    fn handle_reply(&mut self, ip: IpAddr, bytes: &[u8]) {
        let Some(tcp_packet) = TcpPacket::new(bytes) else {
            return;
        };

        let key = (ip, tcp_packet.get_source());
        let Some(&(sent_seq, sent_at)) = self.pending.get(&key) else {
            return;
        };

        // Guards against stray or spoofed packets being mistaken for a reply.
        if tcp_packet.get_acknowledgement().wrapping_sub(1) != sent_seq {
            return;
        }

        let Some(response) = tcp::classify_probe_response(&tcp_packet) else {
            return;
        };

        self.pending.remove(&key);
        self.deadline.mark_activity();
        self.deadline.record_rtt(sent_at.elapsed());

        let state = match response {
            ProbeResponse::Open => PortState::Open,
            ProbeResponse::Closed => PortState::Closed,
        };
        self.record_port(ip, key.1, state);
    }

    /// Marks every probe still outstanding once the scan winds down as
    /// filtered: no SYN+ACK, no RST, nothing - the most common signature of
    /// a firewall silently dropping the packet rather than answering it.
    fn resolve_remaining_as_filtered(&mut self) {
        let remaining: Vec<(IpAddr, u16)> = self.pending.drain().map(|(key, _)| key).collect();
        for (ip, port) in remaining {
            self.record_port(ip, port, PortState::Filtered);
        }
    }

    fn record_port(&mut self, ip: IpAddr, port_num: u16, state: PortState) {
        let mut port = Port::new(port_num, Protocol::Tcp, state);
        let service_name = crate::fingerprinting::lookup_service_name(port_num, Protocol::Tcp)
            .unwrap_or("???".to_string());
        port.set_service(Service::new(service_name, 0));

        let mut host = self.ctx.store.entry(ip).or_insert_with(|| Host::new(ip));
        host.add_port(port);
        drop(host);

        let _ = self.ctx.events_tx.send(ScanEvent::HostUpdated(ip));
    }
}

// ╔════════════════════════════════════════════╗
// ║ ████████╗███████╗███████╗████████╗███████╗ ║
// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
// ║    ██║   ███████╗███████║   ██║   ███████║ ║
// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
// ╚════════════════════════════════════════════╝

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::Ipv4Addr;

    use pnet::ipnetwork::{IpNetwork, Ipv4Network};
    use pnet::packet::tcp::MutableTcpPacket;

    use crate::core::session::ScanSession;
    use crate::network::capture::CaptureGuard;
    use crate::network::probe::{MockSender, ProbeTransport};

    const SYN: u8 = 1 << 1;
    const RST: u8 = 1 << 2;
    const ACK: u8 = 1 << 4;
    const TARGET: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 200));

    /// An interface whose /24 contains [`TARGET`], so source resolution
    /// answers on-link without a kernel route probe.
    fn on_link_interface() -> pnet::datalink::NetworkInterface {
        pnet::datalink::NetworkInterface {
            name: "test0".to_string(),
            description: String::new(),
            index: 0,
            mac: None,
            ips: vec![IpNetwork::V4(
                Ipv4Network::new(Ipv4Addr::new(192, 168, 1, 50), 24).unwrap(),
            )],
            flags: 0,
        }
    }

    /// Builds a bare 20-byte TCP segment carrying the given source port,
    /// acknowledgement number, and flags - the shape a captured reply arrives
    /// in after the link and IP headers are stripped.
    fn tcp_segment(src_port: u16, ack: u32, flags: u8) -> Vec<u8> {
        let mut buf = vec![0u8; 20];
        let mut tcp = MutableTcpPacket::new(&mut buf).unwrap();
        tcp.set_source(src_port);
        tcp.set_destination(40_000);
        tcp.set_data_offset(5);
        tcp.set_acknowledgement(ack);
        tcp.set_flags(flags);
        buf
    }

    /// A scanner wired to a recording [`MockSender`] and an idle capture
    /// stream, plus the session store to assert against.
    fn scanner_with_mock() -> (SynPortScanner, ScanSession) {
        let (session, ctx) = ScanSession::new();
        let (_reply_tx, reply_rx) = tokio::sync::mpsc::unbounded_channel();
        let transport = ProbeTransport::from_parts(
            Box::new(MockSender::default()),
            reply_rx,
            CaptureGuard::noop(),
        );
        let resolver = SourceResolver::from_interfaces(&[on_link_interface()]);
        let scanner = SynPortScanner::with_transport(resolver, ctx, transport, 8);
        (scanner, session)
    }

    /// Sends a probe to `TARGET:port` and returns the sequence number it was
    /// recorded under, so a matching reply can be synthesized.
    fn probe(scanner: &mut SynPortScanner, port: u16) -> SeqNum {
        scanner.send_probe(Target {
            ip: TARGET,
            port,
            protocol: Protocol::Tcp,
        });
        scanner
            .pending
            .get(&(TARGET, port))
            .expect("probe recorded")
            .0
    }

    fn port_state(session: &ScanSession, port: u16) -> Option<PortState> {
        session
            .store
            .get(&TARGET)
            .and_then(|h| h.ports().find(|p| p.number() == port).map(|p| p.state()))
    }

    #[test]
    fn syn_ack_matching_probe_is_open() {
        let (mut scanner, session) = scanner_with_mock();
        let seq = probe(&mut scanner, 80);

        scanner.handle_reply(TARGET, &tcp_segment(80, seq.wrapping_add(1), SYN | ACK));

        assert_eq!(port_state(&session, 80), Some(PortState::Open));
        assert!(!scanner.pending.contains_key(&(TARGET, 80)));
    }

    #[test]
    fn rst_matching_probe_is_closed() {
        let (mut scanner, session) = scanner_with_mock();
        let seq = probe(&mut scanner, 81);

        scanner.handle_reply(TARGET, &tcp_segment(81, seq.wrapping_add(1), RST | ACK));

        assert_eq!(port_state(&session, 81), Some(PortState::Closed));
    }

    #[test]
    fn reply_with_wrong_ack_is_ignored() {
        let (mut scanner, session) = scanner_with_mock();
        let seq = probe(&mut scanner, 82);

        // Acknowledgement doesn't correspond to our sequence number: a stray
        // or spoofed segment, not a reply to our probe.
        scanner.handle_reply(TARGET, &tcp_segment(82, seq.wrapping_add(999), SYN | ACK));

        assert_eq!(port_state(&session, 82), None);
        assert!(scanner.pending.contains_key(&(TARGET, 82)));
    }

    #[test]
    fn reply_for_unprobed_port_is_ignored() {
        let (mut scanner, session) = scanner_with_mock();
        let seq = probe(&mut scanner, 80);

        // Same host, but a port we never probed.
        scanner.handle_reply(TARGET, &tcp_segment(1234, seq.wrapping_add(1), SYN | ACK));

        assert_eq!(port_state(&session, 1234), None);
        assert!(scanner.pending.contains_key(&(TARGET, 80)));
    }

    #[test]
    fn unanswered_probes_resolve_as_filtered() {
        let (mut scanner, session) = scanner_with_mock();
        probe(&mut scanner, 443);

        scanner.resolve_remaining_as_filtered();

        assert_eq!(port_state(&session, 443), Some(PortState::Filtered));
        assert!(scanner.pending.is_empty());
    }

    #[test]
    fn non_tcp_targets_are_not_probed() {
        let (mut scanner, _session) = scanner_with_mock();
        scanner.send_probe(Target {
            ip: TARGET,
            port: 53,
            protocol: Protocol::Udp,
        });
        assert!(scanner.pending.is_empty());
    }
}