zond-engine 0.18.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # Forward name resolution
//!
//! Turns the names a person writes, such as `example.com`, `raspberrypi.local`
//! and `nas`, into the addresses a scan can probe. This is the half of
//! resolution that runs before a scan, deciding what it will cover. The reverse
//! half, which attaches names to hosts a scan has already found, lives in
//! [`crate::scanner::rdns`] and answers the opposite question from the same
//! sources: the hosts file first, then the server the address's reverse zone
//! is scoped to or the global ones.
//!
//! ## Where a name is answered
//!
//! [`Resolver::resolve`] routes a name by how it is resolved, not by asking the
//! caller to know, in the order the host's own lookups take:
//!
//! - The hosts file first, for every name. A name it lists is answered from it
//!   and asked of nobody, which is how a lab box with no DNS of its own gets a
//!   name, `.local` suffix or not; see `hosts` for why the engine reads it
//!   rather than its DNS client.
//! - A `.local` name is a multicast name (RFC 6762): it is resolved by asking
//!   the link over multicast DNS. A unicast lookup of one fails everywhere the
//!   host has no mDNS-aware resolver, which on Linux is the common case, so the
//!   engine speaks mDNS itself rather than hoping the system does. The
//!   exception is a `.local` domain a unicast server is configured to answer
//!   for, as an Active Directory domain named `corp.local` is: that name is
//!   asked of the server first, and of the link only if it has no answer.
//! - Any other name goes to unicast DNS as the host has it configured: to the
//!   server a scoped resolver names for its domain, where the host has one, and
//!   otherwise to the global resolvers with the host's own search domains.
//! - A single-label name (`nas`) is tried unicast first, and if nothing answers
//!   and mDNS is enabled, again as `nas.local`, which on a home network is often
//!   what the author meant by it.
//!
//! The hosts file and the resolver configuration are read afresh at every
//! resolution pass, so a front end that runs for hours resolves a name the way
//! the host does now, and nothing a pass learned, a failure included, is kept
//! for the next.
//!
//! Every lookup leaves by the routing table. A scan forced to a source pins its
//! probes and connections, not the questions asked before it starts; see
//! [`ZondConfig::send_source`](crate::config::ZondConfig::send_source).
//!
//! ## Why a resolver, and not just the hook
//!
//! [`crate::model::parse`] already has the seam a name passes through: a
//! [`HostLookup`](crate::model::parse::target::HostLookup) supplied in a
//! [`TargetContext`](crate::model::parse::target::TargetContext). What it does
//! not have is anything to fill it with, because resolving a name means speaking
//! DNS and mDNS, which a target grammar must not do on its own behalf. This
//! module is what fills it, and it does so without the parse layer learning
//! anything about DNS: the engine resolves the names and hands the answers in.
//!
//! ## The synchronous seam, and the two passes
//!
//! That hook is synchronous, called once per name while a target expression is
//! parsed, and resolution is asynchronous and slow, mDNS especially so. Blocking
//! inside the hook would turn a file of two hundred
//! names into two hundred sequential round trips. So resolution is done in two
//! passes, and this module ships both rather than describing them:
//!
//! 1. [`resolve_names`] finds every name in a set of target expressions and
//!    resolves them concurrently into a map.
//! 2. [`to_target_map`] and [`to_set`] then build with a hook that reads the
//!    map, so the parse itself never waits on the network.
//!
//! A caller that only needs one name resolved can reach for [`Resolver::resolve`]
//! directly; a caller assembling a scan wants [`to_target_map`] or [`to_set`],
//! which do the whole of it.
//!
//! ## What it does not decide
//!
//! Whether a scan is allowed to resolve at all, which is what
//! [`ZondConfig::no_dns`](crate::config::ZondConfig::no_dns) means at request
//! time, is the caller's policy rather than this module's. A front end that
//! must not emit name queries resolves with [`Resolver::hosts_file_only`],
//! which answers the names the hosts file lists and sends nothing, so a lab
//! box listed there is still a target; a name the file does not list is then
//! an unknown host. One that supplies no resolver at all has every name
//! refused with
//! [`NoHostLookup`](crate::model::parse::target::TargetParseError::NoHostLookup)
//! rather than covering less than its input said.

mod hosts;
mod links;
mod mdns;
mod targets;
mod unicast;

pub use links::{LinkError, for_listening, for_listening_on};
#[cfg(feature = "import-request")]
pub(crate) use targets::for_request;
pub use targets::{
    DiscoveryTargets, PortScanTargets, for_discovery, for_discovery_with, for_exclusion,
    for_exclusion_with, for_port_scan, resolve_names, to_set, to_target_map,
};

use std::fmt;
use std::net::IpAddr;
use std::time::Duration;

use crate::warn;

pub(crate) use hosts::HostsTable;
pub(crate) use unicast::{DnsConfig, Reverse, ScopedServers, Unicast, covers, reverse_name};

/// The default mDNS reply window. See [`ResolveConfig::mdns_timeout`] for why it
/// is a whole second.
const DEFAULT_MDNS_TIMEOUT: Duration = Duration::from_secs(1);

