zond-engine 0.14.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # Routed host discovery
//!
//! Finds hosts reached through a gateway, as against ones sitting on the local
//! segment. One raw TCP SYN per target, and anything that comes back credits
//! the host: the handshake is never completed, so an address answers whether or
//! not the port it was asked about is open.
//!
//! The counterpart of [`local`](super::local), which reaches a segment at the
//! link layer. Between them they are what a privileged discovery sweep is made
//! of, and which one a target gets is decided by
//! [`plan`](crate::scanner::plan) from this host's own routing table.
//!
//! Raw sockets, so root. What a probe is built from and how it reaches the wire
//! is [`raw`](super::raw), shared with every other strategy that opens one.

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

use crate::config::ProbeTuning;
use crate::evasion::SegmentShaping;
use crate::info;
use crate::journal::settle::{Outcome, Settled};
use crate::model::host::{HostStatus, StatusProtocol, StatusReason};
use crate::model::ip::set::IpSet;
use crate::model::technique::{TcpReply, TcpScanTechnique};
use crate::protocols as protocol;
use crate::scanner::pacing::deadline::AdaptiveDeadline;
use crate::scanner::pacing::retry::{ProbeLedger, Resolution, RetryPolicy};
use crate::scanner::session::ScanContext;
use crate::system::interface::RoutedTarget;
use crate::transport::probe::{Emission, ProbeKind, ProbeTransport};
use async_trait::async_trait;
use tokio::sync::mpsc::UnboundedSender;

use crate::report::ScannerKind;
use crate::report::StopReason;
use crate::scanner::strategy::raw::{
    DEADLINE_CONFIG, EvasionParts, RETRY_POLICY, SendFaults, SynToken, pacing_for, rate_within,
    send_init, send_syn,
};
use crate::scanner::strategy::sweep::HostSweep;
use crate::scanner::strategy::{HostScanner, StrategyError};

/// The fastest a routed sweep puts probes on the wire, in probes per second.
///
/// A probe's chance of being answered is not a constant of the path; it falls
/// as the rate rises. Unpaced, a sweep of a large range loses most of its first
/// attempt, and the hosts behind those packets are recovered only by
/// retransmitting into a quieter moment - coverage bought at several times the
/// traffic, and only where the attempt budget happens to outlast the policer.
///
/// So the rate is set below where that loss sets in rather than at whatever the
/// socket will accept. Measured against a /22 where every address answers, the
/// first attempt alone finds a sixth to a third of the range unpaced and around
/// three quarters of it at this rate, and the sweep needs roughly half the
/// packets to finish. Loss becomes visible again several times higher.
///
/// What it costs is the time a large range takes to emit, which grows linearly:
/// a /22 leaves in a quarter of a second, a /16 in sixteen. That is the trade,
/// and it is the right way round - a probe not yet sent and a probe dropped by a
/// policer are equally invisible, and only the first is under our control.
pub(super) const PROBE_RATE_PER_SEC: NonZeroU32 = NonZeroU32::new(4_000).expect("a non-zero rate");

/// Whether `bytes` is one of the two segments a SYN probe can draw *and be
/// credited for without correlating it*.
///
/// A SYN+ACK and a RST each require the target to have received the probe and
/// answered it, and nothing else a SYN elicits sets either flag. Anything else
/// from the same address is traffic that happens to share a host with the scan.
///
/// A challenge ACK is excluded, though it is a genuine answer.
/// It says a listener holds a connection half-open, which the port scanner acts
/// on, but the port scanner earns that by checking the probe's nonce against
/// its ledger, and this sweep has no ledger and checks nothing. A bare ACK is
/// the commonest segment on any network: every established connection emits a
/// stream of them, and a scan of an address somebody is talking to would credit
/// the host on the strength of that conversation. The flags of a SYN+ACK or a
/// RST are their own correlation; the flags of an ACK are not.
///
/// The asymmetry is the point. Evidence usable where it can be tied to a probe
/// is not usable where it cannot.
fn answers_a_syn_probe(bytes: &[u8]) -> bool {
    protocol::tcp::parse(bytes)
        .ok()
        .and_then(|tcp| protocol::tcp::classify_probe_response(&tcp))
        .is_some_and(|reply| !matches!(reply, TcpReply::ChallengeAck))
}

