Skip to main content

zond_engine/scanner/
strategy.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//! # What a scanning strategy is
10//!
11//! Two traits, one per phase, and the error a strategy fails with.
12//! [`discover`](crate::scanner::discover) and [`scan`](crate::scanner::scan)
13//! know nothing about any strategy beyond these methods.
14//!
15//! ## How the submodules are arranged
16//!
17//! By the phase a strategy serves, the same axis
18//! [`ScanKind`](crate::report::ScanKind) and
19//! [`PhaseRecorder`](crate::scanner::recorder::PhaseRecorder) use. Transport and
20//! privilege vary inside a category, because abstracting over them is what the two
21//! traits are for.
22//!
23//! | module | what it is |
24//! |---|---|
25//! | [`local`], [`routed`], [`connect`] | which hosts are there: at the link layer, through a gateway, or by ordinary connect |
26//! | [`ports`] | which ports are open |
27//! | [`identify`] | what a machine is, asked of hosts already found |
28//! | [`topology`] | what is between here and a host |
29//! | [`passive`] | what a link already carries, having sent nothing |
30//! | [`composite`] | routes each target to a strategy that covers its protocol |
31//! | `raw`, `frames`, `icmp_error`, `sweep` | internal: what strategies are built from, what they read, and what they all keep track of |
32//!
33//! ## Findings go to the context
34//!
35//! Neither trait returns what it found. A strategy writes hosts and ports into the
36//! [`ScanContext`] it was built with, and its run method reports only whether the
37//! attempt got to the end. That makes an ARP sweep, a raw SYN scan and a TCP connect
38//! interchangeable to a caller (build one, run it, read the store), and lets several
39//! strategies write into one live view while they run.
40//!
41//! A target that did not answer is a finding and lands in the store. A strategy that
42//! could not open its socket is a failure and comes back as [`StrategyError`]: then
43//! the absence of hosts proves nothing.
44//!
45//! ## Shape of the traits
46//!
47//! Both carry a [`kind`](HostScanner::kind), take `&mut self` and return
48//! `Result<(), StrategyError>`. A [`PortScanner`] is fed its targets on a channel and
49//! declares which protocols it covers, because several run at once and each target
50//! must be routed to one that can take it. A [`HostScanner`] owns its targets from
51//! construction, because a sweep is aimed at a whole segment.
52//!
53//! Neither consumes `self`: taking `self: Box<Self>` would force every caller to box
54//! a scanner it already owns.
55
56use async_trait::async_trait;
57use tokio::sync::mpsc;
58
59use crate::journal::settle::Outcome;
60use crate::model::port::{PortState, Protocol};
61use crate::model::target::PlannedTarget;
62use crate::report::ScannerKind;
63use crate::scanner::session::ScanContext;
64
65/// Why one scanning strategy could not start, or could not finish.
66///
67/// A scan runs several strategies and carries on with whatever survives, so
68/// [`discover`](crate::scanner::discover) and [`scan`](crate::scanner::scan) record
69/// one of these in the report's [`failures`](crate::report::ScanReport::failures)
70/// and announce it on the event stream. It reaches a caller directly only when they
71/// build and run a strategy themselves.
72///
73/// The variants are the layers a strategy is assembled from. A [`Transport`],
74/// [`Channel`] or [`Capture`] failure is most often missing privileges, which a
75/// scan's unprivileged fallback covers; the underlying error says which. An
76/// [`Interface`] failure concerns one interface and leaves the others unaffected.
77///
78/// [`Transport`]: StrategyError::Transport
79/// [`Channel`]: StrategyError::Channel
80/// [`Capture`]: StrategyError::Capture
81/// [`Interface`]: StrategyError::Interface
82#[non_exhaustive]
83#[derive(Debug, thiserror::Error)]
84pub enum StrategyError {
85    /// The raw probe transport could not be opened.
86    #[error(transparent)]
87    Transport(#[from] crate::transport::probe::TransportError),
88
89    /// The link-layer channel a local sweep needs could not be opened.
90    #[error(transparent)]
91    Channel(#[from] crate::transport::channel::ChannelError),
92
93    /// Nothing could be captured on the links a listener was given.
94    ///
95    /// The capture's own error, which names each link and what refused it.
96    #[error(transparent)]
97    Capture(#[from] crate::transport::capture::CaptureError),
98
99    /// The interface this strategy was given cannot be probed from.
100    #[error("{interface} cannot be probed from: {reason}")]
101    Interface {
102        /// The interface in question.
103        interface: String,
104        /// What is missing.
105        reason: &'static str,
106    },
107
108    /// The transport a port scan was handed was opened for another kind of
109    /// probe, so its capture would admit none of the scan's answers.
110    ///
111    /// Refused because a scan that hears nothing files every port as silent,
112    /// which looks exactly like a network that drops everything. Every port it was
113    /// handed is recorded as unasked.
114    #[error(
115        "{} transport cannot hear {} port scan's answers",
116        .kind.spoken(),
117        spoken_protocol(*.protocol)
118    )]
119    MismatchedTransport {
120        /// The kind the transport was opened for.
121        kind: crate::transport::probe::ProbeKind,
122        /// The protocol of the port scan it was handed to.
123        protocol: crate::model::port::Protocol,
124    },
125
126    /// The strategy's probes could not be built. A bug or an impossible target,
127    /// since a probe is built from values this engine chose.
128    #[error("the probes for this strategy could not be built: {0}")]
129    Probe(String),
130
131    /// A strategy panicked.
132    ///
133    /// Always an engine bug. Reported so the scan does not look merely empty.
134    #[error("the {scanner:?} scanner panicked: {detail}")]
135    Panicked {
136        /// Which strategy went down.
137        scanner: ScannerKind,
138        /// What the runtime said about it.
139        detail: String,
140    },
141}
142
143/// A port scan's protocol in words, with its article, as
144/// [`StrategyError::MismatchedTransport`] names the scan it was handed.
145const fn spoken_protocol(protocol: crate::model::port::Protocol) -> &'static str {
146    use crate::model::port::Protocol;
147    match protocol {
148        Protocol::Tcp => "a TCP",
149        Protocol::Udp => "a UDP",
150        Protocol::Sctp => "an SCTP",
151    }
152}
153
154/// A strategy that finds which hosts, among the targets it was built with, are
155/// reachable.
156///
157/// The discovery half of the pair. Implementations differ in how they ask: ARP and
158/// ICMPv6 on a local segment, raw TCP SYN through a gateway, or an ordinary connect
159/// where neither is possible.
160#[async_trait]
161pub trait HostScanner: Send {
162    /// Identifies the strategy, so a failure can be attributed to it in the
163    /// report and on the event stream.
164    fn kind(&self) -> ScannerKind;
165
166    /// Probes every target this strategy owns and records what answered in the
167    /// shared store.
168    ///
169    /// Returns `Ok` when the run reached its end, including an end forced by
170    /// [`ScanHandle::abort`](crate::scanner::handle::ScanHandle::abort), and
171    /// `Err` only when the strategy itself could not do its job.
172    async fn discover_hosts(&mut self) -> Result<(), StrategyError>;
173}
174
175/// A strategy that classifies the ports of targets handed to it one at a time.
176///
177/// The port-scan half of the pair. It consumes the shuffled [`PlannedTarget`]
178/// stream a [`Dispatcher`](crate::scanner::dispatcher::Dispatcher) produces, so
179/// several strategies can share one stream of work without knowing how it was
180/// ordered.
181#[async_trait]
182pub trait PortScanner: Send {
183    /// Identifies the strategy, so a failure can be attributed to it in the
184    /// report and on the event stream.
185    fn kind(&self) -> ScannerKind;
186
187    /// The transport protocols this strategy can actually probe.
188    ///
189    /// Read when a scan is assembled, to decide which protocols still need an
190    /// unprivileged fallback, and again by
191    /// [`CompositePortScanner`](crate::scanner::strategy::composite::CompositePortScanner)
192    /// to route each target. A strategy that under-reports its coverage is never
193    /// given that work.
194    fn supported_protocols(&self) -> Vec<Protocol>;
195
196    /// Probes every target arriving on `targets` and records each port's state
197    /// in the shared store.
198    ///
199    /// Returns `Ok` when the run reached its end, including an end forced by
200    /// [`ScanHandle::abort`](crate::scanner::handle::ScanHandle::abort), and
201    /// `Err` only when the strategy itself could not do its job.
202    async fn scan(&mut self, targets: mpsc::Receiver<PlannedTarget>) -> Result<(), StrategyError>;
203
204    /// Second-pass service identification, run once after a successful
205    /// [`scan`](PortScanner::scan) that was not aborted.
206    ///
207    /// A raw strategy holds no connection to fingerprint through, so it opens one
208    /// here for each open port. A connect strategy fingerprints inline while it
209    /// holds the live stream, and takes the default no-op.
210    async fn detect_services(&mut self, _ctx: &ScanContext) {}
211}
212
213/// Records `target`, which no scanner asked about, as a port nobody asked
214/// about: on its host as [`PortState::Unasked`], and owed to a resume.
215///
216/// Used by whoever leaves a port unprobed: a scanner stopped with it still queued,
217/// a scanner that refused its whole plan, and a router with no scanner left to hand
218/// it to. Without it a truncated port list reads like a complete one, an unreached
219/// host is missing from the report, and a diff against another scan shows the
220/// network moving. The outcome carries no position, so a resume asks the question.
221pub(crate) fn record_unasked(ctx: &ScanContext, target: &PlannedTarget) {
222    let port =
223        crate::fingerprint::baseline_port(target.port(), target.protocol(), PortState::Unasked);
224    ctx.update_host(target.ip(), |host| {
225        host.add_port(port);
226    });
227    ctx.record_outcome(Outcome::Unasked);
228}
229
230pub mod composite;
231pub mod connect;
232// ICMP error parsing shared by the UDP port scan (a port's verdict) and the trace
233// (a router's identity).
234pub(crate) mod icmp_error;
235// Frame readers shared by the local sweep, for replies to its probes, and the
236// passive listener, for unsolicited frames.
237pub(crate) mod frames;
238pub mod local;
239// What a machine is, asked of hosts already in the store.
240pub mod identify;
241pub mod passive;
242// Which ports are open, and the machinery all four raw port scanners share.
243pub mod ports;
244// Which IP protocols a host accepts. Runs after the port scan, only against hosts
245// that answered.
246pub mod protocols;
247// What every raw strategy is built from: how a probe reaches the wire, and the
248// timings a probe over a routed path is held to.
249pub(crate) mod raw;
250pub mod routed;
251// What the three probing sweeps keep track of in common.
252pub(crate) mod sweep;
253// What is between here and a host. Runs after the port scan, because the ports
254// that reach a host decide how to probe the path to it.
255pub mod topology;