/// The shortest window that can hear a conformant responder.
///
/// RFC 6762 §6.3 permits a responder to defer a reply by up to half a second so
/// it can aggregate answers, so a window below that closes while a correct
/// implementation is still waiting to speak. A caller asking for less has asked
/// for a lookup that cannot succeed, and gets this instead: unlike the scan
/// settings in [`ZondConfig`](crate::config::ZondConfig), nothing here is
/// carried into a report, so raising a window costs nobody a record that says
/// one thing while the run did another.
const MIN_MDNS_TIMEOUT: Duration = Duration::from_millis(500);

/// How a [`Resolver`] behaves, independent of the host it reads its unicast
/// configuration from.
///
/// Non-exhaustive and [`Default`]-constructed, like
/// [`ZondConfig`](crate::config::ZondConfig): the next thing worth saying about
/// how a name is resolved is an additive change rather than a major version.
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub struct ResolveConfig {
    /// Whether `.local` names are resolved over multicast, and whether a
    /// single-label name falls back to one.
    ///
    /// Off leaves a `.local` name to the hosts file and to a unicast server
    /// configured for its domain, rather than sending it to one that will
    /// answer NXDOMAIN for it. For an environment where multicast is filtered
    /// or unwanted, or where the only names in play are global.
    pub mdns: bool,

    /// How long to listen for mDNS replies before accepting that a `.local`
    /// name has no answer on the segment.
    ///
    /// A responder may defer a reply by up to half a second to aggregate
    /// answers (RFC 6762 §6.3), and one on a busy or sleepy device can take
    /// longer, so the default is a whole second: short enough not to stall a
    /// scan, long enough that a device answering slowly is found rather than
    /// declared absent.
    ///
    /// A window shorter than the half second the RFC permits is raised to it.
    /// Below that the lookup cannot hear a correct responder at all, so it is a
    /// preference the protocol overrules rather than a value to refuse: zero,
    /// taken as written, would produce a listener that closes before it opens.
    pub mdns_timeout: Duration,
}

impl Default for ResolveConfig {
    fn default() -> Self {
        Self {
            mdns: true,
            mdns_timeout: DEFAULT_MDNS_TIMEOUT,
        }
    }
}

/// Resolves names to addresses from the hosts file, unicast DNS and multicast
/// DNS.
///
/// Holds no state of the host's: the hosts file and the resolver
/// configuration are read at each resolution pass, so one resolver kept for
/// the life of a front end resolves as the host does at the time. Cheap to
/// clone, and shared across the concurrent lookups [`resolve_names`] runs.
#[derive(Clone)]
pub struct Resolver {
    origin: Origin,
    config: ResolveConfig,
    /// Whether a lookup may put a question on the network, unicast or
    /// multicast, or is answered from the hosts file alone.
    asks: bool,
}

/// Where a resolver reads what the host says about names.
#[derive(Clone)]
enum Origin {
    /// The system's hosts file and resolver configuration.
    System,
    /// Given in their place, so a test decides what a pass reads and which
    /// servers it may ask, and no query leaves the machine.
    #[cfg(test)]
    Given(std::sync::Arc<dyn Fn() -> (String, DnsConfig) + Send + Sync>),
}

/// What the host says about names at one moment: the hosts file and the
/// unicast servers, read once and shared by every lookup of a pass.
pub(crate) struct Snapshot {
    hosts: HostsTable,
    /// `None` for a resolver that asks nobody, which reads no server
    /// configuration either.
    unicast: Option<Unicast>,
}

impl Resolver {
    /// Builds a resolver from the host's own configuration, with mDNS
    /// enabled.
    ///
    /// A host whose resolver configuration cannot be read, as in a container
    /// or a lab VM with no name server in `resolv.conf`, still resolves: names
    /// in its hosts file and `.local` names answer as ever, and a name that
    /// needed a DNS server comes back empty, with a warning saying why. A
    /// scan that resolves fewer names is still a scan.
    pub fn from_system() -> Self {
        Self::with_config(ResolveConfig::default())
    }

    /// Builds a resolver with an explicit [`ResolveConfig`].
    pub fn with_config(config: ResolveConfig) -> Self {
        Self {
            origin: Origin::System,
            config,
            asks: true,
        }
    }

    /// Builds a resolver that answers from the host's hosts file alone and
    /// puts nothing on the network: no unicast query and no multicast one.
    ///
    /// For a caller forbidden to send name queries, as a scan under
    /// [`ZondConfig::no_dns`](crate::config::ZondConfig::no_dns) is. Reading
    /// the file sends nothing, and it is where a lab box reached over a VPN
    /// gets its name, so refusing every name would refuse the one kind a
    /// caller avoiding leaks can resolve without one. A name the file does
    /// not list resolves to nothing, which the target functions report as an
    /// unknown host rather than asking anybody about it.
    pub fn hosts_file_only() -> Self {
        Self {
            origin: Origin::System,
            config: ResolveConfig::default(),
            asks: false,
        }
    }

    /// A resolver reading the hosts file text and unicast configuration
    /// `read` returns, at each pass, instead of the system's.
    #[cfg(test)]
    pub(crate) fn given(
        config: ResolveConfig,
        read: impl Fn() -> (String, DnsConfig) + Send + Sync + 'static,
    ) -> Self {
        Self {
            origin: Origin::Given(std::sync::Arc::new(read)),
            config,
            asks: true,
        }
    }