/// The port a SYN sweep asks about.
///
/// Any port answers a discovery probe, since the handshake is never completed
/// and both a SYN+ACK and a RST prove the host. 443 is chosen because a filter
/// that passes anything usually passes it.
const SYN_DISCOVERY_PORT: u16 = 443;

/// Which packet a routed sweep asks with.
///
/// The sweep is the same either way. Its pacing, its retry schedule, its
/// deadline and its audit are properties of asking a list of addresses whether
/// anything is there, not of the packet that asks. Four things do follow from
/// the packet: the transport the probes and their answers travel over, what a
/// probe is, what counts as an answer to one, and what the report says the host
/// was found by.
///
/// There are two because a scan asking about SCTP ports and a scan asking about
/// TCP ports are putting different questions to the network. A host behind a
/// filter that passes one transport and drops the other answers exactly one of
/// these probes, and sweeping it with the wrong one reports it down while its
/// ports are listening.
/// Non-exhaustive: a probe kind per transport, and the transports a sweep can
/// ask with is a list that has grown twice already.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SweepProbe {
    /// A TCP SYN, never completed.
    Syn {
        /// The port every probe leaves from when a caller pinned one, or `None`
        /// for a fresh high port per probe. A fresh port and a fresh sequence
        /// number together are what let a reply name the attempt it answers; a
        /// pinned one keeps the sequence number varying and buys a port a filter
        /// is known to trust.
        src_port: Option<u16>,
        /// The port every probe is aimed at.
        dst_port: u16,
    },
    /// An SCTP INIT, for a scan that asked about SCTP.
    ///
    /// Both answers it can draw prove the host: an INIT-ACK is an endpoint
    /// accepting the association, an ABORT is the same stack refusing it. The
    /// association is never completed, so nothing is left half-open.
    Init {
        /// The one port every probe leaves from. Fixed rather than fresh per
        /// probe, because it is what the capture filter narrows on; the Initiate
        /// Tag is what varies per attempt.
        src_port: u16,
        /// The port every probe is aimed at, which a caller takes from the ports
        /// the scan is about. A filter that passes SCTP at all is likeliest to
        /// pass it to the port something is running on.
        dst_port: u16,
    },
}

impl SweepProbe {
    /// A SYN sweep, asking the port a discovery probe asks by default.
    ///
    /// Any port serves, since the handshake is never completed and both answers
    /// prove the host; 443 is picked because a filter that passes anything
    /// usually passes it.
    pub const fn syn(src_port: Option<u16>) -> Self {
        Self::Syn {
            src_port,
            dst_port: SYN_DISCOVERY_PORT,
        }
    }

    /// An INIT sweep, leaving from `src_port` and asking `dst_port`.
    pub const fn init(src_port: u16, dst_port: u16) -> Self {
        Self::Init { src_port, dst_port }
    }

    /// The transport this sweep's probes and answers travel over.
    const fn transport(self) -> ProbeKind {
        match self {
            Self::Syn { .. } => ProbeKind::TcpSyn,
            Self::Init { src_port, .. } => ProbeKind::Sctp {
                reply_port: src_port,
            },
        }
    }

    /// Which strategy a sweep asking this way reports itself as.
    const fn scanner_kind(self) -> ScannerKind {
        match self {
            Self::Syn { .. } => ScannerKind::Routed,
            Self::Init { .. } => ScannerKind::RoutedSctp,
        }
    }

