zond_engine/config.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 scan is asked to do
10//!
11//! [`ZondConfig`] is one value, built once, handed to [`scan`](crate::scanner::scan) or
12//! [`discover`](crate::scanner::discover), and read by every strategy the run assembles.
13//! The default sends what a scan must and no more.
14//!
15//! ## Effort levels
16//!
17//! Most of what a person wants to say about a scan is how hard it should try.
18//! [`ScanEffort`] sets how many attempts a probe gets and how long each waits.
19//! [`OsDetection`] and [`ServiceDetection`] set how far a run may go to name what it
20//! found.
21//!
22//! [`ScanPace`] is a preset over them: one dial for how gently a scan treats the network.
23//! It writes the gaps between probes and the patience into the other fields and is not
24//! read by anything itself, so a scan always runs under the fields, and a setting chosen
25//! after the pace replaces what the pace wrote.
26//!
27//! All four are built alike: an ordered scale, an `ALL` in that order, a `name` and a
28//! `level` for each rung, and a `FromStr` that takes either spelling, so a front end can
29//! accept a word from a settings file and a number from a flag. The first three are
30//! carried into the report; a pace is carried as the fields it wrote.
31//!
32//! [`ScanEffort`] and [`OsDetection`] default low, since effort and traffic are what a
33//! caller should have to ask for. [`ServiceDetection`] defaults to its top level, which is
34//! also its fastest against an unrecognised port; the reasoning is at the variant.
35//!
36//! The numbers a strategy actually paces by are not set here. A raw scanner measures its
37//! own round trips and sizes its patience from them; the connect paths, which cannot
38//! measure, use the shared constants in [`limits`]. A caller supplies a ceiling and a
39//! preference, and the engine decides the rest against the network in front of it.
40//!
41//! ## Evasion and permission
42//!
43//! [`EvasionProfile`] changes the shape of what goes on the wire, and is inert by
44//! default: a strategy handed a default profile sends exactly what it would without one.
45//!
46//! [`DetectionEnvelope`] is a permission. A detection declares how intrusive it is and
47//! runs only where the envelope allows that class, so raising it is an operator's
48//! decision. See [`envelope`] for the ordering.
49//!
50//! ## Output is not configured here
51//!
52//! The engine emits `tracing` events and installs no subscriber, so verbosity, colour
53//! and format belong to whoever embeds the crate. This type is also the record of how a
54//! scan was run ([`ScanSettings`](crate::report::ScanSettings) is derived from it into
55//! every report), so it holds only fields that can change a finding.
56
57pub mod envelope;
58pub mod limits;
59
60pub use crate::config::envelope::DetectionEnvelope;
61
62use std::collections::{BTreeMap, BTreeSet};
63use std::fmt;
64use std::net::IpAddr;
65use std::num::{NonZeroU8, NonZeroU32};
66use std::str::FromStr;
67use std::time::Duration;
68
69use crate::evasion::EvasionProfile;
70use crate::model::exclusion::Exclusions;
71use crate::model::technique::{SctpScanTechnique, TcpScanTechnique};
72use crate::transport::probe::SendMode;
73
74/// Reads a level written as its name or as its number, shared by every scale in this
75/// module. A settings file says `passive` and a command line says `2`; parsing both here
76/// keeps the correspondence in one place.
77fn parse_level<T: Copy>(
78 written: &str,
79 all: &[T],
80 name: fn(T) -> &'static str,
81 from_level: fn(u8) -> Option<T>,
82) -> Option<T> {
83 let written = written.trim();
84
85 if let Ok(level) = written.parse::<u8>() {
86 return from_level(level);
87 }
88
89 all.iter()
90 .copied()
91 .find(|level| name(*level).eq_ignore_ascii_case(written))
92}
93
94/// The `expected one of` half of every parse error in this module, built from the
95/// levels themselves so a new variant is named without editing the message.
96fn expected_levels<T: Copy>(
97 all: &[T],
98 name: fn(T) -> &'static str,
99 f: &mut fmt::Formatter<'_>,
100) -> fmt::Result {
101 let names: Vec<&str> = all.iter().copied().map(name).collect();
102 let highest = all.len().saturating_sub(1);
103 write!(
104 f,
105 "expected one of: {} (or 0 to {highest})",
106 names.join(", ")
107 )
108}
109
110/// How much effort a scan spends before accepting silence as an answer.
111///
112/// Every probing path has its own `RetryPolicy`, tuned to what its protocol requires: a
113/// SYN is answered as fast as the path allows, an ICMP error only as fast as the host is
114/// permitted to send one. This scales that starting point, so choosing "fast" cannot hand
115/// the UDP scanner a schedule its protocol cannot satisfy.
116#[non_exhaustive]
117#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
118pub enum ScanEffort {
119 /// One probe per target and no repeats.
120 ///
121 /// For address-space-scale sweeps, where per-probe state cannot be afforded and
122 /// coverage comes from a second pass.
123 Single,
124 /// Fewer attempts and less patience. For a network already known to be
125 /// healthy, where a missed host is cheaper than the time spent confirming
126 /// one is absent.
127 Fast,
128 /// The default. Enough attempts to ride out ordinary loss, and enough patience for
129 /// a host on the far side of a slow link.
130 #[default]
131 Balanced,
132 /// More attempts, more patience, and no shortcuts on hosts that stay
133 /// silent. For a lossy path, or a result someone is going to act on.
134 Thorough,
135}
136
137impl ScanEffort {
138 /// Every level, ordered from least effort to most. The index of a level in
139 /// this array is its [`level`](Self::level) number.
140 pub const ALL: &'static [Self] = &[
141 ScanEffort::Single,
142 ScanEffort::Fast,
143 ScanEffort::Balanced,
144 ScanEffort::Thorough,
145 ];
146
147 /// The name this level is written under, wherever it arrives as text.
148 pub const fn name(self) -> &'static str {
149 match self {
150 ScanEffort::Single => "single",
151 ScanEffort::Fast => "fast",
152 ScanEffort::Balanced => "balanced",
153 ScanEffort::Thorough => "thorough",
154 }
155 }
156
157 /// The number this level is written as, for a front end that offers it as a dial.
158 ///
159 /// # Examples
160 ///
161 /// ```
162 /// use zond_engine::config::ScanEffort;
163 ///
164 /// assert_eq!(ScanEffort::default().level(), 2);
165 /// ```
166 pub const fn level(self) -> u8 {
167 match self {
168 ScanEffort::Single => 0,
169 ScanEffort::Fast => 1,
170 ScanEffort::Balanced => 2,
171 ScanEffort::Thorough => 3,
172 }
173 }
174
175 /// The level with this number, or `None` past the highest there is. Not
176 /// saturating, for the reason [`OsDetection::from_level`] gives.
177 pub const fn from_level(level: u8) -> Option<Self> {
178 match level {
179 0 => Some(ScanEffort::Single),
180 1 => Some(ScanEffort::Fast),
181 2 => Some(ScanEffort::Balanced),
182 3 => Some(ScanEffort::Thorough),
183 _ => None,
184 }
185 }
186}
187
188impl std::fmt::Display for ScanEffort {
189 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
190 f.write_str(self.name())
191 }
192}
193
194/// The error parsing a [`ScanEffort`] returns. Its message lists the accepted names,
195/// built from [`ScanEffort::ALL`], so a front end can print it verbatim.
196#[non_exhaustive]
197#[derive(Debug, Clone, PartialEq, Eq)]
198pub struct UnknownScanEffort {
199 /// What the caller wrote.
200 pub input: String,
201}
202
203impl fmt::Display for UnknownScanEffort {
204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205 write!(f, "unknown scan effort '{}', ", self.input)?;
206 expected_levels(ScanEffort::ALL, ScanEffort::name, f)
207 }
208}
209
210impl std::error::Error for UnknownScanEffort {}
211
212impl std::str::FromStr for ScanEffort {
213 type Err = UnknownScanEffort;
214
215 /// Parses an effort by name or number, ignoring case and surrounding whitespace.
216 ///
217 /// # Examples
218 ///
219 /// ```
220 /// use zond_engine::config::ScanEffort;
221 ///
222 /// assert_eq!("Thorough".parse(), Ok(ScanEffort::Thorough));
223 /// assert!("maximum".parse::<ScanEffort>().is_err());
224 /// ```
225 fn from_str(s: &str) -> Result<Self, Self::Err> {
226 parse_level(s, Self::ALL, Self::name, Self::from_level).ok_or_else(|| UnknownScanEffort {
227 input: s.to_string(),
228 })
229 }
230}
231
232/// How far a scan goes to identify the operating system behind a host.
233///
234/// Four levels, ordered by what they put on the wire. Each is a superset of the one
235/// below, so raising the level only adds evidence, and
236/// [`is_active`](Self::is_active) (whether a level may send packets of its own) has a
237/// single answer.
238///
239/// # Why the default is on
240///
241/// [`Passive`](Self::Passive) sends **nothing**. Every signal it reads is already in a
242/// reply the scan drew for another reason: the hop count, fragmentation policy and
243/// identifier in an IP header, and the window and options of a segment the port scanner
244/// was waiting for anyway. Traffic and run time are byte-for-byte the same with it on or
245/// off, so there is nothing to weigh.
246///
247/// [`Off`](Self::Off) is for a caller who wants a report to contain only what was asked
248/// for, or to reproduce a run made without OS detection.
249///
250/// # Why the higher levels are not
251///
252/// From [`Active`](Self::Active) upward this costs packets. They are ordinary (a SYN
253/// identical to the one a port scan sends, and a ping), but they are extra: a host is
254/// asked several more times than classifying its ports required, at addresses a caller
255/// may only have meant to enumerate. Traffic sent for a second purpose has to be asked
256/// for.
257///
258/// [`Aggressive`](Self::Aggressive) is where deliberately malformed probes would belong,
259/// the traffic intrusion-detection systems are written to notice. No level sends one
260/// yet; each level is documented for what it does.
261#[non_exhaustive]
262#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
263pub enum OsDetection {
264 /// Level 0. Identify nothing, and record nothing about the stacks that
265 /// answered.
266 Off,
267
268 /// Level 1, and the default. Read the operating system out of replies the
269 /// scan already drew, and send nothing extra.
270 ///
271 /// Answers at the level of a family (the shape of a stack, not its version), and
272 /// only for hosts that replied to something.
273 #[default]
274 Passive,
275
276 /// Level 2. Everything [`Passive`](Self::Passive) reads, plus probes of this
277 /// engine's own aimed at the hosts whose replies were not enough.
278 ///
279 /// Ordinary, well-formed packets, with no flag combination a real connection
280 /// lacks:
281 ///
282 /// - **A series of SYNs**, to a host with an open or closed TCP port. The same
283 /// segment a SYN scan sends, from a fresh source port each time, because whether
284 /// a stack's IP identifier counts or is random, whether its sequence numbers are
285 /// hashed or stepped, and how fast its timestamp clock ticks show only across
286 /// several replies. Release-level rules turn on these features.
287 /// - **One SNMP request**, to a host whose kernel is still unknown. On a Unix host
288 /// `sysDescr` is the output of `uname -a`, so an agent that answers states the
289 /// exact kernel, which packet analysis cannot establish and a
290 /// known-vulnerability lookup keys on. Sent with the default `public` community,
291 /// read-only, for one object.
292 /// - **One ICMP echo**, to a host that answered no TCP probe. A stock Windows
293 /// firewall drops TCP silently, so a desktop with nothing exposed emits no
294 /// segment to read; a ping is the one packet it still answers.
295 ///
296 /// None of them touches the port list, so no probe goes to a port the caller
297 /// excluded. The probes go only to hosts where the passive evidence was thin.
298 Active,
299
300 /// Level 3. The same probes [`Active`](Self::Active) sends, more of them, and at
301 /// every host, including those already identified.
302 ///
303 /// Twice the samples per host, and hosts already named with high confidence are
304 /// probed too. That suits someone measuring: a reading from a machine whose
305 /// operating system is known is how a rule gets authored. It is more traffic,
306 /// sustained longer, at more addresses.
307 ///
308 /// # Malformed probes
309 ///
310 /// This level sends none yet. Reserved fields set, impossible flag combinations and
311 /// headers that disagree with their own lengths separate stacks that agree on
312 /// everything legal, but rules are authored from what this engine's own probes have
313 /// measured, and nothing has measured those. If they are added, they go here.
314 Aggressive,
315}
316
317impl OsDetection {
318 /// Every level, ordered from least effort to most. The index of a level in
319 /// this array is its [`level`](Self::level) number.
320 pub const ALL: &'static [Self] = &[
321 OsDetection::Off,
322 OsDetection::Passive,
323 OsDetection::Active,
324 OsDetection::Aggressive,
325 ];
326
327 /// The name this level is written under, wherever it arrives as text.
328 pub const fn name(self) -> &'static str {
329 match self {
330 OsDetection::Off => "off",
331 OsDetection::Passive => "passive",
332 OsDetection::Active => "active",
333 OsDetection::Aggressive => "aggressive",
334 }
335 }
336
337 /// The number this level is written as, for a front end that offers it as a dial.
338 ///
339 /// # Examples
340 ///
341 /// ```
342 /// use zond_engine::config::OsDetection;
343 ///
344 /// assert_eq!(OsDetection::default().level(), 1);
345 /// ```
346 pub const fn level(self) -> u8 {
347 match self {
348 OsDetection::Off => 0,
349 OsDetection::Passive => 1,
350 OsDetection::Active => 2,
351 OsDetection::Aggressive => 3,
352 }
353 }
354
355 /// The level with this number, or `None` past the highest there is.
356 ///
357 /// Not saturating: a caller who writes `9` meaning "as much as possible" has asked
358 /// for something this engine does not offer, and quietly giving them the top level
359 /// would hide that.
360 pub const fn from_level(level: u8) -> Option<Self> {
361 match level {
362 0 => Some(OsDetection::Off),
363 1 => Some(OsDetection::Passive),
364 2 => Some(OsDetection::Active),
365 3 => Some(OsDetection::Aggressive),
366 _ => None,
367 }
368 }
369
370 /// Whether identification happens at all.
371 pub const fn is_enabled(self) -> bool {
372 !matches!(self, OsDetection::Off)
373 }
374
375 /// Whether this level may put probes of its own on the wire.
376 ///
377 /// A scan that must add no traffic of its own, and a report that has to say whether
378 /// it did, both turn on this.
379 ///
380 /// # Examples
381 ///
382 /// ```
383 /// use zond_engine::config::OsDetection;
384 ///
385 /// assert!(!OsDetection::Passive.is_active(), "the default sends nothing");
386 /// assert!(OsDetection::Aggressive.is_active());
387 /// ```
388 pub const fn is_active(self) -> bool {
389 matches!(self, OsDetection::Active | OsDetection::Aggressive)
390 }
391}
392
393impl fmt::Display for OsDetection {
394 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
395 f.write_str(self.name())
396 }
397}
398
399/// The error parsing an [`OsDetection`] returns. Its message lists the accepted values,
400/// built from [`OsDetection::ALL`], so a front end can print it verbatim.
401#[non_exhaustive]
402#[derive(Debug, Clone, PartialEq, Eq)]
403pub struct UnknownOsDetection {
404 /// What the caller wrote.
405 pub input: String,
406}
407
408impl fmt::Display for UnknownOsDetection {
409 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
410 write!(f, "unknown OS detection level '{}', ", self.input)?;
411 expected_levels(OsDetection::ALL, OsDetection::name, f)
412 }
413}
414
415impl std::error::Error for UnknownOsDetection {}
416
417impl FromStr for OsDetection {
418 type Err = UnknownOsDetection;
419
420 /// Parses a level by name or by number, ignoring case and surrounding whitespace.
421 ///
422 /// # Examples
423 ///
424 /// ```
425 /// use zond_engine::config::OsDetection;
426 ///
427 /// assert_eq!("Aggressive".parse(), Ok(OsDetection::Aggressive));
428 /// assert_eq!("0".parse(), Ok(OsDetection::Off));
429 /// assert!("maximum".parse::<OsDetection>().is_err());
430 /// ```
431 fn from_str(s: &str) -> Result<Self, Self::Err> {
432 parse_level(s, Self::ALL, Self::name, Self::from_level).ok_or_else(|| UnknownOsDetection {
433 input: s.to_string(),
434 })
435 }
436}
437
438/// The TCP ports a network printer prints whatever arrives on: 9100 for its
439/// first queue and 9101 to 9107 for the rest.
440///
441/// Raw printing (JetDirect, AppSocket) has no protocol: every byte a connection carries
442/// is printed. The default for [`ZondConfig::listen_only_ports`].
443pub const RAW_PRINT_PORTS: &[u16] = &[9100, 9101, 9102, 9103, 9104, 9105, 9106, 9107];
444
445/// How far a scan may go to identify what is listening behind an open port.
446///
447/// The port scan establishes that a port is *open*; naming what is on it is a second
448/// pass that needs a real connection to every open port. A scan mapping what exists may
449/// not want that cost; a scan auditing what is deployed does.
450///
451/// Ordered by what each level puts on the wire.
452#[non_exhaustive]
453#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
454pub enum ServiceDetection {
455 /// Level 0. Do not connect. A port keeps whatever its number implies and
456 /// nothing more.
457 ///
458 /// The fastest and quietest: after a raw scan no connection is completed, so
459 /// nothing appears in the target's logs. It yields no versions or products: a port
460 /// is reported `open http` because it is port 80, whatever is actually there.
461 Off,
462 /// Level 1. Connect and listen. Send nothing.
463 ///
464 /// For services that greet on connect, such as SSH, SMTP, FTP and IRC, this learns
465 /// what a probe would, without sending a byte. For everything else it establishes
466 /// only that the port accepts connections.
467 ///
468 /// Use it against equipment that must not be sent anything unexpected. Industrial
469 /// controllers, medical devices and old embedded stacks have been knocked over by
470 /// well-formed requests they did not anticipate.
471 Banner,
472 /// Level 2, and the default. Connect, listen, and ask.
473 ///
474 /// Sends each port the probes its service registered and, where nothing registers
475 /// the port, one generic request. That identifies the long tail: an open port on an
476 /// unregistered number is most often an HTTP server, and one request names it.
477 ///
478 /// A port that answers none of that, in the clear or through TLS, is then asked
479 /// the likeliest of the questions other services registered, the bottom of the
480 /// scale [`probe_intensity`](Self::probe_intensity) reaches. Such a port is most
481 /// often a database moved off its number, which speaks only when spoken to in its
482 /// own protocol. Each question costs a connection and a read. Across a path slower
483 /// than a third of a second only the likeliest is asked.
484 ///
485 /// The default because it is the most informative level and, against an
486 /// unrecognised port, the fastest: waiting for a greeting that never comes and then
487 /// trying TLS costs two seconds per port, where asking gets an answer in a round
488 /// trip.
489 #[default]
490 Probe,
491 /// Level 3. Everything above, and then every question the corpus has.
492 ///
493 /// A port that stayed silent through everything else gets every probe authored for
494 /// *other* services, in rarity order. That reaches a service which speaks only when
495 /// spoken to, is off its registered port, and is rarer than the default's guesses.
496 ///
497 /// Costs a connection and a round trip per probe, paid only where everything else
498 /// drew a blank, which on an ordinary host is a port or two.
499 Thorough,
500}
501
502impl ServiceDetection {
503 /// Every level, ordered from least effort to most. The index of a level in
504 /// this array is its [`level`](Self::level) number.
505 pub const ALL: &'static [Self] = &[
506 ServiceDetection::Off,
507 ServiceDetection::Banner,
508 ServiceDetection::Probe,
509 ServiceDetection::Thorough,
510 ];
511
512 /// The name this level is written under, wherever it arrives as text.
513 pub const fn name(self) -> &'static str {
514 match self {
515 ServiceDetection::Off => "off",
516 ServiceDetection::Banner => "banner",
517 ServiceDetection::Probe => "probe",
518 ServiceDetection::Thorough => "thorough",
519 }
520 }
521
522 /// The number this level is written as, for a front end that offers it as a dial.
523 pub const fn level(self) -> u8 {
524 match self {
525 ServiceDetection::Off => 0,
526 ServiceDetection::Banner => 1,
527 ServiceDetection::Probe => 2,
528 ServiceDetection::Thorough => 3,
529 }
530 }
531
532 /// The level with this number, or `None` past the highest there is.
533 pub const fn from_level(level: u8) -> Option<Self> {
534 match level {
535 0 => Some(ServiceDetection::Off),
536 1 => Some(ServiceDetection::Banner),
537 2 => Some(ServiceDetection::Probe),
538 3 => Some(ServiceDetection::Thorough),
539 _ => None,
540 }
541 }
542
543 /// Whether this level opens a connection at all.
544 ///
545 /// Below this boundary the scan leaves no trace in application logs; at or above
546 /// it every open port records a connection.
547 ///
548 /// ```
549 /// use zond_engine::config::ServiceDetection;
550 ///
551 /// assert!(!ServiceDetection::Off.connects());
552 /// assert!(ServiceDetection::default().connects());
553 /// ```
554 pub const fn connects(self) -> bool {
555 !matches!(self, ServiceDetection::Off)
556 }
557
558 /// Whether this level sends anything once connected.
559 ///
560 /// ```
561 /// use zond_engine::config::ServiceDetection;
562 ///
563 /// assert!(!ServiceDetection::Banner.sends());
564 /// assert!(ServiceDetection::Probe.sends());
565 /// ```
566 pub const fn sends(self) -> bool {
567 matches!(self, ServiceDetection::Probe | ServiceDetection::Thorough)
568 }
569
570 /// How far up the corpus's rarity scale this level reaches, for a probe
571 /// nothing registered against the port being asked.
572 ///
573 /// The scale runs 1 to 9 and is the one the imported corpora are authored
574 /// on; see [`Probe::rarity`](crate::fingerprint::Probe::rarity). Zero
575 /// reaches nothing, which is what every level below [`Probe`] wants.
576 ///
577 /// The default reaches 1, the questions a port silent to everything else most
578 /// often answers, and the thorough level the whole scale. The default stops at 1
579 /// because only the bottom of the scale is authored so far; it can rise as the
580 /// corpus fills in.
581 ///
582 /// ```
583 /// use zond_engine::config::ServiceDetection;
584 ///
585 /// assert_eq!(ServiceDetection::Banner.probe_intensity(), 0);
586 /// assert_eq!(ServiceDetection::Thorough.probe_intensity(), 9);
587 /// ```
588 ///
589 /// [`Probe`]: Self::Probe
590 pub const fn probe_intensity(self) -> u8 {
591 match self {
592 ServiceDetection::Off | ServiceDetection::Banner => 0,
593 ServiceDetection::Probe => 1,
594 ServiceDetection::Thorough => 9,
595 }
596 }
597}
598
599impl fmt::Display for ServiceDetection {
600 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
601 f.write_str(self.name())
602 }
603}
604
605/// The error parsing a [`ServiceDetection`] returns. Its message lists the accepted
606/// values, built from [`ServiceDetection::ALL`], so a front end can print it verbatim.
607#[non_exhaustive]
608#[derive(Debug, Clone, PartialEq, Eq)]
609pub struct UnknownServiceDetection {
610 /// What the caller wrote.
611 pub input: String,
612}
613
614impl fmt::Display for UnknownServiceDetection {
615 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
616 write!(f, "unknown service detection level '{}', ", self.input)?;
617 expected_levels(ServiceDetection::ALL, ServiceDetection::name, f)
618 }
619}
620
621impl std::error::Error for UnknownServiceDetection {}
622
623impl FromStr for ServiceDetection {
624 type Err = UnknownServiceDetection;
625
626 /// Parses a level by name or by number, ignoring case and surrounding whitespace.
627 ///
628 /// ```
629 /// use zond_engine::config::ServiceDetection;
630 ///
631 /// assert_eq!("banner".parse(), Ok(ServiceDetection::Banner));
632 /// assert_eq!("0".parse(), Ok(ServiceDetection::Off));
633 /// assert_eq!("3".parse(), Ok(ServiceDetection::Thorough));
634 /// assert!("exhaustive".parse::<ServiceDetection>().is_err());
635 /// ```
636 fn from_str(input: &str) -> Result<Self, Self::Err> {
637 parse_level(input, Self::ALL, Self::name, Self::from_level).ok_or_else(|| {
638 UnknownServiceDetection {
639 input: input.to_string(),
640 }
641 })
642 }
643}
644
645/// How gently a scan treats the network it is pointed at, as one dial.
646///
647/// A preset over several settings, for a caller who knows how much load a network can
648/// take but not which knobs express that. [`apply_to`](Self::apply_to) writes the pace
649/// into a [`ZondConfig`]; nothing downstream reads a pace, so a scan runs under (and the
650/// report records) the fields it set. An explicit setting applied afterwards replaces
651/// what the pace wrote.
652///
653/// # What the levels change
654///
655/// [`Normal`](Self::Normal) changes nothing, so a caller who picks it gets
656/// exactly [`ZondConfig::default`]. Below it the pace spaces the scan's probes;
657/// above it the pace shortens how long the scan waits for answers.
658///
659/// | Level | Name | Writes |
660/// |---|---|---|
661/// | 0 | `trickle` | one probe a second, across the scan and at any one host; twice the patience |
662/// | 1 | `sparing` | ten probes a second, across the scan and at any one host; half again the patience |
663/// | 2 | `gentle` | two hundred a second across the scan, twenty at any one host |
664/// | 3 | `normal` | nothing |
665/// | 4 | `brisk` | [`ScanEffort::Fast`] |
666/// | 5 | `hurried` | [`ScanEffort::Fast`], and half that patience again |
667///
668/// The slow levels space probes with [`probe_interval`](ZondConfig::probe_interval) and
669/// [`host_probe_interval`](ZondConfig::host_probe_interval), the bound every pass
670/// shares. They leave [`max_probe_rate`](ZondConfig::max_probe_rate) alone: a rate
671/// replaces each scanner's own default, so a rate gentle for a TCP scan would be
672/// *faster* than the UDP scan's own pace.
673///
674/// Every slow level sets a per-host gap; the two slowest set it equal to the scan-wide
675/// one. That keeps each host spared if a caller later loosens the scan-wide gap for a
676/// range too large to cover at it.
677///
678/// The slow levels also raise the patience, which at their spacing costs nothing: each
679/// probe waits out the gap anyway, and a longer timeout inside that wait catches late
680/// answers from slow devices.
681///
682/// # The fast levels
683///
684/// They do not push harder. A TCP port scan paces itself on how fast its targets answer,
685/// through a congestion window no setting overrides, because pushing a target harder than
686/// it answers turns loss into verdicts. The fast levels trade patience (fewer attempts,
687/// shorter waits) for time, which works on a network that answers promptly and poorly on
688/// one that does not. [`hurried`](Self::Hurried) never goes below the shortest wait a
689/// protocol allows; see [`TimeoutScale`].
690///
691/// # Cost
692///
693/// The slow levels leave out the operating-system timestamp series, whose samples
694/// cannot be taken slower than they are sent; see
695/// [`probe_interval`](ZondConfig::probe_interval).
696///
697/// A spaced scan takes as long as its probes take to leave: a thousand ports at
698/// `sparing` is a hundred seconds before any retry, and at `trickle` a quarter of an
699/// hour. Setting [`scan_timeout`](ZondConfig::scan_timeout) alongside a slow level
700/// bounds that, and the report says which hosts the budget left part-scanned.
701#[non_exhaustive]
702#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
703pub enum ScanPace {
704 /// Level 0. One probe a second across the whole scan, and twice the usual
705 /// patience for each.
706 ///
707 /// For a network that must barely notice the scan: a link a few kilobits wide,
708 /// equipment known to fall over under sustained traffic, or an owner who asked
709 /// for less than a packet a second.
710 Trickle,
711 /// Level 1. Ten probes a second across the whole scan, and half again the
712 /// usual patience for each.
713 ///
714 /// For a network whose owner wants the scan well below anything its monitoring
715 /// would call load, and who can wait minutes for a host's ports.
716 Sparing,
717 /// Level 2. At most two hundred probes a second across the whole scan, and
718 /// twenty a second at any one host.
719 ///
720 /// For a network with fragile hosts on it: a controller, a printer or an old
721 /// embedded stack that copes with a scan but not a burst. The per-host bound spares
722 /// them on a range scan, where the scan-wide one alone would still allow a burst at
723 /// one host.
724 Gentle,
725 /// Level 3, and the default. Every setting as it is; each pass paces
726 /// itself as it would with no pace chosen.
727 #[default]
728 Normal,
729 /// Level 4. [`ScanEffort::Fast`]: an attempt fewer and less patience per
730 /// probe.
731 ///
732 /// For a network known to be healthy, where a missed port is cheaper than the time
733 /// spent confirming its silence.
734 Brisk,
735 /// Level 5. [`ScanEffort::Fast`], with each wait halved again.
736 ///
737 /// For a quick look at a network that answers promptly. Anything slow to answer is
738 /// reported as silent, so a result is a first look, not a verdict.
739 Hurried,
740}
741
742impl ScanPace {
743 /// Every level, ordered from gentlest to fastest. The index of a level in
744 /// this array is its [`level`](Self::level) number.
745 pub const ALL: &'static [Self] = &[
746 ScanPace::Trickle,
747 ScanPace::Sparing,
748 ScanPace::Gentle,
749 ScanPace::Normal,
750 ScanPace::Brisk,
751 ScanPace::Hurried,
752 ];
753
754 /// The name this level is written under, wherever it arrives as text.
755 pub const fn name(self) -> &'static str {
756 match self {
757 ScanPace::Trickle => "trickle",
758 ScanPace::Sparing => "sparing",
759 ScanPace::Gentle => "gentle",
760 ScanPace::Normal => "normal",
761 ScanPace::Brisk => "brisk",
762 ScanPace::Hurried => "hurried",
763 }
764 }
765
766 /// The number this level is written as, for a front end that offers it as a dial.
767 ///
768 /// # Examples
769 ///
770 /// ```
771 /// use zond_engine::config::ScanPace;
772 ///
773 /// assert_eq!(ScanPace::default().level(), 3);
774 /// ```
775 pub const fn level(self) -> u8 {
776 match self {
777 ScanPace::Trickle => 0,
778 ScanPace::Sparing => 1,
779 ScanPace::Gentle => 2,
780 ScanPace::Normal => 3,
781 ScanPace::Brisk => 4,
782 ScanPace::Hurried => 5,
783 }
784 }
785
786 /// The level with this number, or `None` past the highest there is. Not
787 /// saturating, for the reason [`OsDetection::from_level`] gives.
788 pub const fn from_level(level: u8) -> Option<Self> {
789 match level {
790 0 => Some(ScanPace::Trickle),
791 1 => Some(ScanPace::Sparing),
792 2 => Some(ScanPace::Gentle),
793 3 => Some(ScanPace::Normal),
794 4 => Some(ScanPace::Brisk),
795 5 => Some(ScanPace::Hurried),
796 _ => None,
797 }
798 }
799
800 /// Writes this pace into `config`, leaving every field it has no view on
801 /// as it was.
802 ///
803 /// Apply it before anything the caller set explicitly, which then replaces what the
804 /// pace wrote.
805 ///
806 /// A slow level never loosens what `config` already holds: it takes the longer of
807 /// its own gap and one already set, and the larger of the two patiences. A fast
808 /// level sets effort and patience outright and touches no gap or rate.
809 ///
810 /// # Examples
811 ///
812 /// ```
813 /// use std::time::Duration;
814 /// use zond_engine::config::{ScanPace, ZondConfig};
815 ///
816 /// let mut cfg = ZondConfig::default();
817 /// ScanPace::Sparing.apply_to(&mut cfg);
818 /// assert_eq!(cfg.probe_interval, Some(Duration::from_millis(100)));
819 ///
820 /// // An explicit setting applied afterwards is the one that holds.
821 /// cfg.probe_interval = Some(Duration::from_millis(250));
822 /// ```
823 pub fn apply_to(self, config: &mut ZondConfig) {
824 let Some(spacing) = self.spacing() else {
825 match self {
826 ScanPace::Brisk => config.retry.effort = ScanEffort::Fast,
827 ScanPace::Hurried => {
828 config.retry.effort = ScanEffort::Fast;
829 config.retry.timeout_scale = TimeoutScale::new(HURRIED_PATIENCE);
830 }
831 _ => {}
832 }
833 return;
834 };
835
836 config.probe_interval = config.probe_interval.max(Some(spacing.anywhere));
837 config.host_probe_interval = config.host_probe_interval.max(Some(spacing.at_host));
838 if let Some(patience) = spacing.patience {
839 config.retry.timeout_scale = match config.retry.timeout_scale {
840 Some(set) if set >= patience => Some(set),
841 _ => Some(patience),
842 };
843 }
844 }
845
846 /// What a slow level writes, or `None` for a level that spaces nothing.
847 fn spacing(self) -> Option<PaceSpacing> {
848 let patience = |factor| TimeoutScale::new(factor);
849 match self {
850 ScanPace::Trickle => Some(PaceSpacing {
851 anywhere: Duration::from_secs(1),
852 at_host: Duration::from_secs(1),
853 patience: patience(2.0),
854 }),
855 ScanPace::Sparing => Some(PaceSpacing {
856 anywhere: Duration::from_millis(100),
857 at_host: Duration::from_millis(100),
858 patience: patience(1.5),
859 }),
860 ScanPace::Gentle => Some(PaceSpacing {
861 anywhere: Duration::from_millis(5),
862 at_host: Duration::from_millis(50),
863 patience: None,
864 }),
865 ScanPace::Normal | ScanPace::Brisk | ScanPace::Hurried => None,
866 }
867 }
868}
869
870/// The patience [`ScanPace::Hurried`] scales every wait by, on top of what
871/// [`ScanEffort::Fast`] already takes off.
872///
873/// Half, so the level is a clear step past `brisk`: `Fast` waits six tenths of the
874/// usual time, and this makes it three tenths. No scale moves the floor every policy
875/// keeps under its timeouts, so this shortens only the long waits a slow path earns.
876const HURRIED_PATIENCE: f64 = 0.5;
877
878/// What a slow [`ScanPace`] writes: the gap across the scan, the gap at one
879/// host, and the patience where it raises it.
880struct PaceSpacing {
881 anywhere: Duration,
882 at_host: Duration,
883 patience: Option<TimeoutScale>,
884}
885
886impl fmt::Display for ScanPace {
887 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
888 f.write_str(self.name())
889 }
890}
891
892/// The error parsing a [`ScanPace`] returns. Its message lists the accepted names, so a
893/// front end can print it verbatim.
894#[non_exhaustive]
895#[derive(Debug, Clone, PartialEq, Eq)]
896pub struct UnknownScanPace {
897 /// What the caller wrote.
898 pub input: String,
899}
900
901impl fmt::Display for UnknownScanPace {
902 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
903 write!(f, "unknown scan pace '{}', ", self.input)?;
904 expected_levels(ScanPace::ALL, ScanPace::name, f)
905 }
906}
907
908impl std::error::Error for UnknownScanPace {}
909
910impl FromStr for ScanPace {
911 type Err = UnknownScanPace;
912
913 /// Parses a pace written as its name or its number, ignoring case and
914 /// surrounding whitespace.
915 ///
916 /// # Examples
917 ///
918 /// ```
919 /// use zond_engine::config::ScanPace;
920 ///
921 /// assert_eq!("Gentle".parse(), Ok(ScanPace::Gentle));
922 /// assert_eq!("0".parse(), Ok(ScanPace::Trickle));
923 /// assert!("6".parse::<ScanPace>().is_err());
924 /// ```
925 fn from_str(input: &str) -> Result<Self, Self::Err> {
926 parse_level(input, Self::ALL, Self::name, Self::from_level).ok_or_else(|| UnknownScanPace {
927 input: input.to_string(),
928 })
929 }
930}
931
932/// A multiplier on how long a scan is willing to wait.
933///
934/// Always positive and finite. Zero, negative and NaN scales cannot be honoured, and
935/// would otherwise be dropped where the policy is built while the report still recorded
936/// them as applied.
937#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
938pub struct TimeoutScale(f64);
939
940impl TimeoutScale {
941 /// The scale `factor` names, or `None` if no schedule could be built from
942 /// it: zero, negative, infinite, or NaN.
943 ///
944 /// # Examples
945 ///
946 /// ```
947 /// use zond_engine::config::TimeoutScale;
948 ///
949 /// assert!(TimeoutScale::new(2.5).is_some());
950 /// assert!(TimeoutScale::new(0.0).is_none());
951 /// assert!(TimeoutScale::new(f64::NAN).is_none());
952 /// ```
953 pub fn new(factor: f64) -> Option<Self> {
954 (factor.is_finite() && factor > 0.0).then_some(Self(factor))
955 }
956
957 /// The multiplier, as the number a duration is scaled by.
958 pub const fn get(self) -> f64 {
959 self.0
960 }
961}
962
963impl fmt::Display for TimeoutScale {
964 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
965 write!(f, "{}", self.0)
966 }
967}
968
969/// User control over retransmission, applied on top of each scanner's own
970/// profile.
971///
972/// Comparable so a report can state whether two runs asked for the same effort. Not
973/// [`Eq`], because `timeout_scale` is a float.
974///
975/// Every override is optional and typed narrowly enough that any value reaching this
976/// struct is one the engine can honour; see [`TimeoutScale`].
977#[non_exhaustive]
978#[derive(Debug, Clone, Copy, PartialEq)]
979pub struct RetryConfig {
980 /// How hard the scan tries before the fields below override any part of it.
981 pub effort: ScanEffort,
982 /// Replaces the attempt budget outright, whatever `effort` implies. One
983 /// attempt disables retransmission.
984 ///
985 /// Non-zero: a zero would have to be silently raised to one where the policy is
986 /// built.
987 pub max_attempts: Option<NonZeroU8>,
988 /// Multiplies how long the scan is willing to wait.
989 ///
990 /// The shortest timeout a policy allows is unaffected. That floor is what the
991 /// protocol costs: retrying a UDP probe sooner than the target is permitted to
992 /// answer only wastes a packet.
993 pub timeout_scale: Option<TimeoutScale>,
994 /// Whether a host that answers nothing at all may have its budget cut.
995 /// Turning this off spends the full budget on every port of every silent
996 /// address, which is thorough and expensive.
997 pub dampen_silent_hosts: bool,
998}
999
1000impl Default for RetryConfig {
1001 fn default() -> Self {
1002 Self {
1003 effort: ScanEffort::default(),
1004 max_attempts: None,
1005 timeout_scale: None,
1006 dampen_silent_hosts: true,
1007 }
1008 }
1009}
1010
1011/// The knobs a probing strategy is built from, carried together so adding one does not
1012/// change every constructor.
1013///
1014/// Not every strategy reads every field: local discovery builds its own Ethernet frames
1015/// and ignores [`SendMode`], while every strategy that sends a probe uses
1016/// [`RetryConfig`]. `max_probe_rate` is read by routed host discovery and the raw port
1017/// scanners: the sweep and the UDP scan are paced by it, while a TCP port scan paces
1018/// itself by a congestion window and treats it only as a ceiling. The unprivileged paths
1019/// pace themselves by their connection concurrency.
1020///
1021/// Built by [`ZondConfig::probe_tuning`] and, in tests, from [`Default`].
1022#[non_exhaustive]
1023#[derive(Debug, Clone, Default)]
1024pub struct ProbeTuning {
1025 /// Which layer a strategy puts its probes on the wire through, where it has
1026 /// the choice.
1027 pub send_mode: SendMode,
1028
1029 /// How many attempts a probe gets and how long each waits, as an effort
1030 /// level with optional overrides.
1031 pub retry: RetryConfig,
1032
1033 /// The most probes per second a strategy may emit, or `None` for the pacing
1034 /// each one arrives at on its own.
1035 ///
1036 /// Non-zero, since a ceiling of zero probes per second would be no scan at all.
1037 pub max_probe_rate: Option<NonZeroU32>,
1038
1039 /// The fewest probes per second a strategy should emit, or `None` for
1040 /// whatever pace it arrives at.
1041 ///
1042 /// Read in the same places as [`max_probe_rate`](Self::max_probe_rate): a floor
1043 /// under a pace where the rate is the pace, and a floor under a ceiling where it is
1044 /// only a ceiling. Non-zero, since a floor of zero is what `None` already says.
1045 pub min_probe_rate: Option<NonZeroU32>,
1046
1047 /// Which segment a TCP port probe carries. Read only by the raw TCP port scanner;
1048 /// host discovery always uses SYN, since the other techniques are no better at
1049 /// finding whether anything is there.
1050 pub tcp_technique: TcpScanTechnique,
1051 /// Which chunk an SCTP port probe carries. Read only by the raw SCTP port scanner;
1052 /// a sweep always sends an INIT, since a COOKIE-ECHO draws nothing from the open
1053 /// port a sweep hopes to hear from.
1054 pub sctp_technique: SctpScanTechnique,
1055
1056 /// How far a strategy may go to identify the operating system behind a host.
1057 ///
1058 /// Read by the raw TCP port scanner, where the replies that carry a stack's shape
1059 /// arrive. At [`OsDetection::Passive`] it changes no packet and no timing.
1060 pub os_detection: OsDetection,
1061
1062 /// How far a strategy may go to name what is behind an open port.
1063 ///
1064 /// Read by every strategy that fingerprints: the raw scanners, as a second pass over
1065 /// the ports they found, and the connect scanner, inline over the connection it
1066 /// already holds. Turning it off means neither completes a connection for
1067 /// identification.
1068 pub service_detection: ServiceDetection,
1069
1070 /// What the caller has chosen to change about the probes each strategy emits.
1071 ///
1072 /// A default profile is inert. Read wherever a strategy chooses a probe field a
1073 /// caller may override; the conversations that follow a probe over their own
1074 /// connections ignore it. See [`EvasionProfile`], and
1075 /// [what a profile shapes](crate::evasion#a-profile-shapes-the-probes).
1076 pub evasion: EvasionProfile,
1077
1078 /// Whether the capture admits ICMP errors for a technique that finds open
1079 /// and closed ports without them. See [`ZondConfig::icmp_evidence`].
1080 pub icmp_evidence: bool,
1081
1082 /// Source addresses to force, one per family. See
1083 /// [`ZondConfig::send_source`].
1084 pub send_source: Vec<IpAddr>,
1085}
1086
1087/// A third party whose IP-ID counter an idle scan reads to learn a target's ports
1088/// without addressing the target from the scanner's own address.
1089///
1090/// The idle (or zombie) scan is the quietest technique this engine has. Its probes carry
1091/// the zombie's source address, so the target answers the zombie. The result is read
1092/// from the zombie's global IP-ID counter, which advances by one for every packet the
1093/// zombie sends: read the counter, forge a probe, read it again. An open port drew an
1094/// answer the zombie had to reset, advancing the counter an extra step; a closed or
1095/// unreached one did not.
1096///
1097/// So the zombie must have a single shared IP-ID counter, and the forged probe needs a
1098/// self-built Ethernet frame to carry a source address the kernel would not choose. A
1099/// scan that cannot have both is refused; see the idle port scanner.
1100#[non_exhaustive]
1101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1102pub struct IdleScan {
1103 /// The zombie's address.
1104 ///
1105 /// It must have a single global IP-ID counter (a counting generator, in the terms
1106 /// the OS-detection series uses), and be idle enough that its counter moves for
1107 /// this scan's probes and little else. The scan qualifies the zombie first and
1108 /// refuses an unsuitable one with the counter class it found.
1109 pub zombie: IpAddr,
1110
1111 /// A port on the zombie to probe for its counter, or `None` for the engine's
1112 /// default.
1113 ///
1114 /// An unsolicited SYN/ACK draws a reset whether the port is open or closed, so any
1115 /// port works as long as the zombie's own filter does not drop the probe.
1116 pub zombie_port: Option<u16>,
1117}
1118
1119impl IdleScan {
1120 /// An idle scan through `zombie`, on whichever port the engine picks.
1121 pub const fn new(zombie: IpAddr) -> Self {
1122 Self {
1123 zombie,
1124 zombie_port: None,
1125 }
1126 }
1127
1128 /// Names the port on the zombie to read its counter from.
1129 ///
1130 /// For a zombie whose filter drops the engine's default. See
1131 /// [`zombie_port`](Self::zombie_port).
1132 #[must_use]
1133 pub const fn with_port(mut self, port: u16) -> Self {
1134 self.zombie_port = Some(port);
1135 self
1136 }
1137}
1138
1139/// What a scan does, and what it is allowed to put on the wire.
1140///
1141/// Every field changes packets or timing. Rendering belongs to whoever embeds the crate:
1142/// the engine emits `tracing` events and installs no subscriber. This type is also the
1143/// record of how a scan was run, derived into every report as
1144/// [`ScanSettings`](crate::report::ScanSettings).
1145///
1146/// Start from [`default`](Default::default) and set the fields the scan needs:
1147///
1148/// ```
1149/// use zond_engine::ZondConfig;
1150///
1151/// let mut cfg = ZondConfig::default();
1152/// cfg.traceroute = true;
1153/// ```
1154#[non_exhaustive]
1155#[derive(Debug, Clone)]
1156pub struct ZondConfig {
1157 /// Forbids the scan from making any name query of its own: no A, AAAA or PTR query,
1158 /// to a resolver or to a host's multicast DNS responder. Found hosts are named only
1159 /// from the hosts file.
1160 ///
1161 /// Set it when the traffic itself is the problem: a query to a resolver the target
1162 /// operates announces the scan to whoever runs it. The cost is that hosts missing
1163 /// from the hosts file are reported by address, and active operating-system
1164 /// identification asks for a device-info record only from hosts whose `.local` name
1165 /// the scan already holds.
1166 ///
1167 /// Port probes are unaffected: a UDP probe of a name service's port still carries
1168 /// that service's question, and the device-info question to a probed host is still
1169 /// asked.
1170 ///
1171 /// This governs only what this engine sends. Traffic the host's own stack generates
1172 /// is outside what this crate can promise.
1173 ///
1174 /// Reading the hosts file sends nothing. Resolve the targets of such a scan with
1175 /// [`Resolver::hosts_file_only`](crate::Resolver::hosts_file_only), so a lab box
1176 /// listed there is still a target and no name leaves the machine; the scan names
1177 /// found hosts from the same file.
1178 pub no_dns: bool,
1179
1180 /// Whether discovery may probe the whole segment, beyond the addresses it was
1181 /// given.
1182 ///
1183 /// A segment sweep sends the ICMPv6 all-nodes echo, which every IPv6 neighbour may
1184 /// answer, and records those that do. That is right for a sweep of `lan`, where an
1185 /// IPv6 neighbour with no address in the IPv4 range is found no other way. It is
1186 /// wrong for a scan of one named address, where a report listing eight machines
1187 /// would be surprising and, on someone else's network, indiscreet.
1188 ///
1189 /// Off by default. The engine receives already-resolved addresses and cannot tell
1190 /// `lan` from the range it expanded to, so whoever parsed the target expression has
1191 /// to set this.
1192 pub segment_sweep: bool,
1193
1194 /// Whether a port scan skips the liveness check and scans every target.
1195 ///
1196 /// Off by default, so [`scan`](crate::scan) confirms a target is there before
1197 /// probing its ports. Without the check, a dead address costs a full scan and comes
1198 /// back with every port as no reply.
1199 ///
1200 /// Set it when the liveness check is wrong: a host behind a firewall that drops
1201 /// ICMP and answers nothing on the discovery ports is reported down and never
1202 /// scanned, though it may be up.
1203 ///
1204 /// The liveness phase probes only the addresses it was given; see
1205 /// [`segment_sweep`](Self::segment_sweep) for sweeping a segment.
1206 pub assume_up: bool,
1207
1208 /// Whether to measure the route to each host that answered.
1209 ///
1210 /// Off by default. A trace costs roughly one probe per router per host and
1211 /// describes the network in between, not the host: useful for mapping a network,
1212 /// not for auditing a server.
1213 ///
1214 /// Only hosts that answered something are traced, because a path is measured
1215 /// backwards from the target's distance, read from a reply it sent. See
1216 /// [`traceroute`](crate::scanner::strategy::topology::traceroute).
1217 ///
1218 /// Needs raw sockets. An unprivileged run records the refusal, since an empty path
1219 /// would read as a network with no routers.
1220 pub traceroute: bool,
1221
1222 /// Whether to characterise the filter in front of each host that answered.
1223 ///
1224 /// Off by default: it costs a handful of extra probes per live host and describes
1225 /// the filtering between scanner and host, which a firewall test wants and an
1226 /// inventory scan does not.
1227 ///
1228 /// A separate pass, run after the ports are known and only against hosts that
1229 /// answered. Its diagnostic probes are read as
1230 /// [`Filtering`](crate::model::host::Filtering) conclusions and leave the port
1231 /// verdicts alone; its bad-checksum probe would make every port read as no reply if
1232 /// a scan ran under it.
1233 pub characterise: bool,
1234
1235 /// Which IP protocols to ask each host that answered whether it takes
1236 /// delivery of, one layer below the ports.
1237 ///
1238 /// Empty by default, which runs no pass: it costs a probe per host per protocol.
1239 /// It reveals a firewall's *protocol* policy, often the more telling one on a
1240 /// perimeter review, and what a host with no open TCP port still terminates: a
1241 /// tunnel endpoint answers for 47, 50 or 51 and a router for 89 or 112.
1242 ///
1243 /// [`DEFAULT_PROTOCOLS`](crate::scanner::strategy::protocols::DEFAULT_PROTOCOLS)
1244 /// is a sensible set for a caller who wants the pass without choosing numbers. The
1245 /// full `0..=255` range costs a raw socket per number, so it has to be asked for.
1246 ///
1247 /// A separate pass, run after the ports are known and only against hosts that
1248 /// answered. Its results are [`IpProtocolState`](crate::model::host::IpProtocolState)
1249 /// verdicts on the host; port verdicts are untouched.
1250 pub ip_protocols: BTreeSet<u8>,
1251
1252 /// Whether to establish every version and cipher suite each TLS port *accepts*.
1253 ///
1254 /// Off by default because of the cost. Service detection records the one version
1255 /// and suite a single handshake negotiated. This offers the endpoint each version in
1256 /// turn and narrows the cipher list until it stops answering, so the report says
1257 /// what the endpoint *would* negotiate, which is what PCI scans, ASV reports and
1258 /// internal audits ask.
1259 ///
1260 /// The cost is connections: a dozen for a current server accepting a handful of
1261 /// suites, a few dozen for one accepting everything under three versions. Each is a
1262 /// bare TCP connection carrying one ClientHello, torn down before the handshake
1263 /// completes, so no application sees a session, but the target's connection log
1264 /// sees every one.
1265 ///
1266 /// A separate pass, run after service detection, which supplies the list of TLS
1267 /// ports. Bounded per host by [`host_timeout`](Self::host_timeout), worth setting
1268 /// alongside this on anything unattended.
1269 ///
1270 /// ```
1271 /// # use zond_engine::ZondConfig;
1272 /// # use std::time::Duration;
1273 /// let mut cfg = ZondConfig::default();
1274 /// cfg.tls_enumeration = true;
1275 /// cfg.host_timeout = Some(Duration::from_secs(120));
1276 /// ```
1277 pub tls_enumeration: bool,
1278
1279 /// The TCP ports a scan connects to and listens on, and sends nothing.
1280 ///
1281 /// [`RAW_PRINT_PORTS`] by default. A printer prints whatever bytes arrive on those,
1282 /// so each probe would be a page of gibberish. The rule follows the port number,
1283 /// because identifying the host as a printer would take the very probe that prints.
1284 ///
1285 /// On a listed port, identification reads only what the port volunteers on
1286 /// connecting, as [`ServiceDetection::Banner`] does, and no detection, TLS
1287 /// handshake, enumeration or other conversation is opened. Finding the port open is
1288 /// unaffected, since that probe carries no payload. The report records this set,
1289 /// so a reader can tell a port left unprobed on purpose from one with nothing to
1290 /// say; see
1291 /// [`ScanSettings::listen_only_ports`](crate::report::ScanSettings::listen_only_ports).
1292 /// To send a port nothing at all, exclude it; see
1293 /// [`excluded_ports`](Self::excluded_ports).
1294 ///
1295 /// Clear it to probe these ports like any other, accepting that a printer may
1296 /// print. Add ports whose devices cannot be trusted with an unexpected request.
1297 /// UDP is unaffected.
1298 ///
1299 /// ```
1300 /// # use zond_engine::ZondConfig;
1301 /// let mut cfg = ZondConfig::default();
1302 /// assert!(cfg.listen_only_ports.contains(&9100));
1303 /// // Probe the printers' ports too, knowing each probe may print.
1304 /// cfg.listen_only_ports.clear();
1305 /// ```
1306 pub listen_only_ports: BTreeSet<u16>,
1307
1308 /// When set, scan TCP ports through a third-party zombie. See [`IdleScan`].
1309 ///
1310 /// This replaces the ordinary TCP port scan, so
1311 /// [`tcp_technique`](Self::tcp_technique) does not apply: every probe is a forged
1312 /// SYN read through the zombie's counter. UDP targets are left unprobed, since a
1313 /// UDP port cannot be read this way and probing it directly would reveal the
1314 /// scanner. Without privilege, a self-built frame, or a suitable zombie, the scan is
1315 /// refused; it never falls back to the scanner's own address.
1316 pub idle_scan: Option<IdleScan>,
1317
1318 /// Addresses this scan may not probe, whatever else it was asked to cover.
1319 ///
1320 /// Empty by default. This is how an engagement scoped as "10.0.0.0/8, except the
1321 /// cardholder segment" is expressed, and breaking it breaks a contract.
1322 ///
1323 /// Enforced twice, before the first packet and again at every finding; see
1324 /// [`Exclusions`] for why. The second check matters because a segment sweep learns
1325 /// addresses that were never in the target list.
1326 ///
1327 /// Narrowing only: no value can make a scan send a packet it would not otherwise
1328 /// send, which makes it safe to accept from a settings file (unlike
1329 /// [`segment_sweep`](Self::segment_sweep)). See `import::settings::Settings`.
1330 pub exclusions: Exclusions,
1331
1332 /// Ports this scan may not probe on any target, whatever else it was asked
1333 /// to cover.
1334 ///
1335 /// Empty by default. Removed from the port list before anything numbers it, so the
1336 /// port scan never asks an excluded port, and the passes that follow
1337 /// (identification, detection, TLS enumeration, the operating-system series,
1338 /// filter characterisation, route tracing) work from the ports it found. Ports a
1339 /// pass picks for itself are held to it too: a liveness pass skips excluded common
1340 /// ports, and the operating-system passes send no SNMP or device-info question to a
1341 /// port excluded on UDP. The report records the set; see
1342 /// [`ScanSettings::excluded_ports`](crate::report::ScanSettings::excluded_ports).
1343 ///
1344 /// For a port whose device misbehaves when anything arrives, or that an engagement
1345 /// puts out of bounds. Stronger than [`listen_only_ports`](Self::listen_only_ports),
1346 /// which still finds a port open: this sends the port nothing. The raw-print ports
1347 /// default to the weaker setting, since a printer prints what a connection carries,
1348 /// not the handshake, and excluding them would hide the printers.
1349 ///
1350 /// Not covered: name lookups, which [`no_dns`](Self::no_dns) decides, and the
1351 /// [IP protocol pass](Self::ip_protocols), which asks about a protocol and aims at
1352 /// a port chosen to be closed.
1353 ///
1354 /// Narrowing only, like [`exclusions`](Self::exclusions), so it is safe to accept
1355 /// from a settings file.
1356 ///
1357 /// ```
1358 /// # use zond_engine::ZondConfig;
1359 /// # use zond_engine::model::port::PortSet;
1360 /// let mut cfg = ZondConfig::default();
1361 /// // The raw-print ports, sent nothing at all.
1362 /// cfg.excluded_ports = PortSet::try_from("9100-9107").unwrap();
1363 /// ```
1364 pub excluded_ports: crate::model::port::PortSet,
1365
1366 /// The name each address was asked for by, where a target named a host.
1367 ///
1368 /// A web server routes a request by the name in it (the `Host` header, or the TLS
1369 /// server name), and a server holding several sites at one address answers an
1370 /// unnamed request with its default site or refuses the handshake. So a port on an
1371 /// address reached by name is identified using that name, and the host's record
1372 /// carries it as its hostname, which a reverse lookup leaves alone.
1373 ///
1374 /// Only names that were written are used, never one a lookup, report or redirect
1375 /// suggests. Where two names led to one address, the first written wins.
1376 ///
1377 /// One name per address, because a port holds one identification and one TLS
1378 /// record. The certificate the first name drew is not checked against a second
1379 /// name, since a server choosing its certificate by name would present a different
1380 /// one. To identify each site and check its certificate, scan each name in its own
1381 /// run.
1382 ///
1383 /// Empty by default, and set by whoever resolved the target expressions, since the
1384 /// names are gone once a scan has addresses; see
1385 /// [`resolve::for_port_scan`](crate::resolve::for_port_scan).
1386 pub target_names: BTreeMap<IpAddr, String>,
1387
1388 /// Whether identifying detail should be masked wherever the scan's findings
1389 /// leave the process: hostnames, hardware addresses, and the host part of an
1390 /// IPv6 address.
1391 ///
1392 /// For a report going somewhere that needs a network's shape without knowing
1393 /// which device is which: a client, an auditor, a screenshot in an issue.
1394 ///
1395 /// The scan itself keeps everything it found. This records the caller's intent,
1396 /// which reaches the point of use through [`ScanSettings`](crate::report::ScanSettings)
1397 /// and the export layer's [`Redaction`](crate::export::Redaction) policy, so the
1398 /// unmasked data stays recoverable.
1399 pub redact: bool,
1400
1401 /// How raw SYN probes are placed on the wire. Defaults to
1402 /// [`SendMode::Auto`], which is correct on every supported platform;
1403 /// override it only to force Layer-2 sends for host-stack-bypass scanning.
1404 pub send_mode: SendMode,
1405
1406 /// The fastest a scan may put probes on the wire, in probes per second.
1407 /// `None` leaves each scanner's own default in force.
1408 ///
1409 /// Mainly a coverage control. A probe's chance of being answered falls as the rate
1410 /// rises: on a policed path a burst loses most of its first attempt, recovered if
1411 /// at all by retransmitting later. A lower rate buys first-attempt coverage; a
1412 /// higher one trades coverage for time.
1413 ///
1414 /// For a TCP port scan it is only a ceiling. That scan learns how fast each target
1415 /// answers and settles there, almost always well below any configured rate (see
1416 /// `congestion`), so this matters only for a target that must not be pushed. The
1417 /// discovery sweep and the UDP port scan *are* paced by it, having no evidence to
1418 /// adapt on.
1419 ///
1420 /// Non-zero, since a ceiling of zero would be no scan and the report must not
1421 /// record a ceiling that was never applied.
1422 pub max_probe_rate: Option<NonZeroU32>,
1423
1424 /// The slowest a scan may put probes on the wire, in probes per second.
1425 /// `None` leaves each scanner's own pace in force.
1426 ///
1427 /// For a plan so large that finishing is in doubt. A scan with a
1428 /// [`scan_timeout`](Self::scan_timeout) can spend its whole budget on a fraction of
1429 /// its targets and report the rest as
1430 /// [`timed_out`](crate::report::ScanPhase::timed_out); a floor keeps the pace high
1431 /// enough to finish in time.
1432 ///
1433 /// Read by the same strategies as [`max_probe_rate`](Self::max_probe_rate). The
1434 /// discovery sweep and the UDP port scan are paced by the rate, so a floor raises
1435 /// their pace. A TCP port scan reads the rate only as a ceiling, so a floor raises
1436 /// the ceiling and its congestion window still decides, since pushing a target
1437 /// harder than it answers loses coverage.
1438 ///
1439 /// A floor above an explicit [`max_probe_rate`](Self::max_probe_rate) does not
1440 /// lift it: the safety limit wins.
1441 ///
1442 /// Non-zero, since a floor of zero is what `None` already says.
1443 pub min_probe_rate: Option<NonZeroU32>,
1444
1445 /// The shortest gap between two probes aimed at one host, or `None` to let
1446 /// every pass send as fast as its own pacing allows.
1447 ///
1448 /// **Every length is read literally, `Duration::MAX` included.** "No limit" is
1449 /// `None`; the largest gap admits one probe per host and never another, so a scan
1450 /// asking a host more than one question waits until stopped by the caller or by
1451 /// [`scan_timeout`](Self::scan_timeout), and files what it never asked as
1452 /// [`Unasked`](crate::model::port::PortState::Unasked). Reading the maximum as "no
1453 /// gap" would turn spacing off for a gap computed by saturating arithmetic, exactly
1454 /// when the caller asked for the most of it.
1455 ///
1456 /// This expresses what an operator knows about a target: this appliance falls over
1457 /// above twenty probes a second, this sensor fires at more than one every hundred
1458 /// milliseconds. Those limits are per source and destination, which
1459 /// [`max_probe_rate`](Self::max_probe_rate) cannot express without throttling the
1460 /// whole range.
1461 ///
1462 /// A duration because that is what the gate holds; converting a rate would round,
1463 /// and the report would record a bound the scan never applied (see `pacing_for`).
1464 ///
1465 /// The plan's keyed order already interleaves hosts in a scan of many, but that
1466 /// gives no bound, and nothing at all for a scan of one fragile address.
1467 ///
1468 /// A held probe is deferred, not dropped, so a tight gap makes a scan take longer.
1469 /// With [`scan_timeout`](Self::scan_timeout) set, the report says which hosts the
1470 /// budget left part-scanned.
1471 ///
1472 /// ## What reads this
1473 ///
1474 /// Every pass that sends toward a target, privileged or not: the raw port scans,
1475 /// the routed and segment sweeps, the identification, characterisation,
1476 /// IP-protocol, route and idle passes, and every connection and datagram opened
1477 /// through the host's own TCP and UDP (the connect scans and sweep, service
1478 /// identification and its further connections, TLS enumeration, the detections,
1479 /// and the SNMP and multicast DNS questions). All take slots from one shared gate,
1480 /// deciding and recording in one step, so concurrent passes share one gap.
1481 ///
1482 /// Three things send without it. The passive listener sends nothing. Next-hop
1483 /// hardware address resolution and name queries go to a neighbour or a name
1484 /// server, not a target. The timestamp series is timed: its spacing is the
1485 /// measurement. It runs under this gap unchanged; see
1486 /// [`probe_interval`](Self::probe_interval) for the gap it does not.
1487 ///
1488 /// ## What a gap counts
1489 ///
1490 /// One probe. On the raw paths that is one packet except in two places, where a
1491 /// question sent as several back-to-back packets counts as one probe, since
1492 /// deferring part of it would leave the rest unanswerable. The identification pass
1493 /// asks an IPv4 target for an echo and a timestamp (two packets). The routed sweep
1494 /// asks on each of its [`SynPorts`](crate::scanner::strategy::routed::SynPorts)
1495 /// (five, or up to eight in a port scan's liveness pass). So a gap of 100 ms admits
1496 /// that many packets per tenth of a second at one address while those run, and one
1497 /// elsewhere.
1498 ///
1499 /// Over the host's own sockets, one probe is one connection attempt (retries and
1500 /// redials included) or the first datagram of one exchange. The conversation over
1501 /// an answered connection is not spaced. A probe waits for its slot before its
1502 /// socket is opened, and the wait counts against no connection or conversation
1503 /// timeout, so a long gap costs time but never an identification.
1504 ///
1505 /// The idle scan counts a read of its zombie's counter at the zombie and each
1506 /// forged probe at the target. A route trace counts each probe at its target,
1507 /// though routers on the way answer it.
1508 ///
1509 /// A probe this machine refused before anything left (no descriptor, no source
1510 /// address, a local route's refusal) gets its slot back. A probe still waiting when
1511 /// the scan stops or its host's budget runs out is never sent and is reported as
1512 /// never asked.
1513 pub host_probe_interval: Option<Duration>,
1514
1515 /// The shortest gap between any two probes the scan sends, whatever host
1516 /// each is aimed at, or `None` to leave the pace to each pass.
1517 ///
1518 /// The scan-wide counterpart of [`host_probe_interval`](Self::host_probe_interval),
1519 /// for when the path must not be pushed: a thin link, a busy firewall's session
1520 /// table, an owner who asked for a few packets a second. A gap of a second is one
1521 /// probe a second across the whole range, where the same per-host gap still lets a
1522 /// scan of a thousand hosts send a thousand a second.
1523 ///
1524 /// A duration because the pacing gate holds one, and because this is used at the
1525 /// slow end, where [`max_probe_rate`](Self::max_probe_rate), a whole number per
1526 /// second, cannot express one probe every five seconds.
1527 ///
1528 /// [`max_probe_rate`](Self::max_probe_rate) is each pass's own ceiling, so two
1529 /// concurrent passes may each reach it. This gap is shared and claimed probe by
1530 /// probe, so concurrent passes divide it.
1531 ///
1532 /// It applies to the same probes as [`host_probe_interval`](Self::host_probe_interval),
1533 /// counted the same way and read literally on the same terms, `Duration::MAX`
1534 /// included. A probe waits out whichever gap ends later. It also covers the frames
1535 /// the segment sweep sends to a group (the router solicitation, the configuration
1536 /// request and the all-nodes echo), which spend this gap and no host's.
1537 ///
1538 /// The timestamp series is skipped under a gap longer than its send cadence of a
1539 /// quarter of a millisecond: its samples are read for the interval between them,
1540 /// and spread out they would read as a stalled counter. The report's record of
1541 /// this gap accounts for that, and hosts are named by the remaining
1542 /// operating-system passes.
1543 ///
1544 /// A held probe is deferred, not dropped: a thousand ports a second apart is a
1545 /// quarter of an hour before any retry. With [`scan_timeout`](Self::scan_timeout)
1546 /// set, the report says which hosts the budget left part-scanned.
1547 pub probe_interval: Option<Duration>,
1548
1549 /// The longest a scan will keep working on one host before leaving it with
1550 /// what it has, or `None` for no bound.
1551 ///
1552 /// The clock starts on the first probe aimed at an address and covers every later
1553 /// pass that sends to it: the port scan, the service pass, and the identification,
1554 /// path and detection passes. Once it expires the host is left alone and its
1555 /// address is written into
1556 /// [`ScanPhase::timed_out`](crate::report::ScanPhase::timed_out), so a short port
1557 /// list is not mistaken for a quiet machine.
1558 ///
1559 /// For a host that answers slowly: silence already costs a known number of
1560 /// probes, but a tarpit, a rate-limited appliance or a stack answering one probe in
1561 /// ten costs whatever it decides to.
1562 ///
1563 /// Not covered: reverse lookups, which go to a resolver (see
1564 /// [`no_dns`](Self::no_dns)), and discovery, whose liveness sweep runs a fixed
1565 /// schedule per address (see [`scan_timeout`](Self::scan_timeout)).
1566 ///
1567 /// It stops new probes, not those in flight, so a host may keep answering until
1568 /// the retry schedule of its last window runs out. That tail is bounded by the
1569 /// schedule.
1570 ///
1571 /// Zero expires before the first probe: the scan asks nothing and records every
1572 /// host as cut short.
1573 pub host_timeout: Option<Duration>,
1574
1575 /// The longest the whole call may run before it winds down, or `None` for
1576 /// no bound.
1577 ///
1578 /// Measured from when the scan is assembled, covering every phase: discovery, the
1579 /// port scan, and everything that enriches their findings. On expiry the strategies
1580 /// stop on their next pass and the run ends as an aborted one does, except each
1581 /// scanner records [`StopReason::TimedOut`](crate::report::StopReason::TimedOut).
1582 ///
1583 /// This makes an unattended run safe to schedule. The other bounds cover a probe, a
1584 /// retry or a host, and a range with enough slow addresses has no finishing time a
1585 /// caller can work out in advance.
1586 ///
1587 /// What was found is kept, and ports with no verdict are recorded
1588 /// [`Unasked`](crate::model::port::PortState::Unasked).
1589 ///
1590 /// It bounds this call, so each sitting of a resumed scan gets the full budget
1591 /// again; bounding the whole job is up to the caller.
1592 ///
1593 /// A budget longer than a clock can count from now, such as `Duration::MAX`, never
1594 /// runs out.
1595 pub scan_timeout: Option<Duration>,
1596
1597 /// Which segment a TCP port probe carries, and so what its answers mean.
1598 ///
1599 /// Defaults to [`TcpScanTechnique::Syn`], the only technique that identifies an open
1600 /// port positively and the only one the unprivileged connect fallback can
1601 /// approximate. The rest need raw sockets; asking for one without them records a
1602 /// failure, since a connect scan answers a different question.
1603 ///
1604 /// Affects the port-scan phase only. [`discover`](crate::scanner::discover)
1605 /// is unaffected.
1606 pub tcp_technique: TcpScanTechnique,
1607
1608 /// Which chunk an SCTP port probe carries, and so what its answers mean.
1609 ///
1610 /// Defaults to [`SctpScanTechnique::Init`], the only technique that names an open
1611 /// SCTP port. [`CookieEcho`](SctpScanTechnique::CookieEcho) draws an answer only
1612 /// from a port with nothing behind it, so its best verdict is open or no reply, but
1613 /// it passes filters written against INIT.
1614 ///
1615 /// Both need raw sockets. Affects the port-scan phase only: a discovery sweep always
1616 /// sends an INIT.
1617 pub sctp_technique: SctpScanTechnique,
1618
1619 /// How hard the scan tries before accepting silence as an answer.
1620 ///
1621 /// Scales each probing path's own schedule, so no effort level can hand a scanner a
1622 /// schedule its protocol cannot satisfy. Defaults to [`ScanEffort::Balanced`].
1623 pub retry: RetryConfig,
1624
1625 /// How far the scan goes to identify the operating system behind each host.
1626 ///
1627 /// Defaults to [`OsDetection::Passive`], which reads replies the scan already drew
1628 /// and sends nothing. See [`OsDetection`] for what each level puts on the wire.
1629 pub os_detection: OsDetection,
1630
1631 /// How far the scan goes to identify what is listening behind each open
1632 /// port.
1633 ///
1634 /// Defaults to [`ServiceDetection::Probe`], which connects to every open port and
1635 /// asks what it is. A scan that must stay out of the target's application logs
1636 /// turns it off. Affects the port-scan phase only.
1637 pub service_detection: ServiceDetection,
1638
1639 /// How intrusive a detection the scan may run against an identified service.
1640 ///
1641 /// After service detection names a port, the flow corpus can probe further to find
1642 /// what is *wrong* with it. This is the ceiling on how far that goes. The default
1643 /// permits only passive detections, which read what the service pass collected;
1644 /// active-benign ones, and ones that mutate, exploit or degrade the target, run
1645 /// only when the operator raises the ceiling. See [`DetectionEnvelope`]'s `Default`.
1646 /// Read by the detection phase, and only when service detection ran.
1647 pub detection: DetectionEnvelope,
1648
1649 /// What the scan changes about the probes it sends, over the defaults.
1650 ///
1651 /// Defaults to an inert profile. Carried into [`probe_tuning`](Self::probe_tuning)
1652 /// for the strategies, and into the report. The conversations that follow a probe
1653 /// over their own connections are not shaped; see
1654 /// [what a profile shapes](crate::evasion#a-profile-shapes-the-probes).
1655 pub evasion: EvasionProfile,
1656
1657 /// Whether to capture ICMP errors for a technique that finds open and
1658 /// closed ports without them, such as a SYN scan. On by default.
1659 ///
1660 /// An ICMP error is a firewall answering, and it tells a
1661 /// [`Blocked`](crate::model::port::PortState::Blocked) port from one that drew
1662 /// [`NoReply`](crate::model::port::PortState::NoReply). A scan too outrun to read
1663 /// silence as a verdict can still report a refusal. Turn it off on a link noisy
1664 /// with ICMP. The other TCP techniques read ICMP for their verdicts regardless.
1665 pub icmp_evidence: bool,
1666
1667 /// Source addresses to send probes to routed targets from, overriding the routing
1668 /// table's choice. At most one per family is used; empty lets the host decide. Set
1669 /// it to send from a chosen interface when the default route is a VPN the
1670 /// link-layer path cannot traverse.
1671 ///
1672 /// Connections follow the probes: the connect scan, the service pass, TLS
1673 /// enumeration and the detections all reach a routed target from the forced source
1674 /// through its interface. Targets on a directly attached link, and targets of a
1675 /// family with no forced source, follow the routing table, so with only an IPv4
1676 /// source forced, an IPv6 target may still go through a VPN holding the default
1677 /// route. To avoid the routing table entirely, force a source for each family the
1678 /// targets span.
1679 ///
1680 /// A connection is held to its interface by binding the socket to it, which Linux
1681 /// allows without `CAP_NET_RAW` from 5.7 on. On older kernels an unprivileged
1682 /// scan's pinned connections are refused, and their targets are reported as
1683 /// unreachable from this host.
1684 ///
1685 /// Name lookups are not pinned. Reverse lookups ask the configured resolvers and
1686 /// each interface's gateway by the routing table, as the system resolver does.
1687 /// Under a full-tunnel VPN the configured resolver is often reachable only through
1688 /// the tunnel, so a pinned lookup would fail, and the system resolver opens its own
1689 /// sockets anyway. To keep the scan's names off the tunnel, set
1690 /// [`no_dns`](Self::no_dns).
1691 pub send_source: Vec<IpAddr>,
1692}
1693
1694impl Default for ZondConfig {
1695 /// Hand-written so [`icmp_evidence`](Self::icmp_evidence) defaults on and
1696 /// [`listen_only_ports`](Self::listen_only_ports) to the printers' ports;
1697 /// every other field takes its own type's default.
1698 fn default() -> Self {
1699 Self {
1700 icmp_evidence: true,
1701 send_source: Vec::new(),
1702 no_dns: Default::default(),
1703 segment_sweep: Default::default(),
1704 assume_up: Default::default(),
1705 traceroute: Default::default(),
1706 characterise: Default::default(),
1707 ip_protocols: Default::default(),
1708 tls_enumeration: Default::default(),
1709 listen_only_ports: RAW_PRINT_PORTS.iter().copied().collect(),
1710 idle_scan: Default::default(),
1711 exclusions: Default::default(),
1712 excluded_ports: Default::default(),
1713 target_names: Default::default(),
1714 redact: Default::default(),
1715 send_mode: Default::default(),
1716 max_probe_rate: Default::default(),
1717 min_probe_rate: Default::default(),
1718 host_probe_interval: Default::default(),
1719 probe_interval: Default::default(),
1720 host_timeout: Default::default(),
1721 scan_timeout: Default::default(),
1722 tcp_technique: Default::default(),
1723 sctp_technique: Default::default(),
1724 retry: Default::default(),
1725 os_detection: Default::default(),
1726 service_detection: Default::default(),
1727 detection: Default::default(),
1728 evasion: Default::default(),
1729 }
1730 }
1731}
1732
1733impl ZondConfig {
1734 /// The probe-level knobs, bundled for the strategies that need them.
1735 ///
1736 /// `self` is destructured with every field named, so a new field not handled here
1737 /// fails to compile. The dropped fields govern which phases run and where a scan
1738 /// may go, which the orchestrator decides.
1739 pub fn probe_tuning(&self) -> ProbeTuning {
1740 let Self {
1741 send_mode,
1742 retry,
1743 max_probe_rate,
1744 min_probe_rate,
1745 tcp_technique,
1746 sctp_technique,
1747 os_detection,
1748 service_detection,
1749 evasion,
1750 icmp_evidence,
1751 send_source,
1752
1753 // Read elsewhere.
1754 no_dns: _,
1755 segment_sweep: _,
1756 assume_up: _,
1757 traceroute: _,
1758 characterise: _,
1759 ip_protocols: _,
1760 tls_enumeration: _,
1761 idle_scan: _,
1762 // Held by the scan's context, which every pass asks before sending to
1763 // a port.
1764 listen_only_ports: _,
1765 exclusions: _,
1766 // Taken out of the port list before a scan starts, and read by the
1767 // passes that pick a port of their own.
1768 excluded_ports: _,
1769 // Read by the identification, which asks each port by it.
1770 target_names: _,
1771 redact: _,
1772 detection: _,
1773
1774 // The wall-clock bounds: the scan's rides on the `ScanHandle` every
1775 // probing loop reads, the host's on the context the strategies share.
1776 host_timeout: _,
1777 scan_timeout: _,
1778
1779 // The gaps live in one gate every pass claims from; a copy per
1780 // strategy would let each pass use the whole gap.
1781 host_probe_interval: _,
1782 probe_interval: _,
1783 } = self;
1784
1785 ProbeTuning {
1786 send_mode: *send_mode,
1787 retry: *retry,
1788 max_probe_rate: *max_probe_rate,
1789 min_probe_rate: *min_probe_rate,
1790 tcp_technique: *tcp_technique,
1791 sctp_technique: *sctp_technique,
1792 os_detection: *os_detection,
1793 service_detection: *service_detection,
1794 evasion: evasion.clone(),
1795 icmp_evidence: *icmp_evidence,
1796 send_source: send_source.clone(),
1797 }
1798 }
1799}
1800
1801// ╔════════════════════════════════════════════╗
1802// ║ ████████╗███████╗███████╗████████╗███████╗ ║
1803// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
1804// ║ ██║ █████╗ ███████╗ ██║ ███████╗ ║
1805// ║ ██║ ██╔══╝ ╚════██║ ██║ ╚════██║ ║
1806// ║ ██║ ███████╗███████║ ██║ ███████║ ║
1807// ║ ╚═╝ ╚══════╝╚══════╝ ╚═╝ ╚══════╝ ║
1808// ╚════════════════════════════════════════════╝
1809
1810#[cfg(test)]
1811mod tests {
1812
1813 /// A scan left as it came sends nothing to a printer's raw-print ports,
1814 /// 9100 and the seven queues after it, and nothing else is spared.
1815 ///
1816 /// The default is the protection: a front end unaware of the setting still prints
1817 /// nothing.
1818 #[test]
1819 fn a_default_scan_only_listens_on_the_raw_print_ports() {
1820 let cfg = ZondConfig::default();
1821 assert_eq!(
1822 cfg.listen_only_ports,
1823 (9100..=9107).collect::<BTreeSet<u16>>()
1824 );
1825 assert_eq!(
1826 crate::report::ScanSettings::from(&cfg).listen_only_ports,
1827 (9100..=9107).collect::<Vec<u16>>(),
1828 "the report records what the scan held back"
1829 );
1830 }
1831
1832 /// The capture knob reaches the strategies.
1833 #[test]
1834 fn icmp_evidence_reaches_the_probe_tuning_and_is_on_unless_declined() {
1835 let mut cfg = ZondConfig::default();
1836 assert!(
1837 cfg.probe_tuning().icmp_evidence,
1838 "an error is a verdict a scan that was outrun cannot reach any other way"
1839 );
1840
1841 cfg.icmp_evidence = false;
1842 assert!(
1843 !cfg.probe_tuning().icmp_evidence,
1844 "and a caller may decline it"
1845 );
1846 }
1847 use super::*;
1848 use std::num::NonZeroU8;
1849
1850 /// What holds for one scale holds for all of them.
1851 #[test]
1852 fn every_scale_agrees_with_its_own_numbering() {
1853 fn check<T: Copy + std::fmt::Debug + PartialEq>(
1854 all: &[T],
1855 name: fn(T) -> &'static str,
1856 level: fn(T) -> u8,
1857 from_level: fn(u8) -> Option<T>,
1858 ) {
1859 for (index, value) in all.iter().copied().enumerate() {
1860 assert_eq!(usize::from(level(value)), index, "{value:?}");
1861 assert_eq!(from_level(level(value)), Some(value), "{value:?}");
1862 assert!(!name(value).is_empty());
1863 }
1864 let past_the_end = all.len() as u8;
1865 assert_eq!(
1866 from_level(past_the_end),
1867 None,
1868 "a level this engine does not offer is refused, not rounded down"
1869 );
1870 }
1871
1872 check(
1873 ScanEffort::ALL,
1874 ScanEffort::name,
1875 ScanEffort::level,
1876 ScanEffort::from_level,
1877 );
1878 check(
1879 OsDetection::ALL,
1880 OsDetection::name,
1881 OsDetection::level,
1882 OsDetection::from_level,
1883 );
1884 check(
1885 ServiceDetection::ALL,
1886 ServiceDetection::name,
1887 ServiceDetection::level,
1888 ServiceDetection::from_level,
1889 );
1890 check(
1891 ScanPace::ALL,
1892 ScanPace::name,
1893 ScanPace::level,
1894 ScanPace::from_level,
1895 );
1896 }
1897
1898 /// Both spellings are one setting for every scale: `2` from a flag and `balanced`
1899 /// from a settings file must give the same scan.
1900 #[test]
1901 fn every_scale_parses_the_same_by_name_and_by_number() {
1902 for &effort in ScanEffort::ALL {
1903 assert_eq!(effort.name().parse(), Ok(effort));
1904 assert_eq!(effort.name().to_uppercase().parse(), Ok(effort));
1905 assert_eq!(format!(" {} ", effort.level()).parse(), Ok(effort));
1906 }
1907 assert!("4".parse::<ScanEffort>().is_err());
1908 assert!("maximum".parse::<ScanEffort>().is_err());
1909
1910 for &detection in OsDetection::ALL {
1911 assert_eq!(detection.name().parse(), Ok(detection));
1912 assert_eq!(detection.level().to_string().parse(), Ok(detection));
1913 }
1914 for &detection in ServiceDetection::ALL {
1915 assert_eq!(detection.name().parse(), Ok(detection));
1916 assert_eq!(detection.level().to_string().parse(), Ok(detection));
1917 }
1918 for &pace in ScanPace::ALL {
1919 assert_eq!(pace.name().parse(), Ok(pace));
1920 assert_eq!(pace.level().to_string().parse(), Ok(pace));
1921 }
1922 }
1923
1924 /// The message a front end prints is built from the levels themselves, so a new
1925 /// level is named in it.
1926 #[test]
1927 fn a_parse_error_names_every_level_that_would_have_worked() {
1928 let effort = "maximum".parse::<ScanEffort>().unwrap_err().to_string();
1929 for &level in ScanEffort::ALL {
1930 assert!(effort.contains(level.name()), "{effort} omits {level}");
1931 }
1932 assert!(effort.contains("0 to 3"), "{effort}");
1933
1934 let os = "9".parse::<OsDetection>().unwrap_err().to_string();
1935 for &level in OsDetection::ALL {
1936 assert!(os.contains(level.name()), "{os} omits {level}");
1937 }
1938
1939 let service = "exhaustive"
1940 .parse::<ServiceDetection>()
1941 .unwrap_err()
1942 .to_string();
1943 for &level in ServiceDetection::ALL {
1944 assert!(service.contains(level.name()), "{service} omits {level}");
1945 }
1946 assert!(service.contains("0 to 3"), "{service}");
1947
1948 let pace = "6".parse::<ScanPace>().unwrap_err().to_string();
1949 for &level in ScanPace::ALL {
1950 assert!(pace.contains(level.name()), "{pace} omits {level}");
1951 }
1952 assert!(pace.contains("0 to 5"), "{pace}");
1953 }
1954
1955 /// The default pace is the default scan, to the last field.
1956 ///
1957 /// A scan run at `normal` must be the scan run with no pace chosen. Compared as a
1958 /// whole, so a field added later is covered too.
1959 #[test]
1960 fn the_default_pace_changes_nothing() {
1961 let mut paced = ZondConfig::default();
1962 ScanPace::default().apply_to(&mut paced);
1963 assert_eq!(ScanPace::default(), ScanPace::Normal);
1964 assert_eq!(format!("{paced:?}"), format!("{:?}", ZondConfig::default()));
1965 }
1966
1967 /// Every level is at least as gentle as the one above it: no slower level
1968 /// spaces probes closer, at one host or across the scan, or waits less
1969 /// for an answer.
1970 ///
1971 /// Patience is compared through a retry schedule, since effort and scale both move
1972 /// how long a probe is given.
1973 #[test]
1974 fn a_slower_pace_never_spaces_closer_or_waits_less() {
1975 use crate::scanner::pacing::retry::RetryPolicy;
1976
1977 let policy = RetryPolicy::new(
1978 3,
1979 Duration::from_millis(500),
1980 Duration::from_millis(50),
1981 Duration::from_secs(3),
1982 2.0,
1983 0.2,
1984 None,
1985 );
1986 let paced: Vec<(Duration, Duration, Duration)> = ScanPace::ALL
1987 .iter()
1988 .map(|pace| {
1989 let mut cfg = ZondConfig::default();
1990 pace.apply_to(&mut cfg);
1991 (
1992 cfg.probe_interval.unwrap_or_default(),
1993 cfg.host_probe_interval.unwrap_or_default(),
1994 policy.configured(cfg.retry).longest_probe_lifetime(),
1995 )
1996 })
1997 .collect();
1998
1999 for (slower, faster) in ScanPace::ALL.iter().zip(&ScanPace::ALL[1..]) {
2000 let (a, b) = (
2001 paced[slower.level() as usize],
2002 paced[faster.level() as usize],
2003 );
2004 assert!(a.0 >= b.0, "{slower} spaces the scan closer than {faster}");
2005 assert!(a.1 >= b.1, "{slower} spaces a host closer than {faster}");
2006 assert!(a.2 >= b.2, "{slower} waits less than {faster}");
2007 }
2008 assert!(
2009 paced[0].0 > paced[5].0 && paced[0].2 > paced[5].2,
2010 "and the dial moves something from one end to the other"
2011 );
2012 }
2013
2014 /// A slow pace takes the longer of its own gap and one already set, and the larger
2015 /// patience, so it never shortens a gap somebody chose.
2016 #[test]
2017 fn a_slow_pace_never_loosens_what_the_configuration_holds() {
2018 let mut cfg = ZondConfig {
2019 probe_interval: Some(Duration::from_secs(2)),
2020 host_probe_interval: Some(Duration::from_secs(3)),
2021 ..ZondConfig::default()
2022 };
2023 cfg.retry.timeout_scale = TimeoutScale::new(4.0);
2024
2025 ScanPace::Gentle.apply_to(&mut cfg);
2026 ScanPace::Trickle.apply_to(&mut cfg);
2027
2028 assert_eq!(cfg.probe_interval, Some(Duration::from_secs(2)));
2029 assert_eq!(cfg.host_probe_interval, Some(Duration::from_secs(3)));
2030 assert_eq!(cfg.retry.timeout_scale, TimeoutScale::new(4.0));
2031
2032 // Where nothing was set, the level's own values are written.
2033 let mut fresh = ZondConfig::default();
2034 ScanPace::Gentle.apply_to(&mut fresh);
2035 assert_eq!(fresh.probe_interval, Some(Duration::from_millis(5)));
2036 assert_eq!(fresh.host_probe_interval, Some(Duration::from_millis(50)));
2037 }
2038
2039 /// A fast pace changes only patience, never a gap or a rate, so it cannot lift a
2040 /// ceiling a settings file set to protect a network.
2041 #[test]
2042 fn a_fast_pace_touches_no_gap_and_no_rate() {
2043 for pace in [ScanPace::Brisk, ScanPace::Hurried] {
2044 let mut cfg = ZondConfig {
2045 max_probe_rate: NonZeroU32::new(100),
2046 probe_interval: Some(Duration::from_millis(250)),
2047 ..ZondConfig::default()
2048 };
2049 pace.apply_to(&mut cfg);
2050
2051 assert_eq!(cfg.max_probe_rate, NonZeroU32::new(100), "{pace}");
2052 assert_eq!(cfg.min_probe_rate, None, "{pace}");
2053 assert_eq!(
2054 cfg.probe_interval,
2055 Some(Duration::from_millis(250)),
2056 "{pace}"
2057 );
2058 assert_eq!(cfg.retry.effort, ScanEffort::Fast, "{pace}");
2059 }
2060 }
2061
2062 /// A scale no schedule can be built from is refused where it is set, so the report
2063 /// never records one that did not apply.
2064 #[test]
2065 fn a_retry_override_can_only_hold_a_value_a_scan_could_honour() {
2066 for factor in [0.0, -1.0, -0.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
2067 assert_eq!(TimeoutScale::new(factor), None, "scale {factor}");
2068 }
2069 assert_eq!(TimeoutScale::new(2.5).map(TimeoutScale::get), Some(2.5));
2070
2071 // Absurd but honourable: the schedule it produces is the one asked for.
2072 assert!(TimeoutScale::new(f64::MIN_POSITIVE).is_some());
2073 }
2074
2075 /// Every override in a retry configuration is a narrower type than the field
2076 /// it sets, so what reaches a strategy is what a scan can honour.
2077 #[test]
2078 fn the_retry_overrides_are_unset_by_default() {
2079 let retry = RetryConfig::default();
2080 assert_eq!(retry.max_attempts, None);
2081 assert_eq!(retry.timeout_scale, None);
2082 assert_eq!(retry.effort, ScanEffort::Balanced);
2083 assert!(retry.dampen_silent_hosts);
2084 }
2085
2086 /// The knobs a strategy reads arrive intact. `probe_tuning` destructures `self`, so
2087 /// an omitted field fails to compile; this catches a field wired to the wrong place.
2088 #[test]
2089 fn every_probe_level_knob_reaches_the_strategies() {
2090 let cfg = ZondConfig {
2091 send_mode: SendMode::Ethernet,
2092 retry: RetryConfig {
2093 effort: ScanEffort::Thorough,
2094 max_attempts: NonZeroU8::new(7),
2095 timeout_scale: TimeoutScale::new(3.5),
2096 dampen_silent_hosts: false,
2097 },
2098 // Different numbers, so a bound copied from the other rate is caught.
2099 max_probe_rate: NonZeroU32::new(1234),
2100 min_probe_rate: NonZeroU32::new(567),
2101 tcp_technique: TcpScanTechnique::Xmas,
2102 sctp_technique: SctpScanTechnique::CookieEcho,
2103 os_detection: OsDetection::Aggressive,
2104 service_detection: ServiceDetection::Banner,
2105 evasion: EvasionProfile::default(),
2106 ..Default::default()
2107 };
2108
2109 let tuning = cfg.probe_tuning();
2110 assert_eq!(tuning.send_mode, cfg.send_mode);
2111 assert_eq!(tuning.retry, cfg.retry);
2112 assert_eq!(tuning.max_probe_rate, cfg.max_probe_rate);
2113 assert_eq!(tuning.min_probe_rate, cfg.min_probe_rate);
2114 assert_eq!(tuning.tcp_technique, cfg.tcp_technique);
2115 assert_eq!(tuning.sctp_technique, cfg.sctp_technique);
2116 assert_eq!(tuning.os_detection, cfg.os_detection);
2117 assert_eq!(tuning.service_detection, cfg.service_detection);
2118 assert_eq!(tuning.evasion, cfg.evasion);
2119 }
2120
2121 /// `connects` is what the target's application logs record; `sends` is what its
2122 /// services are handed. The two boundaries differ.
2123 #[test]
2124 fn each_service_detection_level_says_what_it_puts_on_the_wire() {
2125 assert!(!ServiceDetection::Off.connects());
2126 assert!(!ServiceDetection::Off.sends());
2127
2128 assert!(ServiceDetection::Banner.connects());
2129 assert!(
2130 !ServiceDetection::Banner.sends(),
2131 "listening is the whole of what this level does"
2132 );
2133
2134 assert!(ServiceDetection::Probe.connects());
2135 assert!(ServiceDetection::Probe.sends());
2136
2137 assert!(
2138 ServiceDetection::default().sends(),
2139 "the default asks, because asking is both the informative answer and \
2140 the fast one"
2141 );
2142 }
2143
2144 /// Where the wire cost begins. The default level emits nothing, which is what makes
2145 /// it safe to leave on, so which levels answer `true` is a behavioural contract.
2146 #[test]
2147 fn os_detection_sends_nothing_below_the_active_level() {
2148 assert!(!OsDetection::Off.is_active());
2149 assert!(!OsDetection::Passive.is_active());
2150 assert!(OsDetection::Active.is_active());
2151 assert!(OsDetection::Aggressive.is_active());
2152
2153 assert!(!OsDetection::default().is_active(), "the default is silent");
2154 assert!(OsDetection::default().is_enabled(), "and it is still on");
2155 }
2156}