    /// Reads what the host says about names now, for one resolution pass.
    ///
    /// A caller resolving many names reads it once and resolves them all
    /// against it with [`resolve_in`](Self::resolve_in), so every name in a
    /// target list sees the same file and the same servers.
    pub(crate) fn snapshot(&self) -> Snapshot {
        let (hosts, dns) = match &self.origin {
            Origin::System => (
                HostsTable::read_system(),
                self.asks.then(DnsConfig::read_system),
            ),
            #[cfg(test)]
            Origin::Given(read) => {
                let (hosts, dns) = read();
                (HostsTable::parse(&hosts), self.asks.then_some(dns))
            }
        };
        Snapshot {
            hosts,
            unicast: dns.map(Unicast::from_config),
        }
    }

    /// Resolves one name to every address it stands for, in first-seen order.
    ///
    /// An empty result means nothing answered for the name, which a caller treats
    /// the same as a name that resolved to nothing, since both are a target that
    /// is not there. Routing is by name: see the module documentation for where
    /// each kind is answered. Reads the host's configuration for this one name;
    /// a caller with many wants [`resolve_names`], which reads it once.
    pub async fn resolve(&self, name: &str) -> Vec<IpAddr> {
        self.resolve_in(&self.snapshot(), name).await
    }

    /// [`resolve`](Self::resolve), against a configuration already read.
    pub(crate) async fn resolve_in(&self, snapshot: &Snapshot, name: &str) -> Vec<IpAddr> {
        let name = name.trim_end_matches('.');

        if let Some(listed) = from_hosts(snapshot, name) {
            return listed;
        }
        let Some(unicast) = &snapshot.unicast else {
            return Vec::new();
        };

        if is_multicast_local(name) {
            return self.resolve_local(unicast, name).await;
        }

        let answered = unicast.lookup(name).await;
        if !answered.is_empty() || !is_single_label(name) {
            return answered;
        }

        // A bare `nas` that unicast could not place is, on a home or office
        // segment, most often `nas.local`. Tried only after unicast so a real
        // search-domain match is never shadowed by a multicast one.
        let local = format!("{name}.local");
        if let Some(listed) = from_hosts(snapshot, &local) {
            return listed;
        }
        self.resolve_local(unicast, &local).await
    }

    /// A `.local` name the hosts file does not list: unicast first when a
    /// configured server answers for its domain, then the link.
    async fn resolve_local(&self, unicast: &Unicast, name: &str) -> Vec<IpAddr> {
        if unicast.claims(name) {
            let unicast = unicast.lookup(name).await;
            if !unicast.is_empty() {
                return unicast;
            }
        }
        self.resolve_mdns(name).await
    }

    /// The multicast half, honouring the config's mDNS switch.
    async fn resolve_mdns(&self, name: &str) -> Vec<IpAddr> {
        if !self.config.mdns {
            return Vec::new();
        }
        let window = self.config.mdns_timeout.max(MIN_MDNS_TIMEOUT);
        mdns::resolve(name, window).await
    }
}

impl Snapshot {
    /// Resolves `ip` back to a name from the same sources, and by the same
    /// routes, a name is resolved forward.
    ///
    /// The hosts file first, and alone for an address it lists: it is
    /// authoritative in both directions, and a lab box's address asked of a
    /// resolver somebody else operates tells them what was found. A loopback
    /// address it does not list is asked of nobody, since RFC 6761 section
    /// 6.3 has its reverse zone answered on the machine rather than sent to a
    /// server, and the answer a library makes up for it, `localhost` for every
    /// address in `127.0.0.0/8`, names nothing the hosts file said. Anything
    /// else goes to the server its reverse zone is scoped to, or the global
    /// ones; see [`Unicast::reverse`].
    pub(crate) async fn reverse(&self, ip: IpAddr) -> Reverse {
        if let Some(name) = self.hosts.name_of(ip) {
            return Reverse::Listed(name.to_owned());
        }
        match (&self.unicast, self.reverse_route(ip)) {
            (Some(unicast), ReverseRoute::Scoped(_) | ReverseRoute::Global) => {
                unicast.reverse(ip).await
            }
            _ => Reverse::Unasked,
        }
    }

    /// Which way [`reverse`](Self::reverse) takes `ip`, decided without
    /// asking anything.
    ///
    /// For a caller that must tell one server's silence from another's: a
    /// global resolver that answers nothing says nothing about the server a
    /// VPN scopes to its own reverse zone, and giving up on both at once
    /// leaves every address under that zone unnamed.
    pub(crate) fn reverse_route(&self, ip: IpAddr) -> ReverseRoute {
        match &self.unicast {
            _ if self.hosts.name_of(ip).is_some() => ReverseRoute::Local,
            Some(unicast) if !ip.is_loopback() => unicast
                .reverse_scope(ip)
                .map_or(ReverseRoute::Global, ReverseRoute::Scoped),
            _ => ReverseRoute::Local,
        }
    }
}