    /// Whether `bytes` answers a probe of this kind at all.
    ///
    /// The capture filter has already narrowed what arrives, but it is a
    /// performance boundary rather than a guarantee: over IPv6 the TCP half
    /// cannot be narrowed on flags at all, and a transport can be built with no
    /// filter. This is what holds both families to one standard.
    fn answers(self, bytes: &[u8]) -> bool {
        match self {
            Self::Syn { .. } => answers_a_syn_probe(bytes),
            // Either chunk an INIT can draw, and nothing else. A packet from an
            // association this sweep is not part of carries neither.
            Self::Init { .. } => protocol::sctp::parse(bytes)
                .ok()
                .and_then(|packet| protocol::sctp::classify_probe_response(&packet))
                .is_some(),
        }
    }

    /// The attempt `bytes` names, for matching against an outstanding probe.
    fn token_of(self, bytes: &[u8], padding: u16) -> Option<SweepToken> {
        match self {
            Self::Syn { .. } => protocol::tcp::parse(bytes).ok().map(|tcp| {
                SweepToken::Syn(SynToken {
                    seq: protocol::tcp::echoed_nonce(TcpScanTechnique::Syn, &tcp, padding),
                    src_port: tcp.destination_port(),
                })
            }),
            Self::Init { .. } => protocol::sctp::parse(bytes)
                .ok()
                .map(|packet| SweepToken::Init(protocol::sctp::echoed_nonce(&packet))),
        }
    }

    /// What a report says about a host this probe found.
    fn evidence(self) -> StatusReason {
        match self {
            // A TCP segment from a probed address is proof of a live stack
            // whichever flags it carries: a SYN+ACK and a RST both require the
            // host to have received the probe and answered it.
            Self::Syn { .. } => {
                StatusReason::new(StatusProtocol::TcpSyn, "tcp reply to a discovery probe")
            }
            Self::Init { .. } => {
                StatusReason::new(StatusProtocol::Sctp, "sctp reply to a discovery probe")
            }
        }
    }
}

/// What identifies one attempt of a sweep's probe on the wire.
/// Non-exhaustive, and for the same reason as [`SweepProbe`]: one token kind per
/// probe kind, so the two grow together.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SweepToken {
    /// A SYN's sequence number and source port. See [`SynToken`].
    Syn(SynToken),
    /// An INIT's Initiate Tag, which RFC 4960 §3.3.2 obliges a peer to echo in
    /// the verification tag of whatever it answers with.
    Init(u32),
}

/// Checks whether addresses behind a gateway are alive, putting one raw probe
/// to each and crediting whatever comes back.
///
/// The handshake is never completed, so an address answers whether or not the
/// port it was asked about is open, and every probe leaves from the source
/// address its route named. [`new`](Self::new) opens the raw transport it
/// sends through, which takes root; [`with_transport`](Self::with_transport)
/// takes one the caller opened.
pub struct RoutedScanner {
    /// Shared state (host store, event channel, abort signal) for the scan
    /// this explorer is part of.
    ctx: ScanContext,
    /// The source address to probe each target from. Kept for the whole sweep
    /// rather than consumed by the first pass, since a retry has to leave from
    /// the same place the probe it repeats did.
    sources: HashMap<IpAddr, IpAddr>,
    /// Membership-and-count view of the targets, used to filter incoming
    /// replies and to size the adaptive deadline.
    ips: IpSet,
    /// Transport used to send SYN probes and receive replies.
    transport: ProbeTransport,
    /// What this sweep asks with, and everything that follows from it: the
    /// packet, what counts as an answer, and what the report credits.
    probe: SweepProbe,
    /// The IP-header state every SYN carries: its hop limit and any evasion
    /// override of the IP header.
    emission: Emission,
    /// The segment-level shaping every SYN carries: payload padding, and a bad
    /// TCP checksum when the sweep asked for one.
    shaping: SegmentShaping,
    /// The decoy source addresses every SYN is copied from, or empty.
    decoys: Vec<IpAddr>,
    /// Governs how long this sweep keeps running, adapting to observed
    /// round-trip times.
    deadline: AdaptiveDeadline,
    /// Where to forward newly discovered addresses for hostname
    /// resolution, if enabled.
    dns_tx: Option<UnboundedSender<IpAddr>>,
    /// The outstanding probes, the retry queue, what has answered and the
    /// run's counters, shared with the other two probing sweeps.
    sweep: HostSweep<SweepToken>,
    /// Targets whose first probe has not left yet, released by the send ticker.
    pending: std::vec::IntoIter<IpAddr>,
    /// How often the send ticker fires, and how many probes it releases each
    /// time. Together they are the configured rate; see [`pacing_for`].
    send_tick: Duration,
    batch: usize,
    /// Why probes that could not be sent could not be sent, if any could not.
    ///
    /// Kept so the reason survives into the report. The count of failed sends is
    /// already in the audit, but a count cannot distinguish a host with no route
    /// to the target from one refusing raw sockets, and those call for opposite
    /// responses from whoever is reading.
    faults: SendFaults,
}

