Skip to main content

zond_engine/import/
request.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//! # One scan, described as a document
10//!
11//! What to scan and how, as a document.
12//! [`import::settings`](crate::import::settings) covers the values worth setting
13//! once and keeping; this covers the ones that change from run to run, and the
14//! targets.
15//!
16//! ```toml
17//! targets = ["192.0.2.0/24", "db.internal"]
18//! exclude = ["192.0.2.7"]
19//! ports = "1-1024,8080"
20//!
21//! service_detection = "thorough"
22//! os_detection = "active"
23//! traceroute = true
24//!
25//! [settings]
26//! effort = "balanced"
27//! host_timeout = 60
28//!
29//! [evasion]
30//! source_port = 53
31//! ttl = 12
32//! ```
33//!
34//! [`ScanRequest`] is an ordinary deserializable struct, so the same document
35//! can be JSON or anything else `serde` reads:
36//!
37//! ```
38//! # #[cfg(feature = "import-json")]
39//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
40//! use zond_engine::import::request::ScanRequest;
41//!
42//! let request: ScanRequest = serde_json::from_str(r#"{
43//!     "targets": ["192.0.2.0/24"],
44//!     "ports": "22,80,443",
45//!     "service_detection": "thorough"
46//! }"#)?;
47//!
48//! assert_eq!(request.targets.len(), 1);
49//! # Ok(())
50//! # }
51//! # #[cfg(not(feature = "import-json"))]
52//! # fn main() {}
53//! ```
54//!
55//! ## Where it sits in the layering
56//!
57//! `import::settings` describes a chain, each layer overriding the one before:
58//!
59//! ```text
60//! ZondConfig::default()  →  system file  →  user file  →  named profile  →  the caller
61//! ```
62//!
63//! A request is the last arrow: it overrides everything a settings file said,
64//! because it was written for this run. That is also why it may name targets
65//! and widen a scan, which a settings file may not.
66//!
67//! ## An unknown key is refused
68//!
69//! A settings file only warns
70//! ([`SettingsWarning`](crate::import::settings::SettingsWarning)), because it
71//! outlives the engine that reads it and an older build must still read a
72//! profile written for a newer one. A request is written for one run and whoever
73//! wrote it is holding the error, so `deny_unknown_fields` refuses a misspelled
74//! key and names the keys that would have worked.
75//!
76//! The `[settings]` table inside a request keeps the settings document's rule:
77//! an unknown key there is ignored, and
78//! [`settings::parse`](crate::import::settings::parse) is the reader that
79//! reports them.
80//!
81//! ## Two steps, because one of them touches the network
82//!
83//! [`apply_to`](ScanRequest::apply_to) writes the settings into a
84//! [`ZondConfig`]. It is synchronous, total, and reads nothing outside the
85//! request.
86//!
87//! [`resolve`](ScanRequest::resolve) turns the target and exclusion expressions
88//! into addresses, and into the plan a port scan runs, which keeps the ports a
89//! target was written with: `192.0.2.1:8080` is scanned on 8080. It reads this
90//! host's interface table for `lan` and the `%interface` suffix, and may send
91//! DNS queries, so it is asynchronous and fallible and the caller decides when
92//! to run it. Target expressions are held as written so that deserializing does
93//! no lookups.
94
95use std::collections::BTreeSet;
96use std::net::IpAddr;
97
98use serde::Deserialize;
99
100use crate::config::envelope::DetectionEnvelope;
101use crate::config::{IdleScan, OsDetection, ServiceDetection, ZondConfig};
102use crate::evasion::EvasionProfile;
103use crate::import::settings::{Settings, de_named};
104use crate::model::exclusion::Exclusions;
105use crate::model::ip::set::IpSet;
106use crate::model::mac::MacAddr;
107use crate::model::parse::target::TargetParseError;
108use crate::model::port::PortSet;
109use crate::resolve::{self, DiscoveryTargets, PortScanTargets, Resolver};
110
111/// What went wrong turning a request into a scan.
112#[non_exhaustive]
113#[derive(Debug, thiserror::Error)]
114pub enum RequestError {
115    /// A target or exclusion expression could not be read.
116    #[error("{0}")]
117    Targets(#[from] TargetParseError),
118
119    /// The port specification was not a valid one.
120    #[error("ports = '{spec}': {reason}")]
121    Ports {
122        /// What was written.
123        spec: String,
124        /// Why it was refused.
125        reason: String,
126    },
127
128    /// The request named nothing to scan.
129    #[error("the request names no targets")]
130    NoTargets,
131}
132
133/// One scan, as a document.
134///
135/// Every field is optional, and an absent one leaves the value already in the
136/// [`ZondConfig`]. See the module documentation for where this layer sits.
137///
138/// A request can widen what a scan asks but cannot loosen what keeps it safe:
139/// nothing here drops an exclusion or takes a port off
140/// [`ZondConfig::listen_only_ports`], so a service passing on requests from
141/// somebody else cannot be made to print probes on every printer on a segment.
142/// Clearing that set is the caller's decision, made in code.
143#[non_exhaustive]
144#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
145#[serde(default, deny_unknown_fields)]
146pub struct ScanRequest {
147    /// What to scan, in the target grammar: addresses, ranges, CIDR blocks,
148    /// hostnames, `lan`, and a `%interface` suffix on a link-local address.
149    ///
150    /// Held as written. [`resolve`](Self::resolve) reads them.
151    pub targets: Vec<String>,
152
153    /// What this scan may not probe, in the same grammar as `targets`.
154    ///
155    /// A settings file's `exclude` takes literal addresses only, since it is
156    /// read on machines where `lan` and `db.internal` mean different things. A
157    /// request is resolved on the machine that runs the scan.
158    ///
159    /// Added to whatever the configuration already forbids, so applying a
160    /// request cannot drop an exclusion a settings file set.
161    pub exclude: Vec<String>,
162
163    /// The ports to scan, in the [`PortSet`] grammar: `22`, `1-1024`,
164    /// `U:53,161`, `T:80,443`.
165    ///
166    /// Held as written, and parsed by [`ports`](Self::ports). Falls back to the
167    /// `[settings]` table's `default_ports` when the request names none.
168    pub ports: Option<String>,
169
170    /// The values a settings file could also have set.
171    ///
172    /// Lets one document carry a whole scan. Keys set here override what was
173    /// loaded from disk.
174    pub settings: Settings,
175
176    /// Treats every target as reachable and goes straight to the ports.
177    pub assume_up: Option<bool>,
178
179    /// Measures the path to each host that answered.
180    pub traceroute: Option<bool>,
181
182    /// Reads what a host's stack and services reveal about it beyond which ports
183    /// are open.
184    pub characterise: Option<bool>,
185
186    /// Keeps the ICMP messages a probe drew as evidence in the report, beside
187    /// the verdict they settled.
188    pub icmp_evidence: Option<bool>,
189
190    /// The IP protocol numbers to ask each host about, one layer below the
191    /// ports. Replaces the configured set.
192    pub ip_protocols: Option<BTreeSet<u8>>,
193
194    /// The addresses to send every probe from, overriding the routing table's
195    /// choice. At most one per family is used, and an empty list gives the
196    /// choice back to the host. Replaces the configured list.
197    pub send_source: Option<Vec<IpAddr>>,
198
199    /// How far to go establishing the operating system: `off`, `passive`,
200    /// `active` or `aggressive`.
201    #[serde(deserialize_with = "de_named")]
202    pub os_detection: Option<OsDetection>,
203
204    /// How far to go identifying what is behind each open port: `off`, `banner`,
205    /// `probe` or `thorough`.
206    #[serde(deserialize_with = "de_named")]
207    pub service_detection: Option<ServiceDetection>,
208
209    /// The most intrusive class of detection this scan may run.
210    #[serde(deserialize_with = "de_named")]
211    pub detection: Option<DetectionEnvelope>,
212
213    /// Scans through a third host.
214    #[serde(deserialize_with = "de_idle_scan")]
215    pub idle_scan: Option<IdleScan>,
216
217    /// How probes are shaped to get past a filter.
218    ///
219    /// Replaces the configured profile whole, since a profile mixed field by
220    /// field from two sources would be one nobody chose. Refused at read time
221    /// if [`EvasionProfile::validate`] rejects it.
222    #[serde(deserialize_with = "de_evasion")]
223    pub evasion: Option<EvasionProfile>,
224}
225
226impl ScanRequest {
227    /// A request that changes nothing and names no targets.
228    pub fn new() -> Self {
229        Self::default()
230    }
231
232    /// The port set this request scans, if it settles one.
233    ///
234    /// The request's own `ports` first, then the `[settings]` table's
235    /// `default_ports`. [`None`] when neither names any, leaving the choice to
236    /// the caller.
237    ///
238    /// # Errors
239    ///
240    /// [`RequestError::Ports`] if the specification is malformed or names no
241    /// ports. Parsed here, not at deserialization, so the rest of a request is
242    /// readable when this key is wrong.
243    pub fn ports(&self) -> Option<Result<PortSet, RequestError>> {
244        if let Some(spec) = self.ports.as_deref() {
245            return Some(
246                PortSet::parse_scan(spec).map_err(|error| RequestError::Ports {
247                    spec: spec.to_string(),
248                    reason: error.to_string(),
249                }),
250            );
251        }
252
253        self.settings.ports().map(|parsed| {
254            parsed.map_err(|error| RequestError::Ports {
255                spec: self.settings.default_ports.clone().unwrap_or_default(),
256                reason: error.to_string(),
257            })
258        })
259    }
260
261    /// Applies everything this request says to `config`, leaving the rest as it
262    /// was.
263    ///
264    /// The `[settings]` table goes on first and the request's own fields
265    /// override it, so a document that says `effort = "thorough"` under
266    /// `[settings]` and `service_detection = "off"` at the top level means both.
267    ///
268    /// Targets are not applied here; they need [`resolve`](Self::resolve).
269    pub fn apply_to(&self, config: &mut ZondConfig) {
270        self.settings.apply_to(config);
271
272        if let Some(value) = self.assume_up {
273            config.assume_up = value;
274        }
275        if let Some(value) = self.traceroute {
276            config.traceroute = value;
277        }
278        if let Some(value) = self.characterise {
279            config.characterise = value;
280        }
281        if let Some(value) = self.icmp_evidence {
282            config.icmp_evidence = value;
283        }
284        if let Some(protocols) = &self.ip_protocols {
285            config.ip_protocols = protocols.clone();
286        }
287        if let Some(sources) = &self.send_source {
288            config.send_source = sources.clone();
289        }
290        if let Some(value) = self.os_detection {
291            config.os_detection = value;
292        }
293        if let Some(value) = self.service_detection {
294            config.service_detection = value;
295        }
296        if let Some(value) = self.detection {
297            config.detection = value;
298        }
299        if self.idle_scan.is_some() {
300            config.idle_scan = self.idle_scan;
301        }
302        if let Some(profile) = &self.evasion {
303            config.evasion = profile.clone();
304        }
305    }
306
307    /// Resolves the target and exclusion expressions into addresses.
308    ///
309    /// `names` is the DNS policy, as on [`resolve::for_discovery`]: [`Some`]
310    /// resolves hostnames and [`None`] refuses them, as a scan under
311    /// [`no_dns`](ZondConfig::no_dns) needs.
312    ///
313    /// # Errors
314    ///
315    /// [`RequestError::NoTargets`] if the request names none, and
316    /// [`RequestError::Targets`] if an expression cannot be read or a hostname
317    /// does not resolve.
318    pub async fn resolve(&self, names: Option<&Resolver>) -> Result<Resolved, RequestError> {
319        if self.targets.is_empty() {
320            return Err(RequestError::NoTargets);
321        }
322
323        let (targets, plan) = resolve::for_request(&self.targets, names).await?;
324        let exclude = if self.exclude.is_empty() {
325            Exclusions::none()
326        } else {
327            resolve::for_exclusion(&self.exclude, names).await?
328        };
329        let ports = self.ports().transpose()?;
330
331        Ok(Resolved {
332            targets,
333            plan,
334            exclude,
335            ports,
336        })
337    }
338}
339
340/// What a request's expressions turned out to mean.
341///
342/// Produced by [`ScanRequest::resolve`]. The addresses go to
343/// [`discover`](crate::scanner::discover); the exclusions and the sweep flag go
344/// to the configuration through [`apply_to`](Self::apply_to).
345#[non_exhaustive]
346#[derive(Debug, Clone)]
347pub struct Resolved {
348    targets: DiscoveryTargets,
349    /// The targets with the ports each wrote, and the empty set on those that
350    /// wrote none; see [`port_scan`](Self::port_scan).
351    plan: PortScanTargets,
352    exclude: Exclusions,
353    ports: Option<PortSet>,
354}
355
356impl Resolved {
357    /// The addresses to probe.
358    pub fn ips(&self) -> &IpSet {
359        self.targets.ips()
360    }
361
362    /// Takes the addresses, for handing to [`discover`](crate::scanner::discover).
363    pub fn into_ips(self) -> IpSet {
364        self.targets.into_ips()
365    }
366
367    /// The ports the request settled on, if it settled any.
368    ///
369    /// What a target written without ports of its own is scanned on. One
370    /// written with them, such as `192.0.2.1:8080`, is scanned on those; see
371    /// [`port_scan`](Self::port_scan).
372    pub fn ports(&self) -> Option<&PortSet> {
373        self.ports.as_ref()
374    }
375
376    /// The port scan these targets ask for, and the name each address was
377    /// reached by.
378    ///
379    /// A target written with ports, such as `192.0.2.1:8080`, is scanned on
380    /// those. Every other target is scanned on the request's ports, or on
381    /// `default_ports` where the request settled none.
382    pub fn port_scan(&self, default_ports: &PortSet) -> PortScanTargets {
383        self.plan
384            .with_unported_on(self.ports.as_ref().unwrap_or(default_ports))
385    }
386
387    /// The addresses this scan may not probe.
388    pub fn exclusions(&self) -> &Exclusions {
389        &self.exclude
390    }
391
392    /// Takes the addresses and the request's ports.
393    ///
394    /// Ports written on a target are lost, so a map built from these scans
395    /// `192.0.2.1:8080` on the request's ports. [`port_scan`](Self::port_scan)
396    /// is the plan that keeps them.
397    pub fn into_parts(self) -> (IpSet, Option<PortSet>) {
398        (self.targets.into_ips(), self.ports)
399    }
400
401    /// Writes what these targets imply into `config`.
402    ///
403    /// The exclusions, whether a whole network was named, and the name each
404    /// address was reached by. Exclusions are
405    /// added to what `config` already forbids, so the order a request and a
406    /// settings file are applied in cannot lose either one's exclusions.
407    pub fn apply_to(&self, config: &mut ZondConfig) {
408        self.targets.apply_to(config);
409        self.plan.apply_to(config);
410        config.exclusions.extend(&self.exclude);
411    }
412}
413
414// ---------------------------------------------------------------------------
415// Deserialization of the fields that are tables of their own
416// ---------------------------------------------------------------------------
417
418/// The document form of [`IdleScan`], which carries no `Deserialize` of its own.
419#[derive(Deserialize)]
420#[serde(deny_unknown_fields)]
421struct IdleScanDocument {
422    zombie: IpAddr,
423    #[serde(default)]
424    zombie_port: Option<u16>,
425}
426
427/// Reads an `[idle_scan]` table.
428fn de_idle_scan<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<IdleScan>, D::Error> {
429    let Some(document) = Option::<IdleScanDocument>::deserialize(d)? else {
430        return Ok(None);
431    };
432
433    Ok(Some(IdleScan {
434        zombie: document.zombie,
435        zombie_port: document.zombie_port,
436    }))
437}
438
439/// The document form of [`EvasionProfile`].
440#[derive(Default, Deserialize)]
441#[serde(default, deny_unknown_fields)]
442struct EvasionDocument {
443    source_port: Option<u16>,
444    ttl: Option<u8>,
445    padding: Option<u16>,
446    bad_tcp_checksum: bool,
447    #[serde(deserialize_with = "de_named")]
448    spoof_mac: Option<MacAddr>,
449    fragment: Option<u16>,
450    decoys: Vec<IpAddr>,
451    /// The TCP flag byte, as the constants in
452    /// [`protocols::tcp::flags`](crate::protocols::tcp::flags) name it.
453    flags: Option<u8>,
454}
455
456/// Reads an `[evasion]` table, refusing a profile the engine would refuse later.
457fn de_evasion<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<EvasionProfile>, D::Error> {
458    let Some(document) = Option::<EvasionDocument>::deserialize(d)? else {
459        return Ok(None);
460    };
461
462    let profile = EvasionProfile {
463        source_port: document.source_port,
464        ttl: document.ttl,
465        padding: document.padding,
466        bad_tcp_checksum: document.bad_tcp_checksum,
467        spoof_mac: document.spoof_mac,
468        fragment: document.fragment,
469        decoys: document.decoys,
470        flags: document.flags,
471    };
472
473    profile.validate().map_err(serde::de::Error::custom)?;
474
475    Ok(Some(profile))
476}
477
478#[cfg(test)]
479mod tests {
480    use super::*;
481    use crate::config::ScanEffort;
482    use crate::model::finding::DetectionClass;
483    use crate::model::technique::TcpScanTechnique;
484
485    /// Reads a request the way a caller would, and fails naming what stopped it.
486    fn request(document: &str) -> ScanRequest {
487        toml::from_str(document).expect("the document is a request")
488    }
489
490    /// A configuration away from its defaults, so anything a request
491    /// overwrites is visible.
492    fn settled() -> ZondConfig {
493        ZondConfig {
494            assume_up: true,
495            traceroute: true,
496            characterise: true,
497            icmp_evidence: true,
498            os_detection: OsDetection::Aggressive,
499            service_detection: ServiceDetection::Thorough,
500            tcp_technique: TcpScanTechnique::Fin,
501            send_source: vec!["198.51.100.1".parse().expect("literal")],
502            ..Default::default()
503        }
504    }
505
506    /// No request takes a port off the listen-only list, at its top level or
507    /// in its settings table. A key naming the list is refused or ignored; one
508    /// that replaced the set would fail here.
509    #[test]
510    fn no_request_can_take_a_port_off_the_listen_only_list() {
511        for text in [
512            "listen_only_ports = []\n",
513            "probe_print_ports = true\n",
514            "[settings]\nlisten_only_ports = []\n",
515        ] {
516            let Ok(request) = toml::from_str::<ScanRequest>(text) else {
517                // A refused request keeps the list whole.
518                continue;
519            };
520            let mut config = ZondConfig::default();
521            request.apply_to(&mut config);
522
523            for port in crate::config::RAW_PRINT_PORTS {
524                assert!(
525                    config.listen_only_ports.contains(port),
526                    "{text:?} took {port} off the list"
527                );
528            }
529        }
530    }
531
532    /// A request layers over a configuration somebody else built, so an absent
533    /// key must change nothing.
534    #[test]
535    fn a_request_that_says_nothing_changes_no_setting() {
536        let mut config = settled();
537        ScanRequest::new().apply_to(&mut config);
538
539        assert!(config.assume_up);
540        assert!(config.traceroute);
541        assert!(config.characterise);
542        assert!(config.icmp_evidence);
543        assert_eq!(config.os_detection, OsDetection::Aggressive);
544        assert_eq!(config.service_detection, ServiceDetection::Thorough);
545        assert_eq!(config.tcp_technique, TcpScanTechnique::Fin);
546        assert_eq!(config.send_source, settled().send_source);
547        assert!(config.idle_scan.is_none());
548        assert!(!config.evasion.is_active());
549    }
550
551    #[test]
552    fn every_key_a_request_understands_reaches_the_configuration() {
553        let request = request(
554            r#"
555            targets = ["192.0.2.0/24"]
556            ports = "22,80"
557            assume_up = false
558            traceroute = false
559            characterise = false
560            icmp_evidence = false
561            ip_protocols = [1, 47, 50]
562            send_source = ["192.0.2.2"]
563            os_detection = "passive"
564            service_detection = "banner"
565            detection = "exploit"
566
567            [settings]
568            effort = "single"
569            tcp_technique = "syn"
570
571            [idle_scan]
572            zombie = "192.0.2.9"
573            zombie_port = 445
574
575            [evasion]
576            source_port = 53
577            ttl = 12
578            decoys = ["192.0.2.5"]
579            "#,
580        );
581
582        let mut config = settled();
583        request.apply_to(&mut config);
584
585        assert!(!config.assume_up);
586        assert!(!config.traceroute);
587        assert!(!config.characterise);
588        assert!(!config.icmp_evidence);
589        assert_eq!(config.ip_protocols, BTreeSet::from([1, 47, 50]));
590        assert_eq!(
591            config.send_source,
592            vec!["192.0.2.2".parse::<IpAddr>().expect("literal")]
593        );
594        assert_eq!(config.os_detection, OsDetection::Passive);
595        assert_eq!(config.service_detection, ServiceDetection::Banner);
596        assert_eq!(config.detection.ceiling(), Some(DetectionClass::Exploit));
597        assert_eq!(config.retry.effort, ScanEffort::Single);
598        assert_eq!(config.tcp_technique, TcpScanTechnique::Syn);
599
600        let idle = config.idle_scan.expect("the request named a zombie");
601        assert_eq!(idle.zombie, "192.0.2.9".parse::<IpAddr>().expect("literal"));
602        assert_eq!(idle.zombie_port, Some(445));
603
604        assert_eq!(config.evasion.source_port, Some(53));
605        assert_eq!(config.evasion.ttl, Some(12));
606        assert_eq!(config.evasion.decoys.len(), 1);
607
608        let ports = request
609            .ports()
610            .expect("the request named ports")
611            .expect("valid");
612        assert!(ports.has_tcp(22) && ports.has_tcp(80));
613    }
614
615    /// A settings file warns about an unknown key; a request is refused and
616    /// the error names the field.
617    #[test]
618    fn a_misspelled_key_is_refused_rather_than_ignored() {
619        let error = toml::from_str::<ScanRequest>("traceroot = true\n")
620            .expect_err("a key nobody knows is not a request");
621
622        let message = error.to_string();
623        assert!(
624            message.contains("traceroot"),
625            "the error should name the key that was written: {message}"
626        );
627        assert!(
628            message.contains("traceroute"),
629            "the error should name the keys that would have worked: {message}"
630        );
631    }
632
633    /// A request is the layer after a settings file, so where the two speak
634    /// about one key the request wins.
635    #[test]
636    fn a_request_overrides_the_settings_a_file_had_already_applied() {
637        let mut config = ZondConfig::default();
638
639        let from_disk: Settings =
640            toml::from_str("effort = \"single\"\ntls_enumeration = false\n").expect("settings");
641        from_disk.apply_to(&mut config);
642
643        request("[settings]\neffort = \"thorough\"\n").apply_to(&mut config);
644
645        assert_eq!(config.retry.effort, ScanEffort::Thorough);
646        assert!(
647            !config.tls_enumeration,
648            "a key the request said nothing about keeps what the file set"
649        );
650    }
651
652    /// The engine refuses a profile like this when a scan starts. Refusing it
653    /// at read time names the key.
654    #[test]
655    fn an_evasion_table_the_engine_would_refuse_is_refused_as_it_is_read() {
656        let error = toml::from_str::<ScanRequest>("[evasion]\nfragment = 4\n")
657            .expect_err("an unfragmentable MTU is not a profile");
658
659        assert!(
660            error.to_string().contains("fragment"),
661            "the error should say which value was wrong: {error}"
662        );
663    }
664
665    #[test]
666    fn ports_fall_back_to_the_settings_table_when_the_request_names_none() {
667        let request = request("[settings]\ndefault_ports = \"443\"\n");
668        let ports = request
669            .ports()
670            .expect("the settings named ports")
671            .expect("valid");
672
673        assert!(ports.has_tcp(443));
674        assert_eq!(ports.len(), 1);
675    }
676
677    #[test]
678    fn a_port_specification_that_is_not_one_names_what_was_written() {
679        let request = request("ports = \"nope\"\n");
680        let error = request
681            .ports()
682            .expect("the request named ports")
683            .expect_err("'nope' is not a port specification");
684
685        assert!(matches!(&error, RequestError::Ports { spec, .. } if spec == "nope"));
686    }
687
688    /// A specification that names no ports would silently scan nothing, so
689    /// both places a request can name its ports refuse one.
690    #[test]
691    fn a_port_specification_naming_nothing_is_refused_rather_than_scanning_nothing() {
692        for document in [
693            "ports = \"\"\n",
694            "ports = \" , \"\n",
695            "[settings]\ndefault_ports = \"\"\n",
696        ] {
697            let error = request(document)
698                .ports()
699                .expect("the request named ports")
700                .expect_err("a specification naming nothing");
701            assert!(
702                error.to_string().contains("names no ports"),
703                "{document}: {error}"
704            );
705        }
706    }
707
708    #[tokio::test]
709    async fn resolving_adds_exclusions_to_what_the_configuration_already_forbids() {
710        let mut already = IpSet::new();
711        already.insert_range("198.51.100.0/24".parse().expect("a valid range"));
712
713        let mut config = ZondConfig {
714            exclusions: Exclusions::new(already),
715            ..Default::default()
716        };
717
718        let resolved = request("targets = [\"192.0.2.0/24\"]\nexclude = [\"192.0.2.7\"]\n")
719            .resolve(None)
720            .await
721            .expect("literal addresses resolve without a resolver");
722
723        resolved.apply_to(&mut config);
724
725        for excluded in ["198.51.100.1", "192.0.2.7"] {
726            assert!(
727                config
728                    .exclusions
729                    .excludes(&excluded.parse().expect("literal")),
730                "{excluded} was excluded by one of the two and must still be"
731            );
732        }
733        assert!(
734            !config
735                .exclusions
736                .excludes(&"192.0.2.8".parse().expect("literal"))
737        );
738        assert_eq!(resolved.ips().len(), 256);
739    }
740
741    /// A port written on a target is the port that target is scanned on.
742    #[tokio::test]
743    async fn a_port_written_on_a_target_is_the_port_it_is_scanned_on() {
744        let defaults = PortSet::try_from("22").expect("a specification");
745        let on = |plan: &PortScanTargets, address: &str| {
746            let address: IpAddr = address.parse().expect("literal");
747            plan.map()
748                .units
749                .iter()
750                .find(|unit| unit.ips().contains(&address))
751                .map(|unit| unit.ports().to_string())
752        };
753
754        let unported = request("targets = [\"192.0.2.1:8080\", \"192.0.2.2\"]\n")
755            .resolve(None)
756            .await
757            .expect("literal addresses resolve without a resolver");
758        let plan = unported.port_scan(&defaults);
759        assert_eq!(on(&plan, "192.0.2.1").as_deref(), Some("8080"));
760        assert_eq!(on(&plan, "192.0.2.2").as_deref(), Some("22"));
761        assert_eq!(unported.ips().len(), 2, "both reach the discovery sweep");
762
763        let ported = request("targets = [\"192.0.2.1:u:53\", \"192.0.2.2\"]\nports = \"443\"\n")
764            .resolve(None)
765            .await
766            .expect("resolves");
767        let plan = ported.port_scan(&defaults);
768        assert_eq!(on(&plan, "192.0.2.1").as_deref(), Some("u:53"));
769        assert_eq!(on(&plan, "192.0.2.2").as_deref(), Some("443"));
770    }
771
772    #[tokio::test]
773    async fn a_request_naming_no_targets_is_refused_rather_than_resolving_to_nothing() {
774        let error = ScanRequest::new()
775            .resolve(None)
776            .await
777            .expect_err("a request with no targets cannot be resolved");
778
779        assert!(matches!(error, RequestError::NoTargets));
780    }
781}