/// The way a reverse lookup of one address goes; see
/// [`Snapshot::reverse_route`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ReverseRoute {
    /// Answered on the machine or not at all: from the hosts file, for a
    /// loopback address, or on a host with no server to ask.
    Local,
    /// The resolver scoped to a reverse zone, by its place among them.
    Scoped(usize),
    /// The global resolvers.
    Global,
}

/// What the hosts file answers for `name`, saying so when a later line for it
/// goes unused.
///
/// Said at the default verbosity because it changes what is scanned: a stale
/// line left above a new one for the same box sends the scan to the old
/// address, and only the user can say which line is right.
fn from_hosts(snapshot: &Snapshot, name: &str) -> Option<Vec<IpAddr>> {
    let answer = snapshot.hosts.lookup(name)?;
    for unused in &answer.shadowed {
        warn!("{name}: hosts line for {unused} ignored (earlier line wins)");
    }
    Some(answer.addresses)
}

impl fmt::Debug for Resolver {
    /// Says what this resolver reads and whether multicast is on, which with
    /// the host's own configuration decide where a name goes.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let origin = match self.origin {
            Origin::System => "system",
            #[cfg(test)]
            Origin::Given(_) => "given",
        };
        f.debug_struct("Resolver")
            .field("origin", &origin)
            .field("config", &self.config)
            .field("asks", &self.asks)
            .finish()
    }
}

/// Whether `name` is resolved over multicast: a multi-label name whose last
/// label is `local`.
///
/// A bare `local` is not one. It is a single-label name the fallback path may try
/// as `local.local`, rather than a `.local` host in its own right.
fn is_multicast_local(name: &str) -> bool {
    name.contains('.')
        && name
            .rsplit('.')
            .next()
            .is_some_and(|tld| tld.eq_ignore_ascii_case("local"))
}

/// Whether `name` is a single label, and so a candidate for the `.local`
/// fallback once unicast has had its say.
fn is_single_label(name: &str) -> bool {
    !name.is_empty() && !name.contains('.')
}

// ╔════════════════════════════════════════════╗
// ║ ████████╗███████╗███████╗████████╗███████╗ ║
// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
// ║    ██║   ███████╗███████║   ██║   ███████║ ║
// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
// ╚════════════════════════════════════════════╝

#[cfg(test)]
mod tests {
    use super::*;

    /// The routing predicate decides which protocol a name is resolved by, so a
    /// misclassification sends a `.local` host to a unicast server that cannot
    /// answer for it, or a global name to a multicast group that will not.
    #[test]
    fn only_a_dotted_local_name_is_a_multicast_name() {
        assert!(is_multicast_local("raspberrypi.local"));
        assert!(is_multicast_local("Printer.LOCAL"));
        assert!(is_multicast_local("host.sub.local"));

        assert!(!is_multicast_local("example.com"));
        assert!(!is_multicast_local("localhost"));
        // A bare `local` has no host part; it is a short name, not a `.local`
        // one.
        assert!(!is_multicast_local("local"));
    }

    /// A window too short to hear a conformant responder is raised to one that
    /// can, rather than producing a lookup that closes before it opens.
    ///
    /// RFC 6762 §6.3 lets a responder defer a reply half a second to aggregate
    /// answers, so half a second is the floor the protocol sets. Zero, taken as
    /// written, would reach the listener that way.
    ///
    /// Raised rather than refused, unlike the overrides in
    /// [`RetryConfig`](crate::config::RetryConfig): nothing in a
    /// [`ResolveConfig`] is carried into a report, so a window the engine
    /// overrules costs nobody a record claiming a run did something it did not.
    #[test]
    fn a_window_shorter_than_the_protocol_allows_is_raised_to_it() {
        for asked in [Duration::ZERO, Duration::from_millis(1), MIN_MDNS_TIMEOUT] {
            assert_eq!(asked.max(MIN_MDNS_TIMEOUT), MIN_MDNS_TIMEOUT);
        }

        // A window the caller meant is the window they get.
        let generous = Duration::from_secs(5);
        assert_eq!(generous.max(MIN_MDNS_TIMEOUT), generous);
        assert_eq!(
            DEFAULT_MDNS_TIMEOUT.max(MIN_MDNS_TIMEOUT),
            DEFAULT_MDNS_TIMEOUT,
            "the default is above the floor, or the floor is the default"
        );
    }

    /// A resolver says what it reads and whether multicast is on, which is
    /// what a caller debugging a resolution needs from it.
    #[test]
    fn a_resolver_reports_what_it_reads_and_whether_multicast_is_on() {
        let rendered = format!("{:?}", Resolver::with_config(ResolveConfig::default()));

        assert!(rendered.starts_with("Resolver"), "{rendered}");
        assert!(rendered.contains("origin: \"system\""), "{rendered}");
        assert!(rendered.contains("mdns: true"), "{rendered}");
    }

    #[test]
    fn a_single_label_is_a_fallback_candidate_and_a_dotted_name_is_not() {
        assert!(is_single_label("nas"));
        assert!(!is_single_label("nas.local"));
        assert!(!is_single_label("example.com"));
        assert!(!is_single_label(""));
    }

