Skip to main content

zond_engine/
resolve.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//! # Forward name resolution
10//!
11//! Turns the names a person writes, such as `example.com`, `raspberrypi.local`
12//! and `nas`, into the addresses a scan can probe, before the scan starts. The
13//! reverse half, which names hosts a scan has found, lives in
14//! [`crate::scanner::rdns`] and uses the same sources: the hosts file first,
15//! then the server the address's reverse zone is scoped to, or the global ones.
16//!
17//! ## Where a name is answered
18//!
19//! [`Resolver::resolve`] routes a name in the order the host's own lookups take:
20//!
21//! - The hosts file first, for every name. A name it lists is answered from it
22//!   and asked of nobody, which is how a lab box with no DNS of its own gets a
23//!   name, `.local` suffix or not; see `hosts` for why the engine reads the file
24//!   itself.
25//! - A `.local` name is a multicast name (RFC 6762) and is asked of the link
26//!   over multicast DNS. A unicast lookup of one fails wherever the host has no
27//!   mDNS-aware resolver, which on Linux is the common case, so the engine
28//!   speaks mDNS itself. The exception is a `.local` domain a unicast server is
29//!   configured to answer for, such as an Active Directory domain named
30//!   `corp.local`: that name is asked of the server first, and of the link only
31//!   if the server has no answer.
32//! - Any other name goes to unicast DNS as the host has it configured: to the
33//!   server a scoped resolver names for its domain, where there is one, and
34//!   otherwise to the global resolvers with the host's search domains.
35//! - A single-label name (`nas`) is tried unicast first and, if nothing answers
36//!   and mDNS is enabled, again as `nas.local`, which on a home network is often
37//!   what the author meant.
38//!
39//! The hosts file and the resolver configuration are read afresh at every
40//! resolution pass, so a front end that runs for hours resolves a name the way
41//! the host does at that moment. Nothing a pass learned, failures included, is
42//! kept for the next.
43//!
44//! Every lookup leaves by the routing table. A scan forced to a source pins its
45//! probes and connections, but not the lookups made before it starts; see
46//! [`ZondConfig::send_source`](crate::config::ZondConfig::send_source).
47//!
48//! ## Relation to the parse hook
49//!
50//! [`crate::model::parse`] takes names through a
51//! [`HostLookup`](crate::model::parse::target::HostLookup) supplied in a
52//! [`TargetContext`](crate::model::parse::target::TargetContext). The target
53//! grammar does not speak DNS itself; this module resolves the names and hands
54//! the answers to that hook.
55//!
56//! ## Two passes
57//!
58//! The hook is synchronous and called once per name during parsing, while
59//! resolution is asynchronous and slow, mDNS especially. Blocking inside the hook
60//! would turn a file of two hundred names into two hundred sequential round
61//! trips, so resolution takes two passes:
62//!
63//! 1. [`resolve_names`] finds every name in a set of target expressions and
64//!    resolves them concurrently into a map.
65//! 2. [`to_target_map`] and [`to_set`] then parse with a hook that reads the
66//!    map, so the parse never waits on the network.
67//!
68//! [`Resolver::resolve`] resolves a single name; [`to_target_map`] and
69//! [`to_set`] do the whole job for a caller assembling a scan.
70//!
71//! ## Policy left to the caller
72//!
73//! Whether a scan may resolve at all
74//! ([`ZondConfig::no_dns`](crate::config::ZondConfig::no_dns)) is the caller's
75//! decision. A front end that must not emit name queries resolves with
76//! [`Resolver::hosts_file_only`], which answers the names the hosts file lists
77//! and sends nothing, so a lab box listed there is still a target and any other
78//! name is an unknown host. A caller that supplies no resolver at all has every
79//! name refused with
80//! [`NoHostLookup`](crate::model::parse::target::TargetParseError::NoHostLookup).
81
82mod hosts;
83mod links;
84mod mdns;
85mod targets;
86mod unicast;
87
88pub use links::{LinkError, for_listening, for_listening_on};
89#[cfg(feature = "import-request")]
90pub(crate) use targets::for_request;
91pub use targets::{
92    DiscoveryTargets, PortScanTargets, for_discovery, for_discovery_with, for_exclusion,
93    for_exclusion_with, for_port_scan, resolve_names, to_set, to_target_map,
94};
95
96use std::fmt;
97use std::net::IpAddr;
98use std::time::Duration;
99
100use crate::warn;
101
102pub(crate) use hosts::HostsTable;
103pub(crate) use unicast::{
104    DnsConfig, Reverse, ScopedServers, ServerPolicy, Unicast, covers, reverse_name,
105};
106
107/// The default mDNS reply window. See [`ResolveConfig::mdns_timeout`] for why it
108/// is a whole second.
109const DEFAULT_MDNS_TIMEOUT: Duration = Duration::from_secs(1);
110
111/// The shortest window that can hear a conformant responder.
112///
113/// RFC 6762 §6.3 lets a responder defer a reply by up to half a second to
114/// aggregate answers, so a shorter window closes while a correct responder is
115/// still waiting to speak. A shorter request is raised to this. Nothing in a
116/// [`ResolveConfig`] is carried into a report, so raising it misrecords nothing.
117const MIN_MDNS_TIMEOUT: Duration = Duration::from_millis(500);
118
119/// How a [`Resolver`] behaves, independent of the host it reads its unicast
120/// configuration from.
121///
122/// Non-exhaustive and [`Default`]-constructed, like
123/// [`ZondConfig`](crate::config::ZondConfig), so new settings are additive.
124#[non_exhaustive]
125#[derive(Debug, Clone, Copy)]
126pub struct ResolveConfig {
127    /// Whether `.local` names are resolved over multicast, and whether a
128    /// single-label name falls back to one.
129    ///
130    /// Off leaves a `.local` name to the hosts file and to a unicast server
131    /// configured for its domain. For networks where multicast is filtered or
132    /// unwanted, or where only global names are in play.
133    pub mdns: bool,
134
135    /// How long to listen for mDNS replies before accepting that a `.local`
136    /// name has no answer on the segment.
137    ///
138    /// A responder may defer a reply by up to half a second to aggregate
139    /// answers (RFC 6762 §6.3), and a busy or sleeping device can take longer,
140    /// so the default is one second: short enough not to stall a scan, long
141    /// enough to hear a slow device.
142    ///
143    /// A window shorter than half a second is raised to it, since a shorter one
144    /// cannot hear a correct responder at all.
145    pub mdns_timeout: Duration,
146}
147
148impl Default for ResolveConfig {
149    fn default() -> Self {
150        Self {
151            mdns: true,
152            mdns_timeout: DEFAULT_MDNS_TIMEOUT,
153        }
154    }
155}
156
157/// Resolves names to addresses from the hosts file, unicast DNS and multicast
158/// DNS.
159///
160/// The hosts file and the resolver configuration are read at each resolution
161/// pass, so one resolver kept for the life of a front end resolves as the host
162/// does at the time. Cheap to clone, and shared across the concurrent lookups
163/// [`resolve_names`] runs.
164#[derive(Clone)]
165pub struct Resolver {
166    origin: Origin,
167    config: ResolveConfig,
168    /// Whether a lookup may put a question on the network, unicast or
169    /// multicast, or is answered from the hosts file alone.
170    asks: bool,
171}
172
173/// Where a resolver reads what the host says about names.
174#[derive(Clone)]
175enum Origin {
176    /// The system's hosts file and resolver configuration.
177    System,
178    /// Supplied by a test, which decides what a pass reads and which servers
179    /// it may ask.
180    #[cfg(test)]
181    Given(std::sync::Arc<dyn Fn() -> (String, DnsConfig) + Send + Sync>),
182}
183
184/// What the host says about names at one moment: the hosts file and the
185/// unicast servers, read once and shared by every lookup of a pass.
186pub(crate) struct Snapshot {
187    hosts: HostsTable,
188    /// `None` for a resolver that asks nobody, which reads no server
189    /// configuration either.
190    unicast: Option<Unicast>,
191}
192
193impl Resolver {
194    /// Builds a resolver from the host's own configuration, with mDNS
195    /// enabled.
196    ///
197    /// A host whose resolver configuration cannot be read, such as a container
198    /// or a lab VM with no name server in `resolv.conf`, still resolves names
199    /// in its hosts file and `.local` names. A name that needed a DNS server
200    /// comes back empty, with a warning saying why.
201    pub fn from_system() -> Self {
202        Self::with_config(ResolveConfig::default())
203    }
204
205    /// Builds a resolver with an explicit [`ResolveConfig`].
206    pub fn with_config(config: ResolveConfig) -> Self {
207        Self {
208            origin: Origin::System,
209            config,
210            asks: true,
211        }
212    }
213
214    /// Builds a resolver that answers from the host's hosts file alone and
215    /// puts nothing on the network: no unicast query and no multicast one.
216    ///
217    /// For a caller that must not send name queries, such as a scan under
218    /// [`ZondConfig::no_dns`](crate::config::ZondConfig::no_dns). The hosts
219    /// file is where a lab box reached over a VPN gets its name, and reading it
220    /// sends nothing. A name the file does not list resolves to nothing, which
221    /// the target functions report as an unknown host.
222    pub fn hosts_file_only() -> Self {
223        Self {
224            origin: Origin::System,
225            config: ResolveConfig::default(),
226            asks: false,
227        }
228    }
229
230    /// A resolver reading the hosts file text and unicast configuration
231    /// `read` returns at each pass.
232    #[cfg(test)]
233    pub(crate) fn given(
234        config: ResolveConfig,
235        read: impl Fn() -> (String, DnsConfig) + Send + Sync + 'static,
236    ) -> Self {
237        Self {
238            origin: Origin::Given(std::sync::Arc::new(read)),
239            config,
240            asks: true,
241        }
242    }
243
244    /// Reads what the host currently says about names, for one resolution pass.
245    ///
246    /// A caller resolving many names reads it once and resolves them all
247    /// against it with [`resolve_in`](Self::resolve_in), so every name in a
248    /// target list sees the same file and the same servers.
249    pub(crate) fn snapshot(&self) -> Snapshot {
250        self.snapshot_asking(&mut ServerPolicy::every())
251    }
252
253    /// [`snapshot`](Self::snapshot), asking only the servers `policy` allows.
254    pub(crate) fn snapshot_asking(&self, policy: &mut ServerPolicy<'_>) -> Snapshot {
255        let (hosts, dns) = match &self.origin {
256            Origin::System => (
257                HostsTable::read_system(),
258                self.asks.then(DnsConfig::read_system),
259            ),
260            #[cfg(test)]
261            Origin::Given(read) => {
262                let (hosts, dns) = read();
263                (HostsTable::parse(&hosts), self.asks.then_some(dns))
264            }
265        };
266        Snapshot {
267            hosts,
268            unicast: dns.map(|dns| Unicast::from_config(dns.withholding(policy))),
269        }
270    }
271
272    /// Resolves one name to every address it stands for, in first-seen order.
273    ///
274    /// An empty result means nothing answered for the name. See the module
275    /// documentation for where each kind of name is answered. Reads the host's
276    /// configuration for this one name; a caller with many wants
277    /// [`resolve_names`], which reads it once.
278    pub async fn resolve(&self, name: &str) -> Vec<IpAddr> {
279        self.resolve_in(&self.snapshot(), name).await
280    }
281
282    /// [`resolve`](Self::resolve), against a configuration already read.
283    pub(crate) async fn resolve_in(&self, snapshot: &Snapshot, name: &str) -> Vec<IpAddr> {
284        let name = name.trim_end_matches('.');
285
286        if let Some(listed) = from_hosts(snapshot, name) {
287            return listed;
288        }
289        let Some(unicast) = &snapshot.unicast else {
290            return Vec::new();
291        };
292
293        if is_multicast_local(name) {
294            return self.resolve_local(unicast, name).await;
295        }
296
297        let answered = unicast.lookup(name).await;
298        if !answered.is_empty() || !is_single_label(name) {
299            return answered;
300        }
301
302        // A bare `nas` that unicast could not place is most often `nas.local`.
303        // Tried after unicast so a multicast answer cannot shadow a
304        // search-domain match.
305        let local = format!("{name}.local");
306        if let Some(listed) = from_hosts(snapshot, &local) {
307            return listed;
308        }
309        self.resolve_local(unicast, &local).await
310    }
311
312    /// A `.local` name the hosts file does not list: unicast first when a
313    /// configured server answers for its domain, then the link.
314    async fn resolve_local(&self, unicast: &Unicast, name: &str) -> Vec<IpAddr> {
315        if unicast.claims(name) {
316            let unicast = unicast.lookup(name).await;
317            if !unicast.is_empty() {
318                return unicast;
319            }
320        }
321        self.resolve_mdns(name).await
322    }
323
324    /// The multicast half, honouring the config's mDNS switch.
325    async fn resolve_mdns(&self, name: &str) -> Vec<IpAddr> {
326        if !self.config.mdns {
327            return Vec::new();
328        }
329        let window = self.config.mdns_timeout.max(MIN_MDNS_TIMEOUT);
330        mdns::resolve(name, window).await
331    }
332}
333
334impl Snapshot {
335    /// Resolves `ip` back to a name from the same sources, and by the same
336    /// routes, a name is resolved forward.
337    ///
338    /// An address the hosts file lists is answered from it alone: the file is
339    /// authoritative in both directions, and asking a resolver somebody else
340    /// operates about a lab box's address tells them what was found. A
341    /// loopback address the file does not list is asked of nobody, since RFC
342    /// 6761 section 6.3 keeps its reverse zone on the machine; the `localhost`
343    /// a DNS library would invent for all of `127.0.0.0/8` is not a name the
344    /// hosts file gave. Anything else goes to the server its reverse zone is
345    /// scoped to, or the global ones; see [`Unicast::reverse`].
346    pub(crate) async fn reverse(&self, ip: IpAddr) -> Reverse {
347        if let Some(name) = self.hosts.name_of(ip) {
348            return Reverse::Listed(name.to_owned());
349        }
350        match (&self.unicast, self.reverse_route(ip)) {
351            (Some(unicast), ReverseRoute::Scoped(_) | ReverseRoute::Global) => {
352                unicast.reverse(ip).await
353            }
354            _ => Reverse::Unasked,
355        }
356    }
357
358    /// Which way [`reverse`](Self::reverse) takes `ip`, decided without
359    /// asking anything.
360    ///
361    /// For a caller that tracks each server's silence separately: a global
362    /// resolver that answers nothing says nothing about the server a VPN scopes
363    /// to its reverse zone, and giving up on both leaves every address under
364    /// that zone unnamed.
365    pub(crate) fn reverse_route(&self, ip: IpAddr) -> ReverseRoute {
366        match &self.unicast {
367            _ if self.hosts.name_of(ip).is_some() => ReverseRoute::Local,
368            Some(unicast) if !ip.is_loopback() => unicast
369                .reverse_scope(ip)
370                .map_or(ReverseRoute::Global, ReverseRoute::Scoped),
371            _ => ReverseRoute::Local,
372        }
373    }
374}
375
376/// The way a reverse lookup of one address goes; see
377/// [`Snapshot::reverse_route`].
378#[derive(Debug, Clone, Copy, PartialEq, Eq)]
379pub(crate) enum ReverseRoute {
380    /// Answered on the machine or not at all: from the hosts file, for a
381    /// loopback address, or on a host with no server to ask.
382    Local,
383    /// The resolver scoped to a reverse zone, by its place among them.
384    Scoped(usize),
385    /// The global resolvers.
386    Global,
387}
388
389/// What the hosts file answers for `name`, saying so when a later line for it
390/// goes unused.
391///
392/// Warned at the default verbosity because it changes what is scanned: a stale
393/// line above a new one for the same box sends the scan to the old address, and
394/// only the user can say which line is right.
395fn from_hosts(snapshot: &Snapshot, name: &str) -> Option<Vec<IpAddr>> {
396    let answer = snapshot.hosts.lookup(name)?;
397    for unused in &answer.shadowed {
398        warn!("{name}: hosts line for {unused} ignored (earlier line wins)");
399    }
400    Some(answer.addresses)
401}
402
403impl fmt::Debug for Resolver {
404    /// Says what this resolver reads and whether multicast is on.
405    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406        let origin = match self.origin {
407            Origin::System => "system",
408            #[cfg(test)]
409            Origin::Given(_) => "given",
410        };
411        f.debug_struct("Resolver")
412            .field("origin", &origin)
413            .field("config", &self.config)
414            .field("asks", &self.asks)
415            .finish()
416    }
417}
418
419/// Whether `name` is resolved over multicast: a multi-label name whose last
420/// label is `local`.
421///
422/// A bare `local` is a single-label name, which the fallback may try as
423/// `local.local`.
424fn is_multicast_local(name: &str) -> bool {
425    name.contains('.')
426        && name
427            .rsplit('.')
428            .next()
429            .is_some_and(|tld| tld.eq_ignore_ascii_case("local"))
430}
431
432/// Whether `name` is a single label, and so a candidate for the `.local`
433/// fallback once unicast has had its say.
434fn is_single_label(name: &str) -> bool {
435    !name.is_empty() && !name.contains('.')
436}
437
438// ╔════════════════════════════════════════════╗
439// ║ ████████╗███████╗███████╗████████╗███████╗ ║
440// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
441// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
442// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
443// ║    ██║   ███████╗███████║   ██║   ███████║ ║
444// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
445// ╚════════════════════════════════════════════╝
446
447#[cfg(test)]
448mod tests {
449    use super::*;
450
451    /// A misclassified name goes to a protocol that cannot answer it: a `.local`
452    /// host to a unicast server, or a global name to the multicast group.
453    #[test]
454    fn only_a_dotted_local_name_is_a_multicast_name() {
455        assert!(is_multicast_local("raspberrypi.local"));
456        assert!(is_multicast_local("Printer.LOCAL"));
457        assert!(is_multicast_local("host.sub.local"));
458
459        assert!(!is_multicast_local("example.com"));
460        assert!(!is_multicast_local("localhost"));
461        // A bare `local` has no host part; it is a short name.
462        assert!(!is_multicast_local("local"));
463    }
464
465    /// A window too short to hear a conformant responder is raised to the half
466    /// second RFC 6762 §6.3 lets a responder defer its reply.
467    ///
468    /// Raised, where the overrides in [`RetryConfig`](crate::config::RetryConfig)
469    /// are refused: nothing in a [`ResolveConfig`] is carried into a report, so
470    /// the raised value misrecords nothing.
471    #[test]
472    fn a_window_shorter_than_the_protocol_allows_is_raised_to_it() {
473        for asked in [Duration::ZERO, Duration::from_millis(1), MIN_MDNS_TIMEOUT] {
474            assert_eq!(asked.max(MIN_MDNS_TIMEOUT), MIN_MDNS_TIMEOUT);
475        }
476
477        let generous = Duration::from_secs(5);
478        assert_eq!(generous.max(MIN_MDNS_TIMEOUT), generous);
479        assert_eq!(
480            DEFAULT_MDNS_TIMEOUT.max(MIN_MDNS_TIMEOUT),
481            DEFAULT_MDNS_TIMEOUT,
482            "the default is above the floor, or the floor is the default"
483        );
484    }
485
486    /// A resolver's debug output says what it reads and whether multicast is on.
487    #[test]
488    fn a_resolver_reports_what_it_reads_and_whether_multicast_is_on() {
489        let rendered = format!("{:?}", Resolver::with_config(ResolveConfig::default()));
490
491        assert!(rendered.starts_with("Resolver"), "{rendered}");
492        assert!(rendered.contains("origin: \"system\""), "{rendered}");
493        assert!(rendered.contains("mdns: true"), "{rendered}");
494    }
495
496    #[test]
497    fn a_single_label_is_a_fallback_candidate_and_a_dotted_name_is_not() {
498        assert!(is_single_label("nas"));
499        assert!(!is_single_label("nas.local"));
500        assert!(!is_single_label("example.com"));
501        assert!(!is_single_label(""));
502    }
503
504    // ── Where a name is answered ────────────────────────────────────────────
505    //
506    // Each test hands a resolver its hosts file and fake servers on loopback,
507    // which record what a lookup asks and of whom. mDNS is off throughout so no
508    // multicast packet leaves the test.
509
510    use std::collections::HashMap;
511    use std::net::{Ipv4Addr, SocketAddr};
512    use std::sync::{Arc, Mutex};
513
514    use hickory_resolver::config::{NameServerConfig, ResolverConfig, ResolverOpts};
515    use hickory_resolver::proto::op::{Message, MessageType, ResponseCode};
516    use hickory_resolver::proto::rr::rdata::{A, PTR, SOA};
517    use hickory_resolver::proto::rr::{Name, RData, Record, RecordType};
518
519    use crate::logging::logged;
520    use unicast::ScopedServers;
521
522    /// A name server on loopback that answers A queries for the names it
523    /// holds, PTR queries for the addresses it names, and NXDOMAIN for any
524    /// other, noting every question it is asked.
525    ///
526    /// Its NXDOMAIN carries the zone's SOA, as a real server's does, because
527    /// that is what lets a client cache the failure; without it a client that
528    /// holds failures across passes would go unnoticed.
529    struct FakeDns {
530        at: SocketAddr,
531        records: Arc<Mutex<HashMap<String, Ipv4Addr>>>,
532        /// Hostnames keyed by the reverse name a PTR query asks.
533        names: Arc<Mutex<HashMap<String, String>>>,
534        asked: Arc<Mutex<Vec<String>>>,
535        serving: tokio::task::JoinHandle<()>,
536    }
537
538    impl FakeDns {
539        async fn start(records: &[(&str, Ipv4Addr)]) -> Self {
540            let socket = tokio::net::UdpSocket::bind("127.0.0.1:0")
541                .await
542                .expect("a loopback socket binds");
543            let at = socket.local_addr().expect("a bound socket has an address");
544            let records = Arc::new(Mutex::new(
545                records
546                    .iter()
547                    .map(|(name, ip)| (format!("{name}."), *ip))
548                    .collect::<HashMap<_, _>>(),
549            ));
550            let asked = Arc::new(Mutex::new(Vec::new()));
551            let names = Arc::new(Mutex::new(HashMap::new()));
552
553            let (held, noted) = (Arc::clone(&records), Arc::clone(&asked));
554            let reverse = Arc::clone(&names);
555            let serving = tokio::spawn(async move {
556                let mut buf = [0u8; 1500];
557                while let Ok((len, from)) =
558                    crate::testing::loopback::recv_from_this_process(&socket, &mut buf).await
559                {
560                    let Ok(query) = Message::from_vec(&buf[..len]) else {
561                        continue;
562                    };
563                    let Some(question) = query.queries.first().cloned() else {
564                        continue;
565                    };
566                    let name = question.name().to_ascii().to_ascii_lowercase();
567                    noted
568                        .lock()
569                        .expect("unpoisoned")
570                        .push(format!("{name} {}", question.query_type()));
571
572                    let known = held.lock().expect("unpoisoned").get(&name).copied();
573                    let named = reverse.lock().expect("unpoisoned").get(&name).cloned();
574                    let mut reply = Message::response(query.metadata.id, query.metadata.op_code);
575                    reply.metadata.message_type = MessageType::Response;
576                    reply.metadata.recursion_desired = query.metadata.recursion_desired;
577                    reply.metadata.recursion_available = true;
578                    reply.add_query(question.clone());
579                    match known {
580                        _ if question.query_type() == RecordType::PTR && named.is_some() => {
581                            let host = named.expect("checked above");
582                            reply.add_answer(Record::from_rdata(
583                                question.name().clone(),
584                                300,
585                                RData::PTR(PTR(Name::from_ascii(&host).expect("a host name"))),
586                            ));
587                        }
588                        Some(ip) if question.query_type() == RecordType::A => {
589                            reply.add_answer(Record::from_rdata(
590                                question.name().clone(),
591                                300,
592                                RData::A(A(ip)),
593                            ));
594                        }
595                        Some(_) => {}
596                        None => {
597                            reply.metadata.response_code = ResponseCode::NXDomain;
598                            let zone = Name::from_ascii("example.").expect("a zone name");
599                            let soa =
600                                SOA::new(zone.clone(), zone.clone(), 1, 3600, 600, 86400, 3600);
601                            reply.add_authority(Record::from_rdata(zone, 3600, RData::SOA(soa)));
602                        }
603                    }
604                    let bytes = reply.to_vec().expect("a reply encodes");
605                    let _ = socket.send_to(&bytes, from).await;
606                }
607            });
608
609            Self {
610                at,
611                records,
612                names,
613                asked,
614                serving,
615            }
616        }
617
618        /// Starts answering a reverse lookup of `ip` with `host`.
619        fn name(&self, ip: IpAddr, host: &str) {
620            self.names
621                .lock()
622                .expect("unpoisoned")
623                .insert(format!("{}.", reverse_name(ip)), format!("{host}."));
624        }
625
626        /// The questions this server has been asked, as `name. TYPE`.
627        fn asked(&self) -> Vec<String> {
628            self.asked.lock().expect("unpoisoned").clone()
629        }
630
631        /// Starts answering for `name`.
632        fn add(&self, name: &str, ip: Ipv4Addr) {
633            self.records
634                .lock()
635                .expect("unpoisoned")
636                .insert(format!("{name}."), ip);
637        }
638
639        /// A global configuration naming this server, with `search` as its
640        /// search list.
641        fn as_global(&self, search: &[&str]) -> (ResolverConfig, ResolverOpts) {
642            let mut server = NameServerConfig::udp(self.at.ip());
643            for connection in &mut server.connections {
644                connection.port = self.at.port();
645            }
646            let search = search
647                .iter()
648                .map(|s| s.parse().expect("a search domain parses"))
649                .collect();
650            let mut opts = ResolverOpts::default();
651            opts.attempts = 1;
652            (ResolverConfig::from_parts(None, search, vec![server]), opts)
653        }
654    }
655
656    impl Drop for FakeDns {
657        fn drop(&mut self) {
658            self.serving.abort();
659        }
660    }
661
662    fn no_mdns() -> ResolveConfig {
663        ResolveConfig {
664            mdns: false,
665            ..ResolveConfig::default()
666        }
667    }
668
669    fn v4(s: &str) -> IpAddr {
670        s.parse().expect("a test address parses")
671    }
672
673    /// A resolver reading `hosts`, asking `global`, and asking `scoped` for
674    /// the names under their domains.
675    fn resolver_over(
676        hosts: &str,
677        global: Result<(ResolverConfig, ResolverOpts), String>,
678        scoped: Vec<ScopedServers>,
679    ) -> Resolver {
680        let hosts = hosts.to_owned();
681        Resolver::given(no_mdns(), move || {
682            (
683                hosts.clone(),
684                DnsConfig {
685                    global: global.clone(),
686                    scoped: scoped.clone(),
687                },
688            )
689        })
690    }
691
692    /// A name the hosts file lists is answered from it and asked of no server,
693    /// in either family.
694    ///
695    /// The file lists an A address. A lookup that consulted it per record type
696    /// would still ask upstream for AAAA, telling a resolver somebody else
697    /// operates which lab box is being scanned, and waiting out its timeout
698    /// where that resolver is unreachable.
699    #[tokio::test]
700    async fn a_name_the_hosts_file_lists_is_answered_without_asking_dns() {
701        let dns = FakeDns::start(&[]).await;
702        let resolver = resolver_over(
703            "198.51.100.7 box.example\n",
704            Ok(dns.as_global(&[])),
705            Vec::new(),
706        );
707
708        assert_eq!(
709            resolver.resolve("box.example").await,
710            vec![v4("198.51.100.7")]
711        );
712        assert_eq!(
713            dns.asked(),
714            Vec::<String>::new(),
715            "the hosts name reached DNS"
716        );
717    }
718
719    /// Of two hosts lines for one name, the first is scanned and the second is
720    /// named in a warning.
721    ///
722    /// An old box and its replacement both left in the file is the usual way a
723    /// name gets two lines. Scanning both covers a host nobody meant; the
724    /// warning lets the user delete the right line.
725    #[test]
726    fn a_stale_hosts_line_for_a_name_is_neither_scanned_nor_silent() {
727        let resolver = resolver_over(
728            "198.51.100.23 box.example\n198.51.100.99 box.example\n",
729            Err("none configured".into()),
730            Vec::new(),
731        );
732        let runtime = tokio::runtime::Builder::new_current_thread()
733            .enable_all()
734            .build()
735            .expect("a runtime builds");
736
737        let mut resolved = Vec::new();
738        let lines = logged(|| resolved = runtime.block_on(resolver.resolve("box.example")));
739
740        assert_eq!(resolved, vec![v4("198.51.100.23")]);
741        let warned: Vec<_> = lines.iter().filter(|l| l.verbosity == 0).collect();
742        assert!(
743            warned
744                .iter()
745                .any(|l| l.message.contains("box.example") && l.message.contains("198.51.100.99")),
746            "no default-verbosity line names the unused address: {lines:?}"
747        );
748    }
749
750    /// A `.local` name the hosts file lists resolves from it, as it does for
751    /// `ping` and `ssh`.
752    ///
753    /// Lab domains such as `htb.local` exist only as hosts lines on the
754    /// attacker's machine; asking the link for them finds nothing.
755    #[tokio::test]
756    async fn a_local_name_the_hosts_file_lists_resolves_from_it() {
757        let resolver = resolver_over(
758            "198.51.100.161 forest.corp.local corp.local\n",
759            Err("none configured".into()),
760            Vec::new(),
761        );
762
763        for name in ["forest.corp.local", "corp.local"] {
764            assert_eq!(
765                resolver.resolve(name).await,
766                vec![v4("198.51.100.161")],
767                "{name}"
768            );
769        }
770    }
771
772    /// A `.local` name under a domain the host's search list names is asked of
773    /// unicast DNS, and one under no configured domain is not.
774    ///
775    /// An Active Directory domain named `corp.local` is answered by its domain
776    /// controller, and a host joined to it searches that domain. A `.local`
777    /// name nothing configured claims is a name on the link, and asking a
778    /// unicast server about it only leaks it.
779    #[tokio::test]
780    async fn a_local_name_under_a_searched_domain_is_asked_of_unicast_dns() {
781        let dns = FakeDns::start(&[("dc01.corp.local", Ipv4Addr::new(198, 51, 100, 10))]).await;
782        let resolver = resolver_over("", Ok(dns.as_global(&["corp.local"])), Vec::new());
783
784        assert_eq!(
785            resolver.resolve("dc01.corp.local").await,
786            vec![v4("198.51.100.10")]
787        );
788
789        let before = dns.asked().len();
790        assert_eq!(
791            resolver.resolve("printer.local").await,
792            Vec::<IpAddr>::new()
793        );
794        assert_eq!(
795            dns.asked().len(),
796            before,
797            "a link-only name reached unicast DNS"
798        );
799    }
800
801    /// A name under a scoped resolver's domain is asked of that domain's server
802    /// alone, and any other name of the global one.
803    ///
804    /// A VPN's match domain is served by the VPN's resolver. The global one
805    /// cannot answer for it, and asking it would put a private name on the
806    /// public path.
807    #[tokio::test]
808    async fn a_name_under_a_scoped_domain_is_asked_of_that_domains_server_alone() {
809        let global = FakeDns::start(&[("www.example", Ipv4Addr::new(203, 0, 113, 80))]).await;
810        let scoped =
811            FakeDns::start(&[("host.corp.example", Ipv4Addr::new(198, 51, 100, 20))]).await;
812        let resolver = resolver_over(
813            "",
814            Ok(global.as_global(&[])),
815            vec![ScopedServers {
816                domain: "corp.example".into(),
817                servers: Ok(vec![scoped.at]),
818            }],
819        );
820
821        assert_eq!(
822            resolver.resolve("host.corp.example").await,
823            vec![v4("198.51.100.20")]
824        );
825        assert!(
826            global.asked().iter().all(|q| !q.contains("corp.example")),
827            "the scoped name reached the global server: {:?}",
828            global.asked()
829        );
830
831        assert_eq!(
832            resolver.resolve("www.example").await,
833            vec![v4("203.0.113.80")]
834        );
835        assert!(
836            scoped.asked().iter().all(|q| !q.contains("www.example")),
837            "a global name reached the scoped server: {:?}",
838            scoped.asked()
839        );
840    }
841
842    /// With no DNS server configured, the hosts file still answers, and a name
843    /// that needed a server comes back empty with a warning saying why.
844    ///
845    /// A host-only lab VM often has a `resolv.conf` with no name server; its
846    /// hosts file is then the only way its boxes have names at all.
847    #[test]
848    fn the_hosts_file_answers_when_no_dns_server_is_configured() {
849        let resolver = resolver_over(
850            "198.51.100.5 hostsonly\n",
851            Err("no nameservers found in config".into()),
852            Vec::new(),
853        );
854        let runtime = tokio::runtime::Builder::new_current_thread()
855            .enable_all()
856            .build()
857            .expect("a runtime builds");
858
859        let (mut listed, mut global) = (Vec::new(), Vec::new());
860        let lines = logged(|| {
861            listed = runtime.block_on(resolver.resolve("hostsonly"));
862            global = runtime.block_on(resolver.resolve("www.example"));
863        });
864
865        assert_eq!(listed, vec![v4("198.51.100.5")]);
866        assert_eq!(global, Vec::<IpAddr>::new());
867        assert!(
868            lines
869                .iter()
870                .any(|l| l.verbosity == 0 && l.message.contains("no DNS server configured")),
871            "{lines:?}"
872        );
873    }
874
875    /// One resolver kept across passes sees a hosts line added after it was
876    /// built, and asks again for a name DNS did not answer before.
877    ///
878    /// A long-lived front end sees a box come up, its line go into the hosts
879    /// file or its record into DNS, and then scans it. A resolver holding the
880    /// file it read at construction, or a cached failure, would miss the box
881    /// until the front end restarted.
882    #[tokio::test]
883    async fn a_kept_resolver_sees_names_that_appeared_after_it_was_built() {
884        let dns = FakeDns::start(&[]).await;
885        let hosts = Arc::new(Mutex::new(String::new()));
886        let global = dns.as_global(&[]);
887        let file = Arc::clone(&hosts);
888        let resolver = Resolver::given(no_mdns(), move || {
889            (
890                file.lock().expect("unpoisoned").clone(),
891                DnsConfig {
892                    global: Ok(global.clone()),
893                    scoped: Vec::new(),
894                },
895            )
896        });
897
898        assert_eq!(
899            resolver.resolve("newbox.example").await,
900            Vec::<IpAddr>::new()
901        );
902        assert_eq!(
903            resolver.resolve("record.example").await,
904            Vec::<IpAddr>::new()
905        );
906
907        *hosts.lock().expect("unpoisoned") = "198.51.100.44 newbox.example\n".into();
908        dns.add("record.example", Ipv4Addr::new(198, 51, 100, 45));
909
910        assert_eq!(
911            resolver.resolve("record.example").await,
912            vec![v4("198.51.100.45")]
913        );
914        assert_eq!(
915            resolver.resolve("newbox.example").await,
916            vec![v4("198.51.100.44")]
917        );
918    }
919
920    // ── Where an address is answered ────────────────────────────────────────
921
922    /// An address under a scoped reverse zone is asked of that zone's server
923    /// alone, and any other address of the global one.
924    ///
925    /// A VPN that serves the reverse zone of its addresses installs a scoped
926    /// resolver for it, as it does for its domain. Asked of the global resolver,
927    /// the PTR fails and tells a resolver outside the VPN which private address
928    /// the scan found.
929    #[tokio::test]
930    async fn an_address_under_a_scoped_reverse_zone_is_asked_of_that_zones_server_alone() {
931        let global = FakeDns::start(&[]).await;
932        global.name(v4("203.0.113.80"), "www.example");
933        let scoped = FakeDns::start(&[]).await;
934        scoped.name(v4("198.51.100.20"), "host.corp.example");
935        let resolver = resolver_over(
936            "",
937            Ok(global.as_global(&[])),
938            vec![ScopedServers {
939                domain: "100.51.198.in-addr.arpa".into(),
940                servers: Ok(vec![scoped.at]),
941            }],
942        );
943        let snapshot = resolver.snapshot();
944
945        // The route a caller tracks silence by matches the one the lookup takes.
946        assert_eq!(
947            snapshot.reverse_route(v4("198.51.100.20")),
948            ReverseRoute::Scoped(0)
949        );
950        assert_eq!(
951            snapshot.reverse_route(v4("203.0.113.80")),
952            ReverseRoute::Global
953        );
954        assert_eq!(snapshot.reverse_route(v4("127.0.0.9")), ReverseRoute::Local);
955
956        assert_eq!(
957            snapshot.reverse(v4("198.51.100.20")).await,
958            Reverse::Named("host.corp.example.".into())
959        );
960        assert_eq!(
961            global.asked(),
962            Vec::<String>::new(),
963            "an address in the scoped zone reached the global resolver"
964        );
965
966        assert_eq!(
967            snapshot.reverse(v4("203.0.113.80")).await,
968            Reverse::Named("www.example.".into())
969        );
970        assert_eq!(
971            scoped.asked(),
972            vec!["20.100.51.198.in-addr.arpa. PTR".to_string()],
973            "an address outside the zone reached its server"
974        );
975    }
976
977    /// An address the hosts file lists is named by the first line listing it
978    /// and asked of nobody, as a name the file lists is answered forward.
979    ///
980    /// The later of two lines gives a name the rest of the system does not use,
981    /// and a query for a lab box's address tells a resolver somebody else
982    /// operates what the scan found.
983    #[tokio::test]
984    async fn an_address_the_hosts_file_lists_is_named_by_its_first_line_and_asked_of_nobody() {
985        let global = FakeDns::start(&[]).await;
986        global.name(v4("198.51.100.23"), "from-dns.example");
987        let resolver = resolver_over(
988            "198.51.100.23 old-box.example\n198.51.100.23 new-box.example\n",
989            Ok(global.as_global(&[])),
990            Vec::new(),
991        );
992
993        assert_eq!(
994            resolver.snapshot().reverse(v4("198.51.100.23")).await,
995            Reverse::Listed("old-box.example".into())
996        );
997        assert_eq!(global.asked(), Vec::<String>::new());
998    }
999
1000    /// A loopback address is named by the hosts file or not at all, and never
1001    /// asked of a server.
1002    ///
1003    /// RFC 6761 keeps loopback's reverse zone off the network, and the
1004    /// `localhost` a DNS library invents for all of `127.0.0.0/8` is a name no
1005    /// line gave the address.
1006    #[tokio::test]
1007    async fn a_loopback_address_is_named_by_the_hosts_file_or_not_at_all() {
1008        let global = FakeDns::start(&[]).await;
1009        let resolver = resolver_over(
1010            "127.0.0.1 localhost\n",
1011            Ok(global.as_global(&[])),
1012            Vec::new(),
1013        );
1014        let snapshot = resolver.snapshot();
1015
1016        assert_eq!(
1017            snapshot.reverse(v4("127.0.0.1")).await,
1018            Reverse::Listed("localhost".into())
1019        );
1020        assert_eq!(snapshot.reverse(v4("127.0.0.9")).await, Reverse::Unasked);
1021        assert_eq!(snapshot.reverse(v4("::1")).await, Reverse::Unasked);
1022        assert_eq!(global.asked(), Vec::<String>::new());
1023    }
1024
1025    /// With no DNS server configured, reverse lookups say so once, as forward
1026    /// ones do, and the hosts file still names what it lists.
1027    ///
1028    /// A lab VM with no name server in `resolv.conf` names its boxes only in its
1029    /// hosts file. Silence would leave every other host unnamed with no sign of
1030    /// why, and a warning per host would bury the scan.
1031    #[test]
1032    fn with_no_dns_server_configured_reverse_lookups_say_so_once() {
1033        let resolver = resolver_over(
1034            "198.51.100.5 hostsonly\n",
1035            Err("no nameservers found in config".into()),
1036            Vec::new(),
1037        );
1038        let runtime = tokio::runtime::Builder::new_current_thread()
1039            .enable_all()
1040            .build()
1041            .expect("a runtime builds");
1042
1043        let mut answers = Vec::new();
1044        let lines = logged(|| {
1045            let snapshot = resolver.snapshot();
1046            for ip in ["198.51.100.5", "198.51.100.6", "198.51.100.7"] {
1047                answers.push(runtime.block_on(snapshot.reverse(v4(ip))));
1048            }
1049        });
1050
1051        assert_eq!(
1052            answers,
1053            vec![
1054                Reverse::Listed("hostsonly".into()),
1055                Reverse::Unasked,
1056                Reverse::Unasked
1057            ]
1058        );
1059        let said: Vec<_> = lines
1060            .iter()
1061            .filter(|l| l.verbosity == 0 && l.message.contains("no DNS server configured"))
1062            .collect();
1063        assert_eq!(said.len(), 1, "{lines:?}");
1064    }
1065
1066    /// A resolver confined to the hosts file answers the names it lists and
1067    /// asks nobody about any other.
1068    ///
1069    /// It is what a caller that must not send name queries resolves with: a lab
1070    /// box listed in the file is reachable without a query, and every other name
1071    /// stays on this machine.
1072    #[tokio::test]
1073    async fn a_hosts_file_only_resolver_answers_listed_names_and_asks_nobody() {
1074        let dns = FakeDns::start(&[("www.example", Ipv4Addr::new(203, 0, 113, 80))]).await;
1075        let mut resolver =
1076            resolver_over("198.51.100.9 box.htb\n", Ok(dns.as_global(&[])), Vec::new());
1077        resolver.asks = false;
1078
1079        assert_eq!(resolver.resolve("box.htb").await, vec![v4("198.51.100.9")]);
1080        for name in ["www.example", "printer.local", "nas"] {
1081            assert_eq!(resolver.resolve(name).await, Vec::<IpAddr>::new(), "{name}");
1082        }
1083        assert_eq!(dns.asked(), Vec::<String>::new());
1084    }
1085}