#[async_trait]
impl HostScanner for RoutedScanner {
    fn kind(&self) -> ScannerKind {
        self.probe.scanner_kind()
    }

    async fn discover_hosts(&mut self) -> Result<(), StrategyError> {
        let mut send_tick = tokio::time::interval(self.send_tick);
        // Without this, a ticker that went unpolled while the loop was busy with
        // replies hands back every missed tick at once, and the pacing it exists
        // to impose evaporates exactly when the queue is longest.
        send_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);

        // The loop yields why it stopped, so the audit cannot report a reason
        // the code never actually took.
        let reason = loop {
            let now = Instant::now();
            // A sweep settles: it was asked whether an address is there and
            // has now asked as many times as the policy allows.
            self.sweep.service_retries(&self.ctx, now);

            let all_responded = self.sweep.all_responded(self.ips.len());
            if let Some(cause) = self.ctx.handle.stopped() {
                break cause.into();
            }
            if all_responded {
                break StopReason::AllResponded;
            }
            // Nothing outstanding and nothing left to send means every target
            // has either answered or been asked as many times as it is going
            // to be. Waiting longer cannot change the result.
            //
            // Both queues have to be checked, not just the ledger: at the first
            // iteration the ledger is empty because no probe has left yet, and
            // stopping there would end the sweep before it began.
            if self.nothing_left_to_send() && self.sweep.ledger.is_empty() {
                break StopReason::AttemptsSpent;
            }
            if self.deadline.hard_deadline_passed() {
                break StopReason::DeadlineExpired;
            }

            let sending = !self.nothing_left_to_send();
            let tick = self.sweep.idle_delay(&self.deadline, now);

            tokio::select! {
                res = self.transport.rx.recv() => {
                    match res {
                        Some(reply) => {
                            self.sweep.audit.record_segment();
                            self.handle_discovery_reply(reply.source, &reply.bytes, Instant::now());
                        }
                        None => break StopReason::StreamClosed,
                    }
                },

                _ = send_tick.tick(), if sending => {
                    self.send_allowance(Instant::now());
                }

                // Wakes when the next probe is due, so a retry is queued on time
                // even though nothing is arriving to wake the loop otherwise.
                // Only while idle: with probes still to send, the ticker above
                // is what governs how often the loop comes round.
                _ = tokio::time::sleep(tick), if !sending => {}
            }
        };

        // What the sweep did not earn a verdict for, so a resumed one asks again
        // rather than skipping it. None of these carries a position: a probe
        // still mid-schedule was cut off rather than spent, one still queued was
        // never sent, and one with no route was never asked.
        let outstanding = self.sweep.ledger.drain_unresolved().len() as u64;
        self.ctx
            .record_many_outcomes(Outcome::Interrupted, outstanding);
        self.ctx
            .record_many_outcomes(Outcome::Unasked, self.pending.len() as u64);
        // Distinct addresses rather than failed sends: a target with no route
        // fails on every retry, and counting each of those would report more
        // unreached addresses than the sweep had.
        self.ctx
            .record_many_outcomes(Outcome::Unroutable, self.faults.addresses.len() as u64);

