Skip to main content

zond_engine/transport/
probe.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//! # Probe Transport
10//!
11//! One handle the raw scanners send probes through and receive replies from, whatever
12//! carries those packets to the wire.
13//!
14//! Sending and receiving use separate mechanisms, because the constraints differ by
15//! direction and by OS:
16//!
17//! - **Receiving** always goes through a `libpcap` capture
18//!   ([`crate::transport::capture`]). A raw Layer-4 socket receives replies on Linux
19//!   but not on macOS/BSD, whose kernels never hand TCP/UDP to raw sockets; capturing
20//!   at the link layer works everywhere.
21//! - **Sending** goes through a [`ProbeSender`]. [`RawIpSender`] emits segments over a
22//!   raw Layer-4 socket, which sends fine on every supported Unix and lets the kernel
23//!   handle routing, ARP/NDP and fragmentation. The Ethernet sender builds frames
24//!   itself, for Windows (which blocks raw TCP sends) or to bypass the host stack.
25//!
26//! [`ProbeTransport`] owns a `Box<dyn ProbeSender>` and a capture-fed receive stream,
27//! and every scanner depends only on those two.
28
29use std::fmt;
30use std::net::IpAddr;
31use std::str::FromStr;
32
33use pnet_packet::Packet;
34use pnet_packet::ip::IpNextHeaderProtocols;
35
36use crate::model::capture::CaptureCounts;
37use crate::model::ip::scoped::Zone;
38use crate::model::ip::set::IpSet;
39use crate::model::mac::MacAddr;
40use crate::model::port::Protocol;
41use crate::system::interface::{Link, RoutedTargets};
42use crate::transport::capture::{self, CaptureGuard, CaptureOptions, CaptureStream};
43use crate::transport::kernel_neighbors::KernelNeighbors;
44use crate::transport::link::{EthernetSender, LinkNeighbors};
45use crate::transport::raw::{self, TransportSenderHandle, TransportType};
46
47/// How many captured segments may wait for a scanner to read them.
48///
49/// Deep enough that a burst of real replies never stalls the reader, and shallow
50/// enough that traffic the filter could not narrow stays bounded: at
51/// [`REPLY_SNAP_LEN`](capture::REPLY_SNAP_LEN) a full queue is a few megabytes. See
52/// [`capture::segments`] for which filters leave that possible.
53const REPLY_QUEUE_DEPTH: usize = 4096;
54
55/// The error [`SendMode::from_str`] returns, carrying the valid names so a front end
56/// can print it verbatim.
57#[non_exhaustive]
58#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
59#[error("unknown send mode '{input}', expected one of: auto, raw_socket, ethernet")]
60pub struct UnknownSendMode {
61    /// What the caller wrote.
62    pub input: String,
63}
64
65/// How the privileged (raw) scanners put probe packets on the wire.
66///
67/// Affects only the raw-socket SYN paths; the unprivileged TCP-connect fallback and
68/// the on-link ARP/ICMPv6 [`LocalScanner`](crate::scanner) discovery ignore it.
69#[non_exhaustive]
70#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
71pub enum SendMode {
72    /// Pick per platform. On Linux, a raw Layer-4 socket, which the kernel routes,
73    /// ARPs and fragments for, and which works through VPN tunnels. On Windows,
74    /// self-built Layer-2 Ethernet frames, since the OS blocks raw-socket TCP sends.
75    /// On macOS, frames first with the socket behind them: a large scan's raw sends
76    /// are accepted there and a quarter dropped before the wire, and an unprivileged
77    /// run has no socket to fall back to.
78    #[default]
79    Auto,
80    /// Force a raw Layer-4 socket regardless of platform.
81    RawSocket,
82    /// Force self-built Layer-2 Ethernet frames, bypassing the host IP stack (and the
83    /// local firewall and connection tracking a raw-socket send still passes through).
84    /// Requires an Ethernet-capable interface and can't reach tunnel-only
85    /// destinations, or loopback except on macOS, whose loopback interface takes a
86    /// frame too.
87    Ethernet,
88}
89impl SendMode {
90    /// Every mode, in the order a front end should offer them.
91    pub const ALL: &'static [Self] = &[SendMode::Auto, SendMode::RawSocket, SendMode::Ethernet];
92
93    /// The name this mode is written under, wherever it arrives as text.
94    pub const fn name(self) -> &'static str {
95        match self {
96            SendMode::Auto => "auto",
97            SendMode::RawSocket => "raw_socket",
98            SendMode::Ethernet => "ethernet",
99        }
100    }
101
102    /// Whether a transport this process opens in this mode reaches what a self-built
103    /// frame cannot: loopback, this host's own addresses, a target the kernel routes
104    /// through a tunnel, and an IPv6 neighbour.
105    ///
106    /// A raw socket reaches all of it, since the kernel carries the packet; a frame
107    /// reaches what has Ethernet in front of it. `Auto` is whichever this platform
108    /// opens: the socket on Linux, frames alone on Windows, and on macOS frames with
109    /// the socket behind them for a process allowed to open one. An unprivileged run
110    /// there with the BPF devices given to its group has only the frames.
111    pub(crate) fn reaches_past_frames(self) -> bool {
112        match self {
113            SendMode::RawSocket => true,
114            SendMode::Ethernet => false,
115            SendMode::Auto => {
116                #[cfg(windows)]
117                {
118                    false
119                }
120                #[cfg(target_os = "macos")]
121                {
122                    crate::system::privilege::can_send_raw()
123                }
124                #[cfg(not(any(windows, target_os = "macos")))]
125                {
126                    true
127                }
128            }
129        }
130    }
131}
132impl fmt::Display for SendMode {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        f.write_str(self.name())
135    }
136}
137impl FromStr for SendMode {
138    type Err = UnknownSendMode;
139
140    /// Parses a mode name, ignoring case and surrounding whitespace, so text input (an
141    /// argument, a form field, a settings file) needs no mapping table of its own.
142    ///
143    /// # Examples
144    ///
145    /// ```
146    /// use zond_engine::transport::probe::SendMode;
147    ///
148    /// assert_eq!("Ethernet".parse(), Ok(SendMode::Ethernet));
149    /// assert!("layer2".parse::<SendMode>().is_err());
150    /// ```
151    fn from_str(s: &str) -> Result<Self, Self::Err> {
152        let name = s.trim().to_ascii_lowercase();
153        Self::ALL
154            .iter()
155            .copied()
156            .find(|mode| mode.name() == name)
157            .ok_or_else(|| UnknownSendMode {
158                input: s.to_string(),
159            })
160    }
161}
162
163/// Which kind of raw probe traffic a [`ProbeTransport`] carries. Decides both the raw
164/// sockets opened for sending and the kernel BPF filter that picks which captured
165/// frames are copied to userspace.
166#[non_exhaustive]
167#[derive(Debug, Clone, Copy)]
168pub enum ProbeKind {
169    /// TCP SYN probes and their SYN+ACK / RST replies, over IPv4 and IPv6, where the
170    /// sender picks a fresh source port per probe.
171    TcpSyn,
172    /// TCP port probes and their replies, for a scan that sends every probe from one
173    /// source port.
174    TcpProbe {
175        /// The port every probe in the scan leaves from, and so the port its replies
176        /// come back to. A fixed port makes the TCP half of the filter expressible for
177        /// both families: `dst port` compiles over IPv6 where the flag test in
178        /// [`ProbeKind::TcpSyn`] cannot, so the scan sees only its own answers.
179        reply_port: u16,
180        /// Whether ICMP destination-unreachable messages are wanted as well.
181        ///
182        /// They tell a probe it was stopped in the path, but an ICMP error carries no
183        /// ports of its own (the probe it refers to is quoted in its payload), so
184        /// admitting them means admitting all ICMP on every captured interface and
185        /// matching it in userspace. Only a scan whose verdicts depend on that
186        /// evidence should pay for it.
187        icmp_errors: bool,
188    },
189    /// UDP service probes (DNS / mDNS) and their replies, over IPv4.
190    UdpResolve,
191    /// ICMP echo requests and the replies and errors they draw, over both address
192    /// families.
193    ///
194    /// For asking a host something its TCP stack cannot be made to answer. A host
195    /// with no open and no closed port still answers a ping, and the reply reflects
196    /// the same stack.
197    IcmpEcho {
198        /// The identifier every echo in the scan carries, and so the one its replies
199        /// carry back.
200        ///
201        /// RFC 792 and RFC 4443 §4.2 require a reply to echo the identifier and
202        /// sequence unchanged, which is the only thing separating this scan's answers
203        /// from every other ping on the host. It cannot be expressed in a kernel
204        /// filter, since it sits past a header of variable length over IPv6, so it is
205        /// matched in userspace against this field.
206        identifier: u16,
207    },
208    /// SCTP port probes and the chunks they draw, over both address families.
209    ///
210    /// One kind for both techniques: an INIT and a COOKIE-ECHO are the same protocol
211    /// from the same port, so one filter serves both.
212    Sctp {
213        /// The port every probe in the scan leaves from, and so the port its answers
214        /// come back to.
215        ///
216        /// Fixed for the same reason as [`UdpProbe`](Self::UdpProbe)'s: the kernel
217        /// filter narrows on it, and the packet quoted inside an ICMP error is checked
218        /// against it.
219        reply_port: u16,
220    },
221    /// Bare datagrams of one arbitrary IP protocol, and the ICMP messages they draw.
222    ///
223    /// What an [IP protocol scan](crate::scanner::strategy::protocols) sends. The
224    /// number is the next-header value the probe carries, and is itself what the scan
225    /// asks about.
226    ///
227    /// The number does not narrow the filter, which is the same for every number. Most
228    /// protocols worth asking about have no header this crate parses, no ports and no
229    /// reply of their own; the host's ICMP answers, and an ICMP message names what
230    /// provoked it only in the packet it quotes. So errors are admitted whole and
231    /// matched against the quotation in userspace, as [`UdpProbe`](Self::UdpProbe)
232    /// does.
233    IpProtocol {
234        /// The next-header value the probes carry: the protocol the scan asks whether
235        /// the host accepts.
236        number: u8,
237    },
238    /// UDP port probes and their ICMP unreachable / direct UDP replies.
239    UdpProbe {
240        /// The source port every probe in the scan is sent from, and so the
241        /// destination port its direct replies come back to. A fixed port lets the
242        /// kernel filter the UDP half down to this scan's own traffic; otherwise the
243        /// only expressible filter is all UDP, mostly other people's packets on a busy
244        /// host.
245        reply_port: u16,
246    },
247}
248
249impl ProbeKind {
250    /// The kind in words, with its article, as a message names the traffic a transport
251    /// was opened for: `a UDP probe`, `an ICMP echo`. The fields are left out.
252    pub(crate) const fn spoken(self) -> &'static str {
253        match self {
254            ProbeKind::TcpSyn => "a TCP SYN",
255            ProbeKind::TcpProbe { .. } => "a TCP probe",
256            ProbeKind::UdpResolve => "a UDP resolver",
257            ProbeKind::IcmpEcho { .. } => "an ICMP echo",
258            ProbeKind::Sctp { .. } => "an SCTP probe",
259            ProbeKind::IpProtocol { .. } => "an IP protocol probe",
260            ProbeKind::UdpProbe { .. } => "a UDP probe",
261        }
262    }
263
264    /// The port a transport for this kind admits replies to, where the kind fixes one.
265    const fn reply_port(self) -> Option<u16> {
266        match self {
267            ProbeKind::TcpProbe { reply_port, .. }
268            | ProbeKind::UdpProbe { reply_port }
269            | ProbeKind::Sctp { reply_port } => Some(reply_port),
270            ProbeKind::TcpSyn
271            | ProbeKind::UdpResolve
272            | ProbeKind::IcmpEcho { .. }
273            | ProbeKind::IpProtocol { .. } => None,
274        }
275    }
276
277    /// Whether a transport opened for this kind hears the answers a port scan of
278    /// `protocol` reads.
279    ///
280    /// A port scan over a transport that does not would read every answer as silence,
281    /// which is a verdict, so the mismatch is refused. Either TCP kind carries a TCP
282    /// scan: both admit the resets and SYN+ACKs it reads. A UDP scan needs its own
283    /// kind, since the resolver's admits only name-service replies.
284    pub(crate) const fn carries_port_scan(self, protocol: Protocol) -> bool {
285        match protocol {
286            Protocol::Tcp => matches!(self, ProbeKind::TcpSyn | ProbeKind::TcpProbe { .. }),
287            Protocol::Udp => matches!(self, ProbeKind::UdpProbe { .. }),
288            Protocol::Sctp => matches!(self, ProbeKind::Sctp { .. }),
289        }
290    }
291
292    /// The raw-socket transport type used for the send half.
293    fn transport_type(self) -> TransportType {
294        match self {
295            ProbeKind::TcpSyn | ProbeKind::TcpProbe { .. } => TransportType::TcpLayer4,
296            ProbeKind::UdpResolve | ProbeKind::UdpProbe { .. } => TransportType::UdpLayer4,
297            ProbeKind::Sctp { .. } => TransportType::SctpLayer4,
298            ProbeKind::IcmpEcho { .. } => TransportType::IcmpLayer4,
299            ProbeKind::IpProtocol { number } => TransportType::IpProtocol(number),
300        }
301    }
302
303    /// The IP protocol numbers this kind's probes carry, one per address family, for a
304    /// sender that writes the IP header itself.
305    ///
306    /// The raw-socket path takes the number from the socket's protocol; a Layer-2
307    /// sender builds the header and has only this. A wrong number is invisible
308    /// locally: the datagram reaches the wrong protocol handler and is never answered.
309    pub(crate) fn ip_protocols(self) -> IpProtocols {
310        match self {
311            ProbeKind::TcpSyn | ProbeKind::TcpProbe { .. } => {
312                IpProtocols::same(IpNextHeaderProtocols::Tcp.0)
313            }
314            ProbeKind::UdpResolve | ProbeKind::UdpProbe { .. } => {
315                IpProtocols::same(IpNextHeaderProtocols::Udp.0)
316            }
317            ProbeKind::Sctp { .. } => IpProtocols::same(IpNextHeaderProtocols::Sctp.0),
318            // The one kind whose two families are different protocols.
319            ProbeKind::IcmpEcho { .. } => IpProtocols {
320                v4: IpNextHeaderProtocols::Icmp.0,
321                v6: IpNextHeaderProtocols::Icmpv6.0,
322            },
323            // The one kind whose number is the question itself, so the caller
324            // chooses it.
325            ProbeKind::IpProtocol { number } => IpProtocols::same(number),
326        }
327    }
328
329    /// The `libpcap`/`tcpdump` filter expression compiled into a kernel BPF program for
330    /// the receive half. Only the replies a scan can act on reach userspace.
331    fn filter(self) -> String {
332        match self {
333            // SYN+ACK (open) and RST (closed) both set SYN or RST; nothing else a SYN
334            // probe can draw does.
335            //
336            // Only IPv4 can be narrowed this way. `tcp[tcpflags]` is `proto[x]`
337            // indexing, and an IPv6 next-header chain puts the transport header at no
338            // fixed offset, so libpcap cannot compile it, and does not say so: written
339            // as one unqualified `tcp`, the expression is silently restricted to IPv4
340            // and every IPv6 frame is rejected at the EtherType. Prefixing `ip6` fails
341            // to compile outright.
342            //
343            // So the IPv6 half is admitted unnarrowed and the flags are checked in
344            // userspace. Every IPv6 TCP segment on every captured interface is copied
345            // up; on a host with live IPv6 connections that is real traffic, and it
346            // shows in the audit's `off-target` count. It is the only IPv6 receive
347            // path there is.
348            ProbeKind::TcpSyn => {
349                "(ip and tcp and (tcp[tcpflags] & (tcp-syn|tcp-rst)) != 0) or (ip6 and tcp)"
350                    .to_string()
351            }
352            // Every reply to this kind comes back to the one port the scan sends
353            // from, so that is the whole narrowing, and both families get it. What
354            // reaches userspace is this scan's own traffic.
355            //
356            // The flags are checked in userspace: a segment to the right port still
357            // has to be one of the two answers a probe can draw, and carry back the
358            // value the probe went out with.
359            ProbeKind::TcpProbe {
360                reply_port,
361                icmp_errors,
362            } => {
363                // Both directions. The outbound half is the scan watching its own
364                // probes leave, which tells a port that stayed quiet from one whose
365                // probe the OS discarded: macOS does that to raw-socket writes under
366                // load and still returns success. It costs one captured frame per
367                // probe, all of it this scan's own.
368                let tcp = format!("tcp and port {reply_port}");
369                // An ICMP error names no ports; the probe it refers to is quoted in
370                // its payload, so this half is matched in userspace.
371                if icmp_errors {
372                    format!("icmp or icmp6 or ({tcp})")
373                } else {
374                    tcp
375                }
376            }
377            // DNS (53) and mDNS (5353) responses, by source port.
378            ProbeKind::UdpResolve => "udp and (src port 53 or src port 5353)".to_string(),
379            // A UDP probe draws two kinds of answer. A direct UDP reply comes back
380            // to the scan's source port, so it narrows to this scan. An ICMP error
381            // carries no ports (the probe is quoted in its payload), so ICMP is
382            // matched in userspace.
383            ProbeKind::UdpProbe { reply_port } => {
384                format!("icmp or icmp6 or (udp and dst port {reply_port})")
385            }
386            // The ICMP halves of the two filters above, and nothing else. A protocol
387            // probe's only possible answer is an ICMP message about it, so every
388            // error is admitted and the quotation read in userspace; see
389            // [`ProbeKind::IpProtocol`].
390            ProbeKind::IpProtocol { .. } => "icmp or icmp6".to_string(),
391            // The same shape as the UDP filter, for the same reasons: every answer an
392            // INIT can draw comes back to the scan's one port, and an ICMP error
393            // carries no ports, so the error half is admitted whole and matched
394            // against the quoted probe in userspace.
395            ProbeKind::Sctp { reply_port } => {
396                format!("icmp or icmp6 or (sctp and dst port {reply_port})")
397            }
398            // Unnarrowed. The identifier that separates this scan's replies from
399            // other pings sits four bytes into the ICMP message, which is `proto[x]`
400            // indexing: expressible over IPv4 but not IPv6, whose next-header chain
401            // puts the message at no fixed offset. Narrowing only one family would
402            // make the two behave differently without any visible reason, so both
403            // come up whole and the identifier is matched in userspace.
404            //
405            // The errors are wanted as well: a host answering an echo with
406            // "administratively prohibited" has said something, and it did not come
407            // from the host's own stack.
408            ProbeKind::IcmpEcho { .. } => "icmp or icmp6".to_string(),
409        }
410    }
411}
412
413/// Why one probe could not be put on the wire.
414///
415/// Split by whose fact the failure is, since each calls for a different response.
416/// [`Unroutable`](Self::Unroutable) and [`Unresolved`](Self::Unresolved) are facts
417/// about the destination: it cannot be reached from here, and the sender still works.
418/// [`HeldDown`](Self::HeldDown) is one too, while the kernel holds it; asked again
419/// after that, the address may answer. [`Unsupported`](Self::Unsupported) is a fact
420/// about this transport that holds for the next probe too, so a scan should give up on
421/// the path. [`Refused`](Self::Refused) came from this host and may not recur: a full
422/// send buffer clears. [`is_unroutable`](Self::is_unroutable) is the test a scan
423/// reports by.
424///
425/// A refusal carries the operating system's own words. "No route to host" and
426/// "Permission denied" call for completely different responses from the reader, and
427/// no enum could keep pace with what kernels say.
428#[non_exhaustive]
429#[derive(Debug, thiserror::Error)]
430pub enum SendError {
431    /// This host has no route to that address.
432    ///
433    /// A fact about the destination, not about this scanner, and the two call for
434    /// opposite responses. A send path that does not work is a strategy that did not
435    /// run, and the caller must be told the scan covered less than asked. An address
436    /// with no route is ordinary: a dual-stack name on an IPv4-only network resolves
437    /// to an AAAA nobody here can reach, and calling that a broken scan would make
438    /// every such scan look partial.
439    ///
440    /// Still an error and still reported, as something known about that address.
441    #[error("{0}")]
442    Unroutable(String),
443
444    /// The neighbour this probe had to be framed to was asked for its hardware address
445    /// and did not answer.
446    ///
447    /// A dead host on the local segment, or a missing gateway. A fact about the
448    /// destination like [`Unroutable`](Self::Unroutable), kept separate for a sender
449    /// holding a second path. No route on one path is a reason to try another. An
450    /// unanswered resolution is an answer about the destination, and a second path
451    /// would only ask the same neighbour again, with its own pace and memory deciding
452    /// per probe whether it is accepted, queued or refused. See [`SendMode::Auto`] on
453    /// macOS.
454    #[error("{0}")]
455    Unresolved(String),
456
457    /// The kernel will not send to this neighbour because a recent resolution failed,
458    /// and will not ask again until its own hold-down has passed.
459    ///
460    /// macOS returns this, as `EHOSTDOWN`, to every write to an on-link neighbour for
461    /// twenty seconds by default after five unanswered requests
462    /// (`net.link.ether.inet.host_down_time` and `maxtries`); it asks at most once a
463    /// second, and only when a write needs it. The write it gives up on is refused with
464    /// `EHOSTUNREACH`, as is every write through a gateway it holds down, so this is
465    /// the one refusal that names a hold-down. Linux keeps none: its sockets take every
466    /// write to a neighbour it gave up on, and the write restarts resolution.
467    ///
468    /// A fact about the destination, like [`Unresolved`](Self::Unresolved), but that
469    /// one is a resolution this sender asked for and waited out. This one is a kernel
470    /// declining to ask, based on a failure it remembers from whoever asked last,
471    /// possibly another process, or a moment the neighbour was asleep. Asked after the
472    /// hold-down, the question is new.
473    #[error("{0}")]
474    HeldDown(String),
475
476    /// The host would not send the packet, in its own words.
477    #[error("{0}")]
478    Refused(String),
479
480    /// This transport cannot express the probe it was handed, and never will.
481    #[error("this transport cannot send that probe: {0}")]
482    Unsupported(&'static str),
483
484    /// This process, or the system, had no descriptor left to open what the send
485    /// needed: a socket, or a link's handle for frames.
486    ///
487    /// A fact about this machine, like [`Refused`](Self::Refused), but separate because
488    /// every layer the open passed through wraps its own words around the one fact a
489    /// reader can act on: the file limit.
490    #[error("file limit reached")]
491    OutOfDescriptors,
492}
493
494impl SendError {
495    /// Classifies a failure from a lower layer, keeping its whole cause chain.
496    ///
497    /// Walks `source()`, so a wrapper naming which probe failed does not hide the
498    /// operating system's explanation. `thiserror`'s `#[error]` strings already
499    /// interpolate their source, so the text is the whole chain.
500    ///
501    /// Reads the operating system's error kind, since message text differs per
502    /// platform and locale. Only the unreachable kinds are singled out; everything
503    /// else stays a refusal, including lookalikes: a full send buffer or a permission
504    /// failure says nothing about whether the destination exists.
505    ///
506    /// `EHOSTDOWN` has no [`ErrorKind`](std::io::ErrorKind) of its own and is read by
507    /// number, as [`HeldDown`](Self::HeldDown). As a refusal, it would make a scan of
508    /// one dead address report itself broken.
509    pub(crate) fn from_io<E: std::error::Error + 'static>(error: E) -> Self {
510        let chain = || {
511            std::iter::successors(Some(&error as &dyn std::error::Error), |cause| {
512                cause.source()
513            })
514            .filter_map(|cause| cause.downcast_ref::<std::io::Error>())
515        };
516
517        if chain().any(crate::system::descriptors::exhausted) {
518            Self::OutOfDescriptors
519        } else if chain().any(host_is_down) {
520            Self::HeldDown(error.to_string())
521        } else if chain().any(|io| {
522            matches!(
523                io.kind(),
524                std::io::ErrorKind::HostUnreachable | std::io::ErrorKind::NetworkUnreachable
525            )
526        }) {
527            Self::Unroutable(error.to_string())
528        } else {
529            Self::Refused(error.to_string())
530        }
531    }
532
533    /// A probe not sent because the routing table gave no answer to the lookup of its
534    /// source, in the lookup's own words.
535    ///
536    /// Always a refusal, never read by [`from_io`](Self::from_io): a failed lookup says
537    /// nothing about the destination, and an `EHOSTDOWN` read there would file the host
538    /// as one whose neighbour did not answer.
539    pub(crate) fn unanswered_route(error: &std::io::Error) -> Self {
540        Self::Refused(format!("route lookup failed: {error}"))
541    }
542
543    /// Whether this failure is about the destination instead of the sending host: no
544    /// route to it, or no answer from the neighbour a route leads through, lately or
545    /// just now.
546    ///
547    /// Separates "the scan could not run" from "that address is not reachable from
548    /// here", which are reported differently.
549    pub fn is_unroutable(&self) -> bool {
550        matches!(
551            self,
552            Self::Unroutable(_) | Self::Unresolved(_) | Self::HeldDown(_)
553        )
554    }
555}
556
557/// Whether `error` is the kernel's `EHOSTDOWN`: the next hop's address resolution
558/// failed lately, and the kernel refuses sends to it for now. See
559/// [`SendError::HeldDown`].
560pub(crate) fn host_is_down(error: &std::io::Error) -> bool {
561    #[cfg(unix)]
562    {
563        error.raw_os_error() == Some(libc::EHOSTDOWN)
564    }
565    #[cfg(not(unix))]
566    {
567        let _ = error;
568        false
569    }
570}
571
572/// What a caller decides about the IP header carrying a probe.
573///
574/// Addresses, protocol number, lengths and checksums follow from the probe and its
575/// destination, so a sender derives them. What is left are the header fields nothing
576/// downstream can infer: the hop limit, and on the link-layer path a spoofed source
577/// hardware address and fragmentation.
578///
579/// A struct so further per-probe header choices (IP options, an intentionally wrong
580/// checksum) can be added without changing every sender's signature.
581///
582/// Both backends honour the hop limit: the link-layer sender writes the field in the
583/// header it builds, and the raw-socket sender sets it on the socket before the send,
584/// under the lock that serialises sends anyway. See
585/// `raw::TransportSenderHandle::send_to`.
586#[non_exhaustive]
587#[derive(Debug, Clone, Copy, PartialEq, Eq)]
588pub struct Emission {
589    /// How many hops the probe may cross before a router discards it and reports
590    /// having done so.
591    pub hop_limit: u8,
592    /// The hardware address the frame claims to come from, or `None` for the sending
593    /// interface's own. Only a self-built Ethernet frame can carry it, so an emission
594    /// with this set cannot go over a raw socket. See
595    /// [`requires_link_layer`](Self::requires_link_layer).
596    pub source_mac: Option<MacAddr>,
597    /// The largest size in bytes of each IP fragment this probe is split into, or
598    /// `None` to send it whole. Only a self-built Ethernet frame carries fragments
599    /// this engine chose, for either address family. See
600    /// [`requires_link_layer`](Self::requires_link_layer).
601    pub fragment: Option<u16>,
602}
603
604impl Emission {
605    /// What an ordinary probe wants: far enough for any path on the public internet.
606    /// See [`ip::HOP_LIMIT_ROUTED`](crate::protocols::ip::HOP_LIMIT_ROUTED).
607    pub const fn routed() -> Self {
608        Self {
609            hop_limit: crate::protocols::ip::HOP_LIMIT_ROUTED,
610            source_mac: None,
611            fragment: None,
612        }
613    }
614
615    /// A probe built to expire `hops` routers away, so the router that discards it
616    /// names itself in the error it sends back.
617    ///
618    /// This is how a path is measured. A hop limit of zero would be discarded by this
619    /// host's own stack, so it is raised to one, the first router.
620    pub const fn at_hop(hops: u8) -> Self {
621        Self {
622            hop_limit: if hops == 0 { 1 } else { hops },
623            source_mac: None,
624            fragment: None,
625        }
626    }
627
628    /// The same emission with its hop limit replaced. Carries an evasion profile's
629    /// hop limit; path measurement uses [`at_hop`](Self::at_hop).
630    #[must_use]
631    pub const fn with_hop_limit(mut self, hop_limit: u8) -> Self {
632        self.hop_limit = hop_limit;
633        self
634    }
635
636    /// The same emission sent from a spoofed hardware address. Only a self-built
637    /// Ethernet frame can carry it; see
638    /// [`requires_link_layer`](Self::requires_link_layer).
639    #[must_use]
640    pub const fn with_source_mac(mut self, source_mac: MacAddr) -> Self {
641        self.source_mac = Some(source_mac);
642        self
643    }
644
645    /// The same emission split into IP fragments of at most `mtu` bytes. Only a
646    /// self-built Ethernet frame can carry the fragments, for either address family;
647    /// see [`requires_link_layer`](Self::requires_link_layer).
648    #[must_use]
649    pub const fn with_fragment(mut self, mtu: u16) -> Self {
650        self.fragment = Some(mtu);
651        self
652    }
653
654    /// Whether this emission can only leave as a self-built Ethernet frame, because it
655    /// sets a field a raw socket cannot place: a spoofed source hardware address, or
656    /// fragments this engine chose.
657    #[must_use]
658    pub const fn requires_link_layer(&self) -> bool {
659        self.source_mac.is_some() || self.fragment.is_some()
660    }
661}
662
663impl Default for Emission {
664    fn default() -> Self {
665        Self::routed()
666    }
667}
668
669/// Sends an already-built Layer-4 `segment` to `dst`.
670///
671/// `src` is the source address the segment's checksum was computed against; a
672/// raw-socket sender lets the kernel stamp it into the IP header, while a link-layer
673/// sender uses it to build the header. `emission` is what the caller decides about
674/// that header; see [`Emission`]. Implementations must be safe to share across
675/// threads.
676pub trait ProbeSender: Send + Sync {
677    /// Emits one probe, or says why it did not leave.
678    ///
679    /// `zone` is the interface a link-local `dst` is valid on, and `None` for every
680    /// address that identifies its host on its own. `fe80::1` names a different
681    /// machine on every segment, so without a zone it is unreachable.
682    ///
683    /// [`SendError::Unroutable`] is about `dst`: that address was not covered, while
684    /// the sender still works.
685    fn send(
686        &self,
687        segment: &[u8],
688        src: IpAddr,
689        dst: IpAddr,
690        zone: Option<u32>,
691        emission: Emission,
692    ) -> Result<(), SendError>;
693}
694
695/// The IP protocol number a kind's probes carry, per address family.
696///
697/// A pair because [`ProbeKind::IcmpEcho`] is two protocols: ICMP is next-header 1 and
698/// ICMPv6 is 58. Every other kind names the same protocol twice; see
699/// [`same`](Self::same).
700#[derive(Debug, Clone, Copy, PartialEq, Eq)]
701pub struct IpProtocols {
702    /// What an IPv4 header carrying this kind's probes says it carries.
703    pub v4: u8,
704    /// What an IPv6 header carrying this kind's probes says it carries.
705    pub v6: u8,
706}
707
708impl IpProtocols {
709    /// One protocol under both families.
710    pub const fn same(protocol: u8) -> Self {
711        Self {
712            v4: protocol,
713            v6: protocol,
714        }
715    }
716
717    /// The number to stamp into a header addressed to `destination`.
718    pub const fn for_destination(self, destination: IpAddr) -> u8 {
719        match destination {
720            IpAddr::V4(_) => self.v4,
721            IpAddr::V6(_) => self.v6,
722        }
723    }
724}
725
726/// Why a probe transport could not be opened.
727///
728/// Named by the half that failed, since only one has an alternative. A scan that
729/// cannot capture cannot hear answers and is over; a scan that cannot open its send
730/// socket may still have a link-layer path, which [`SendMode`] selects.
731#[non_exhaustive]
732#[derive(Debug, thiserror::Error)]
733pub enum TransportError {
734    /// The receive half could not be started.
735    #[error("the reply capture could not be started: {0}")]
736    Capture(#[from] capture::CaptureError),
737
738    /// The raw send socket could not be opened. Needs root, and on Windows raw TCP
739    /// sends are blocked whatever the privileges.
740    #[error("the raw send socket could not be opened: {0}")]
741    RawSocket(String),
742
743    /// Layer-2 sending was asked for and this host has nothing to send from, holding
744    /// only tunnels or loopback. The raw-socket path works here.
745    #[error("no Ethernet-capable interface for Layer-2 send: {0}")]
746    NoEthernetInterface(String),
747}
748
749/// A borrowed Layer-4 segment presented as a `pnet` packet, so raw bytes can be handed
750/// straight to a `TransportSender` without a copy. The whole slice is the packet; it
751/// has no separate payload as far as the transport is concerned.
752struct RawSegment<'a>(&'a [u8]);
753
754impl Packet for RawSegment<'_> {
755    fn packet(&self) -> &[u8] {
756        self.0
757    }
758    fn payload(&self) -> &[u8] {
759        &[]
760    }
761}
762
763/// The default sender: emits segments over a raw Layer-4 socket and lets the kernel
764/// route them. Works on Linux and macOS for on-link and off-link destinations, with no
765/// ARP/NDP or gateway bookkeeping of its own.
766pub struct RawIpSender {
767    handle: TransportSenderHandle,
768}
769
770impl RawIpSender {
771    fn open(kind: ProbeKind) -> Result<Self, TransportError> {
772        raw::open_sender(kind.transport_type())
773            .map(|handle| Self { handle })
774            .map_err(|e| TransportError::RawSocket(format!("{e:#}")))
775    }
776}
777
778impl ProbeSender for RawIpSender {
779    fn send(
780        &self,
781        segment: &[u8],
782        src: IpAddr,
783        dst: IpAddr,
784        zone: Option<u32>,
785        emission: Emission,
786    ) -> Result<(), SendError> {
787        // The kernel builds the IP header and the frame here, so a field only a
788        // self-built frame can carry, such as a spoofed hardware address, cannot be
789        // honoured. Refused with the reason, so a scan that reports a spoof did one.
790        if emission.requires_link_layer() {
791            return Err(SendError::Unsupported(
792                "this emission sets a field only a self-built Ethernet frame can carry",
793            ));
794        }
795        self.handle
796            .send_from(RawSegment(segment), src, dst, zone, emission.hop_limit)
797            .map(|_| ())
798            .map_err(SendError::from_io)
799    }
800}
801
802/// Builds its own Ethernet frames, and falls back to the raw socket for destinations
803/// [`EthernetSender`] cannot frame: on-link IPv6 (no NDP) and tunnels. Loopback it
804/// frames, to the loopback interface.
805///
806/// The macOS default. There the raw socket accepts a large scan's sends and drops a
807/// quarter of them before the wire, where a self-built frame goes out.
808///
809/// Two failures are final. An emission only a frame can carry would leave the socket
810/// as a different probe from the one asked for. And a neighbour that did not answer
811/// its address resolution ([`SendError::Unresolved`]) was reachable by a frame and
812/// asked: the socket would hand the kernel the same question, which it answers in its
813/// own time. macOS takes the first few writes while it asks and discards them, then
814/// refuses the rest for twenty seconds once it gives up, so each port's verdict would
815/// depend on where the kernel was in that cycle. Refusing here treats every probe to
816/// the address alike, and the scan reads one absent host.
817///
818/// Generic over its two senders so the rule is tested on this type; the transport
819/// only builds the one pairing.
820struct LinkLayerFirst<L = EthernetSender, S = RawIpSender> {
821    link: L,
822    /// [`None`] when this process may inject frames but not open a raw socket: an
823    /// unprivileged run on macOS with the BPF devices given to a group. Only the
824    /// fallback goes missing: anything with Ethernet in front of it, and loopback, is
825    /// still reached by frame; only tunnel-only addresses and IPv6 neighbours needed
826    /// the socket.
827    socket: Option<S>,
828}
829
830impl<L: ProbeSender, S: ProbeSender> ProbeSender for LinkLayerFirst<L, S> {
831    fn send(
832        &self,
833        segment: &[u8],
834        src: IpAddr,
835        dst: IpAddr,
836        zone: Option<u32>,
837        emission: Emission,
838    ) -> Result<(), SendError> {
839        let framed = self.link.send(segment, src, dst, zone, emission);
840        let final_answer = match &framed {
841            Ok(()) | Err(SendError::Unresolved(_)) => true,
842            Err(_) => emission.requires_link_layer(),
843        };
844        if final_answer {
845            return framed;
846        }
847        match &self.socket {
848            Some(socket) => socket.send(segment, src, dst, zone, emission),
849            // The frame's own error, since it is why this destination went
850            // unreached.
851            None => framed,
852        }
853    }
854}
855
856/// A sender that refuses to send. Paired with a capture for receive-only transports
857/// (the DNS/mDNS resolver only listens), so no raw send socket is opened needlessly,
858/// and a stray send fails loudly.
859struct NoopSender;
860
861impl ProbeSender for NoopSender {
862    fn send(
863        &self,
864        _segment: &[u8],
865        _src: IpAddr,
866        _dst: IpAddr,
867        _zone: Option<u32>,
868        _emission: Emission,
869    ) -> Result<(), SendError> {
870        Err(SendError::Unsupported("it is receive-only"))
871    }
872}
873
874/// A probe transport: a swappable sender paired with a capture-fed receive stream.
875/// Scanners hold one of these and depend only on [`ProbeTransport::tx`] and
876/// [`ProbeTransport::rx`].
877#[non_exhaustive]
878pub struct ProbeTransport {
879    /// The send half, boxed so the backend can vary without touching callers.
880    pub tx: Box<dyn ProbeSender>,
881    /// Parsed replies ([`capture::CapturedSegment`]), merged across every captured
882    /// interface.
883    pub rx: CaptureStream,
884    /// Keeps the capture threads alive for this transport's lifetime, and holds the
885    /// counters they publish.
886    capture: CaptureGuard,
887    /// Where the send half's address resolution stands, for a scan that holds a host's
888    /// probes while its neighbour is resolved. See [`NeighborWatch`]. `None` where an
889    /// unanswering neighbour is refused at the send with nothing to read beforehand: a
890    /// raw socket on macOS.
891    ///
892    /// Boxed so the watch's locks sit behind a pointer; the transport's auto traits are
893    /// public and would otherwise carry them.
894    neighbors: Option<Box<NeighborWatch>>,
895    /// The kind this transport was opened for, which decides what its capture admits
896    /// and so what a scan over it can hear. `None` for one built from parts, whose
897    /// receive stream carries whatever is pushed onto it. See
898    /// [`reply_port`](Self::reply_port) and [`mismatched_for`](Self::mismatched_for).
899    kind: Option<ProbeKind>,
900}
901
902/// Where the address resolution a transport's sends depend on stands, read by a scan
903/// before it hands a probe over.
904///
905/// Two kinds, because who resolves a neighbour decides what a scan can see of it and
906/// when resolution starts.
907pub(crate) enum NeighborWatch {
908    /// The kernel's own resolution, behind a raw socket on Linux. A write to a
909    /// neighbour starts it, and the kernel tells the socket nothing of how it went;
910    /// its table does. See [`KernelNeighbors`].
911    Kernel(KernelNeighbors),
912    /// A frame sender's own resolution. Asking where it stands starts it, and a send
913    /// to a neighbour still being resolved waits for it. See [`LinkNeighbors`].
914    Frames(LinkNeighbors),
915}
916
917impl ProbeTransport {
918    /// What the receive path's kernel buffers have done so far, summed over every
919    /// interface this transport captures on.
920    ///
921    /// The scanner knows how many replies it saw; only this knows how many arrived and
922    /// were discarded before it could read them, so a scanner reports both. `None` for
923    /// a transport with no capture behind it.
924    pub fn capture_counts(&self) -> Option<CaptureCounts> {
925        self.capture.counts()
926    }
927
928    /// Where the address resolution this transport's sends wait on stands. See
929    /// [`NeighborWatch`].
930    pub(crate) fn neighbors(&self) -> Option<&NeighborWatch> {
931        self.neighbors.as_deref()
932    }
933
934    /// The port this transport's capture admits replies to, where the kind it was
935    /// opened for fixes one: [`ProbeKind::TcpProbe`], [`ProbeKind::UdpProbe`] and
936    /// [`ProbeKind::Sctp`]. `None` for a kind that fixes none, and for a transport
937    /// built from parts.
938    ///
939    /// A scan over this transport sends from this port, whatever port it was handed
940    /// beside it: answers come back to the port their probes left from, and the
941    /// capture filters out answers to any other. So the port lives here, with the
942    /// capture that filters on it.
943    pub fn reply_port(&self) -> Option<u16> {
944        self.kind.and_then(ProbeKind::reply_port)
945    }
946
947    /// The kind this transport was opened for, where its capture filters on one, if
948    /// that kind cannot carry a port scan of `protocol`.
949    ///
950    /// A transport built from parts filters nothing, so it carries anything.
951    pub(crate) fn mismatched_for(&self, protocol: Protocol) -> Option<ProbeKind> {
952        self.kind.filter(|kind| !kind.carries_port_scan(protocol))
953    }
954
955    /// This transport, standing in for one opened for `kind`.
956    #[cfg(test)]
957    pub(crate) fn opened_for(mut self, kind: ProbeKind) -> Self {
958        self.kind = Some(kind);
959        self
960    }
961
962    /// This transport, reading `neighbors` as the kernel's neighbour table.
963    #[cfg(test)]
964    pub(crate) fn with_kernel_neighbors(mut self, neighbors: KernelNeighbors) -> Self {
965        self.neighbors = Some(Box::new(NeighborWatch::Kernel(neighbors)));
966        self
967    }
968
969    /// This transport, reading `neighbors` as its frame sender's resolutions.
970    #[cfg(test)]
971    pub(crate) fn with_link_neighbors(mut self, neighbors: LinkNeighbors) -> Self {
972        self.neighbors = Some(Box::new(NeighborWatch::Frames(neighbors)));
973        self
974    }
975    /// Opens a transport for `kind` with the platform-default send backend
976    /// ([`SendMode::Auto`]).
977    pub fn open(kind: ProbeKind) -> Result<Self, TransportError> {
978        Self::open_with(kind, SendMode::Auto)
979    }
980
981    /// Opens a transport for `kind`, choosing the send backend per `mode`.
982    ///
983    /// Every mode pairs with a filtered `libpcap` capture on every interface that is
984    /// up, loopback included, so a reply is caught whichever interface the kernel
985    /// routed the probe out of. The egress path can differ per destination,
986    /// especially under a VPN.
987    pub fn open_with(kind: ProbeKind, mode: SendMode) -> Result<Self, TransportError> {
988        Self::open_capturing(kind, mode, &capturable_interfaces())
989    }
990
991    /// [`open_with`](Self::open_with), capturing on `links` alone.
992    ///
993    /// For a scan that knows where its targets are. Each capture holds a system
994    /// device, on macOS one of a fixed number of BPF devices shared by every process,
995    /// and a capture on a link no reply can arrive by wastes one. See
996    /// [`capture_links_toward`].
997    pub(crate) fn open_capturing(
998        kind: ProbeKind,
999        mode: SendMode,
1000        links: &[Zone],
1001    ) -> Result<Self, TransportError> {
1002        match mode {
1003            SendMode::Ethernet => Self::open_ethernet_capturing(kind, links),
1004            SendMode::RawSocket => Self::open_on(kind, links),
1005            // Windows blocks raw-socket TCP sends; macOS accepts them and silently
1006            // drops a quarter. Elsewhere the raw socket reaches everything without
1007            // ARP. See [`LinkLayerFirst`].
1008            SendMode::Auto => {
1009                #[cfg(windows)]
1010                {
1011                    Self::open_ethernet_capturing(kind, links)
1012                }
1013                #[cfg(target_os = "macos")]
1014                {
1015                    Self::open_link_first_capturing(kind, links)
1016                }
1017                #[cfg(not(any(windows, target_os = "macos")))]
1018                {
1019                    Self::open_on(kind, links)
1020                }
1021            }
1022        }
1023    }
1024
1025    /// [`open`](Self::open) against an explicit list of links.
1026    pub fn open_on(kind: ProbeKind, links: &[Zone]) -> Result<Self, TransportError> {
1027        let (rx, capture) = capture::segments(
1028            links,
1029            &CaptureOptions::for_replies(kind.filter()),
1030            REPLY_QUEUE_DEPTH,
1031        )?;
1032        let tx: Box<dyn ProbeSender> = Box::new(RawIpSender::open(kind)?);
1033        Ok(Self {
1034            tx,
1035            rx,
1036            capture,
1037            neighbors: KernelNeighbors::from_system()
1038                .map(|table| Box::new(NeighborWatch::Kernel(table))),
1039            kind: Some(kind),
1040        })
1041    }
1042
1043    /// A `LinkLayerFirst` transport: frames what it can, raw socket for the rest. The
1044    /// macOS default. A host with no Ethernet interface gets the plain raw-socket
1045    /// transport.
1046    pub fn open_link_first(kind: ProbeKind) -> Result<Self, TransportError> {
1047        Self::open_link_first_capturing(kind, &capturable_interfaces())
1048    }
1049
1050    /// [`open_link_first`](Self::open_link_first), capturing on `links` alone.
1051    fn open_link_first_capturing(kind: ProbeKind, links: &[Zone]) -> Result<Self, TransportError> {
1052        let Some(link) = EthernetSender::from_system(kind.ip_protocols()) else {
1053            return Self::open_on(kind, links);
1054        };
1055        let (rx, capture) = capture::segments(
1056            links,
1057            &CaptureOptions::for_replies(kind.filter()),
1058            REPLY_QUEUE_DEPTH,
1059        )?;
1060        let neighbors = Some(Box::new(NeighborWatch::Frames(link.neighbors())));
1061        Ok(Self {
1062            tx: Box::new(LinkLayerFirst {
1063                link,
1064                // Not `?`: a process that may inject frames but not open a raw socket
1065                // still scans everything with Ethernet in front of it; failing here
1066                // would fall back to connect scanning with the link-layer path unused.
1067                socket: RawIpSender::open(kind).ok(),
1068            }),
1069            rx,
1070            capture,
1071            neighbors,
1072            kind: Some(kind),
1073        })
1074    }
1075
1076    /// Opens a transport whose send half builds and emits Ethernet frames directly
1077    /// (`EthernetSender`).
1078    ///
1079    /// For Windows (where raw TCP sends are blocked) and for bypassing the host stack.
1080    /// Fails if the host has no Ethernet-capable interface, only tunnels or loopback;
1081    /// then use [`open`](Self::open).
1082    pub fn open_ethernet(kind: ProbeKind) -> Result<Self, TransportError> {
1083        Self::open_ethernet_capturing(kind, &capturable_interfaces())
1084    }
1085
1086    /// [`open_ethernet`](Self::open_ethernet), capturing on `links` alone.
1087    pub(crate) fn open_ethernet_capturing(
1088        kind: ProbeKind,
1089        links: &[Zone],
1090    ) -> Result<Self, TransportError> {
1091        let sender = EthernetSender::from_system(kind.ip_protocols()).ok_or_else(|| {
1092            TransportError::NoEthernetInterface(
1093                "the host has only tunnel or loopback interfaces".to_string(),
1094            )
1095        })?;
1096        let (rx, capture) = capture::segments(
1097            links,
1098            &CaptureOptions::for_replies(kind.filter()),
1099            REPLY_QUEUE_DEPTH,
1100        )?;
1101        let neighbors = Some(Box::new(NeighborWatch::Frames(sender.neighbors())));
1102        Ok(Self {
1103            tx: Box::new(sender),
1104            rx,
1105            capture,
1106            neighbors,
1107            kind: Some(kind),
1108        })
1109    }
1110
1111    /// Opens a receive-only transport: a filtered capture on every up interface, with
1112    /// a sender that refuses to send.
1113    ///
1114    /// For consumers that only listen, such as the passive DNS/mDNS resolver. No raw
1115    /// send socket is opened, so a host that blocks raw sockets can still resolve
1116    /// hostnames.
1117    pub fn open_receiver(kind: ProbeKind) -> Result<Self, TransportError> {
1118        Self::open_receiver_capturing(kind, &capturable_interfaces())
1119    }
1120
1121    /// [`open_receiver`](Self::open_receiver), capturing on `links` alone.
1122    pub(crate) fn open_receiver_capturing(
1123        kind: ProbeKind,
1124        links: &[Zone],
1125    ) -> Result<Self, TransportError> {
1126        let (rx, capture) = capture::segments(
1127            links,
1128            &CaptureOptions::for_replies(kind.filter()),
1129            REPLY_QUEUE_DEPTH,
1130        )?;
1131        Ok(Self {
1132            tx: Box::new(NoopSender),
1133            rx,
1134            capture,
1135            neighbors: None,
1136            kind: Some(kind),
1137        })
1138    }
1139
1140    /// Builds a transport from an explicit sender and receive stream, opening no
1141    /// socket and no capture.
1142    ///
1143    /// Lets a test run a scanner against a synthetic network: `tx` observes the probes
1144    /// the scanner emits, and whatever is pushed onto the sending half of `rx` arrives
1145    /// as though captured off the wire. With no capture threads, the transport holds an
1146    /// inert [`CaptureGuard`].
1147    ///
1148    /// Requires the `test-support` feature outside this crate.
1149    #[cfg(any(test, feature = "test-support"))]
1150    pub fn from_parts(tx: Box<dyn ProbeSender>, rx: CaptureStream) -> Self {
1151        Self {
1152            tx,
1153            rx,
1154            capture: CaptureGuard::noop(),
1155            neighbors: None,
1156            kind: None,
1157        }
1158    }
1159
1160    /// [`from_parts`](Self::from_parts) with a capture already stopped, for testing
1161    /// what a scanner makes of a receive path that went deaf.
1162    #[cfg(test)]
1163    pub(crate) fn from_parts_deaf(tx: Box<dyn ProbeSender>, rx: CaptureStream) -> Self {
1164        Self {
1165            tx,
1166            rx,
1167            capture: CaptureGuard::stopped_early(),
1168            neighbors: None,
1169            kind: None,
1170        }
1171    }
1172}
1173
1174/// The interfaces a capture should listen on: every interface that is up, and
1175/// loopback whether or not it reports being up.
1176///
1177/// [`is_up`](crate::system::interface::Link::is_up) wants a carrier as well as the
1178/// administrative flag, and loopback has no carrier: Linux leaves its operational
1179/// state `unknown` for the life of the machine. That is the right test for what to
1180/// probe out of, but here, deciding what to listen on, it would drop `lo`, and every
1181/// localhost probe would go out with none heard back.
1182///
1183/// Each is named as a [`Zone`], carrying the index with the name. The interface table
1184/// was already read, and a finding scoped to a link needs the index, since a
1185/// link-local address names a different machine on every link.
1186pub(crate) fn capturable_interfaces() -> Vec<Zone> {
1187    capturable(&crate::system::interface::interfaces_or_none())
1188}
1189
1190/// [`capturable_interfaces`] among `links`.
1191fn capturable(links: &[Link]) -> Vec<Zone> {
1192    links
1193        .iter()
1194        .filter(|link| link.is_up() || link.is_loopback())
1195        .map(Link::zone)
1196        .collect()
1197}
1198
1199/// The links a reply to a probe of `targets` can arrive by, sent from `forced` where
1200/// the scan pins its source: what a scan that knows its targets captures on.
1201///
1202/// A reply comes back to the address its probe was sent from, so it arrives by the
1203/// link holding that address. For a target on one of this host's segments, that is
1204/// the segment's link; for a routed one, the link holding the source the routing table
1205/// picks, which is the tunnel's own link under a VPN; for this host's own addresses
1206/// and loopback's, loopback. A pinned source is checked against both the pin and the
1207/// routing table, since the probe may leave by the route while its answer comes back
1208/// to the pin.
1209///
1210/// Every link that is up where routing cannot say: an address with no route, or a
1211/// source no link holds. An extra capture costs a device, a missing one loses the
1212/// reply, so doubt resolves toward listening. Likewise for a plan with more addresses
1213/// than [`MAX_ENUMERABLE_ADDRESSES`]: its phases route each one anyway, and routing
1214/// them again here would double the one planning cost that grows with the plan.
1215///
1216/// [`MAX_ENUMERABLE_ADDRESSES`]: crate::system::interface::MAX_ENUMERABLE_ADDRESSES
1217///
1218/// Worth narrowing because each capture holds a system device: on macOS one of a fixed
1219/// pool of BPF devices shared by every process, which a few scans capturing on every
1220/// link of a machine with dozens of links exhaust.
1221pub(crate) fn capture_links_toward(targets: &IpSet, forced: &[IpAddr]) -> Vec<Zone> {
1222    use crate::system::interface::{
1223        MAX_ENUMERABLE_ADDRESSES, is_enumerable, map_ips_to_interfaces,
1224        map_ips_to_interfaces_forced,
1225    };
1226
1227    let links = crate::system::interface::interfaces_or_none();
1228    // What the routing below would walk address by address: every IPv4 range, and
1229    // the IPv6 ones small enough to walk.
1230    let mut routed_one_by_one = IpSet::new();
1231    for range in targets.v4() {
1232        routed_one_by_one.push_v4_range(*range);
1233    }
1234    for range in targets.v6().iter().filter(|range| is_enumerable(range)) {
1235        routed_one_by_one.push_v6_range(*range);
1236    }
1237    if routed_one_by_one.len_gross() > MAX_ENUMERABLE_ADDRESSES {
1238        return capturable(&links);
1239    }
1240    let mut routings = vec![map_ips_to_interfaces(targets.clone())];
1241    if !forced.is_empty() {
1242        routings.push(map_ips_to_interfaces_forced(targets.clone(), forced));
1243    }
1244    links_replies_reach(&links, &routings).unwrap_or_else(|| capturable(&links))
1245}
1246
1247/// The links among `links` a reply to what `routings` planned arrives by, or `None`
1248/// where one cannot be named; see [`capture_links_toward`].
1249fn links_replies_reach(links: &[Link], routings: &[RoutedTargets]) -> Option<Vec<Zone>> {
1250    let loopback: Vec<&Link> = links.iter().filter(|link| link.is_loopback()).collect();
1251    let mut reached: Vec<Zone> = Vec::new();
1252    for routing in routings {
1253        reached.extend(routing.local.keys().map(Link::zone));
1254        for routed in &routing.routed {
1255            let holder = links.iter().find(|link| {
1256                link.addresses()
1257                    .iter()
1258                    .any(|held| held.address() == routed.source)
1259            })?;
1260            reached.push(holder.zone());
1261        }
1262        let unmapped_is_loopback =
1263            routing
1264                .unmapped
1265                .v4()
1266                .iter()
1267                .all(|range| range.start_addr().is_loopback() && range.end_addr().is_loopback())
1268                && routing.unmapped.v6().iter().all(|range| {
1269                    range.start_addr().is_loopback() && range.end_addr().is_loopback()
1270                });
1271        if !unmapped_is_loopback {
1272            return None;
1273        }
1274        if !routing.ours.is_empty() || !routing.unmapped.is_empty() {
1275            if loopback.is_empty() {
1276                return None;
1277            }
1278            reached.extend(loopback.iter().map(|link| link.zone()));
1279        }
1280    }
1281    reached.sort_by(|one, other| one.name().cmp(other.name()));
1282    reached.dedup();
1283    (!reached.is_empty()).then_some(reached)
1284}
1285
1286/// A record of one recorded send: `(segment, source, destination)`.
1287#[cfg(test)]
1288pub type SentProbe = (Vec<u8>, IpAddr, IpAddr);
1289
1290/// A [`ProbeSender`] that records what it was asked to send, so transport wiring and
1291/// scanner logic can be tested without root. Available crate-wide under `cfg(test)`.
1292#[cfg(test)]
1293#[derive(Clone, Default)]
1294pub struct MockSender {
1295    /// Every probe handed to [`send`](ProbeSender::send), oldest first. Shared, so a
1296    /// clone of the sender given to a scanner reads the same list.
1297    pub sent: std::sync::Arc<std::sync::Mutex<Vec<SentProbe>>>,
1298}
1299
1300#[cfg(test)]
1301impl ProbeSender for MockSender {
1302    fn send(
1303        &self,
1304        segment: &[u8],
1305        src: IpAddr,
1306        dst: IpAddr,
1307        _zone: Option<u32>,
1308        _emission: Emission,
1309    ) -> Result<(), SendError> {
1310        self.sent.lock().unwrap().push((segment.to_vec(), src, dst));
1311        Ok(())
1312    }
1313}
1314
1315// ╔════════════════════════════════════════════╗
1316// ║ ████████╗███████╗███████╗████████╗███████╗ ║
1317// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
1318// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
1319// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
1320// ║    ██║   ███████╗███████║   ██║   ███████║ ║
1321// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
1322// ╚════════════════════════════════════════════╝
1323
1324#[cfg(test)]
1325mod tests {
1326    use super::*;
1327    use crate::system::interface::LinkKind;
1328
1329    /// A link named `name` holding `address`, of `kind`.
1330    fn holding(name: &str, index: u32, kind: LinkKind, address: &str) -> Link {
1331        use crate::system::interface::LinkAddress;
1332        let address: IpAddr = address.parse().expect("an address");
1333        Link::new(name, index)
1334            .with_kind(kind)
1335            .with_addresses(vec![LinkAddress::new(address, 24)])
1336    }
1337
1338    /// Loopback, a wired segment, a VPN's tunnel, and a link no target is on.
1339    fn machine() -> Vec<Link> {
1340        vec![
1341            holding("lo0", 1, LinkKind::Loopback, "127.0.0.1"),
1342            holding("en0", 4, LinkKind::Wired, "192.0.2.10"),
1343            holding("utun4", 20, LinkKind::Virtual, "198.51.100.2"),
1344            holding("awdl0", 11, LinkKind::Wireless, "203.0.113.77"),
1345        ]
1346    }
1347
1348    /// Each port scan is carried by the kinds whose capture admits its answers and no
1349    /// other, and a transport built from parts, which filters nothing, carries every
1350    /// one.
1351    ///
1352    /// The UDP resolver's kind is the near miss: the same protocol, but a capture that
1353    /// admits only name-service replies, so a UDP port scan over it would hear nothing.
1354    #[test]
1355    fn a_transport_carries_the_port_scans_its_capture_admits_answers_to() {
1356        use Protocol::{Sctp, Tcp, Udp};
1357        let tcp = ProbeKind::TcpProbe {
1358            reply_port: 40_000,
1359            icmp_errors: true,
1360        };
1361        let udp = ProbeKind::UdpProbe { reply_port: 40_000 };
1362        let sctp = ProbeKind::Sctp { reply_port: 40_000 };
1363        for (kind, carried) in [
1364            (ProbeKind::TcpSyn, &[Tcp][..]),
1365            (tcp, &[Tcp]),
1366            (udp, &[Udp]),
1367            (sctp, &[Sctp]),
1368            (ProbeKind::UdpResolve, &[]),
1369            (ProbeKind::IcmpEcho { identifier: 7 }, &[]),
1370            (ProbeKind::IpProtocol { number: 47 }, &[]),
1371        ] {
1372            for protocol in [Tcp, Udp, Sctp] {
1373                assert_eq!(
1374                    kind.carries_port_scan(protocol),
1375                    carried.contains(&protocol),
1376                    "{kind:?} for {protocol:?}"
1377                );
1378            }
1379        }
1380
1381        let (_tx, rx) = tokio::sync::mpsc::channel(1);
1382        let parts = ProbeTransport::from_parts(Box::new(MockSender::default()), rx);
1383        assert!(
1384            [Tcp, Udp, Sctp]
1385                .iter()
1386                .all(|p| parts.mismatched_for(*p).is_none())
1387        );
1388        let opened = parts.opened_for(udp);
1389        assert_eq!(opened.reply_port(), Some(40_000));
1390        assert!(opened.mismatched_for(Tcp).is_some());
1391    }
1392
1393    fn names(zones: Option<Vec<Zone>>) -> Option<Vec<String>> {
1394        zones.map(|zones| zones.iter().map(|zone| zone.name().to_owned()).collect())
1395    }
1396
1397    /// **A scan captures only on the links a reply to it can arrive by.**
1398    ///
1399    /// Every capture holds a device, and on macOS the devices are a fixed pool shared
1400    /// by every process. A reply comes back to its probe's source: on the segment of an
1401    /// on-link target, on the link holding a routed target's source (the tunnel's,
1402    /// under a VPN), and over loopback for this host's own addresses.
1403    #[test]
1404    fn a_capture_listens_where_replies_to_its_targets_arrive() {
1405        let links = machine();
1406        let on = |routing: RoutedTargets| names(links_replies_reach(&links, &[routing]));
1407
1408        let loopback = RoutedTargets {
1409            unmapped: "127.0.0.1".parse().expect("an address"),
1410            ..RoutedTargets::default()
1411        };
1412        assert_eq!(on(loopback), Some(vec!["lo0".to_owned()]));
1413
1414        let mut local = std::collections::HashMap::new();
1415        local.insert(links[1].clone(), "192.0.2.0/24".parse().expect("a range"));
1416        let beside_a_vpn = RoutedTargets {
1417            local,
1418            routed: vec![crate::system::interface::RoutedTarget {
1419                target: "203.0.113.5".parse().expect("an address"),
1420                source: "198.51.100.2".parse().expect("an address"),
1421            }],
1422            ..RoutedTargets::default()
1423        };
1424        assert_eq!(
1425            on(beside_a_vpn),
1426            Some(vec!["en0".to_owned(), "utun4".to_owned()])
1427        );
1428
1429        let ours = RoutedTargets {
1430            ours: "192.0.2.10".parse().expect("an address"),
1431            ..RoutedTargets::default()
1432        };
1433        assert_eq!(on(ours), Some(vec!["lo0".to_owned()]), "this host's own");
1434    }
1435
1436    /// Where routing cannot name the link a reply arrives by, a capture listens on
1437    /// every link, since missing that link loses the reply and an extra costs only a
1438    /// device.
1439    #[test]
1440    fn a_capture_whose_replies_the_routing_cannot_place_listens_everywhere() {
1441        let links = machine();
1442        let no_route = RoutedTargets {
1443            unmapped: "203.0.113.9".parse().expect("an address"),
1444            ..RoutedTargets::default()
1445        };
1446        assert_eq!(links_replies_reach(&links, &[no_route]), None);
1447
1448        let unheld_source = RoutedTargets {
1449            routed: vec![crate::system::interface::RoutedTarget {
1450                target: "203.0.113.5".parse().expect("an address"),
1451                source: "198.51.100.99".parse().expect("an address"),
1452            }],
1453            ..RoutedTargets::default()
1454        };
1455        assert_eq!(links_replies_reach(&links, &[unheld_source]), None);
1456    }
1457
1458    /// A raw socket reaches whatever the kernel carries and a frame what has Ethernet
1459    /// in front of it, on every platform. What `Auto` reaches depends on the platform
1460    /// and, on macOS, on the process, so there it is checked against the process's own
1461    /// answer.
1462    #[test]
1463    fn a_socket_reaches_past_frames_and_a_frame_does_not() {
1464        assert!(SendMode::RawSocket.reaches_past_frames());
1465        assert!(!SendMode::Ethernet.reaches_past_frames());
1466
1467        #[cfg(target_os = "macos")]
1468        assert_eq!(
1469            SendMode::Auto.reaches_past_frames(),
1470            crate::system::privilege::can_send_raw(),
1471            "frames first, and the socket behind them only for a process that may open one"
1472        );
1473        #[cfg(windows)]
1474        assert!(!SendMode::Auto.reaches_past_frames(), "frames alone");
1475        #[cfg(not(any(windows, target_os = "macos")))]
1476        assert!(SendMode::Auto.reaches_past_frames(), "the socket alone");
1477    }
1478
1479    #[tokio::test]
1480    async fn transport_forwards_sends_and_delivers_replies() {
1481        use crate::transport::capture::CapturedSegment;
1482        use std::net::Ipv4Addr;
1483
1484        let mock = MockSender::default();
1485        let recorded = mock.sent.clone();
1486        let (reply_tx, reply_rx) = tokio::sync::mpsc::channel(1024);
1487        let mut transport = ProbeTransport::from_parts(Box::new(mock), reply_rx);
1488
1489        let src = IpAddr::V4(Ipv4Addr::new(198, 51, 100, 2));
1490        let dst = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1491        transport
1492            .tx
1493            .send(&[0xAA, 0xBB], src, dst, None, Emission::routed())
1494            .unwrap();
1495
1496        let sent = recorded.lock().unwrap().clone();
1497        assert_eq!(sent, vec![(vec![0xAA, 0xBB], src, dst)]);
1498
1499        // A reply pushed onto the capture stream arrives on rx unchanged.
1500        let reply = CapturedSegment::synthetic(
1501            dst,
1502            pnet_packet::ip::IpNextHeaderProtocols::Udp.0,
1503            vec![1, 2, 3],
1504        );
1505        reply_tx.send(reply.clone()).await.unwrap();
1506        assert_eq!(transport.rx.recv().await, Some(reply));
1507    }
1508
1509    /// The fallback keeps the macOS default from losing reach. The frame path cannot
1510    /// resolve an on-link IPv6 neighbour and has no route to loopback or into a
1511    /// tunnel, and those destinations must keep working.
1512    #[test]
1513    fn a_destination_the_frame_path_cannot_reach_goes_through_the_socket() {
1514        for cannot in [
1515            SendError::Unsupported("no NDP here"),
1516            SendError::Unroutable("no Ethernet route from 198.51.100.1".to_string()),
1517        ] {
1518            let socket = MockSender::default();
1519            let sent = socket.sent.clone();
1520            let sender = LinkLayerFirst {
1521                link: RefusingSender(cannot),
1522                socket: Some(socket),
1523            };
1524
1525            let result = send_one(&sender, Emission::routed());
1526
1527            assert!(result.is_ok(), "the socket served it: {result:?}");
1528            assert_eq!(sent.lock().unwrap().len(), 1);
1529        }
1530    }
1531
1532    /// A probe carrying a field only a self-built frame can express is not retried
1533    /// through the socket, which would send a different probe and report it as the
1534    /// one asked for.
1535    #[test]
1536    fn a_probe_only_a_frame_can_carry_is_never_retried_through_the_socket() {
1537        let socket = MockSender::default();
1538        let sent = socket.sent.clone();
1539        let sender = LinkLayerFirst {
1540            link: RefusingSender(SendError::Refused("the link went down".to_string())),
1541            socket: Some(socket),
1542        };
1543
1544        let spoofed = Emission {
1545            source_mac: Some(crate::model::mac::MacAddr::new(2, 0, 0, 0, 0, 1)),
1546            ..Emission::routed()
1547        };
1548        assert!(spoofed.requires_link_layer(), "test premise");
1549
1550        let result = send_one(&sender, spoofed);
1551
1552        assert!(result.is_err(), "the refusal stands");
1553        assert!(
1554            sent.lock().unwrap().is_empty(),
1555            "and nothing went out the other way"
1556        );
1557    }
1558
1559    /// A neighbour the frame path asked and heard nothing from is not asked again
1560    /// through the kernel. The kernel would ask the same neighbour and accept or refuse
1561    /// each probe depending on its progress, so one dead address's ports would come
1562    /// back part silent and part unasked. The frame's answer stands, as a fact about
1563    /// the destination.
1564    #[test]
1565    fn a_neighbour_that_did_not_answer_is_not_asked_again_through_the_socket() {
1566        let socket = MockSender::default();
1567        let sent = socket.sent.clone();
1568        let sender = LinkLayerFirst {
1569            link: RefusingSender(SendError::Unresolved(
1570                "198.51.100.9 did not answer address resolution on en0".to_string(),
1571            )),
1572            socket: Some(socket),
1573        };
1574
1575        let result = send_one(&sender, Emission::routed());
1576
1577        assert!(
1578            matches!(result, Err(SendError::Unresolved(_))),
1579            "the frame's answer is the one reported: {result:?}"
1580        );
1581        assert!(
1582            result.as_ref().is_err_and(SendError::is_unroutable),
1583            "and it is read as the destination's, not this host's"
1584        );
1585        assert!(
1586            sent.lock().unwrap().is_empty(),
1587            "nothing was handed to the kernel"
1588        );
1589    }
1590
1591    /// A sender that always fails the same way, for exercising the fallback.
1592    struct RefusingSender(SendError);
1593
1594    impl ProbeSender for RefusingSender {
1595        fn send(
1596            &self,
1597            _segment: &[u8],
1598            _src: IpAddr,
1599            _dst: IpAddr,
1600            _zone: Option<u32>,
1601            _emission: Emission,
1602        ) -> Result<(), SendError> {
1603            Err(match &self.0 {
1604                SendError::Unsupported(why) => SendError::Unsupported(why),
1605                SendError::Refused(why) => SendError::Refused(why.clone()),
1606                SendError::Unroutable(why) => SendError::Unroutable(why.clone()),
1607                SendError::Unresolved(why) => SendError::Unresolved(why.clone()),
1608                SendError::HeldDown(why) => SendError::HeldDown(why.clone()),
1609                SendError::OutOfDescriptors => SendError::OutOfDescriptors,
1610            })
1611        }
1612    }
1613
1614    /// One probe through `sender`, to an address the tests share.
1615    fn send_one(sender: &dyn ProbeSender, emission: Emission) -> Result<(), SendError> {
1616        let src = IpAddr::V4(std::net::Ipv4Addr::new(198, 51, 100, 1));
1617        let dst = IpAddr::V4(std::net::Ipv4Addr::new(198, 51, 100, 9));
1618        sender.send(&[0xAA], src, dst, None, emission)
1619    }
1620
1621    /// A Layer-2 sender writes the IP header itself and reads the protocol number only
1622    /// from this. A UDP probe announced as TCP is invisible locally; the target's stack
1623    /// hands it to the wrong protocol handler and it is never answered.
1624    #[test]
1625    fn every_probe_kind_carries_its_own_ip_protocol() {
1626        assert_eq!(
1627            ProbeKind::TcpSyn.ip_protocols(),
1628            IpProtocols::same(IpNextHeaderProtocols::Tcp.0)
1629        );
1630        assert_eq!(
1631            ProbeKind::TcpProbe {
1632                reply_port: 50_000,
1633                icmp_errors: true,
1634            }
1635            .ip_protocols(),
1636            IpProtocols::same(IpNextHeaderProtocols::Tcp.0)
1637        );
1638        assert_eq!(
1639            ProbeKind::UdpResolve.ip_protocols(),
1640            IpProtocols::same(IpNextHeaderProtocols::Udp.0)
1641        );
1642        assert_eq!(
1643            ProbeKind::UdpProbe { reply_port: 40_000 }.ip_protocols(),
1644            IpProtocols::same(IpNextHeaderProtocols::Udp.0)
1645        );
1646    }
1647
1648    /// ICMP is the one kind whose families are different protocols, so the destination
1649    /// chooses the number.
1650    ///
1651    /// Getting it wrong is silent: an ICMPv6 message announced as protocol 1 goes to a
1652    /// handler that will not recognise it, the probe goes unanswered, and a scan wrongly
1653    /// concludes the host did not reply.
1654    #[test]
1655    fn an_icmp_probe_names_a_different_protocol_per_family() {
1656        let protocols = ProbeKind::IcmpEcho { identifier: 1 }.ip_protocols();
1657        assert_eq!(protocols.v4, IpNextHeaderProtocols::Icmp.0);
1658        assert_eq!(protocols.v6, IpNextHeaderProtocols::Icmpv6.0);
1659        assert_eq!(
1660            protocols.for_destination(IpAddr::from([192, 0, 2, 1])),
1661            IpNextHeaderProtocols::Icmp.0
1662        );
1663        assert_eq!(
1664            protocols.for_destination("2001:db8::1".parse().unwrap()),
1665            IpNextHeaderProtocols::Icmpv6.0
1666        );
1667    }
1668
1669    /// The ICMP filter admits both families whole.
1670    ///
1671    /// The echo identifier cannot be expressed in the filter, since it sits past a
1672    /// header of variable length over IPv6. Narrowing only the IPv4 half would make
1673    /// the two families behave differently without any visible reason.
1674    #[test]
1675    fn the_icmp_filter_admits_both_families() {
1676        assert_eq!(
1677            ProbeKind::IcmpEcho { identifier: 4242 }.filter(),
1678            "icmp or icmp6"
1679        );
1680    }
1681
1682    /// The UDP filter must narrow direct replies to the scan's own source port, and
1683    /// leave ICMP unnarrowed, since an ICMP error carries no port to match.
1684    #[test]
1685    fn udp_probe_filter_narrows_replies_to_the_scan_source_port() {
1686        let filter = ProbeKind::UdpProbe { reply_port: 54_321 }.filter();
1687        assert_eq!(filter, "icmp or icmp6 or (udp and dst port 54321)");
1688    }
1689}
1690
1691// ══════════════════════════════════════════════════════════════════════════════
1692// Filter conformance
1693// ══════════════════════════════════════════════════════════════════════════════
1694
1695/// What each [`ProbeKind`]'s filter admits, judged by `libpcap` itself.
1696///
1697/// The only tests in the crate that exercise the receive path's real gatekeeper. Every
1698/// scanner test drives a synthetic transport through [`ProbeTransport::from_parts`],
1699/// which compiles no filter, so a scanner test can pass against a simulated network
1700/// while the same scan on a real one sees nothing. The only check is to compile the
1701/// expression and put a frame through it.
1702///
1703/// The evaluation is `libpcap`'s `pcap_offline_filter` running the compiled program,
1704/// the same program the kernel gets, over a frame built by this crate's packet
1705/// builders. Nothing here reimplements a filter or a parser, since an instrument
1706/// sharing the code's assumptions would confirm them.
1707#[cfg(test)]
1708mod filter_conformance {
1709    use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
1710
1711    use crate::model::mac::MacAddr;
1712    use pnet_packet::icmpv6::{Icmpv6Code, Icmpv6Types, MutableIcmpv6Packet};
1713    use pnet_packet::ip::IpNextHeaderProtocols;
1714    use pnet_packet::tcp::MutableTcpPacket;
1715
1716    use super::ProbeKind;
1717    use crate::protocols::udp;
1718    use crate::transport::frame::{FrameSpec, build_ethernet_frame};
1719
1720    const SRC_V4: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 10));
1721    const DST_V4: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 20));
1722    const SRC_V6: IpAddr = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0x10));
1723    const DST_V6: IpAddr = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0x20));
1724
1725    const SYN: u8 = 1 << 1;
1726    const RST: u8 = 1 << 2;
1727    const ACK: u8 = 1 << 4;
1728
1729    const TCP_HDR_LEN: usize = 20;
1730    const ICMPV6_UNUSED_LEN: usize = 4;
1731
1732    /// The single port a [`ProbeKind::TcpProbe`] scan sends from, and so the port its
1733    /// answers come back to.
1734    const SCAN_PORT: u16 = 50_000;
1735
1736    /// Whether `filter`, compiled for an Ethernet link, admits `frame`.
1737    ///
1738    /// A dead capture is a compiler with no interface behind it, so this needs neither
1739    /// privileges nor a network.
1740    fn admits(filter: &str, frame: &[u8]) -> bool {
1741        admits_on(pcap::Linktype::ETHERNET, filter, frame)
1742    }
1743
1744    /// Whether `filter`, compiled for a link of type `link`, admits `frame`.
1745    fn admits_on(link: pcap::Linktype, filter: &str, frame: &[u8]) -> bool {
1746        let capture = pcap::Capture::dead(link)
1747            .unwrap_or_else(|e| panic!("opening a dead capture for {link:?}: {e}"));
1748        let program = capture
1749            .compile(filter, true)
1750            .unwrap_or_else(|e| panic!("compiling `{filter}` for {link:?}: {e}"));
1751        program.filter(frame)
1752    }
1753
1754    /// An Ethernet-framed TCP segment carrying `flags`, over whichever family `src`
1755    /// and `dst` are, addressed back to the port a scan sent from.
1756    fn tcp_frame(src: IpAddr, dst: IpAddr, flags: u8) -> Vec<u8> {
1757        tcp_frame_to(src, dst, flags, SCAN_PORT)
1758    }
1759
1760    /// [`tcp_frame`] addressed to an explicit port, for filters that narrow on one.
1761    fn tcp_frame_to(src: IpAddr, dst: IpAddr, flags: u8, dst_port: u16) -> Vec<u8> {
1762        let mut segment = vec![0u8; TCP_HDR_LEN];
1763        {
1764            let mut tcp = MutableTcpPacket::new(&mut segment).expect("TCP header buffer");
1765            tcp.set_source(443);
1766            tcp.set_destination(dst_port);
1767            tcp.set_data_offset((TCP_HDR_LEN / 4) as u8);
1768            tcp.set_flags(flags);
1769            tcp.set_window(1024);
1770        }
1771        frame(src, dst, IpNextHeaderProtocols::Tcp, &segment)
1772    }
1773
1774    /// An Ethernet-framed UDP datagram between the given ports.
1775    fn udp_frame(src: IpAddr, dst: IpAddr, src_port: u16, dst_port: u16) -> Vec<u8> {
1776        let segment = udp::build_packet(src, dst, src_port, dst_port, vec![0u8; 4])
1777            .expect("building a UDP datagram");
1778        frame(src, dst, IpNextHeaderProtocols::Udp, &segment)
1779    }
1780
1781    /// An Ethernet-framed SCTP packet between the given ports, carrying the chunk a
1782    /// probe draws back.
1783    fn sctp_frame(src: IpAddr, dst: IpAddr, src_port: u16, dst_port: u16) -> Vec<u8> {
1784        let packet = crate::protocols::sctp::build_init_probe(src_port, dst_port, 0xDEAD_BEEF);
1785        frame(src, dst, IpNextHeaderProtocols::Sctp, &packet)
1786    }
1787
1788    /// An Ethernet-framed ICMPv6 destination-unreachable, the shape a UDP probe draws
1789    /// from a closed port over IPv6.
1790    fn icmpv6_error_frame(src: IpAddr, dst: IpAddr) -> Vec<u8> {
1791        let mut segment = vec![0u8; MutableIcmpv6Packet::minimum_packet_size() + ICMPV6_UNUSED_LEN];
1792        {
1793            let mut icmp = MutableIcmpv6Packet::new(&mut segment).expect("ICMPv6 header buffer");
1794            icmp.set_icmpv6_type(Icmpv6Types::DestinationUnreachable);
1795            icmp.set_icmpv6_code(Icmpv6Code(4));
1796        }
1797        frame(src, dst, IpNextHeaderProtocols::Icmpv6, &segment)
1798    }
1799
1800    fn frame(
1801        src: IpAddr,
1802        dst: IpAddr,
1803        protocol: pnet_packet::ip::IpNextHeaderProtocol,
1804        segment: &[u8],
1805    ) -> Vec<u8> {
1806        build_ethernet_frame(
1807            &FrameSpec {
1808                src_mac: MacAddr::new(0x02, 0, 0, 0, 0, 0x02),
1809                dst_mac: MacAddr::new(0x02, 0, 0, 0, 0, 0x01),
1810                src,
1811                dst,
1812                protocol: protocol.0,
1813                hop_limit: crate::protocols::ip::HOP_LIMIT_ROUTED,
1814            },
1815            segment,
1816        )
1817        .expect("building an Ethernet frame")
1818    }
1819
1820    /// The two send failures that call for opposite responses are told apart by the
1821    /// operating system's error kind, not its wording.
1822    ///
1823    /// Message text differs per platform and locale, so matching on it breaks silently
1824    /// on other machines. Only the two unreachable kinds are singled out: a full buffer
1825    /// or a permission failure says nothing about whether the destination exists, and
1826    /// treating either as unroutable would hide a scan that could not run.
1827    #[test]
1828    fn a_destination_with_no_route_is_not_a_broken_send_path() {
1829        use super::SendError;
1830        use std::io::{Error, ErrorKind};
1831
1832        for kind in [ErrorKind::HostUnreachable, ErrorKind::NetworkUnreachable] {
1833            let error = SendError::from_io(Error::new(
1834                kind,
1835                "failed to send to 2001:db8::1: No route to host",
1836            ));
1837            assert!(error.is_unroutable(), "{kind:?} is about the destination");
1838            assert!(
1839                error.to_string().contains("2001:db8::1"),
1840                "the address survives the classification: {error}"
1841            );
1842        }
1843
1844        for kind in [
1845            ErrorKind::PermissionDenied,
1846            ErrorKind::WouldBlock,
1847            ErrorKind::BrokenPipe,
1848        ] {
1849            let error = SendError::from_io(Error::new(kind, "nope"));
1850            assert!(
1851                !error.is_unroutable(),
1852                "{kind:?} is about this host, not the destination"
1853            );
1854        }
1855    }
1856
1857    /// The kernel's word for a neighbour it gave up on lately is a fact about the
1858    /// destination, named as a hold-down, distinct from a resolution this sender waited
1859    /// out.
1860    ///
1861    /// macOS answers every probe to such a neighbour with `EHOSTDOWN` while it
1862    /// remembers the failure, and `std` has no error kind for it, so it is read by
1863    /// number. As a refusal it would file a dead address as a broken scanner; as an
1864    /// unanswered resolution, a failure from before the scan asked would become the
1865    /// scan's verdict. A full send buffer must stay a refusal beside it, since it is
1866    /// this host's.
1867    #[cfg(unix)]
1868    #[test]
1869    fn a_neighbour_the_kernel_gave_up_on_is_not_a_broken_send_path() {
1870        use super::SendError;
1871        use std::io::Error;
1872
1873        let error = SendError::from_io(Error::from_raw_os_error(libc::EHOSTDOWN));
1874        assert!(
1875            matches!(error, SendError::HeldDown(_)),
1876            "the kernel's hold-down: {error:?}"
1877        );
1878        assert!(error.is_unroutable(), "and about the destination");
1879
1880        let error = SendError::from_io(Error::from_raw_os_error(libc::ENOBUFS));
1881        assert!(!error.is_unroutable(), "a full buffer is this host's");
1882    }
1883
1884    /// A send refused for want of a descriptor is named by the one fact a reader can
1885    /// act on, whatever layers it was opened through.
1886    #[cfg(unix)]
1887    #[test]
1888    fn a_send_refused_for_want_of_a_descriptor_says_the_file_limit() {
1889        use super::SendError;
1890        use std::io::Error;
1891
1892        for code in [libc::EMFILE, libc::ENFILE] {
1893            let error = SendError::from_io(Error::from_raw_os_error(code));
1894            assert!(
1895                matches!(error, SendError::OutOfDescriptors),
1896                "{code}: {error:?}"
1897            );
1898            assert!(!error.is_unroutable(), "a fact about this machine");
1899            assert_eq!(error.to_string(), "file limit reached");
1900        }
1901    }
1902
1903    // ─── TCP SYN ─────────────────────────────────────────────────────────────
1904
1905    #[test]
1906    fn the_syn_filter_admits_the_two_answers_a_syn_probe_draws_over_ipv4() {
1907        let filter = ProbeKind::TcpSyn.filter();
1908
1909        assert!(
1910            admits(&filter, &tcp_frame(SRC_V4, DST_V4, SYN | ACK)),
1911            "a SYN+ACK is an open port and must reach the scanner"
1912        );
1913        assert!(
1914            admits(&filter, &tcp_frame(SRC_V4, DST_V4, RST | ACK)),
1915            "a RST is a closed port and must reach the scanner"
1916        );
1917    }
1918
1919    /// The filter keeps unrelated traffic out of userspace, so an established
1920    /// connection's segments must not reach the scanner.
1921    #[test]
1922    fn the_syn_filter_rejects_established_traffic_over_ipv4() {
1923        assert!(!admits(
1924            &ProbeKind::TcpSyn.filter(),
1925            &tcp_frame(SRC_V4, DST_V4, ACK)
1926        ));
1927    }
1928
1929    /// `tcp[tcpflags]` is `proto[x]` indexing, which `libpcap` cannot compile over
1930    /// IPv6, where the next-header chain makes the offset non-constant. It does not
1931    /// report that: written unqualified it silently narrows the whole expression to
1932    /// IPv4, and the compiled program jumps straight to `ret #0` on EtherType
1933    /// `0x86dd`. With the capture as the only receive path, routed IPv6 discovery and
1934    /// IPv6 SYN port scanning would see no replies.
1935    #[test]
1936    fn the_syn_filter_admits_the_same_answers_over_ipv6() {
1937        let filter = ProbeKind::TcpSyn.filter();
1938
1939        assert!(admits(&filter, &tcp_frame(SRC_V6, DST_V6, SYN | ACK)));
1940        assert!(admits(&filter, &tcp_frame(SRC_V6, DST_V6, RST | ACK)));
1941    }
1942
1943    /// What admitting the IPv6 half unnarrowed costs.
1944    ///
1945    /// An established IPv6 connection's segments reach userspace, where the IPv4
1946    /// equivalent is dropped by the kernel. The filter cannot help (see
1947    /// [`libpcap_cannot_narrow_tcp_flags_over_ipv6`]), so the scanners re-check the
1948    /// flags themselves; this test records the asymmetry next to the filter.
1949    #[test]
1950    fn the_ipv6_half_of_the_syn_filter_is_not_narrowed_to_probe_replies() {
1951        let filter = ProbeKind::TcpSyn.filter();
1952
1953        assert!(
1954            !admits(&filter, &tcp_frame(SRC_V4, DST_V4, ACK)),
1955            "the IPv4 half is narrowed by the kernel"
1956        );
1957        assert!(
1958            admits(&filter, &tcp_frame(SRC_V6, DST_V6, ACK)),
1959            "the IPv6 half cannot be, so userspace has to do it"
1960        );
1961    }
1962
1963    /// Why the test above cannot be fixed by asking for IPv6 explicitly, and the
1964    /// constraint any replacement expression must work around.
1965    ///
1966    /// Records a `libpcap` limitation the engine designs around. If `libpcap` learns
1967    /// to index into IPv6, this test will notice.
1968    #[test]
1969    fn libpcap_cannot_narrow_tcp_flags_over_ipv6() {
1970        let narrowed = "ip6 and tcp and (tcp[tcpflags] & (tcp-syn|tcp-rst)) != 0";
1971        let capture = pcap::Capture::dead(pcap::Linktype::ETHERNET).expect("dead capture");
1972
1973        let admits_a_syn_ack = capture
1974            .compile(narrowed, true)
1975            .map(|program| program.filter(&tcp_frame(SRC_V6, DST_V6, SYN | ACK)))
1976            .unwrap_or(false);
1977
1978        assert!(
1979            !admits_a_syn_ack,
1980            "libpcap now narrows TCP flags over IPv6; the split filter is no longer needed"
1981        );
1982    }
1983
1984    // ─── TCP port probes ─────────────────────────────────────────────────────
1985
1986    fn tcp_probe_filter(icmp_errors: bool) -> String {
1987        ProbeKind::TcpProbe {
1988            reply_port: SCAN_PORT,
1989            icmp_errors,
1990        }
1991        .filter()
1992    }
1993
1994    /// Both answers a port probe can draw, over both families.
1995    #[test]
1996    fn the_tcp_probe_filter_admits_answers_addressed_to_the_scan() {
1997        let filter = tcp_probe_filter(false);
1998
1999        for (src, dst) in [(SRC_V4, DST_V4), (SRC_V6, DST_V6)] {
2000            assert!(
2001                admits(&filter, &tcp_frame(src, dst, SYN | ACK)),
2002                "a SYN+ACK is an open port and must reach the scanner"
2003            );
2004            assert!(
2005                admits(&filter, &tcp_frame(src, dst, RST | ACK)),
2006                "a RST is an answer and must reach the scanner"
2007            );
2008        }
2009    }
2010
2011    /// What narrowing on the scan's own port buys over narrowing on flags, and why a
2012    /// TCP port scan sends every probe from one port.
2013    ///
2014    /// A flag test cannot be compiled over IPv6 (see
2015    /// [`libpcap_cannot_narrow_tcp_flags_over_ipv6`]), so [`ProbeKind::TcpSyn`] admits
2016    /// every IPv6 TCP segment on every captured interface and sorts them in userspace.
2017    /// A destination port compiles for both families, so this filter rejects the
2018    /// host's other conversations in the kernel over IPv6 as over IPv4.
2019    #[test]
2020    fn the_tcp_probe_filter_rejects_traffic_addressed_elsewhere_over_both_families() {
2021        let filter = tcp_probe_filter(false);
2022        let elsewhere = SCAN_PORT + 1;
2023
2024        for (src, dst) in [(SRC_V4, DST_V4), (SRC_V6, DST_V6)] {
2025            assert!(
2026                !admits(&filter, &tcp_frame_to(src, dst, RST | ACK, elsewhere)),
2027                "a segment to a port this scan never sent from is somebody else's"
2028            );
2029        }
2030    }
2031
2032    /// This filter narrows on the conversation, not the flags, so a segment carrying
2033    /// neither answer a probe can draw still reaches userspace if addressed to the
2034    /// scan's port.
2035    ///
2036    /// The scan's port is drawn from the high ephemeral range so nothing else on the
2037    /// host is using it, and the scanner re-checks the flags either way, so this costs
2038    /// a check per segment, not a wrong verdict.
2039    #[test]
2040    fn the_tcp_probe_filter_narrows_on_the_conversation_rather_than_the_flags() {
2041        let filter = tcp_probe_filter(false);
2042
2043        assert!(admits(&filter, &tcp_frame(SRC_V4, DST_V4, ACK)));
2044        assert!(admits(&filter, &tcp_frame(SRC_V6, DST_V6, ACK)));
2045    }
2046
2047    /// ICMP is admitted only when a technique's verdicts depend on it, because an ICMP
2048    /// error names no ports and cannot be narrowed: asking for it copies every ICMP
2049    /// packet on every captured interface to userspace.
2050    #[test]
2051    fn the_tcp_probe_filter_admits_icmp_errors_only_when_asked() {
2052        let error = icmpv6_error_frame(SRC_V6, DST_V6);
2053
2054        assert!(!admits(&tcp_probe_filter(false), &error));
2055        assert!(admits(&tcp_probe_filter(true), &error));
2056    }
2057
2058    /// Asking for ICMP must not lose the answers the scan is waiting for, nor widen
2059    /// what it accepts on the TCP half.
2060    #[test]
2061    fn asking_for_icmp_changes_nothing_about_the_tcp_half() {
2062        let filter = tcp_probe_filter(true);
2063
2064        assert!(admits(&filter, &tcp_frame(SRC_V6, DST_V6, RST | ACK)));
2065        assert!(!admits(
2066            &filter,
2067            &tcp_frame_to(SRC_V6, DST_V6, RST | ACK, SCAN_PORT + 1)
2068        ));
2069    }
2070
2071    // ─── UDP ─────────────────────────────────────────────────────────────────
2072
2073    /// The resolver's filter is family-agnostic, as it must be: a DNS or mDNS answer
2074    /// over IPv6 names hosts as well as one over IPv4.
2075    #[test]
2076    fn the_resolve_filter_admits_dns_answers_over_both_families() {
2077        let filter = ProbeKind::UdpResolve.filter();
2078
2079        assert!(admits(&filter, &udp_frame(SRC_V4, DST_V4, 53, 40_000)));
2080        assert!(admits(&filter, &udp_frame(SRC_V6, DST_V6, 53, 40_000)));
2081        assert!(admits(&filter, &udp_frame(SRC_V6, DST_V6, 5353, 5353)));
2082        assert!(
2083            !admits(&filter, &udp_frame(SRC_V6, DST_V6, 12_345, 40_000)),
2084            "traffic from an unrelated source port is not an answer to anything"
2085        );
2086    }
2087
2088    /// Both answers a UDP probe can draw, over both families. `icmp6` carries the IPv6
2089    /// half here.
2090    #[test]
2091    fn the_udp_probe_filter_admits_direct_replies_and_icmp_errors_over_both_families() {
2092        const REPLY_PORT: u16 = 40_000;
2093        let filter = ProbeKind::UdpProbe {
2094            reply_port: REPLY_PORT,
2095        }
2096        .filter();
2097
2098        assert!(admits(&filter, &udp_frame(SRC_V4, DST_V4, 53, REPLY_PORT)));
2099        assert!(admits(&filter, &udp_frame(SRC_V6, DST_V6, 53, REPLY_PORT)));
2100        assert!(admits(&filter, &icmpv6_error_frame(SRC_V6, DST_V6)));
2101        assert!(
2102            !admits(&filter, &udp_frame(SRC_V6, DST_V6, 53, REPLY_PORT + 1)),
2103            "a datagram to a port this scan never sent from is somebody else's"
2104        );
2105    }
2106
2107    /// The SCTP filter, held to the same three claims as the UDP one: both families
2108    /// admitted, ICMP errors admitted whole, and other associations kept out.
2109    ///
2110    /// `sctp` is a protocol keyword libpcap has to know for this to compile, and a
2111    /// filter that fails to compile is a scanner that reads nothing.
2112    #[test]
2113    fn the_sctp_filter_admits_answers_to_the_scan_over_both_families() {
2114        const REPLY_PORT: u16 = 40_000;
2115        let filter = ProbeKind::Sctp {
2116            reply_port: REPLY_PORT,
2117        }
2118        .filter();
2119
2120        assert!(admits(
2121            &filter,
2122            &sctp_frame(SRC_V4, DST_V4, 2905, REPLY_PORT)
2123        ));
2124        assert!(admits(
2125            &filter,
2126            &sctp_frame(SRC_V6, DST_V6, 2905, REPLY_PORT)
2127        ));
2128        assert!(admits(&filter, &icmpv6_error_frame(SRC_V6, DST_V6)));
2129        assert!(
2130            !admits(&filter, &sctp_frame(SRC_V4, DST_V4, 2905, REPLY_PORT + 1)),
2131            "a packet to a port this scan never sent from belongs to somebody else"
2132        );
2133    }
2134
2135    // ─── Cooked links ────────────────────────────────────────────────────────
2136
2137    /// The data-link type `libpcap` opens a PPP link as, `DLT_LINUX_SLL`.
2138    const LINUX_SLL: pcap::Linktype = pcap::Linktype(113);
2139
2140    /// `frame`, an Ethernet frame, as a PPP link captures the same packet: the Ethernet
2141    /// header replaced by the pseudo-header Linux writes there, laid out from
2142    /// `pcap/sll.h` and naming the same EtherType.
2143    fn as_cooked(frame: &[u8]) -> Vec<u8> {
2144        let (ethernet, packet) = frame.split_at(crate::protocols::sizes::ETH_HDR_LEN);
2145        let mut cooked = vec![
2146            0x00, 0x00, // packet type: addressed to this host
2147            0x02, 0x00, // hardware type: ARPHRD_PPP
2148            0x00, 0x00, // address length: a PPP link has none
2149            0, 0, 0, 0, 0, 0, 0, 0, // the address, unused
2150        ];
2151        cooked.extend_from_slice(&ethernet[12..14]);
2152        cooked.extend_from_slice(packet);
2153        cooked
2154    }
2155
2156    /// Every filter judges a packet arriving over PPP as it judges the same packet
2157    /// over Ethernet.
2158    ///
2159    /// A filter is compiled for the link it is opened on, and on a cooked link
2160    /// `libpcap` finds the protocol and IP header at its own offsets. An expression
2161    /// reaching below IP, through an `ether` qualifier or an offset from the start of
2162    /// the frame, would compile differently there or fail to compile, and a scan
2163    /// through a PPP VPN would hear nothing. Only `DLT_LINUX_SLL` is compiled for, as
2164    /// what a capture of one named link comes up as.
2165    #[test]
2166    fn every_filter_judges_a_packet_on_a_cooked_link_as_it_does_on_ethernet() {
2167        const REPLY_PORT: u16 = 40_000;
2168        let kinds = [
2169            ProbeKind::TcpSyn,
2170            ProbeKind::TcpProbe {
2171                reply_port: SCAN_PORT,
2172                icmp_errors: false,
2173            },
2174            ProbeKind::TcpProbe {
2175                reply_port: SCAN_PORT,
2176                icmp_errors: true,
2177            },
2178            ProbeKind::UdpResolve,
2179            ProbeKind::UdpProbe {
2180                reply_port: REPLY_PORT,
2181            },
2182            ProbeKind::Sctp {
2183                reply_port: REPLY_PORT,
2184            },
2185            ProbeKind::IcmpEcho { identifier: 4242 },
2186            ProbeKind::IpProtocol { number: 47 },
2187        ];
2188        let frames = [
2189            tcp_frame(SRC_V4, DST_V4, SYN | ACK),
2190            tcp_frame(SRC_V6, DST_V6, SYN | ACK),
2191            tcp_frame(SRC_V4, DST_V4, ACK),
2192            tcp_frame(SRC_V6, DST_V6, ACK),
2193            tcp_frame_to(SRC_V4, DST_V4, RST | ACK, SCAN_PORT + 1),
2194            udp_frame(SRC_V4, DST_V4, 53, REPLY_PORT),
2195            udp_frame(SRC_V6, DST_V6, 53, REPLY_PORT),
2196            udp_frame(SRC_V6, DST_V6, 12_345, REPLY_PORT + 1),
2197            sctp_frame(SRC_V4, DST_V4, 2905, REPLY_PORT),
2198            sctp_frame(SRC_V6, DST_V6, 2905, REPLY_PORT),
2199            icmpv6_error_frame(SRC_V6, DST_V6),
2200        ];
2201
2202        let (mut admitted, mut refused) = (0, 0);
2203        for kind in kinds {
2204            let filter = kind.filter();
2205            for frame in &frames {
2206                let over_ethernet = admits(&filter, frame);
2207                assert_eq!(
2208                    admits_on(LINUX_SLL, &filter, &as_cooked(frame)),
2209                    over_ethernet,
2210                    "`{filter}` judged a packet differently over PPP than over Ethernet"
2211                );
2212                if over_ethernet {
2213                    admitted += 1;
2214                } else {
2215                    refused += 1;
2216                }
2217            }
2218        }
2219        // Agreement means nothing if every verdict was the same one.
2220        assert!(
2221            admitted > 0 && refused > 0,
2222            "{admitted} admitted, {refused} refused"
2223        );
2224    }
2225}