    // ── Where a name is answered ────────────────────────────────────────────
    //
    // Each test below hands a resolver its hosts file and its servers, and the
    // servers are fakes on loopback, so what a lookup asks, and of whom, is
    // observed rather than sent anywhere. mDNS is off throughout: a `.local`
    // name that reached the link would be a multicast packet leaving the test.

    use std::collections::HashMap;
    use std::net::{Ipv4Addr, SocketAddr};
    use std::sync::{Arc, Mutex};

    use hickory_resolver::config::{NameServerConfig, ResolverConfig, ResolverOpts};
    use hickory_resolver::proto::op::{Message, MessageType, ResponseCode};
    use hickory_resolver::proto::rr::rdata::{A, PTR, SOA};
    use hickory_resolver::proto::rr::{Name, RData, Record, RecordType};

    use crate::logging::logged;
    use unicast::ScopedServers;

    /// A name server on loopback that answers A queries for the names it
    /// holds, PTR queries for the addresses it names, and NXDOMAIN for any
    /// other, noting every question it is asked.
    ///
    /// Its NXDOMAIN carries the zone's SOA, as a real server's does, because
    /// that is what lets a client cache the failure: an answer without one
    /// would hide a client that holds failures across passes.
    struct FakeDns {
        at: SocketAddr,
        records: Arc<Mutex<HashMap<String, Ipv4Addr>>>,
        /// Hostnames keyed by the reverse name a PTR query asks.
        names: Arc<Mutex<HashMap<String, String>>>,
        asked: Arc<Mutex<Vec<String>>>,
        serving: tokio::task::JoinHandle<()>,
    }

    impl FakeDns {
        async fn start(records: &[(&str, Ipv4Addr)]) -> Self {
            let socket = tokio::net::UdpSocket::bind("127.0.0.1:0")
                .await
                .expect("a loopback socket binds");
            let at = socket.local_addr().expect("a bound socket has an address");
            let records = Arc::new(Mutex::new(
                records
                    .iter()
                    .map(|(name, ip)| (format!("{name}."), *ip))
                    .collect::<HashMap<_, _>>(),
            ));
            let asked = Arc::new(Mutex::new(Vec::new()));
            let names = Arc::new(Mutex::new(HashMap::new()));

            let (held, noted) = (Arc::clone(&records), Arc::clone(&asked));
            let reverse = Arc::clone(&names);
            let serving = tokio::spawn(async move {
                let mut buf = [0u8; 1500];
                while let Ok((len, from)) =
                    crate::testing::loopback::recv_from_this_process(&socket, &mut buf).await
                {
                    let Ok(query) = Message::from_vec(&buf[..len]) else {
                        continue;
                    };
                    let Some(question) = query.queries.first().cloned() else {
                        continue;
                    };
                    let name = question.name().to_ascii().to_ascii_lowercase();
                    noted
                        .lock()
                        .expect("unpoisoned")
                        .push(format!("{name} {}", question.query_type()));

                    let known = held.lock().expect("unpoisoned").get(&name).copied();
                    let named = reverse.lock().expect("unpoisoned").get(&name).cloned();
                    let mut reply = Message::response(query.metadata.id, query.metadata.op_code);
                    reply.metadata.message_type = MessageType::Response;
                    reply.metadata.recursion_desired = query.metadata.recursion_desired;
                    reply.metadata.recursion_available = true;
                    reply.add_query(question.clone());
                    match known {
                        _ if question.query_type() == RecordType::PTR && named.is_some() => {
                            let host = named.expect("checked above");
                            reply.add_answer(Record::from_rdata(
                                question.name().clone(),
                                300,
                                RData::PTR(PTR(Name::from_ascii(&host).expect("a host name"))),
                            ));
                        }
                        Some(ip) if question.query_type() == RecordType::A => {
                            reply.add_answer(Record::from_rdata(
                                question.name().clone(),
                                300,
                                RData::A(A(ip)),
                            ));
                        }
                        Some(_) => {}
                        None => {
                            reply.metadata.response_code = ResponseCode::NXDomain;
                            let zone = Name::from_ascii("example.").expect("a zone name");
                            let soa =
                                SOA::new(zone.clone(), zone.clone(), 1, 3600, 600, 86400, 3600);
                            reply.add_authority(Record::from_rdata(zone, 3600, RData::SOA(soa)));
                        }
                    }
                    let bytes = reply.to_vec().expect("a reply encodes");
                    let _ = socket.send_to(&bytes, from).await;
                }
            });

            Self {
                at,
                records,
                names,
                asked,
                serving,
            }
        }

        /// Starts answering a reverse lookup of `ip` with `host`.
        fn name(&self, ip: IpAddr, host: &str) {
            self.names
                .lock()
                .expect("unpoisoned")
                .insert(format!("{}.", reverse_name(ip)), format!("{host}."));
        }

        /// The questions this server has been asked, as `name. TYPE`.
        fn asked(&self) -> Vec<String> {
            self.asked.lock().expect("unpoisoned").clone()
        }

        /// Starts answering for `name`.
        fn add(&self, name: &str, ip: Ipv4Addr) {
            self.records
                .lock()
                .expect("unpoisoned")
                .insert(format!("{name}."), ip);
        }