        // A sweep whose probes never left is not a sweep that found nothing, and
        // the difference is invisible in every number a caller reads: the host
        // count is zero either way, no strategy errored, and the audit line that
        // does say so is a log at verbosity 1. So it is recorded as a failure,
        // which is the one channel a library consumer sees without opting in.
        //
        // Reported once with the first cause rather than once per probe. Sixteen
        // identical lines say nothing the first does not, and a sweep of a large
        // range would bury everything else in the report.
        //
        // **Only the failures that are about this host.** An address with no
        // route is not a strategy that did not run: the strategy ran, and that
        // address is not reachable from here. Recorded as a failure it made
        // every scan of a dual-stack name on an IPv4-only network report itself
        // as partial, which is the surest way to teach a reader to ignore the
        // warning that matters. It is recorded against the address instead, just
        // below.
        if let Some(reason) = &self.faults.broken {
            let broken = self.sweep.audit.sends_failed - self.faults.unroutable_count;
            self.ctx.record_failure(
                ScannerKind::Routed,
                format!(
                    "{broken} of {} probes could not be sent: {reason}",
                    self.sweep.audit.sends_attempted,
                ),
            );
        }

        // Said once, at the level a person watching a scan sees: an address they
        // named was not covered, and nothing else in the output would tell them
        // so. Nothing is wrong with the scan, so it carries neither an error
        // prefix nor the operating system's errno, that is a diagnostic detail
        // and it is on the `-v` line beside the send that failed.
        //
        // The address and nothing else. That it went unscanned follows from
        // there being no route to it, and saying so out loud is a line of
        // output that tells a reader what they have just read.
        for address in &self.faults.addresses {
            self.ctx.record_unroutable(*address);
        }

        if let Some((address, _)) = &self.faults.unroutable {
            match self.faults.unroutable_count.saturating_sub(1) {
                0 => info!("no route to {address}"),
                1 => info!("no route to {address} and 1 other address"),
                more => info!("no route to {address} and {more} other addresses"),
            }
        }

        // Read before the transport is dropped, since the counters live with
        // the capture threads it keeps alive.
        let capture = self.transport.capture_counts();
        let targets = self.ips.len();
        self.sweep.report(
            &self.ctx,
            "routed-discovery",
            ScannerKind::Routed,
            targets,
            reason,
            capture,
        );
        Ok(())
    }
}

impl RoutedScanner {
    /// A sweep of `targets`, each already paired with the source address to
    /// probe it from, over a transport this constructor opens.
    ///
    /// Hosts land in `ctx`, which is also where an abort is read from, and
    /// every address found is posted to `dns_tx` for a reverse lookup; pass
    /// `None` to resolve no hostnames. `tuning` supplies the retry schedule,
    /// the probe rate the sweep paces itself to, and the evasion profile that
    /// shapes each packet and decides how the transport is opened.
    ///
    /// Fails when that transport cannot be opened, which is what happens
    /// without root.
    pub fn new(
        targets: Vec<RoutedTarget>,
        ctx: ScanContext,
        dns_tx: Option<UnboundedSender<IpAddr>>,
        tuning: ProbeTuning,
    ) -> Result<Self, StrategyError> {
        Self::asking(
            SweepProbe::syn(tuning.evasion.source_port),
            targets,
            ctx,
            dns_tx,
            tuning,
        )
    }

