Skip to main content

zond_engine/scanner/
plan.rs

1// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
2//
3// This file is part of Zond Engine, licensed under the GNU Affero General
4// Public License, version 3 or later. See the LICENSE file for details, or
5// <https://www.gnu.org/licenses/agpl-3.0.html>.
6//
7// SPDX-License-Identifier: AGPL-3.0-or-later
8
9//! # Deciding what a scan will do, before it does any of it
10//!
11//! A plan is the set of strategies a scan intends to run, worked out from the
12//! targets and the host's own network configuration, with nothing opened and
13//! nothing sent. [`discover`](crate::scanner::discover) and
14//! [`scan`](crate::scanner::scan) build one and immediately execute it. A caller
15//! orchestrating their own scan can build one, look at it, change it, and run
16//! the parts they want.
17//!
18//! Planning settles which interface reaches a target, whether a `/64` can be
19//! walked, whether a link-local address without a zone can be probed, whether a
20//! sweep may take leads from the host's neighbour table, and which protocols need an
21//! unprivileged fallback. As a value, a plan can be printed for a dry run, trimmed
22//! (sweep two of five links), or asserted on in a test against a hand-written
23//! interface table.
24//!
25//! ## What a plan costs to build
26//!
27//! No packets and no sockets. Building one reads the interface list, the routing
28//! table and, for a sweep, the IPv6 neighbour table, the same reads
29//! [`crate::system::interface`] performs for any caller.
30//!
31//! ## What a plan does not promise
32//!
33//! That every step will run. A step becomes a strategy through
34//! [`DiscoveryStep::into_scanner`], which opens sockets and can fail: a capture that
35//! cannot be opened, an interface that disappeared since planning. Those surface as
36//! a [`StrategyError`] per step, and the scan continues with the rest.
37
38use std::collections::{BTreeSet, HashMap, HashSet};
39use std::net::IpAddr;
40
41use tokio::sync::mpsc::UnboundedSender;
42
43use crate::config::limits;
44use crate::config::{ProbeTuning, ZondConfig};
45use crate::model::exclusion::Exclusions;
46use crate::model::ip::range::{IpRange, Ipv6Range};
47use crate::model::ip::scoped::ZoneMap;
48use crate::model::ip::set::IpSet;
49use crate::model::mac::MacAddr;
50use crate::model::port::Protocol;
51use crate::model::technique::TcpScanTechnique;
52use crate::report::ScannerKind;
53use crate::scanner::session::ScanContext;
54use crate::scanner::strategy::connect::{
55    ConnectPortScanner, ConnectScanner, ConnectUdpPortScanner,
56};
57use crate::scanner::strategy::local::{LocalScanner, Scope};
58use crate::scanner::strategy::ports::{
59    IdlePortScanner, SctpPortScanner, TcpPortScanner, UdpPortScanner,
60};
61use crate::scanner::strategy::routed::{RoutedScanner, SynPorts};
62use crate::scanner::strategy::{HostScanner, PortScanner, StrategyError};
63use crate::system::interface::Link;
64use crate::system::interface::{self, RoutedTarget};
65use crate::system::neighbor_cache;
66use crate::system::privilege::Privilege;
67use crate::{counted, info, warn};
68
69/// Something the scan will not do, decided at planning time.
70///
71/// The ground was never probed, for a reason knowable before anything is sent. It
72/// is reported so a caller can tell "nothing is there" from "nobody looked".
73#[non_exhaustive]
74#[derive(Debug, Clone)]
75pub struct RefusedStep {
76    /// The strategy that would have taken this work.
77    pub scanner: ScannerKind,
78    /// One short line: the ground, then the reason and any remedy in brief. The
79    /// full reasoning is on the function that builds each refusal.
80    pub reason: String,
81}
82
83impl RefusedStep {
84    /// The TCP half left undone because `technique` cannot be expressed without
85    /// raw sockets.
86    ///
87    /// A connect scan answers roughly what a SYN scan asks, but cannot send a FIN,
88    /// a flagless segment or a bare ACK, so it cannot stand in for those.
89    ///
90    /// Reached from [`PortScanPlan::build`] when there are no raw sockets, and from
91    /// the scan's coverage check when a raw socket was expected and would not open.
92    pub fn technique_needs_raw_sockets(technique: TcpScanTechnique) -> Self {
93        Self {
94            scanner: ScannerKind::for_raw_tcp(technique),
95            reason: format!("tcp ports: {technique} scan needs raw sockets (sudo)"),
96        }
97    }
98
99    /// SCTP ports were named by a scan with no raw sockets to probe them with.
100    ///
101    /// There is no unprivileged INIT scan: the kernel offers no way to send a chunk
102    /// and read the answer without completing an association.
103    pub fn sctp_needs_raw_sockets() -> Self {
104        Self {
105            scanner: ScannerKind::SctpPort,
106            reason: "sctp ports: init scan needs raw sockets (sudo)".to_string(),
107        }
108    }
109
110    /// SCTP ports were named for a scan running as an idle scan, which probes
111    /// through a third party and has no way to carry an INIT.
112    ///
113    /// An INIT sent directly would leave this host's own address on the target.
114    pub fn sctp_not_in_an_idle_scan() -> Self {
115        Self {
116            scanner: ScannerKind::SctpPort,
117            reason: "sctp ports: not probed in an idle scan".to_string(),
118        }
119    }
120
121    /// UDP ports were named for a scan running as an idle scan, for the reason
122    /// [`sctp_not_in_an_idle_scan`](Self::sctp_not_in_an_idle_scan) gives:
123    /// the zombie's counter moves only for the TCP segments it answers, so a
124    /// datagram has no way to be read through it, and one sent directly would
125    /// put this host's address on the target.
126    pub fn udp_not_in_an_idle_scan() -> Self {
127        Self {
128            scanner: ScannerKind::UdpPort,
129            reason: "udp ports: not probed in an idle scan".to_string(),
130        }
131    }
132
133    /// The TCP half left undone on the targets a frames-only run cannot reach.
134    ///
135    /// [`technique_needs_raw_sockets`](Self::technique_needs_raw_sockets) for part
136    /// of a scan: the targets only the kernel can carry.
137    pub(crate) fn technique_beyond_frames(technique: TcpScanTechnique, targets: u128) -> Self {
138        Self {
139            scanner: ScannerKind::for_raw_tcp(technique),
140            reason: format!(
141                "tcp ports on {}: {technique} scan needs a raw socket (sudo)",
142                counted(targets, "target", "targets"),
143            ),
144        }
145    }
146
147    /// The SCTP ports on the targets a frames-only run cannot reach, for the
148    /// reason [`sctp_needs_raw_sockets`](Self::sctp_needs_raw_sockets) gives.
149    pub(crate) fn sctp_beyond_frames(targets: u128) -> Self {
150        Self {
151            scanner: ScannerKind::SctpPort,
152            reason: format!(
153                "sctp ports on {}: init scan needs a raw socket (sudo)",
154                counted(targets, "target", "targets"),
155            ),
156        }
157    }
158
159    /// A pass that sends its own segments to a host, left undone on the hosts a
160    /// frames-only run cannot reach.
161    ///
162    /// No connect can stand in, since each pass reads something only a packet it
163    /// built can ask. `pass` names the pass for a reader.
164    pub(crate) fn pass_beyond_frames(scanner: ScannerKind, pass: &str, hosts: u128) -> Self {
165        Self {
166            scanner,
167            reason: format!(
168                "{pass} on {}: needs a raw socket (sudo)",
169                counted(hosts, "host", "hosts"),
170            ),
171        }
172    }
173
174    /// A pass that would send the target its own packets, asked for under an
175    /// idle scan.
176    ///
177    /// An idle scan forges every probe from its zombie so the target never hears
178    /// from this host, as with
179    /// [`idle_needs_privilege`](Self::idle_needs_privilege). `pass` names it
180    /// briefly for a reader, and `scanner` is the strategy the report files the
181    /// refusal under. The words say what was not run, as
182    /// [`udp_not_in_an_idle_scan`](Self::udp_not_in_an_idle_scan)'s do.
183    pub(crate) fn pass_not_in_an_idle_scan(scanner: ScannerKind, pass: &str) -> Self {
184        Self {
185            scanner,
186            reason: format!("{pass}: not run in an idle scan"),
187        }
188    }
189
190    /// An idle scan was asked for through a zombie the exclusions forbid.
191    ///
192    /// The scan probes the zombie repeatedly, so it would send an excluded address
193    /// the most traffic of anything in the scan. No fallback, as with
194    /// [`idle_needs_privilege`](Self::idle_needs_privilege).
195    pub(crate) fn idle_zombie_excluded(zombie: IpAddr) -> Self {
196        Self {
197            scanner: ScannerKind::Idle,
198            reason: format!("idle scan: zombie {zombie} is excluded"),
199        }
200    }
201
202    /// An idle scan was asked for without the privilege it needs.
203    ///
204    /// The forged source address can only ride a self-built frame, which needs
205    /// privilege. There is no fallback, since scanning under this host's own
206    /// address defeats an idle scan.
207    pub fn idle_needs_privilege() -> Self {
208        Self {
209            scanner: ScannerKind::Idle,
210            reason: "idle scan: needs raw sockets (sudo)".to_owned(),
211        }
212    }
213
214    /// A routed IPv6 range with more addresses than any strategy can walk.
215    ///
216    /// See [`MAX_ENUMERABLE_ADDRESSES`](crate::system::interface::MAX_ENUMERABLE_ADDRESSES)
217    /// for the ceiling.
218    pub fn routed_range_not_enumerable(range: &Ipv6Range) -> Self {
219        Self {
220            scanner: ScannerKind::Routed,
221            reason: format!(
222                "{}: too large to walk (give addresses or a smaller prefix)",
223                describe(range)
224            ),
225        }
226    }
227
228    /// A TCP sweep left with no port to ask, every one it would ask being
229    /// excluded.
230    ///
231    /// A sweep asking nothing would report every address silent. What it would have
232    /// reached by TCP is left unasked; a link-layer sweep is unaffected. `scanner`
233    /// is the sweep refused.
234    pub(crate) fn every_discovery_port_excluded(scanner: ScannerKind) -> Self {
235        Self {
236            scanner,
237            reason: "tcp liveness: every port it asks is excluded".to_owned(),
238        }
239    }
240
241    /// A port target range with more addresses than a port scan can walk.
242    ///
243    /// Whatever the privilege: the multicast that sweeps a segment's `/64` finds
244    /// hosts, not their ports, so the remedy is the addresses a sweep found.
245    /// `scanner` is the port strategy the phase runs under.
246    pub(crate) fn port_range_not_enumerable(range: &Ipv6Range, scanner: ScannerKind) -> Self {
247        Self {
248            scanner,
249            reason: format!(
250                "{}: too large to walk (give addresses or a smaller prefix)",
251                describe(range)
252            ),
253        }
254    }
255
256    /// The same range, refused by an unprivileged scan.
257    ///
258    /// Worded apart from
259    /// [`routed_range_not_enumerable`](Self::routed_range_not_enumerable) because
260    /// the remedy differs: on the local segment, raw sockets reach a range this size
261    /// through the all-nodes echo, one packet per `/64`.
262    pub fn unprivileged_range_not_enumerable(range: &Ipv6Range) -> Self {
263        Self {
264            scanner: ScannerKind::Connect,
265            reason: format!(
266                "{}: too large to walk (sudo sweeps a segment)",
267                describe(range)
268            ),
269        }
270    }
271
272    /// A port target that is link-local and names no interface.
273    ///
274    /// Every interface holds an `fe80::/64`, so `fe80::1` names a different machine
275    /// on each. Written as `fe80::1%en0`, it names one. The reason suggests the
276    /// target with an interface this host has: up, able to broadcast and holding a
277    /// link-local address, preferring the default route's.
278    ///
279    /// [`RoutedTargets::ambiguous`](crate::system::interface::RoutedTargets)
280    /// refuses the same target on the discovery path.
281    pub fn link_local_port_target_needs_an_interface(range: &Ipv6Range) -> Self {
282        let target = name(range);
283        Self {
284            scanner: ScannerKind::SynPort,
285            reason: format!("{target}: {}", name_an_interface(range)),
286        }
287    }
288
289    /// One link-local address given on two interfaces in a single scan.
290    ///
291    /// Each is a different machine, but a port scan records verdicts under the
292    /// address, so both sets of answers would land on one host.
293    pub fn link_local_port_target_names_two_segments(range: &Ipv6Range) -> Self {
294        let target = name(range);
295        Self {
296            scanner: ScannerKind::SynPort,
297            reason: format!("{target}: named on two interfaces (scan one at a time)"),
298        }
299    }
300
301    /// An on-link IPv6 range too large to walk, in a scan that will not sweep
302    /// the segment it is on.
303    ///
304    /// A local segment is covered by the all-nodes solicitation, one packet
305    /// whatever the prefix length, so the remedy is a sweep. A [`Scope::Sweep`] step
306    /// sends that packet and refuses nothing.
307    ///
308    /// Walking the range would fail silently: the address count overflows the
309    /// deadline's target count, and the sweep stops a couple of thousand
310    /// solicitations in having reported the range covered.
311    pub fn local_range_needs_a_sweep(range: &Ipv6Range) -> Self {
312        Self {
313            scanner: ScannerKind::Local,
314            reason: format!(
315                "{}: too large to walk (sweep the segment instead)",
316                describe(range)
317            ),
318        }
319    }
320}
321
322/// Takes the IPv6 ranges out of `targets` that are too large to probe one
323/// address at a time, leaving the rest.
324///
325/// The routed path's test, applied per range by
326/// [`is_enumerable`](interface::is_enumerable), so a set holding a `/64` and three
327/// literal addresses keeps the three. IPv4 is untouched.
328fn withhold_unwalkable(targets: &mut IpSet) -> Vec<Ipv6Range> {
329    let unwalkable: Vec<Ipv6Range> = targets
330        .v6()
331        .iter()
332        .filter(|range| !interface::is_enumerable(range))
333        .copied()
334        .collect();
335
336    if unwalkable.is_empty() {
337        return unwalkable;
338    }
339
340    let mut kept = IpSet::new();
341    for range in targets.v4() {
342        kept.push_v4_range(*range);
343    }
344    for range in targets.v6() {
345        if interface::is_enumerable(range) {
346            kept.push_v6_range(*range);
347        }
348    }
349    kept.canonicalize();
350    *targets = kept;
351
352    unwalkable
353}
354
355impl From<RefusedStep> for crate::report::Refusal {
356    /// The recorded form of a refusal a plan carries.
357    ///
358    /// One direction only: a recorded refusal keeps the words, not the decision.
359    fn from(step: RefusedStep) -> Self {
360        Self::new(step.scanner, step.reason)
361    }
362}
363
364/// A range as a person wrote it: one address when it covers one, and the span
365/// otherwise.
366fn name(range: &Ipv6Range) -> String {
367    match range.start_addr() == range.end_addr() {
368        true => range.start_addr().to_string(),
369        false => format!("{}-{}", range.start_addr(), range.end_addr()),
370    }
371}
372
373/// The opening both refusals above share: which range, and how big it is.
374///
375/// The size is quoted because it is the argument: "18446744073709551616
376/// addresses" says more than "too large".
377fn describe(range: &Ipv6Range) -> String {
378    format!(
379        "{}-{} is {} addresses",
380        range.start_addr(),
381        range.end_addr(),
382        range.len()
383    )
384}
385
386/// One strategy a discovery sweep intends to run.
387///
388/// Each variant names a way of reaching a target and the targets it was given.
389/// Turning one into a running strategy is [`into_scanner`](Self::into_scanner);
390/// until then it is inert.
391#[derive(Debug, Clone)]
392#[non_exhaustive]
393pub enum DiscoveryStep {
394    /// ARP and ICMPv6 across one interface's own segment, for targets that share
395    /// it. The cheapest and most informative of the three: the only one that
396    /// yields a MAC address or finds a neighbour nobody named.
397    Local {
398        /// The interface to sweep from.
399        interface: Box<Link>,
400        /// The addresses on its segment. May be empty for a
401        /// [`Scope::Sweep`], whose most important probe is addressed to nobody.
402        targets: IpSet,
403        /// Whether this sweep may find hosts nobody asked about.
404        scope: Scope,
405    },
406    /// Raw TCP SYN to targets reached through a gateway, each already paired
407    /// with the source address the host would route it from.
408    Routed {
409        /// The destinations, with their source addresses.
410        targets: Vec<RoutedTarget>,
411        /// The ports every target is asked about. The common five unless
412        /// [`DiscoveryPlan::asking_tcp`] said otherwise.
413        ports: SynPorts,
414    },
415    /// Raw SCTP INIT to the same routed targets, for a scan whose ports name
416    /// SCTP.
417    ///
418    /// Runs beside [`Routed`](Self::Routed). A host that answers only SCTP would be
419    /// reported down by a SYN sweep and never have its ports probed.
420    RoutedSctp {
421        /// The destinations, with their source addresses.
422        targets: Vec<RoutedTarget>,
423        /// The port every INIT is aimed at.
424        port: u16,
425    },
426    /// Ordinary TCP connect attempts, for targets with no route and no segment:
427    /// loopback, or anything the OS declined to resolve. Needs no privileges.
428    ///
429    /// For a process whose raw strategies send only frames, also whatever a frame
430    /// cannot reach.
431    Connect {
432        /// The addresses to try.
433        targets: IpSet,
434        /// The ports every address is asked about, the same set a routed step
435        /// asks. The common five unless [`DiscoveryPlan::asking_tcp`] said
436        /// otherwise.
437        ports: SynPorts,
438    },
439}
440
441impl DiscoveryStep {
442    /// Which strategy this step becomes.
443    pub fn kind(&self) -> ScannerKind {
444        match self {
445            Self::Local { .. } => ScannerKind::Local,
446            Self::Routed { .. } => ScannerKind::Routed,
447            Self::RoutedSctp { .. } => ScannerKind::RoutedSctp,
448            Self::Connect { .. } => ScannerKind::Connect,
449        }
450    }
451
452    /// How many addresses this step covers.
453    ///
454    /// Zero is meaningful: a [`Scope::Sweep`] step with no addresses still sends
455    /// the all-nodes solicitation its whole segment may answer.
456    pub fn target_count(&self) -> u128 {
457        match self {
458            Self::Local { targets, .. } | Self::Connect { targets, .. } => targets.len(),
459            Self::Routed { targets, .. } | Self::RoutedSctp { targets, .. } => {
460                targets.len() as u128
461            }
462        }
463    }
464
465    /// Opens whatever this step needs and hands back the strategy to run.
466    ///
467    /// A local step opens a link-layer channel on its interface; a routed step
468    /// opens a raw transport and a capture. Either can fail with a
469    /// [`StrategyError`], and a caller can record it and carry on with the steps
470    /// that did build.
471    ///
472    /// `dns_tx` is where a strategy posts addresses worth a reverse lookup;
473    /// pass `None` to do no hostname resolution.
474    pub fn into_scanner(
475        self,
476        ctx: ScanContext,
477        dns_tx: Option<UnboundedSender<IpAddr>>,
478        tuning: ProbeTuning,
479    ) -> Result<Box<dyn HostScanner>, StrategyError> {
480        match self {
481            Self::Local {
482                interface,
483                targets,
484                scope,
485            } => Ok(Box::new(LocalScanner::new(
486                *interface,
487                targets,
488                ctx,
489                dns_tx,
490                scope,
491                tuning.retry,
492            )?)),
493            Self::Routed { targets, ports } => Ok(Box::new(RoutedScanner::over_tcp(
494                targets, ctx, dns_tx, tuning, ports,
495            )?)),
496            Self::RoutedSctp { targets, port } => Ok(Box::new(RoutedScanner::over_sctp(
497                targets, ctx, dns_tx, tuning, port,
498            )?)),
499            Self::Connect { targets, ports } => Ok(Box::new(ConnectScanner::asking(
500                targets,
501                ctx,
502                &tuning.evasion,
503                ports,
504            ))),
505        }
506    }
507}
508
509/// What a discovery sweep intends to do.
510///
511/// Build one with [`build`](Self::build), read it, change it, run it. See the
512/// [module documentation](self).
513#[derive(Debug, Clone)]
514pub struct DiscoveryPlan {
515    steps: Vec<DiscoveryStep>,
516    refusals: Vec<RefusedStep>,
517    ours: IpSet,
518    /// The neighbours this host's routing table refuses, left to the connect
519    /// step.
520    refused_by_route: IpSet,
521    /// The neighbour-table candidates the exclusions kept from a sweep.
522    withheld: IpSet,
523}
524
525impl DiscoveryPlan {
526    /// Works out which strategies would cover `targets`, opening nothing.
527    ///
528    /// `scope` decides whether the sweep may go beyond what it was given.
529    /// [`Scope::Sweep`] earns a step for the link even when no address mapped to
530    /// it (its all-nodes echo is one packet the whole segment may answer), and
531    /// takes candidate addresses from the host's IPv6 neighbour table, the only
532    /// source of IPv6 addresses nobody named. [`Scope::Targeted`] does neither.
533    ///
534    /// `exclusions` applies to addresses a sweep adds from the neighbour table, in
535    /// `seed_from_neighbor_table`. The target list was already withheld against
536    /// them in `withhold_targets`.
537    ///
538    /// `forced` pins the source addresses off-link targets are probed from,
539    /// empty for a scan that let the routing table choose.
540    pub fn build(targets: IpSet, scope: Scope, exclusions: &Exclusions, forced: &[IpAddr]) -> Self {
541        let mut steps = Vec::new();
542        let mut refusals = Vec::new();
543        let mut refused_by_route = IpSet::new();
544
545        let interface::RoutedTargets {
546            mut local,
547            routed,
548            mut unmapped,
549            ours,
550            ambiguous,
551            unenumerable,
552        } = interface::map_ips_to_interfaces_forced(targets, forced);
553
554        // A link-local target naming no interface: every interface has an
555        // `fe80::/64`, so guessing would scan an arbitrary segment.
556        for range in &ambiguous {
557            refusals.push(RefusedStep {
558                scanner: ScannerKind::Local,
559                reason: format!("{}: {}", range.start_addr(), name_an_interface(range)),
560            });
561        }
562
563        // A routed IPv6 prefix cannot be walked (see `MAX_ENUMERABLE_ADDRESSES`).
564        for range in &unenumerable {
565            refusals.push(RefusedStep::routed_range_not_enumerable(range));
566        }
567
568        // Only a sweep takes leads from the host itself.
569        let mut withheld = IpSet::new();
570        if matches!(scope, Scope::Sweep) {
571            include_swept_link(&mut local);
572            withheld = seed_from_neighbor_table(&mut local, exclusions);
573        }
574
575        for (interface, mut targets) in local {
576            // `map_ips_to_interfaces` keeps an on-link range too large to walk
577            // whole, for the sweep's all-nodes solicitation. A targeted run
578            // would walk it, so it is dropped here. See
579            // `local_range_needs_a_sweep`.
580            for range in withhold_unwalkable(&mut targets) {
581                match scope {
582                    // Covered by the sweep's all-nodes packet.
583                    Scope::Sweep => info!(
584                        verbosity = 1,
585                        "{} is swept by solicitation rather than walked",
586                        describe(&range)
587                    ),
588                    Scope::Targeted => {
589                        refusals.push(RefusedStep::local_range_needs_a_sweep(&range))
590                    }
591                }
592            }
593
594            // A neighbour the routing table refuses is not framed, which would
595            // bypass the table. The connect step gets it, the kernel refuses
596            // the connect, and the address is filed as unreachable. The port
597            // scan does the same; see `SourceResolver::resolve`.
598            let refused = interface::refused_neighbours(&interface, &targets);
599            if !refused.is_empty() {
600                targets.subtract(&refused);
601                for address in refused.iter() {
602                    unmapped.insert(address);
603                    refused_by_route.insert(address);
604                }
605                info!(
606                    verbosity = 1,
607                    "{} on {} refused by a route, not asked by frame",
608                    counted(refused.len(), "address", "addresses"),
609                    interface.name()
610                );
611            }
612
613            // A sweep's link earns a step whether or not any address mapped to
614            // it. A targeted run has nothing to send without targets.
615            if targets.is_empty() && matches!(scope, Scope::Targeted) {
616                continue;
617            }
618            // Logged here, where it is decided; the lookup that found the link
619            // runs more than once a run.
620            if matches!(scope, Scope::Sweep) {
621                info!(
622                    verbosity = 1,
623                    "sweeping {}: {}",
624                    interface.name(),
625                    match targets.len() {
626                        0 => "IPv6 neighbours only, having no IPv4 range to walk".to_string(),
627                        count => counted(count, "address", "addresses"),
628                    }
629                );
630            }
631            steps.push(DiscoveryStep::Local {
632                interface: Box::new(interface),
633                targets,
634                scope,
635            });
636        }
637
638        if !routed.is_empty() {
639            steps.push(DiscoveryStep::Routed {
640                targets: routed,
641                ports: SynPorts::common(),
642            });
643        }
644
645        if !unmapped.is_empty() {
646            steps.push(DiscoveryStep::Connect {
647                targets: unmapped,
648                ports: SynPorts::common(),
649            });
650        }
651
652        Self {
653            steps,
654            refusals,
655            ours,
656            refused_by_route,
657            withheld,
658        }
659    }
660
661    /// The addresses from this host's IPv6 neighbour table that a plan
662    /// [built](Self::build) from the same arguments would take as sweep
663    /// candidates and the exclusions withhold, read without planning or logging.
664    ///
665    /// A scan counts these among the addresses its policy withheld, so a caller
666    /// stating that count before the scan has them to add. Empty for
667    /// [`Scope::Targeted`]. Only a run holding raw sockets or the link layer sweeps
668    /// this way; a run without either withholds none.
669    pub fn withheld_neighbours(
670        targets: IpSet,
671        scope: Scope,
672        exclusions: &Exclusions,
673        forced: &[IpAddr],
674    ) -> IpSet {
675        if !matches!(scope, Scope::Sweep) {
676            return IpSet::new();
677        }
678        let mut local = interface::map_ips_to_interfaces_forced(targets, forced).local;
679        include_swept_link(&mut local);
680        let table = neighbor_cache::ipv6_neighbors();
681        let machines = machines_named(exclusions, &table);
682        let mut withheld = IpSet::new();
683        for intf in local.keys() {
684            for candidate in candidates_on(intf, &table, exclusions, &machines) {
685                if candidate.withheld {
686                    withheld.insert_range(candidate.range);
687                }
688            }
689        }
690        withheld.canonicalize();
691        withheld
692    }
693
694    /// The neighbours this host's routing table refuses, which the plan left
695    /// to the connect step; see
696    /// [`refused_neighbours`](interface::refused_neighbours).
697    pub(crate) fn refused_by_route(&self) -> &IpSet {
698        &self.refused_by_route
699    }
700
701    /// The neighbour-table candidates the exclusions kept from this plan's
702    /// sweep, which its phase counts among the addresses its policy withheld;
703    /// see [`withheld_neighbours`](Self::withheld_neighbours).
704    pub(crate) fn withheld(&self) -> &IpSet {
705        &self.withheld
706    }
707
708    /// Adds an SCTP sweep beside every routed step, asking `port`.
709    ///
710    /// Separate from [`build`](Self::build), like [`PortScanPlan::cover_sctp`],
711    /// because the port specification decides it. A caller that never mentions
712    /// SCTP opens no second socket.
713    ///
714    /// Only the routed steps gain one. ARP and neighbour discovery answer whatever
715    /// the host speaks above them, and a connect step has no raw socket for an
716    /// INIT.
717    pub fn also_over_sctp(&mut self, port: u16) {
718        let sctp: Vec<DiscoveryStep> = self
719            .steps
720            .iter()
721            .filter_map(|step| match step {
722                DiscoveryStep::Routed { targets, .. } => Some(DiscoveryStep::RoutedSctp {
723                    targets: targets.clone(),
724                    port,
725                }),
726                _ => None,
727            })
728            .collect();
729        self.steps.extend(sctp);
730    }
731
732    /// Asks every routed and connect target about `ports` in place of the
733    /// common five.
734    ///
735    /// Separate from [`build`](Self::build), like
736    /// [`also_over_sctp`](Self::also_over_sctp). A port scan's liveness pass passes
737    /// [`SynPorts::for_scan`], so a host that drops SYNs to anything it does not
738    /// serve is still asked about the ports the scan will probe.
739    ///
740    /// The routed and connect steps change alike. A link-layer sweep is left as it
741    /// was.
742    ///
743    /// An empty set removes and refuses the routed and connect steps; see
744    /// `RefusedStep::every_discovery_port_excluded`.
745    pub fn asking_tcp(&mut self, ports: SynPorts) {
746        if ports.is_empty() {
747            let refusals = &mut self.refusals;
748            self.steps.retain(|step| match step {
749                DiscoveryStep::Routed { .. } | DiscoveryStep::Connect { .. } => {
750                    refusals.push(RefusedStep::every_discovery_port_excluded(step.kind()));
751                    false
752                }
753                _ => true,
754            });
755            return;
756        }
757        for step in &mut self.steps {
758            if let DiscoveryStep::Routed { ports: asked, .. }
759            | DiscoveryStep::Connect { ports: asked, .. } = step
760            {
761                *asked = ports;
762            }
763        }
764    }
765
766    /// Takes `targets` out of every step that sends its own packets, and returns
767    /// what was taken.
768    ///
769    /// For a process whose raw strategies only send frames. A frame reaches what
770    /// has Ethernet in front of it; `targets` is the rest, as
771    /// [`beyond_frames`](crate::system::interface::beyond_frames) computed it. Left
772    /// in a routed step, a tunnelled target would get a frame out of the wrong
773    /// interface, and loopback none at all.
774    ///
775    /// A step left with nothing to send is dropped, except a sweep's local step on
776    /// a link that carries frames, whose most important probe is addressed to
777    /// nobody. The connect step is left alone.
778    pub(crate) fn withhold(&mut self, targets: &IpSet) -> IpSet {
779        let mut taken = IpSet::new();
780        if targets.is_empty() {
781            return taken;
782        }
783
784        for step in &mut self.steps {
785            match step {
786                DiscoveryStep::Local { targets: held, .. } => {
787                    let mut kept = held.clone();
788                    kept.subtract(targets);
789                    // What the subtraction removed.
790                    let mut gone = held.clone();
791                    gone.subtract(&kept);
792                    for range in gone.v4() {
793                        taken.push_v4_range(*range);
794                    }
795                    for range in gone.v6() {
796                        taken.push_v6_range(*range);
797                    }
798                    *held = kept;
799                }
800                DiscoveryStep::Routed { targets: held, .. }
801                | DiscoveryStep::RoutedSctp { targets: held, .. } => held.retain(|routed| {
802                    let out = targets.contains(&routed.target);
803                    if out {
804                        taken.insert(routed.target);
805                    }
806                    !out
807                }),
808                DiscoveryStep::Connect { .. } => {}
809            }
810        }
811
812        self.steps.retain(|step| match step {
813            DiscoveryStep::Local {
814                interface,
815                targets,
816                scope,
817            } => {
818                !targets.is_empty() || (matches!(scope, Scope::Sweep) && interface.carries_frames())
819            }
820            DiscoveryStep::Routed { targets, .. } | DiscoveryStep::RoutedSctp { targets, .. } => {
821                !targets.is_empty()
822            }
823            DiscoveryStep::Connect { .. } => true,
824        });
825
826        taken.canonicalize();
827        taken
828    }
829
830    /// [`withhold`](Self::withhold)s `targets` and hands what was taken to the
831    /// connect step, adding one where the plan has none. Returns what moved.
832    ///
833    /// How a frames-only sweep reaches what its frames cannot.
834    pub(crate) fn connect_instead(&mut self, targets: &IpSet) -> IpSet {
835        let moved = self.withhold(targets);
836        if moved.is_empty() {
837            return moved;
838        }
839
840        let existing = self.steps.iter_mut().find_map(|step| match step {
841            DiscoveryStep::Connect { targets, .. } => Some(targets),
842            _ => None,
843        });
844        match existing {
845            Some(held) => {
846                for range in moved.v4() {
847                    held.push_v4_range(*range);
848                }
849                for range in moved.v6() {
850                    held.push_v6_range(*range);
851                }
852                held.canonicalize();
853            }
854            // The routed steps' ports, since a routed step would have swept these.
855            None => {
856                let ports = self
857                    .steps
858                    .iter()
859                    .find_map(|step| match step {
860                        DiscoveryStep::Routed { ports, .. } => Some(*ports),
861                        _ => None,
862                    })
863                    .unwrap_or_else(SynPorts::common);
864                self.steps.push(DiscoveryStep::Connect {
865                    targets: moved.clone(),
866                    ports,
867                });
868            }
869        }
870        moved
871    }
872
873    /// The strategies this plan would run.
874    pub fn steps(&self) -> &[DiscoveryStep] {
875        &self.steps
876    }
877
878    /// The strategies this plan would run, to drop or reorder before running it.
879    pub fn steps_mut(&mut self) -> &mut Vec<DiscoveryStep> {
880        &mut self.steps
881    }
882
883    /// The targets that are this host's own addresses.
884    ///
885    /// Up by construction and covered by no step: the kernel routes traffic for
886    /// an address this host holds through loopback, so a probe never reaches the
887    /// link and nothing there answers for it.
888    ///
889    /// A caller running the plan itself records these as up without probing them,
890    /// as [`orchestrator`](crate::scanner) does.
891    pub fn ours(&self) -> &IpSet {
892        &self.ours
893    }
894
895    /// Ground this plan will not cover, and why.
896    pub fn refusals(&self) -> &[RefusedStep] {
897        &self.refusals
898    }
899
900    /// Takes the steps out, leaving the plan empty.
901    pub fn into_steps(self) -> Vec<DiscoveryStep> {
902        self.steps
903    }
904}
905
906/// One strategy a port scan intends to run.
907#[derive(Debug, Clone, Copy, PartialEq, Eq)]
908#[non_exhaustive]
909pub enum PortScanStep {
910    /// Raw TCP probes classified from a single exchange, without completing a
911    /// handshake. Needs raw sockets.
912    RawTcp {
913        /// Which flags the probe carries, and so which question it asks.
914        technique: TcpScanTechnique,
915    },
916    /// Raw UDP probes, classified from a direct reply or an ICMP unreachable.
917    /// Needs raw sockets.
918    RawUdp,
919    /// Raw SCTP INIT probes, classified from the chunk that answers. Needs raw
920    /// sockets, and has no unprivileged counterpart.
921    RawSctp,
922    /// A full TCP connect per target. Needs no privileges, and answers roughly
923    /// the question a SYN scan asks.
924    ConnectTcp,
925    /// An unprivileged UDP probe.
926    ConnectUdp,
927    /// The idle (zombie) TCP scan: port states read off a third party's IP-ID
928    /// counter, so the target is never addressed under this host's own address.
929    /// Needs the self-built frame a forged source requires.
930    Idle {
931        /// The zombie whose counter is the side channel.
932        zombie: IpAddr,
933        /// The port on the zombie to read the counter from, or `None` for the
934        /// scanner's default.
935        zombie_port: Option<u16>,
936    },
937}
938
939impl PortScanStep {
940    /// Which strategy this step becomes.
941    ///
942    /// The raw TCP name depends on the technique, because
943    /// [`ScannerKind::SynPort`] means a half-open connection attempt was made and
944    /// the flag probes make none. [`ScannerKind::for_raw_tcp`] holds that rule, so
945    /// a step and the scanner it builds agree.
946    pub fn kind(&self) -> ScannerKind {
947        match self {
948            Self::RawTcp { technique } => ScannerKind::for_raw_tcp(*technique),
949            Self::RawUdp => ScannerKind::UdpPort,
950            Self::RawSctp => ScannerKind::SctpPort,
951            Self::ConnectTcp => ScannerKind::Connect,
952            Self::ConnectUdp => ScannerKind::ConnectUdp,
953            Self::Idle { .. } => ScannerKind::Idle,
954        }
955    }
956
957    /// The transport protocol this step probes.
958    pub fn protocol(&self) -> Protocol {
959        match self {
960            Self::RawTcp { .. } | Self::ConnectTcp | Self::Idle { .. } => Protocol::Tcp,
961            Self::RawUdp | Self::ConnectUdp => Protocol::Udp,
962            Self::RawSctp => Protocol::Sctp,
963        }
964    }
965
966    /// Whether this step needs raw sockets.
967    ///
968    /// Decides whether host enrichment is worth running: ARP, ICMPv6 and raw TCP
969    /// yield a MAC and a round trip, the connect fallbacks neither. Not derivable
970    /// from [`kind`](Self::kind), which differs per raw technique.
971    pub fn is_raw(&self) -> bool {
972        matches!(self, Self::RawTcp { .. } | Self::RawUdp | Self::RawSctp)
973    }
974
975    /// Opens whatever this step needs and hands back the strategy to run.
976    ///
977    /// `target_count` sizes the probe ledger, so a raw scanner reserves
978    /// correlation state up front.
979    ///
980    /// `zones` names the interface each link-local target was given on, which
981    /// supplies the scope id both families of scanner send under. Empty for a scan
982    /// that named none.
983    pub fn into_scanner(
984        self,
985        ctx: ScanContext,
986        target_count: usize,
987        tuning: ProbeTuning,
988        zones: ZoneMap,
989    ) -> Result<Box<dyn PortScanner>, StrategyError> {
990        match self {
991            Self::RawTcp { technique } => Ok(Box::new(TcpPortScanner::new(
992                interface::SourceResolver::from_system()
993                    .with_zones(zones)
994                    .with_forced(tuning.send_source.clone()),
995                ctx,
996                technique,
997                target_count,
998                tuning,
999            )?)),
1000            Self::RawUdp => Ok(Box::new(UdpPortScanner::new(
1001                interface::SourceResolver::from_system()
1002                    .with_zones(zones)
1003                    .with_forced(tuning.send_source.clone()),
1004                ctx,
1005                target_count,
1006                tuning,
1007            )?)),
1008            Self::RawSctp => Ok(Box::new(SctpPortScanner::new(
1009                interface::SourceResolver::from_system()
1010                    .with_zones(zones)
1011                    .with_forced(tuning.send_source.clone()),
1012                ctx,
1013                target_count,
1014                tuning,
1015            )?)),
1016            Self::ConnectTcp => Ok(Box::new(
1017                ConnectPortScanner::new(
1018                    ctx,
1019                    limits::CONNECT_CONCURRENCY,
1020                    tuning.service_detection,
1021                    &tuning.evasion,
1022                )
1023                .with_zones(zones),
1024            )),
1025            Self::ConnectUdp => Ok(Box::new(
1026                ConnectUdpPortScanner::with_detection(
1027                    ctx,
1028                    limits::CONNECT_CONCURRENCY,
1029                    &tuning.evasion,
1030                    tuning.service_detection,
1031                )
1032                .with_zones(zones),
1033            )),
1034            Self::Idle {
1035                zombie,
1036                zombie_port,
1037            } => Ok(Box::new(IdlePortScanner::new(
1038                ctx,
1039                zombie,
1040                zombie_port,
1041                tuning,
1042            )?)),
1043        }
1044    }
1045}
1046
1047/// What a port scan intends to do.
1048#[derive(Debug, Clone)]
1049pub struct PortScanPlan {
1050    steps: Vec<PortScanStep>,
1051    refusals: Vec<RefusedStep>,
1052    /// The protocol each of `refusals` leaves unprobed. A target of a refused
1053    /// protocol still reaches the router, which counts it as declined by the plan.
1054    refused: Vec<Protocol>,
1055    technique: TcpScanTechnique,
1056    /// Whether this is an idle scan, whether or not its idle step survived.
1057    ///
1058    /// Kept apart from the steps because a refused idle scan has no idle step but
1059    /// must still refuse other transports. Read from the steps, a privileged run
1060    /// through an excluded zombie would plan SCTP ports as a direct probe from this
1061    /// host's own address.
1062    idle: bool,
1063}
1064
1065impl PortScanPlan {
1066    /// Works out which strategies would probe the requested ports, opening
1067    /// nothing.
1068    ///
1069    /// `privilege` is which sockets the scan would run with, so a caller can plan
1070    /// for a privilege level they do not hold.
1071    ///
1072    /// ## The fallback is decided per protocol
1073    ///
1074    /// A sandbox can permit a raw TCP socket and refuse a raw UDP one. A protocol
1075    /// left with no strategy would never be probed or reported.
1076    ///
1077    /// ## A connect fallback substitutes only for a SYN scan
1078    ///
1079    /// It answers roughly what a SYN scan asks, but cannot send a FIN, a flagless
1080    /// segment or a bare ACK. Where the caller chose one of those and raw sockets
1081    /// are unavailable, the TCP half is refused.
1082    pub fn build(cfg: &ZondConfig, privilege: Privilege) -> Self {
1083        let mut plan = Self {
1084            steps: Vec::new(),
1085            refusals: Vec::new(),
1086            refused: Vec::new(),
1087            technique: cfg.tcp_technique,
1088            idle: cfg.idle_scan.is_some(),
1089        };
1090
1091        // An idle scan replaces the ordinary port scan. It is TCP-only, so no
1092        // step covers UDP; the refusal waits for the targets to name a UDP port
1093        // (see `cover_udp`).
1094        if let Some(idle) = &cfg.idle_scan {
1095            // Checked before privilege, which would be the wrong remedy. The
1096            // zombie is named in settings, not the target list, so nothing else
1097            // withholds it.
1098            if cfg.exclusions.excludes(&idle.zombie) {
1099                plan.refuse(
1100                    Protocol::Tcp,
1101                    RefusedStep::idle_zombie_excluded(idle.zombie),
1102                );
1103            } else if privilege.is_raw() {
1104                plan.steps.push(PortScanStep::Idle {
1105                    zombie: idle.zombie,
1106                    zombie_port: idle.zombie_port,
1107                });
1108            } else {
1109                plan.refuse(Protocol::Tcp, RefusedStep::idle_needs_privilege());
1110            }
1111            return plan;
1112        }
1113
1114        // Raw scanning needs both the privilege and an address to probe from.
1115        let raw = Self::raw_scanning(privilege);
1116        if privilege.is_raw() && !raw {
1117            warn!("no usable network interface found; using TCP connect fallback");
1118        }
1119
1120        // The TCP step alone. UDP is added by [`cover_udp`] when the targets
1121        // name a UDP port, as SCTP is by [`cover_sctp`].
1122        if raw {
1123            plan.steps.push(PortScanStep::RawTcp {
1124                technique: cfg.tcp_technique,
1125            });
1126        } else if cfg.tcp_technique.has_connect_fallback() {
1127            plan.steps.push(PortScanStep::ConnectTcp);
1128        } else {
1129            plan.refuse(
1130                Protocol::Tcp,
1131                RefusedStep::technique_needs_raw_sockets(cfg.tcp_technique),
1132            );
1133        }
1134
1135        plan
1136    }
1137
1138    /// Whether this host can raw-scan: it holds the privilege and has an address
1139    /// to probe from. Shared by the TCP step in [`build`](Self::build) and the UDP
1140    /// step, so the two agree.
1141    fn raw_scanning(privilege: Privilege) -> bool {
1142        privilege.is_raw() && interface::SourceResolver::from_system().has_sources()
1143    }
1144
1145    /// Records that `protocol` will not be probed, and the refusal that says
1146    /// why.
1147    fn refuse(&mut self, protocol: Protocol, refusal: RefusedStep) {
1148        self.refusals.push(refusal);
1149        self.refused.push(protocol);
1150    }
1151
1152    /// The TCP technique this plan was built for.
1153    ///
1154    /// Outlives the steps: if a raw step fails to open, whether a connect scanner
1155    /// may stand in depends on the technique.
1156    pub fn technique(&self) -> TcpScanTechnique {
1157        self.technique
1158    }
1159
1160    /// The strategies this plan would run.
1161    pub fn steps(&self) -> &[PortScanStep] {
1162        &self.steps
1163    }
1164
1165    /// The strategies this plan would run, to drop or reorder before running it.
1166    pub fn steps_mut(&mut self) -> &mut Vec<PortScanStep> {
1167        &mut self.steps
1168    }
1169
1170    /// Ports this plan will not probe, and why.
1171    pub fn refusals(&self) -> &[RefusedStep] {
1172        &self.refusals
1173    }
1174
1175    /// Takes the steps out, leaving the plan empty.
1176    pub fn into_steps(self) -> Vec<PortScanStep> {
1177        self.steps
1178    }
1179
1180    /// Adds the step that probes SCTP, or the refusal that says why it could
1181    /// not be added.
1182    ///
1183    /// Separate from [`build`](Self::build) because SCTP ports are named in a
1184    /// target's port specification, which the plan is built before reading, and no
1185    /// default port list holds one. A scan that never mentions SCTP opens no raw
1186    /// socket or capture for it.
1187    ///
1188    /// Called with the same `privilege` the plan was built for.
1189    pub fn cover_sctp(&mut self, privilege: Privilege) {
1190        if self.idle {
1191            self.refuse(Protocol::Sctp, RefusedStep::sctp_not_in_an_idle_scan());
1192            return;
1193        }
1194
1195        // The same two conditions as raw scanning in `build`.
1196        if privilege.is_raw() && interface::SourceResolver::from_system().has_sources() {
1197            self.steps.push(PortScanStep::RawSctp);
1198        } else {
1199            self.refuse(Protocol::Sctp, RefusedStep::sctp_needs_raw_sockets());
1200        }
1201    }
1202
1203    /// Adds the step that probes UDP, or the refusal that says why it could not
1204    /// be added.
1205    ///
1206    /// Separate from [`build`](Self::build), like [`cover_sctp`](Self::cover_sctp),
1207    /// so a TCP-only scan opens no UDP scanner and an idle scan of TCP ports
1208    /// carries no UDP refusal. Called only when the targets name a UDP port, it
1209    /// adds the connect or raw step the run's privilege calls for, or under an idle
1210    /// scan the refusal.
1211    ///
1212    /// Called with the same `privilege` the plan was built for, so the UDP step
1213    /// is raw exactly where the TCP step is.
1214    pub fn cover_udp(&mut self, privilege: Privilege) {
1215        if self.covers(Protocol::Udp) {
1216            return;
1217        }
1218        if self.idle {
1219            self.refuse(Protocol::Udp, RefusedStep::udp_not_in_an_idle_scan());
1220        } else if Self::raw_scanning(privilege) {
1221            self.steps.push(PortScanStep::RawUdp);
1222        } else {
1223            self.steps.push(PortScanStep::ConnectUdp);
1224        }
1225    }
1226
1227    /// Whether one of [`refusals`](Self::refusals) leaves `protocol`
1228    /// unprobed.
1229    ///
1230    /// Differs from a negated [`covers`](Self::covers): a protocol no step covers
1231    /// and no refusal names was left out silently, and the scan reports its
1232    /// targets as lost; one a refusal names has already been reported.
1233    pub(crate) fn refuses(&self, protocol: Protocol) -> bool {
1234        self.refused.contains(&protocol)
1235    }
1236
1237    /// Whether any step covers `protocol`.
1238    ///
1239    /// Check after editing [`steps_mut`](Self::steps_mut): a plan with nothing for a
1240    /// protocol probes and reports none of its ports.
1241    pub fn covers(&self, protocol: Protocol) -> bool {
1242        self.steps.iter().any(|step| step.protocol() == protocol)
1243    }
1244}
1245
1246/// Makes sure the link a sweep is about is among the links to be scanned, even
1247/// when no address mapped to it.
1248///
1249/// Mapping targets to interfaces only produces interfaces some target named. A
1250/// link addressed only in IPv6 maps to nothing (a `/64` cannot be enumerated and
1251/// there is no IPv4 range), so without this its all-nodes echo is never sent and the
1252/// scan reports an empty network.
1253///
1254/// Matched by name: a `NetworkInterface` compares on every field, and a mismatch
1255/// here would scan one link twice.
1256fn include_swept_link(local: &mut HashMap<Link, IpSet>) {
1257    let Some(link) = interface::lan_link() else {
1258        return;
1259    };
1260
1261    if local.keys().any(|intf| intf.name() == link.link.name()) {
1262        return;
1263    }
1264
1265    local.insert(link.link, IpSet::new());
1266}
1267
1268/// Adds the addresses in this host's IPv6 neighbour table to the targets of
1269/// whichever interface each belongs to.
1270///
1271/// The only source of IPv6 addresses nobody named. A neighbor solicitation can
1272/// only be aimed at a known address, and the all-nodes echo is optional to answer
1273/// and draws only link-local addresses. The OS table accumulates global and
1274/// unique-local ones at no cost in packets: on one test segment it held fifteen the
1275/// engine could not otherwise learn.
1276///
1277/// Three exclusions:
1278///
1279/// - **Other interfaces' entries.** A neighbour on `en1` is not reachable
1280///   through `en0`.
1281/// - **This host's own addresses**, which the table also lists.
1282/// - **Loopback and the unspecified address**, which name nothing on a segment.
1283///
1284/// Entries come from a table that goes stale, so each becomes a probe like any
1285/// other and appears in the report only if it answers now.
1286///
1287/// Returns the candidates `exclusions` kept from the sweep, which the phase
1288/// counts among the addresses its policy withheld.
1289fn seed_from_neighbor_table(local: &mut HashMap<Link, IpSet>, exclusions: &Exclusions) -> IpSet {
1290    let table = neighbor_cache::ipv6_neighbors();
1291    if table.is_empty() {
1292        return IpSet::new();
1293    }
1294    let machines = machines_named(exclusions, &table);
1295    seed_from_neighbor_table_with(local, &table, exclusions, &machines)
1296}
1297
1298/// The machines `exclusions` name, by hardware address, read off both
1299/// neighbour tables, `v6_table` among them: an excluded IPv4 address is tied
1300/// to its machine's IPv6 ones by nothing but the hardware address they share.
1301fn machines_named(
1302    exclusions: &Exclusions,
1303    v6_table: &[neighbor_cache::Neighbor],
1304) -> BTreeSet<MacAddr> {
1305    if exclusions.is_empty() {
1306        return BTreeSet::new();
1307    }
1308    let v4 = neighbor_cache::ipv4_neighbors();
1309    exclusions.hardware_in(v4.iter().chain(v6_table).map(|entry| (entry.ip, entry.mac)))
1310}
1311
1312/// [`seed_from_neighbor_table`] against an explicit table, for tests.
1313///
1314/// `machines` are the hardware addresses of the machines the exclusions name,
1315/// and an entry answering from one is held to the policy as its excluded
1316/// address is; see [`Exclusions::hardware_in`].
1317fn seed_from_neighbor_table_with(
1318    local: &mut HashMap<Link, IpSet>,
1319    table: &[neighbor_cache::Neighbor],
1320    exclusions: &Exclusions,
1321    machines: &BTreeSet<MacAddr>,
1322) -> IpSet {
1323    let mut withheld = IpSet::new();
1324    for (intf, targets) in local.iter_mut() {
1325        let mut seeded = 0usize;
1326        for candidate in candidates_on(intf, table, exclusions, machines) {
1327            // The exclusion policy. `withhold_targets` only subtracted from the
1328            // target list, and these addresses come from the neighbour table.
1329            // Without this a sweep would solicit an excluded address; `write_host`
1330            // would drop the finding, but the packet would already be sent.
1331            if candidate.withheld {
1332                info!(
1333                    verbosity = 2,
1334                    "neighbour {} is excluded, so it is not taken as a candidate",
1335                    candidate.address
1336                );
1337                withheld.insert_range(candidate.range);
1338                continue;
1339            }
1340            targets.insert_range(candidate.range);
1341            seeded += 1;
1342        }
1343
1344        if seeded > 0 {
1345            targets.canonicalize();
1346            info!(
1347                verbosity = 1,
1348                "took {} from the neighbour table as candidates on {}",
1349                counted(seeded as u128, "IPv6 address", "IPv6 addresses"),
1350                intf.name()
1351            );
1352        }
1353    }
1354    withheld.canonicalize();
1355    withheld
1356}
1357
1358/// One neighbour-table address a sweep of a link would take as a candidate.
1359struct Candidate {
1360    /// The address as the table lists it.
1361    address: IpAddr,
1362    /// What a sweep probes for it: the address, with the link's interface
1363    /// where the address is link-local.
1364    range: IpRange,
1365    /// Whether the exclusions keep it from the sweep: they name it, or it is
1366    /// listed under the hardware of a machine they name.
1367    withheld: bool,
1368}
1369
1370/// The neighbour-table candidates on `intf`, in table order, each with
1371/// whether `exclusions` keep it from a sweep; see [`candidates_for`] for which
1372/// entries are candidates at all.
1373fn candidates_on(
1374    intf: &Link,
1375    table: &[neighbor_cache::Neighbor],
1376    exclusions: &Exclusions,
1377    machines: &BTreeSet<MacAddr>,
1378) -> Vec<Candidate> {
1379    let tied: HashSet<IpAddr> = table
1380        .iter()
1381        .filter(|entry| entry.mac.is_some_and(|mac| machines.contains(&mac)))
1382        .map(|entry| entry.ip)
1383        .collect();
1384    candidates_for(intf, table)
1385        .into_iter()
1386        .filter_map(|address| {
1387            let IpAddr::V6(v6) = address else {
1388                return None;
1389            };
1390            // Zoned only where it cannot be probed without one; as in `ScopedIp`,
1391            // a global address through two interfaces is one address.
1392            let zone = v6.is_unicast_link_local().then_some(intf.index());
1393            let range = IpRange::V6(Ipv6Range::scoped(v6, v6, zone).ok()?);
1394            Some(Candidate {
1395                address,
1396                range,
1397                withheld: exclusions.excludes(&address) || tied.contains(&address),
1398            })
1399        })
1400        .collect()
1401}
1402
1403/// The neighbour-table addresses worth probing on `intf`, in table order.
1404fn candidates_for(link: &Link, table: &[neighbor_cache::Neighbor]) -> Vec<IpAddr> {
1405    let own: std::collections::HashSet<IpAddr> =
1406        link.addresses().iter().map(|held| held.address()).collect();
1407
1408    table
1409        .iter()
1410        .filter(|entry| entry.interface_index == link.index())
1411        .filter(|entry| !own.contains(&entry.ip))
1412        .filter(|entry| match entry.ip {
1413            IpAddr::V6(addr) => !addr.is_loopback() && !addr.is_unspecified(),
1414            IpAddr::V4(_) => false,
1415        })
1416        .map(|entry| entry.ip)
1417        .collect()
1418}
1419
1420// ╔════════════════════════════════════════════╗
1421// ║ ████████╗███████╗███████╗████████╗███████╗ ║
1422// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
1423// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
1424// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
1425// ║    ██║   ███████╗███████║   ██║   ███████║ ║
1426// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
1427// ╚════════════════════════════════════════════╝
1428
1429/// The remedy for a link-local target that names no interface: the target
1430/// written with an interface this host has, from its own table.
1431///
1432/// An example shows how to name the interface, using a name the reader has. Where
1433/// the host has no link to suggest, the instruction alone.
1434fn name_an_interface(range: &Ipv6Range) -> String {
1435    match link_local_example(&crate::system::interface::interfaces_or_none()) {
1436        Some(link) => format!(
1437            "link-local, name the interface ({}%{})",
1438            range.start_addr(),
1439            link.name()
1440        ),
1441        None => "link-local, name the interface".to_owned(),
1442    }
1443}
1444
1445/// The link a link-local target is most likely meant on: one that is up, can
1446/// broadcast and holds a link-local address of its own, which is a segment
1447/// `fe80::/64` means something on. The default route's is preferred, otherwise
1448/// the first in system order.
1449fn link_local_example(links: &[Link]) -> Option<&Link> {
1450    let segment = |link: &&Link| {
1451        link.is_up()
1452            && link.is_broadcast()
1453            && !link.is_loopback()
1454            && link
1455                .ipv6()
1456                .any(|(address, _)| address.is_unicast_link_local())
1457    };
1458    links
1459        .iter()
1460        .filter(segment)
1461        .find(|link| link.carries_default_route())
1462        .or_else(|| links.iter().find(segment))
1463}
1464
1465#[cfg(test)]
1466mod tests {
1467    use super::*;
1468
1469    /// **The link-local hint names an interface this host has**, one that is
1470    /// up, broadcasts and holds a link-local address, the default route's
1471    /// first, and suggests none where the host has no such link.
1472    #[test]
1473    fn the_link_local_hint_names_an_interface_this_host_has() {
1474        use crate::system::interface::{Addressing, LinkAddress};
1475        use std::net::Ipv6Addr;
1476
1477        let link_local =
1478            LinkAddress::new(IpAddr::V6(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1)), 64);
1479        let global = LinkAddress::new(
1480            IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1)),
1481            64,
1482        );
1483        let link = |name: &str, addresses: Vec<LinkAddress>| {
1484            Link::new(name, 1)
1485                .with_link_up(true)
1486                .with_addressing(Addressing::Broadcast)
1487                .with_addresses(addresses)
1488        };
1489
1490        let links = [
1491            link("tun0", vec![link_local]).with_addressing(Addressing::PointToPoint),
1492            link("eth1", vec![global]),
1493            link("eth2", vec![link_local]).with_link_up(false),
1494            link("eth0", vec![link_local]),
1495            link("wlan0", vec![link_local]).with_default_route(true),
1496        ];
1497        assert_eq!(link_local_example(&links).map(Link::name), Some("wlan0"));
1498        assert_eq!(
1499            link_local_example(&links[..4]).map(Link::name),
1500            Some("eth0")
1501        );
1502        assert!(link_local_example(&links[..3]).is_none());
1503    }
1504
1505    /// The port a raw TCP scanner built here probes from. Its transport sends
1506    /// nothing, so which one does not matter.
1507    const SRC_PORT: u16 = 54_321;
1508
1509    fn v6(addr: &str) -> IpAddr {
1510        addr.parse().unwrap()
1511    }
1512
1513    fn interface_with(index: u32, name: &str, own: Vec<IpAddr>) -> Link {
1514        use crate::system::interface::LinkAddress;
1515        Link::new(name, index).with_addresses(
1516            own.into_iter()
1517                .map(|ip| LinkAddress::new(ip, if ip.is_ipv4() { 24 } else { 64 }))
1518                .collect(),
1519        )
1520    }
1521
1522    fn entry(ip: &str, index: u32) -> neighbor_cache::Neighbor {
1523        neighbor_cache::Neighbor {
1524            ip: v6(ip),
1525            mac: None,
1526            interface_index: index,
1527        }
1528    }
1529
1530    /// A link a frame can be put on, unlike `interface_with`'s bare one.
1531    fn framed(index: u32, name: &str, own: Vec<IpAddr>) -> Link {
1532        interface_with(index, name, own)
1533            .with_mac(crate::model::mac::MacAddr::new(0x02, 0, 0, 0, 0, 0x10))
1534    }
1535
1536    fn set_of(addresses: &[&str]) -> IpSet {
1537        let mut set = IpSet::new();
1538        for address in addresses {
1539            set.insert(v6(address));
1540        }
1541        set
1542    }
1543
1544    /// What a frames-only sweep cannot reach moves to the connect step. A local
1545    /// step left empty is dropped; one still holding a framable neighbour stays.
1546    #[test]
1547    fn what_a_frame_cannot_reach_moves_to_the_connect_step() {
1548        let mut plan = DiscoveryPlan {
1549            ours: IpSet::new(),
1550            refused_by_route: IpSet::new(),
1551            withheld: IpSet::new(),
1552            steps: vec![
1553                DiscoveryStep::Local {
1554                    interface: Box::new(interface_with(20, "utun9", vec![v6("198.51.100.2")])),
1555                    targets: set_of(&["198.51.100.7"]),
1556                    scope: Scope::Targeted,
1557                },
1558                DiscoveryStep::Local {
1559                    interface: Box::new(framed(4, "en0", vec![v6("192.0.2.10")])),
1560                    targets: set_of(&["192.0.2.50"]),
1561                    scope: Scope::Targeted,
1562                },
1563                DiscoveryStep::Routed {
1564                    targets: vec![
1565                        RoutedTarget {
1566                            target: v6("203.0.113.23"),
1567                            source: v6("198.51.100.2"),
1568                        },
1569                        RoutedTarget {
1570                            target: v6("203.0.113.9"),
1571                            source: v6("192.0.2.10"),
1572                        },
1573                    ],
1574                    ports: SynPorts::common(),
1575                },
1576            ],
1577            refusals: Vec::new(),
1578        };
1579
1580        let moved = plan.connect_instead(&set_of(&["198.51.100.7", "203.0.113.23"]));
1581
1582        assert_eq!(moved.len(), 2);
1583        let kinds: Vec<ScannerKind> = plan.steps().iter().map(DiscoveryStep::kind).collect();
1584        assert_eq!(
1585            kinds,
1586            vec![
1587                ScannerKind::Local,
1588                ScannerKind::Routed,
1589                ScannerKind::Connect
1590            ],
1591            "the tunnel's local step is gone and a connect step has arrived"
1592        );
1593        match &plan.steps()[1] {
1594            DiscoveryStep::Routed { targets, .. } => {
1595                assert_eq!(targets.len(), 1);
1596                assert_eq!(targets[0].target, v6("203.0.113.9"));
1597            }
1598            other => panic!("expected the routed step, found {other:?}"),
1599        }
1600        match &plan.steps()[2] {
1601            DiscoveryStep::Connect { targets, .. } => assert_eq!(*targets, moved),
1602            other => panic!("expected the connect step, found {other:?}"),
1603        }
1604    }
1605
1606    /// A sweep's own link keeps its step with nothing left to address. A link
1607    /// that carries no frames is dropped.
1608    #[test]
1609    fn a_sweeps_step_stays_on_a_framed_link_and_goes_on_a_tunnel() {
1610        let mut plan = DiscoveryPlan {
1611            ours: IpSet::new(),
1612            refused_by_route: IpSet::new(),
1613            withheld: IpSet::new(),
1614            steps: vec![
1615                DiscoveryStep::Local {
1616                    interface: Box::new(framed(4, "en0", vec![v6("192.0.2.10")])),
1617                    targets: set_of(&["192.0.2.50"]),
1618                    scope: Scope::Sweep,
1619                },
1620                DiscoveryStep::Local {
1621                    interface: Box::new(interface_with(20, "utun9", vec![v6("198.51.100.2")])),
1622                    targets: set_of(&["198.51.100.7"]),
1623                    scope: Scope::Sweep,
1624                },
1625            ],
1626            refusals: Vec::new(),
1627        };
1628
1629        plan.withhold(&set_of(&["192.0.2.50", "198.51.100.7"]));
1630
1631        assert_eq!(plan.steps().len(), 1);
1632        match &plan.steps()[0] {
1633            DiscoveryStep::Local {
1634                interface, targets, ..
1635            } => {
1636                assert_eq!(interface.name(), "en0");
1637                assert!(targets.is_empty());
1638            }
1639            other => panic!("expected the sweep's own step, found {other:?}"),
1640        }
1641    }
1642
1643    /// Withholding leaves the connect step as it was.
1644    #[test]
1645    fn withholding_leaves_the_connect_step_as_it_was() {
1646        let mut plan = DiscoveryPlan {
1647            ours: IpSet::new(),
1648            refused_by_route: IpSet::new(),
1649            withheld: IpSet::new(),
1650            steps: vec![DiscoveryStep::Connect {
1651                targets: set_of(&["127.0.0.1"]),
1652                ports: SynPorts::common(),
1653            }],
1654            refusals: Vec::new(),
1655        };
1656
1657        let taken = plan.withhold(&set_of(&["127.0.0.1"]));
1658
1659        assert!(taken.is_empty(), "nothing was taken from a frame step");
1660        match &plan.steps()[0] {
1661            DiscoveryStep::Connect { targets, .. } => assert_eq!(*targets, set_of(&["127.0.0.1"])),
1662            other => panic!("expected the connect step, found {other:?}"),
1663        }
1664    }
1665
1666    /// A port scan's liveness pass asks its routed targets about the scan's
1667    /// own ports, and a plan built for a sweep asks the common five until told
1668    /// otherwise.
1669    #[test]
1670    fn the_routed_steps_ask_the_ports_they_are_given() {
1671        let mut plan = DiscoveryPlan {
1672            ours: IpSet::new(),
1673            refused_by_route: IpSet::new(),
1674            withheld: IpSet::new(),
1675            steps: vec![DiscoveryStep::Routed {
1676                targets: vec![RoutedTarget {
1677                    target: v6("198.51.100.1"),
1678                    source: v6("192.0.2.9"),
1679                }],
1680                ports: SynPorts::common(),
1681            }],
1682            refusals: Vec::new(),
1683        };
1684        let scan = SynPorts::for_scan(&"8443".try_into().expect("a port specification"));
1685
1686        plan.asking_tcp(scan);
1687
1688        assert!(matches!(
1689            plan.steps(),
1690            [DiscoveryStep::Routed { ports, .. }] if *ports == scan
1691        ));
1692    }
1693
1694    /// Connect addresses are asked the same ports as routed ones, so a filtered
1695    /// host serving only a port the scan names is found either way.
1696    #[test]
1697    fn the_connect_step_asks_the_ports_the_routed_steps_are_given() {
1698        let mut plan = DiscoveryPlan {
1699            ours: IpSet::new(),
1700            refused_by_route: IpSet::new(),
1701            withheld: IpSet::new(),
1702            steps: vec![
1703                DiscoveryStep::Routed {
1704                    targets: vec![RoutedTarget {
1705                        target: v6("198.51.100.1"),
1706                        source: v6("192.0.2.9"),
1707                    }],
1708                    ports: SynPorts::common(),
1709                },
1710                DiscoveryStep::Connect {
1711                    targets: set_of(&["127.0.0.1"]),
1712                    ports: SynPorts::common(),
1713                },
1714            ],
1715            refusals: Vec::new(),
1716        };
1717        let scan = SynPorts::for_scan(&"8443".try_into().expect("a port specification"));
1718
1719        plan.asking_tcp(scan);
1720
1721        assert!(
1722            matches!(
1723                plan.steps(),
1724                [DiscoveryStep::Routed { .. }, DiscoveryStep::Connect { ports, .. }] if *ports == scan
1725            ),
1726            "the connect step asks {:?}",
1727            plan.steps()
1728        );
1729    }
1730
1731    /// A plan whose every TCP port is excluded refuses its routed and connect
1732    /// steps, which would otherwise file every address as silent.
1733    #[test]
1734    fn a_plan_left_no_tcp_port_refuses_its_tcp_steps() {
1735        let mut plan = DiscoveryPlan {
1736            ours: IpSet::new(),
1737            refused_by_route: IpSet::new(),
1738            withheld: IpSet::new(),
1739            steps: vec![
1740                DiscoveryStep::Routed {
1741                    targets: vec![RoutedTarget {
1742                        target: v6("198.51.100.1"),
1743                        source: v6("192.0.2.9"),
1744                    }],
1745                    ports: SynPorts::common(),
1746                },
1747                DiscoveryStep::Connect {
1748                    targets: set_of(&["127.0.0.1"]),
1749                    ports: SynPorts::common(),
1750                },
1751            ],
1752            refusals: Vec::new(),
1753        };
1754        let everything = "1-65535".try_into().expect("a port specification");
1755
1756        plan.asking_tcp(SynPorts::common().excluding(&everything));
1757
1758        assert!(plan.steps().is_empty(), "left {:?}", plan.steps());
1759        let refused: Vec<ScannerKind> = plan.refusals().iter().map(|r| r.scanner).collect();
1760        assert_eq!(refused, [ScannerKind::Routed, ScannerKind::Connect]);
1761    }
1762
1763    /// A connect step made after the ports were chosen asks them too.
1764    #[test]
1765    fn a_connect_step_made_for_what_frames_miss_asks_the_routed_ports() {
1766        let mut plan = DiscoveryPlan {
1767            ours: IpSet::new(),
1768            refused_by_route: IpSet::new(),
1769            withheld: IpSet::new(),
1770            steps: vec![DiscoveryStep::Routed {
1771                targets: vec![
1772                    RoutedTarget {
1773                        target: v6("198.51.100.1"),
1774                        source: v6("192.0.2.9"),
1775                    },
1776                    RoutedTarget {
1777                        target: v6("198.51.100.2"),
1778                        source: v6("192.0.2.9"),
1779                    },
1780                ],
1781                ports: SynPorts::common(),
1782            }],
1783            refusals: Vec::new(),
1784        };
1785        let scan = SynPorts::for_scan(&"8443".try_into().expect("a port specification"));
1786
1787        plan.asking_tcp(scan);
1788        plan.connect_instead(&set_of(&["198.51.100.2"]));
1789
1790        assert!(
1791            matches!(
1792                plan.steps(),
1793                [DiscoveryStep::Routed { .. }, DiscoveryStep::Connect { ports, .. }] if *ports == scan
1794            ),
1795            "the connect step asks {:?}",
1796            plan.steps()
1797        );
1798    }
1799
1800    /// An SCTP sweep runs beside each routed step and nowhere else.
1801    #[test]
1802    fn an_sctp_sweep_is_added_to_the_routed_steps_alone() {
1803        let mut plan = DiscoveryPlan {
1804            ours: IpSet::new(),
1805            refused_by_route: IpSet::new(),
1806            withheld: IpSet::new(),
1807            steps: vec![
1808                DiscoveryStep::Routed {
1809                    targets: vec![RoutedTarget {
1810                        target: v6("192.0.2.1"),
1811                        source: v6("192.0.2.9"),
1812                    }],
1813                    ports: SynPorts::common(),
1814                },
1815                DiscoveryStep::Connect {
1816                    targets: IpSet::new(),
1817                    ports: SynPorts::common(),
1818                },
1819            ],
1820            refusals: Vec::new(),
1821        };
1822
1823        plan.also_over_sctp(3868);
1824
1825        let kinds: Vec<ScannerKind> = plan.steps().iter().map(DiscoveryStep::kind).collect();
1826        assert_eq!(
1827            kinds,
1828            vec![
1829                ScannerKind::Routed,
1830                ScannerKind::Connect,
1831                ScannerKind::RoutedSctp
1832            ]
1833        );
1834        assert!(matches!(
1835            plan.steps().last(),
1836            Some(DiscoveryStep::RoutedSctp { port: 3868, .. })
1837        ));
1838    }
1839
1840    /// SCTP has no unprivileged form, so without raw sockets its ports are
1841    /// refused.
1842    #[test]
1843    fn sctp_without_raw_sockets_is_refused_rather_than_substituted() {
1844        let mut plan = PortScanPlan::build(&ZondConfig::default(), Privilege::Connect);
1845        plan.cover_sctp(Privilege::Connect);
1846
1847        assert!(!plan.covers(Protocol::Sctp));
1848        assert!(
1849            plan.refusals()
1850                .iter()
1851                .any(|refusal| refusal.scanner == ScannerKind::SctpPort),
1852            "the sctp ports went unprobed and nothing in the report said so"
1853        );
1854    }
1855
1856    /// An idle scan cannot carry an INIT, and sending one directly would expose
1857    /// this host, so SCTP ports are refused.
1858    #[test]
1859    fn an_idle_scan_refuses_sctp_rather_than_probing_it_directly() {
1860        let cfg = ZondConfig {
1861            idle_scan: Some(crate::config::IdleScan::new(v6("192.0.2.9"))),
1862            ..ZondConfig::default()
1863        };
1864        let mut plan = PortScanPlan::build(&cfg, Privilege::Raw);
1865        plan.cover_sctp(Privilege::Raw);
1866
1867        assert!(!plan.covers(Protocol::Sctp));
1868        let refusal = plan
1869            .refusals()
1870            .iter()
1871            .find(|refusal| refusal.scanner == ScannerKind::SctpPort)
1872            .expect("the sctp ports are accounted for");
1873        assert!(
1874            refusal.reason.contains("idle"),
1875            "the reason names something other than the idle scan: {}",
1876            refusal.reason
1877        );
1878    }
1879
1880    /// A zombie the operator excluded is not scanned through, since the idle scan
1881    /// sends it SYN+ACKs repeatedly. No direct probe replaces it, so no TCP port is
1882    /// planned.
1883    #[test]
1884    fn an_idle_scan_through_an_excluded_zombie_is_refused() {
1885        let zombie = v6("192.0.2.9");
1886        let mut forbidden = IpSet::new();
1887        forbidden.insert(zombie);
1888        let cfg = ZondConfig {
1889            idle_scan: Some(crate::config::IdleScan::new(zombie)),
1890            exclusions: Exclusions::new(forbidden),
1891            ..ZondConfig::default()
1892        };
1893
1894        let plan = PortScanPlan::build(&cfg, Privilege::Raw);
1895
1896        assert!(
1897            !plan
1898                .steps()
1899                .iter()
1900                .any(|step| matches!(step, PortScanStep::Idle { .. })),
1901            "an idle step would probe the excluded zombie"
1902        );
1903        assert!(
1904            !plan.covers(Protocol::Tcp),
1905            "and nothing stands in for it by probing the target directly"
1906        );
1907        let refusal = plan
1908            .refusals()
1909            .iter()
1910            .find(|refusal| refusal.scanner == ScannerKind::Idle)
1911            .expect("the refused scan is accounted for");
1912        assert!(
1913            refusal.reason.contains("192.0.2.9") && refusal.reason.contains("excluded"),
1914            "the reason names the zombie and the exclusion: {}",
1915            refusal.reason
1916        );
1917    }
1918
1919    /// A refused idle scan still refuses other transports. Otherwise a privileged
1920    /// plan would probe the target's SCTP ports from this host's own address once
1921    /// the zombie was excluded.
1922    #[test]
1923    fn a_refused_idle_scan_probes_no_other_transport_directly() {
1924        let zombie = v6("192.0.2.9");
1925        let mut forbidden = IpSet::new();
1926        forbidden.insert(zombie);
1927        let cfg = ZondConfig {
1928            idle_scan: Some(crate::config::IdleScan::new(zombie)),
1929            exclusions: Exclusions::new(forbidden),
1930            ..ZondConfig::default()
1931        };
1932
1933        for privilege in [Privilege::Raw, Privilege::Connect] {
1934            let mut plan = PortScanPlan::build(&cfg, privilege);
1935            plan.cover_sctp(privilege);
1936            plan.cover_udp(privilege);
1937
1938            assert!(
1939                plan.steps().is_empty(),
1940                "{privilege:?}: nothing is probed directly: {:?}",
1941                plan.steps()
1942            );
1943            for protocol in [Protocol::Sctp, Protocol::Udp] {
1944                assert!(plan.refuses(protocol), "{privilege:?}: {protocol:?}");
1945            }
1946            let reasons: Vec<&str> = plan.refusals().iter().map(|r| r.reason.as_str()).collect();
1947            for transport in ["sctp", "udp"] {
1948                assert!(
1949                    reasons
1950                        .iter()
1951                        .any(|reason| reason.contains(transport) && reason.contains("idle scan")),
1952                    "{privilege:?}: {transport} is refused as an idle scan's: {reasons:?}"
1953                );
1954            }
1955        }
1956    }
1957
1958    /// An ordinary scan plans no UDP step until the targets name a UDP port.
1959    #[test]
1960    fn a_udp_step_is_planned_only_when_the_targets_name_udp() {
1961        for privilege in [Privilege::Raw, Privilege::Connect] {
1962            let plan = PortScanPlan::build(&ZondConfig::default(), privilege);
1963            assert!(
1964                !plan.covers(Protocol::Udp),
1965                "{privilege:?}: a plan built before the targets are read names no UDP step, so \
1966                 a TCP-only scan opens no UDP scanner to probe nothing"
1967            );
1968        }
1969
1970        let mut plan = PortScanPlan::build(&ZondConfig::default(), Privilege::Connect);
1971        plan.cover_udp(Privilege::Connect);
1972        assert!(plan.covers(Protocol::Udp) && !plan.refuses(Protocol::Udp));
1973        assert!(plan.refusals().is_empty());
1974    }
1975
1976    fn v6_set(cidr: &str) -> IpSet {
1977        crate::model::parse::ip::to_set(&[cidr], None, None).expect("a range")
1978    }
1979
1980    /// A local `/64` is withheld from a targeted run. Walked, its count overflows
1981    /// `usize` and the sweep stops two thousand solicitations in, having reported
1982    /// the prefix covered.
1983    #[test]
1984    fn a_local_prefix_too_large_to_walk_is_withheld_from_the_targets() {
1985        let mut targets = v6_set("2001:db8:1:1::/64");
1986        assert_eq!(targets.len(), 1u128 << 64, "a /64, kept whole to here");
1987
1988        let withheld = withhold_unwalkable(&mut targets);
1989
1990        assert_eq!(withheld.len(), 1, "the prefix is taken out");
1991        assert!(targets.is_empty(), "and nothing is left to walk");
1992    }
1993
1994    /// Tested per range, so a prefix beside three literal addresses keeps the
1995    /// three.
1996    #[test]
1997    fn withholding_a_prefix_keeps_the_addresses_named_beside_it() {
1998        let mut targets = crate::model::parse::ip::to_set(
1999            &["2001:db8:1:1::/64", "2001:db8:2::1", "192.0.2.7"],
2000            None,
2001            None,
2002        )
2003        .expect("a mixed set");
2004
2005        let withheld = withhold_unwalkable(&mut targets);
2006
2007        assert_eq!(withheld.len(), 1);
2008        assert_eq!(targets.len(), 2, "the literal and the IPv4 address survive");
2009    }
2010
2011    /// A range small enough to walk is left as it was.
2012    #[test]
2013    fn a_walkable_prefix_is_untouched() {
2014        let mut targets = v6_set("2001:db8::/120");
2015        let before = targets.len();
2016
2017        assert!(withhold_unwalkable(&mut targets).is_empty());
2018        assert_eq!(targets.len(), before);
2019    }
2020
2021    /// Another interface's neighbour, this host's own address and loopback never
2022    /// become targets.
2023    #[test]
2024    fn seeding_skips_other_interfaces_our_own_addresses_and_loopback() {
2025        let own = v6("2001:db8::50");
2026        let intf = interface_with(7, "en0", vec![own]);
2027        let table = vec![
2028            entry("2001:db8::aa", 7),
2029            entry("fe80::bb", 7),
2030            entry("2001:db8::cc", 9),
2031            entry("2001:db8::50", 7),
2032            entry("::1", 7),
2033        ];
2034
2035        let seeded = candidates_for(&intf, &table);
2036
2037        assert_eq!(seeded, vec![v6("2001:db8::aa"), v6("fe80::bb")]);
2038    }
2039
2040    /// A link-local candidate carries its interface; a global one does not, as in
2041    /// `ScopedIp`.
2042    #[test]
2043    fn a_seeded_link_local_keeps_its_interface_and_a_global_does_not() {
2044        let intf = interface_with(7, "en0", Vec::new());
2045        let table = vec![entry("fe80::bb", 7), entry("2001:db8::aa", 7)];
2046        let mut local = std::collections::HashMap::from([(intf, IpSet::new())]);
2047
2048        seed_from_neighbor_table_with(&mut local, &table, &Exclusions::none(), &BTreeSet::new());
2049
2050        let targets = local.into_values().next().unwrap();
2051        let zones: Vec<Option<u32>> = targets.v6().iter().map(|range| range.zone()).collect();
2052        assert!(
2053            zones.contains(&Some(7)),
2054            "the link-local needs its interface"
2055        );
2056        assert!(
2057            zones.contains(&None),
2058            "the global address needs no interface"
2059        );
2060    }
2061
2062    /// An unprivileged plan still covers both protocols.
2063    #[test]
2064    fn an_unprivileged_plan_covers_both_protocols() {
2065        let mut plan = PortScanPlan::build(&ZondConfig::default(), Privilege::Connect);
2066        plan.cover_udp(Privilege::Connect);
2067
2068        assert!(plan.covers(Protocol::Tcp));
2069        assert!(plan.covers(Protocol::Udp));
2070        assert!(plan.refusals().is_empty());
2071    }
2072
2073    /// A connect scan substitutes only for a SYN scan. For another technique, an
2074    /// unprivileged plan leaves the TCP half out and says why.
2075    #[test]
2076    fn a_technique_the_fallback_cannot_express_is_refused_at_planning_time() {
2077        let cfg = ZondConfig {
2078            tcp_technique: TcpScanTechnique::Fin,
2079            ..ZondConfig::default()
2080        };
2081        let mut plan = PortScanPlan::build(&cfg, Privilege::Connect);
2082        plan.cover_udp(Privilege::Connect);
2083
2084        assert!(
2085            !plan.covers(Protocol::Tcp),
2086            "a connect scan cannot send a FIN and must not plan to"
2087        );
2088        assert!(plan.covers(Protocol::Udp), "the UDP half is unaffected");
2089
2090        assert_eq!(plan.refusals().len(), 1, "the caller has to be told");
2091        assert_eq!(plan.refusals()[0].scanner, ScannerKind::TcpPort);
2092        assert!(
2093            plan.refusals()[0].reason.contains("fin"),
2094            "the refusal has to name the technique: {}",
2095            plan.refusals()[0].reason
2096        );
2097        assert!(
2098            plan.refuses(Protocol::Tcp) && !plan.refuses(Protocol::Udp),
2099            "and which protocol it leaves unprobed, for the router to count"
2100        );
2101    }
2102
2103    /// A step and the scanner it becomes share a name, so failures are filed
2104    /// under one strategy. In particular a FIN scan is not called
2105    /// [`ScannerKind::SynPort`], which means a half-open connection was attempted.
2106    #[test]
2107    fn a_step_reports_under_the_same_name_as_the_scanner_it_builds() {
2108        use crate::scanner::session::ScanSession;
2109        use crate::scanner::strategy::ports::TcpPortScanner;
2110        use crate::transport::probe::{Emission, ProbeSender, ProbeTransport, SendError};
2111
2112        struct Unsendable;
2113        impl ProbeSender for Unsendable {
2114            fn send(
2115                &self,
2116                _: &[u8],
2117                _: IpAddr,
2118                _: IpAddr,
2119                _: Option<u32>,
2120                _emission: Emission,
2121            ) -> Result<(), SendError> {
2122                Ok(())
2123            }
2124        }
2125
2126        let (_session, ctx) = ScanSession::new();
2127        for &technique in TcpScanTechnique::ALL {
2128            let (_tx, rx) = tokio::sync::mpsc::channel(1024);
2129            let scanner = TcpPortScanner::with_transport(
2130                interface::SourceResolver::from_links(&[]),
2131                ctx.clone(),
2132                technique,
2133                ProbeTransport::from_parts(Box::new(Unsendable), rx),
2134                1,
2135                SRC_PORT,
2136            );
2137
2138            assert_eq!(
2139                PortScanStep::RawTcp { technique }.kind(),
2140                scanner.kind(),
2141                "a {technique} step and its scanner disagree about what to call themselves"
2142            );
2143        }
2144    }
2145
2146    /// Every raw TCP technique counts as raw for host enrichment.
2147    #[test]
2148    fn every_raw_step_is_recognisable_as_one() {
2149        for &technique in TcpScanTechnique::ALL {
2150            assert!(PortScanStep::RawTcp { technique }.is_raw(), "{technique}");
2151        }
2152        assert!(PortScanStep::RawUdp.is_raw());
2153        assert!(!PortScanStep::ConnectTcp.is_raw());
2154        assert!(!PortScanStep::ConnectUdp.is_raw());
2155    }
2156
2157    /// The technique outlives the steps.
2158    #[test]
2159    fn a_plan_remembers_the_technique_it_was_built_for() {
2160        let cfg = ZondConfig {
2161            tcp_technique: TcpScanTechnique::Ack,
2162            ..ZondConfig::default()
2163        };
2164        assert_eq!(
2165            PortScanPlan::build(&cfg, Privilege::Connect).technique(),
2166            TcpScanTechnique::Ack
2167        );
2168    }
2169
2170    /// Editing a plan changes what would run; `covers` reports a protocol edited
2171    /// out.
2172    #[test]
2173    fn dropping_a_step_is_visible_in_what_the_plan_covers() {
2174        let mut plan = PortScanPlan::build(&ZondConfig::default(), Privilege::Connect);
2175        plan.steps_mut()
2176            .retain(|step| step.protocol() != Protocol::Udp);
2177
2178        assert!(plan.covers(Protocol::Tcp));
2179        assert!(!plan.covers(Protocol::Udp));
2180    }
2181
2182    /// **A sweep takes no candidate from the machine an exclusion names.** An
2183    /// excluded IPv4 address and the same machine's IPv6 addresses share only the
2184    /// hardware address the neighbour tables list them under.
2185    ///
2186    /// What the sweep kept back is returned, since the phase counts it as
2187    /// withheld.
2188    #[test]
2189    fn a_swept_plan_takes_no_candidate_from_an_excluded_machine() {
2190        let machine = MacAddr::new(0x02, 0, 0, 0, 0, 0x30);
2191        let other = MacAddr::new(0x02, 0, 0, 0, 0, 0x31);
2192        let at = |ip: &str, mac| neighbor_cache::Neighbor {
2193            mac: Some(mac),
2194            ..entry(ip, 7)
2195        };
2196        let v4 = neighbor_cache::Neighbor {
2197            ip: "192.0.2.30".parse().expect("literal"),
2198            mac: Some(machine),
2199            interface_index: 7,
2200        };
2201        let v6_table = vec![at("2001:db8::30", machine), at("2001:db8::31", other)];
2202
2203        let mut forbidden = IpSet::new();
2204        forbidden.insert(v4.ip);
2205        let exclusions = Exclusions::new(forbidden);
2206        let mut both = vec![v4];
2207        both.extend(v6_table.iter().cloned());
2208        let machines = exclusions.hardware_in(both.iter().map(|entry| (entry.ip, entry.mac)));
2209
2210        let intf = interface_with(7, "en0", Vec::new());
2211        let mut local = std::collections::HashMap::from([(intf, IpSet::new())]);
2212        let withheld = seed_from_neighbor_table_with(&mut local, &v6_table, &exclusions, &machines);
2213
2214        let targets = local.into_values().next().expect("the one interface");
2215        assert!(
2216            !targets.contains(&v6("2001:db8::30")),
2217            "the excluded machine's IPv6 address became a target"
2218        );
2219        assert_eq!(
2220            withheld.iter().collect::<Vec<_>>(),
2221            vec![v6("2001:db8::30")],
2222            "what the sweep kept back went uncounted"
2223        );
2224        assert!(
2225            targets.contains(&v6("2001:db8::31")),
2226            "and its neighbour did"
2227        );
2228    }
2229
2230    /// **A sweep does not take an excluded neighbour as a candidate.**
2231    ///
2232    /// A sweep adds addresses from the host's neighbour table, which were never in
2233    /// the withheld target list. `write_host` would drop the finding, but not the
2234    /// packet already sent.
2235    #[test]
2236    fn a_swept_plan_does_not_take_an_excluded_neighbour_as_a_candidate() {
2237        let intf = interface_with(7, "en0", Vec::new());
2238        let table = vec![entry("2001:db8::aa", 7), entry("2001:dead::bb", 7)];
2239        let mut local = std::collections::HashMap::from([(intf, IpSet::new())]);
2240
2241        let mut forbidden = IpSet::new();
2242        forbidden.insert_range("2001:db8::/64".parse().expect("a valid range"));
2243        seed_from_neighbor_table_with(
2244            &mut local,
2245            &table,
2246            &Exclusions::new(forbidden),
2247            &BTreeSet::new(),
2248        );
2249
2250        let targets = local.into_values().next().expect("the one interface");
2251        let carried: Vec<std::net::Ipv6Addr> = targets
2252            .v6()
2253            .iter()
2254            .map(|range| range.start_addr())
2255            .collect();
2256
2257        assert!(
2258            !carried.contains(&"2001:db8::aa".parse().expect("literal")),
2259            "an excluded neighbour must not become a target"
2260        );
2261        assert!(
2262            carried.contains(&"2001:dead::bb".parse().expect("literal")),
2263            "and everything else still is"
2264        );
2265    }
2266}