        /// A global configuration naming this server, with `search` as its
        /// search list.
        fn as_global(&self, search: &[&str]) -> (ResolverConfig, ResolverOpts) {
            let mut server = NameServerConfig::udp(self.at.ip());
            for connection in &mut server.connections {
                connection.port = self.at.port();
            }
            let search = search
                .iter()
                .map(|s| s.parse().expect("a search domain parses"))
                .collect();
            let mut opts = ResolverOpts::default();
            opts.attempts = 1;
            (ResolverConfig::from_parts(None, search, vec![server]), opts)
        }
    }

    impl Drop for FakeDns {
        fn drop(&mut self) {
            self.serving.abort();
        }
    }

    fn no_mdns() -> ResolveConfig {
        ResolveConfig {
            mdns: false,
            ..ResolveConfig::default()
        }
    }

    fn v4(s: &str) -> IpAddr {
        s.parse().expect("a test address parses")
    }

    /// A resolver reading `hosts`, asking `global`, and asking `scoped` for
    /// the names under their domains.
    fn resolver_over(
        hosts: &str,
        global: Result<(ResolverConfig, ResolverOpts), String>,
        scoped: Vec<ScopedServers>,
    ) -> Resolver {
        let hosts = hosts.to_owned();
        Resolver::given(no_mdns(), move || {
            (
                hosts.clone(),
                DnsConfig {
                    global: global.clone(),
                    scoped: scoped.clone(),
                },
            )
        })
    }

    /// A name the hosts file lists is answered from it and asked of no server,
    /// in either family.
    ///
    /// The file lists an A address; a lookup that consulted it per record type
    /// would still ask upstream for AAAA, telling a resolver somebody else
    /// operates which lab box is being scanned, and on a network where that
    /// resolver is unreachable, waiting out its whole timeout first.
    #[tokio::test]
    async fn a_name_the_hosts_file_lists_is_answered_without_asking_dns() {
        let dns = FakeDns::start(&[]).await;
        let resolver = resolver_over(
            "198.51.100.7 box.example\n",
            Ok(dns.as_global(&[])),
            Vec::new(),
        );

        assert_eq!(
            resolver.resolve("box.example").await,
            vec![v4("198.51.100.7")]
        );
        assert_eq!(
            dns.asked(),
            Vec::<String>::new(),
            "the hosts name reached DNS"
        );
    }

    /// Of two hosts lines for one name, the first is scanned and the second is
    /// named in a warning.
    ///
    /// An old box and its replacement both left in the file is the usual way a
    /// name gets two lines, and scanning both covers a host nobody meant; the
    /// warning is what lets the user delete the right one.
    #[test]
    fn a_stale_hosts_line_for_a_name_is_neither_scanned_nor_silent() {
        let resolver = resolver_over(
            "198.51.100.23 box.example\n198.51.100.99 box.example\n",
            Err("none configured".into()),
            Vec::new(),
        );
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("a runtime builds");

        let mut resolved = Vec::new();
        let lines = logged(|| resolved = runtime.block_on(resolver.resolve("box.example")));

        assert_eq!(resolved, vec![v4("198.51.100.23")]);
        let warned: Vec<_> = lines.iter().filter(|l| l.verbosity == 0).collect();
        assert!(
            warned
                .iter()
                .any(|l| l.message.contains("box.example") && l.message.contains("198.51.100.99")),
            "no default-verbosity line names the unused address: {lines:?}"
        );
    }

    /// A `.local` name the hosts file lists resolves from it, as it does for
    /// `ping` and `ssh`.
    ///
    /// Lab domains such as `htb.local` exist only as hosts lines on the
    /// attacker's machine; asking the link for them finds nothing.
    #[tokio::test]
    async fn a_local_name_the_hosts_file_lists_resolves_from_it() {
        let resolver = resolver_over(
            "198.51.100.161 forest.corp.local corp.local\n",
            Err("none configured".into()),
            Vec::new(),
        );

        for name in ["forest.corp.local", "corp.local"] {
            assert_eq!(
                resolver.resolve(name).await,
                vec![v4("198.51.100.161")],
                "{name}"
            );
        }
    }

    /// A `.local` name under a domain the host's search list names is asked of
    /// unicast DNS, and one under no configured domain is not.
    ///
    /// An Active Directory domain named `corp.local` is answered by its domain
    /// controller, and a host joined to it searches that domain; a `.local`
    /// name nothing configured claims is a name on the link, and a unicast
    /// server asked about it only learns what the link holds.
    #[tokio::test]
    async fn a_local_name_under_a_searched_domain_is_asked_of_unicast_dns() {
        let dns = FakeDns::start(&[("dc01.corp.local", Ipv4Addr::new(198, 51, 100, 10))]).await;
        let resolver = resolver_over("", Ok(dns.as_global(&["corp.local"])), Vec::new());

        assert_eq!(
            resolver.resolve("dc01.corp.local").await,
            vec![v4("198.51.100.10")]
        );

        let before = dns.asked().len();
        assert_eq!(
            resolver.resolve("printer.local").await,
            Vec::<IpAddr>::new()
        );
        assert_eq!(
            dns.asked().len(),
            before,
            "a link-only name reached unicast DNS"
        );
    }