    /// A sweep of `targets` that asks over SCTP, sending one INIT per address to
    /// `dst_port` instead of a SYN.
    ///
    /// For a scan whose ports name SCTP. A host that answers only SCTP is
    /// reported down by a SYN sweep, and its ports are never reached: the port
    /// phase probes what discovery found. `dst_port` is the caller's to choose
    /// from the ports the scan is about; see [`SweepProbe::Init`].
    ///
    /// Fails when the raw transport cannot be opened, which is what happens
    /// without root.
    pub fn over_sctp(
        targets: Vec<RoutedTarget>,
        ctx: ScanContext,
        dns_tx: Option<UnboundedSender<IpAddr>>,
        tuning: ProbeTuning,
        dst_port: u16,
    ) -> Result<Self, StrategyError> {
        let src_port = tuning
            .evasion
            .source_port
            .unwrap_or_else(|| rand::random_range(50_000..u16::MAX));
        Self::asking(
            SweepProbe::init(src_port, dst_port),
            targets,
            ctx,
            dns_tx,
            tuning,
        )
    }

    /// The constructor both of the above are: it opens the transport `probe`
    /// calls for and hands everything else to [`build`](Self::build).
    fn asking(
        probe: SweepProbe,
        targets: Vec<RoutedTarget>,
        ctx: ScanContext,
        dns_tx: Option<UnboundedSender<IpAddr>>,
        tuning: ProbeTuning,
    ) -> Result<Self, StrategyError> {
        let transport = ProbeTransport::open_with(
            probe.transport(),
            tuning.evasion.effective_send_mode(tuning.send_mode),
        )?;
        Ok(Self::build(
            targets,
            ctx,
            dns_tx,
            transport,
            probe,
            tuning.evasion.emission(),
            tuning.evasion.segment_shaping(),
            tuning.evasion.decoys.clone(),
            RETRY_POLICY.configured(tuning.retry),
            rate_within(
                tuning.max_probe_rate,
                tuning.min_probe_rate,
                PROBE_RATE_PER_SEC,
            ),
        ))
    }

    /// Builds a sweep around an already-opened transport, so the caller decides
    /// how probes reach the wire and where replies come from.
    ///
    /// This is the constructor for a caller orchestrating their own scan.
    /// [`new`](Self::new) opens a transport with the settings this engine would
    /// choose; this one takes whatever the caller opened, which is what makes it
    /// possible to scan through a transport built with a particular send mode or
    /// bound to particular interfaces.
    ///
    /// Paired with a synthetic transport (`ProbeTransport::from_parts`, behind
    /// the `test-support` feature) it is also the seam that lets liveness
    /// detection and RTT correlation be driven against a simulated network
    /// rather than a real one.
    pub fn with_transport(
        targets: Vec<RoutedTarget>,
        ctx: ScanContext,
        dns_tx: Option<UnboundedSender<IpAddr>>,
        transport: ProbeTransport,
    ) -> Self {
        Self::with_transport_asking(targets, ctx, dns_tx, transport, SweepProbe::syn(None))
    }

    /// [`with_transport`](Self::with_transport) for a sweep asking something
    /// other than a SYN.
    ///
    /// The transport has to be one `probe` would have opened: an INIT sweep
    /// reading a capture filtered for TCP hears nothing, and the silence is
    /// indistinguishable from a range with nothing on it.
    pub fn with_transport_asking(
        targets: Vec<RoutedTarget>,
        ctx: ScanContext,
        dns_tx: Option<UnboundedSender<IpAddr>>,
        transport: ProbeTransport,
        probe: SweepProbe,
    ) -> Self {
        Self::build(
            targets,
            ctx,
            dns_tx,
            transport,
            probe,
            Emission::routed(),
            SegmentShaping::default(),
            Vec::new(),
            RETRY_POLICY,
            PROBE_RATE_PER_SEC,
        )
    }