    /// A name under a scoped resolver's domain is asked of that domain's server
    /// alone, and any other name of the global one.
    ///
    /// A VPN's match domain is served by the VPN's resolver: the global one
    /// cannot answer for it, and asking it would put a name from inside the
    /// private network on the public path.
    #[tokio::test]
    async fn a_name_under_a_scoped_domain_is_asked_of_that_domains_server_alone() {
        let global = FakeDns::start(&[("www.example", Ipv4Addr::new(203, 0, 113, 80))]).await;
        let scoped =
            FakeDns::start(&[("host.corp.example", Ipv4Addr::new(198, 51, 100, 20))]).await;
        let resolver = resolver_over(
            "",
            Ok(global.as_global(&[])),
            vec![ScopedServers {
                domain: "corp.example".into(),
                servers: Ok(vec![scoped.at]),
            }],
        );

        assert_eq!(
            resolver.resolve("host.corp.example").await,
            vec![v4("198.51.100.20")]
        );
        assert!(
            global.asked().iter().all(|q| !q.contains("corp.example")),
            "the scoped name reached the global server: {:?}",
            global.asked()
        );

        assert_eq!(
            resolver.resolve("www.example").await,
            vec![v4("203.0.113.80")]
        );
        assert!(
            scoped.asked().iter().all(|q| !q.contains("www.example")),
            "a global name reached the scoped server: {:?}",
            scoped.asked()
        );
    }

    /// With no DNS server configured, the hosts file still answers, and a name
    /// that needed a server comes back empty with a warning saying why.
    ///
    /// A host-only lab VM often has a `resolv.conf` with no name server; its
    /// hosts file is then the only way its boxes have names at all.
    #[test]
    fn the_hosts_file_answers_when_no_dns_server_is_configured() {
        let resolver = resolver_over(
            "198.51.100.5 hostsonly\n",
            Err("no nameservers found in config".into()),
            Vec::new(),
        );
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("a runtime builds");

        let (mut listed, mut global) = (Vec::new(), Vec::new());
        let lines = logged(|| {
            listed = runtime.block_on(resolver.resolve("hostsonly"));
            global = runtime.block_on(resolver.resolve("www.example"));
        });

        assert_eq!(listed, vec![v4("198.51.100.5")]);
        assert_eq!(global, Vec::<IpAddr>::new());
        assert!(
            lines
                .iter()
                .any(|l| l.verbosity == 0 && l.message.contains("no DNS server configured")),
            "{lines:?}"
        );
    }

    /// One resolver kept across passes sees a hosts line added after it was
    /// built, and asks again for a name DNS did not answer before.
    ///
    /// The loop a long-lived front end serves is: a box comes up, its line goes
    /// into the hosts file or its record into DNS, and the scan runs. A
    /// resolver holding the file it read at construction, or a cached failure,
    /// would miss the box until the front end restarted.
    #[tokio::test]
    async fn a_kept_resolver_sees_names_that_appeared_after_it_was_built() {
        let dns = FakeDns::start(&[]).await;
        let hosts = Arc::new(Mutex::new(String::new()));
        let global = dns.as_global(&[]);
        let file = Arc::clone(&hosts);
        let resolver = Resolver::given(no_mdns(), move || {
            (
                file.lock().expect("unpoisoned").clone(),
                DnsConfig {
                    global: Ok(global.clone()),
                    scoped: Vec::new(),
                },
            )
        });

        assert_eq!(
            resolver.resolve("newbox.example").await,
            Vec::<IpAddr>::new()
        );
        assert_eq!(
            resolver.resolve("record.example").await,
            Vec::<IpAddr>::new()
        );

        *hosts.lock().expect("unpoisoned") = "198.51.100.44 newbox.example\n".into();
        dns.add("record.example", Ipv4Addr::new(198, 51, 100, 45));

        assert_eq!(
            resolver.resolve("record.example").await,
            vec![v4("198.51.100.45")]
        );
        assert_eq!(
            resolver.resolve("newbox.example").await,
            vec![v4("198.51.100.44")]
        );
    }

    // ── Where an address is answered ────────────────────────────────────────

    /// An address under a scoped reverse zone is asked of that zone's server
    /// alone, and any other address of the global one.
    ///
    /// A VPN that serves the reverse zone of its own addresses installs a
    /// scoped resolver for it as it does for its domain. Asked of the global
    /// resolver, the PTR both fails and tells a resolver outside the VPN which
    /// private address the scan found.
    #[tokio::test]
    async fn an_address_under_a_scoped_reverse_zone_is_asked_of_that_zones_server_alone() {
        let global = FakeDns::start(&[]).await;
        global.name(v4("203.0.113.80"), "www.example");
        let scoped = FakeDns::start(&[]).await;
        scoped.name(v4("198.51.100.20"), "host.corp.example");
        let resolver = resolver_over(
            "",
            Ok(global.as_global(&[])),
            vec![ScopedServers {
                domain: "100.51.198.in-addr.arpa".into(),
                servers: Ok(vec![scoped.at]),
            }],
        );
        let snapshot = resolver.snapshot();

        // The route a caller keeps each resolver's silence by is the one the
        // lookup takes.
        assert_eq!(
            snapshot.reverse_route(v4("198.51.100.20")),
            ReverseRoute::Scoped(0)
        );
        assert_eq!(
            snapshot.reverse_route(v4("203.0.113.80")),
            ReverseRoute::Global
        );
        assert_eq!(snapshot.reverse_route(v4("127.0.0.9")), ReverseRoute::Local);

        assert_eq!(
            snapshot.reverse(v4("198.51.100.20")).await,
            Reverse::Named("host.corp.example.".into())
        );
        assert_eq!(
            global.asked(),
            Vec::<String>::new(),
            "an address in the scoped zone reached the global resolver"
        );

        assert_eq!(
            snapshot.reverse(v4("203.0.113.80")).await,
            Reverse::Named("www.example.".into())
        );
        assert_eq!(
            scoped.asked(),
            vec!["20.100.51.198.in-addr.arpa. PTR".to_string()],
            "an address outside the zone reached its server"
        );
    }

    /// An address the hosts file lists is named by the first line listing it
    /// and asked of nobody, as a name the file lists is answered forward.
    ///
    /// The later line of an old box and its replacement names a host the rest
    /// of the system does not call it, and a query for a lab box's address
    /// tells a resolver somebody else operates what the scan found.
    #[tokio::test]
    async fn an_address_the_hosts_file_lists_is_named_by_its_first_line_and_asked_of_nobody() {
        let global = FakeDns::start(&[]).await;
        global.name(v4("198.51.100.23"), "from-dns.example");
        let resolver = resolver_over(
            "198.51.100.23 old-box.example\n198.51.100.23 new-box.example\n",
            Ok(global.as_global(&[])),
            Vec::new(),
        );

        assert_eq!(
            resolver.snapshot().reverse(v4("198.51.100.23")).await,
            Reverse::Listed("old-box.example".into())
        );
        assert_eq!(global.asked(), Vec::<String>::new());
    }

    /// A loopback address is named by the hosts file or not at all, and never
    /// asked of a server.
    ///
    /// RFC 6761 keeps loopback's reverse zone off the network, and the name a
    /// DNS library makes up in its place, `localhost` for every address in
    /// `127.0.0.0/8`, is a name no line gave the address being scanned.
    #[tokio::test]
    async fn a_loopback_address_is_named_by_the_hosts_file_or_not_at_all() {
        let global = FakeDns::start(&[]).await;
        let resolver = resolver_over(
            "127.0.0.1 localhost\n",
            Ok(global.as_global(&[])),
            Vec::new(),
        );
        let snapshot = resolver.snapshot();

        assert_eq!(
            snapshot.reverse(v4("127.0.0.1")).await,
            Reverse::Listed("localhost".into())
        );
        assert_eq!(snapshot.reverse(v4("127.0.0.9")).await, Reverse::Unasked);
        assert_eq!(snapshot.reverse(v4("::1")).await, Reverse::Unasked);
        assert_eq!(global.asked(), Vec::<String>::new());
    }

    /// With no DNS server configured, reverse lookups say so once, as forward
    /// ones do, and the hosts file still names what it lists.
    ///
    /// A lab VM with no name server in `resolv.conf` has its boxes named only
    /// in its hosts file; saying nothing would leave every other host
    /// unnamed with no sign of why, and saying it per host would bury the
    /// scan under one line per address.
    #[test]
    fn with_no_dns_server_configured_reverse_lookups_say_so_once() {
        let resolver = resolver_over(
            "198.51.100.5 hostsonly\n",
            Err("no nameservers found in config".into()),
            Vec::new(),
        );
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("a runtime builds");

        let mut answers = Vec::new();
        let lines = logged(|| {
            let snapshot = resolver.snapshot();
            for ip in ["198.51.100.5", "198.51.100.6", "198.51.100.7"] {
                answers.push(runtime.block_on(snapshot.reverse(v4(ip))));
            }
        });

        assert_eq!(
            answers,
            vec![
                Reverse::Listed("hostsonly".into()),
                Reverse::Unasked,
                Reverse::Unasked
            ]
        );
        let said: Vec<_> = lines
            .iter()
            .filter(|l| l.verbosity == 0 && l.message.contains("no DNS server configured"))
            .collect();
        assert_eq!(said.len(), 1, "{lines:?}");
    }

    /// A resolver confined to the hosts file answers the names it lists and
    /// asks nobody about any other.
    ///
    /// It is what a caller forbidden to send name queries resolves with: a
    /// lab box listed in the file is a target it can reach without a query,
    /// and every other name staying on this machine is the whole promise.
    #[tokio::test]
    async fn a_hosts_file_only_resolver_answers_listed_names_and_asks_nobody() {
        let dns = FakeDns::start(&[("www.example", Ipv4Addr::new(203, 0, 113, 80))]).await;
        let mut resolver =
            resolver_over("198.51.100.9 box.htb\n", Ok(dns.as_global(&[])), Vec::new());
        resolver.asks = false;

        assert_eq!(resolver.resolve("box.htb").await, vec![v4("198.51.100.9")]);
        for name in ["www.example", "printer.local", "nas"] {
            assert_eq!(resolver.resolve(name).await, Vec::<IpAddr>::new(), "{name}");
        }
        assert_eq!(dns.asked(), Vec::<String>::new());
    }
}