    /// The common constructor, taking the retry schedule and the send rate as
    /// arguments because the sweep's own deadline is derived from both and so
    /// has to be settled before anything is built.
    #[allow(clippy::too_many_arguments)]
    fn build(
        targets: Vec<RoutedTarget>,
        ctx: ScanContext,
        dns_tx: Option<UnboundedSender<IpAddr>>,
        transport: ProbeTransport,
        probe: SweepProbe,
        emission: Emission,
        shaping: SegmentShaping,
        decoys: Vec<IpAddr>,
        retry: RetryPolicy,
        rate_per_sec: NonZeroU32,
    ) -> Self {
        let mut ips = IpSet::new();
        let mut order = Vec::with_capacity(targets.len());
        let mut sources = HashMap::with_capacity(targets.len());
        for RoutedTarget { target, source } in targets {
            ips.insert(target);
            if sources.insert(target, source).is_none() {
                order.push(target);
            }
        }
        ips.canonicalize();

        let target_count = sources.len();

        // The sweep has to outlive both of the limits it sets itself: its own
        // retry schedule, or probes are given up on having never been fully
        // asked, and its own send rate, or the sweep is cut off mid-send. The
        // second fails invisibly - an address never probed is indistinguishable
        // from one with nothing on it - which is why it is derived here rather
        // than left to a constant that has to be remembered.
        let (send_tick, batch) = pacing_for(rate_per_sec);
        let send_duration =
            Duration::from_secs_f64(target_count as f64 / f64::from(rate_per_sec.get()));
        let deadline_config =
            DEADLINE_CONFIG.allowing_for(retry.worst_case_probe_lifetime() + send_duration);

        Self {
            ctx,
            sources,
            ips,
            transport,
            probe,
            emission,
            shaping,
            decoys,
            deadline: AdaptiveDeadline::new(deadline_config, target_count),
            dns_tx,
            sweep: HostSweep::new(ProbeLedger::new(retry, target_count)),
            pending: order.into_iter(),
            send_tick,
            batch,
            faults: SendFaults::default(),
        }
    }

    /// Records a raw TCP reply from `ip` as evidence the host is alive,
    /// crediting it with a round-trip time if the reply's acknowledgement
    /// number matches an outstanding probe.
    fn handle_discovery_reply(&mut self, ip: IpAddr, bytes: &[u8], now: Instant) {
        if !self.ips.contains(&ip) {
            self.sweep.audit.record_off_target();
            return;
        }

        // Not every TCP segment from a probed address answers a probe, and over
        // IPv6 the kernel no longer guarantees otherwise: `tcp[tcpflags]` does
        // not compile for that family, so the transport admits established
        // traffic too and the narrowing has to happen here.
        //
        // Checking it is what keeps the two families held to one standard. The
        // IPv4 half has only ever seen SYN+ACK and RST because the filter
        // dropped the rest; without the same test, an ACK from an IPv6 host the
        // user happens to be connected to would credit a discovery this scan did
        // not make, on evidence the IPv4 path has never accepted.
        if !self.probe.answers(bytes) {
            self.sweep.audit.record_off_target();
            return;
        }

        // The address answered, which is a verdict however the reply was timed.
        self.ctx.settle_address(ip, Settled::Answered);

        let resolution = self.resolve_probe(ip, bytes, now);
        let rtt = resolution.and_then(|resolution| resolution.rtt);
        if rtt.is_none() {
            self.sweep.audit.record_reply_without_rtt();
        }

        // Host mutation only; the guard is dropped and the event emitted inside
        // `write_host`, so the deadline and DNS follow-ups below never run under
        // the store lock.
        // Evidence goes in whatever this sweep has seen before; the return
        // value is ignored, because it reports store novelty and
        // the decisions below are about *this sweep's* first sighting.
        // Whichever answer arrived, it required the host to have received the
        // probe and answered it: a SYN+ACK and a RST both do, and so do an
        // INIT-ACK and an ABORT. Discovery already treats either of a pair as an
        // answer; this records which packet proved it.
        let evidence = self.probe.evidence();
        self.ctx.write_host(ip, |host| {
            let was_up = host.status().is_up();
            host.record_evidence(HostStatus::Up, evidence.clone());

            if let Some(rtt) = rtt {
                host.add_rtt_from(rtt, evidence.protocol.clone());
                return true;
            }
            !was_up
        });

        if self.sweep.responded.insert(ip) {
            self.sweep
                .audit
                .record_host_found(resolution.and_then(|resolution| resolution.answered_attempt));
            self.deadline.mark_activity();
            if let Some(dns) = &self.dns_tx {
                let _ = dns.send(ip);
            }
        }

        if let Some(rtt) = rtt {
            self.deadline.record_rtt(rtt);
        }
    }

    /// Retires the probe to `ip` and reports what resolving it revealed.
    ///
    /// Correlation is attempted twice on purpose. The first pass matches the
    /// segment against the exact attempt it acknowledges, which is what yields a
    /// true round trip even for a target that had to be asked more than once.
    /// The second accepts the reply on its own terms: for discovery the question
    /// is only whether something is there, and a TCP segment from a probed
    /// address answers that whether or not it can be tied to a particular
    /// attempt. Retiring the probe either way is what stops a host that has
    /// already proved it exists from being asked again.
    fn resolve_probe(&mut self, ip: IpAddr, bytes: &[u8], now: Instant) -> Option<Resolution> {
        let token = self
            .probe
            .token_of(bytes, self.shaping.padding.unwrap_or(0));

        token
            .and_then(|token| self.sweep.ledger.resolve(&ip, Some(token), now))
            .or_else(|| self.sweep.ledger.resolve(&ip, None, now))
    }

    /// Whether every probe this sweep intends to send has left.
    fn nothing_left_to_send(&self) -> bool {
        self.sweep.retries.is_empty() && self.pending.len() == 0
    }

    /// Releases one tick's worth of probes: retries first, then targets not yet
    /// asked.
    fn send_allowance(&mut self, now: Instant) {
        for _ in 0..self.batch {
            // A queued retry first, unless its host was asked too recently for
            // the gap the scan keeps. A retry turned away goes to the back of
            // the queue rather than out of it, and the allowance moves on to a
            // fresh target instead of spending the slot waiting.
            //
            // Only a retry can be turned away. The gap is measured from a
            // previous probe and a sweep sends one per host per attempt, so a
            // first attempt reaches an address this sweep has never asked
            // about and there is no earlier probe for it to be too close to.
            let queued = match self.sweep.retries.pop_front() {
                Some(target) if self.ctx.host_ready_at(target, now).is_none() => Some(target),
                Some(target) => {
                    self.sweep.retries.push_back(target);
                    None
                }
                None => None,
            };

            let Some(target) = queued.or_else(|| self.pending.next()) else {
                return;
            };
            self.probe(target, now);
        }
    }

    /// Sends one SYN at `target` and records the attempt.
    ///
    /// Used for the first attempt and every retry alike. A probe that cannot be
    /// sent is not armed; the ledger has already charged the attempt by the time
    /// a retry reaches here, so an unroutable target still runs out of attempts
    /// on schedule.
    fn probe(&mut self, target: IpAddr, now: Instant) {
        let Some(&source) = self.sources.get(&target) else {
            return;
        };

        let token = match self.probe {
            SweepProbe::Syn { src_port, dst_port } => send_syn(
                self.transport.tx.as_ref(),
                source,
                target,
                None,
                dst_port,
                src_port,
                EvasionParts {
                    emission: self.emission,
                    shaping: self.shaping,
                    decoys: &self.decoys,
                },
                &mut self.faults,
            )
            .map(SweepToken::Syn),
            SweepProbe::Init { src_port, dst_port } => send_init(
                self.transport.tx.as_ref(),
                source,
                target,
                None,
                dst_port,
                src_port,
                &self.decoys,
                self.emission,
                &mut self.faults,
            )
            .map(SweepToken::Init),
        };
        self.sweep.audit.record_send(token.is_some());

        if let Some(token) = token {
            // Only for a probe that reached the wire, on the same reasoning
            // `record_send` gives for keeping a refused one out of the
            // congestion window: a packet the kernel would not take occupied
            // nothing at the target and must not spend its slot.
            self.ctx.host_probed(target, now);
            self.sweep.ledger.arm(target, target, token, (), now);
        }
    }
}