Skip to main content

hns_dns_wire/
lib.rs

1//! Strict, runtime-independent DNS wire parsing for HNS DNSSEC and DANE.
2//!
3//! The parser bounds the packet, section counts, RDATA, labels, and compression
4//! jumps before allocation. It rejects forward, out-of-message, and cyclic
5//! compression pointers. DNS AD is exposed only as an untrusted wire claim.
6
7#![forbid(unsafe_code)]
8#![allow(
9    clippy::doc_markdown,
10    clippy::missing_errors_doc,
11    clippy::module_name_repetitions,
12    clippy::similar_names,
13    reason = "DNS acronyms and the crate-wide Error enum make repeated per-method prose less clear"
14)]
15
16use std::fmt;
17use std::net::{Ipv4Addr, Ipv6Addr};
18
19/// DNS class IN.
20pub const CLASS_IN: u16 = 1;
21/// Maximum RFC 1035 label length.
22pub const MAX_LABEL_LEN: usize = 63;
23/// Maximum complete DNS wire name length, including length octets and root.
24pub const MAX_WIRE_NAME_LEN: usize = 255;
25/// Traditional safe DNS-over-UDP payload.
26pub const DEFAULT_UDP_PAYLOAD: u16 = 1_232;
27/// DNSSEC OK bit in the EDNS OPT TTL field.
28pub const EDNS_DO: u16 = 0x8000;
29
30/// Parser and allocation limits.
31#[derive(Clone, Copy, Debug, Eq, PartialEq)]
32pub struct ParseLimits {
33    /// Maximum complete DNS message length.
34    pub max_message_len: usize,
35    /// Maximum number of questions.
36    pub max_questions: usize,
37    /// Maximum total records across all response sections.
38    pub max_records: usize,
39    /// Maximum RDATA length accepted for one record.
40    pub max_rdata_len: usize,
41    /// Maximum labels in one expanded name.
42    pub max_labels_per_name: usize,
43    /// Maximum followed compression pointers in one name.
44    pub max_compression_jumps: usize,
45}
46
47impl ParseLimits {
48    /// Browser production limits for UDP or length-delimited TCP input.
49    #[must_use]
50    pub const fn browser() -> Self {
51        Self {
52            max_message_len: u16::MAX as usize,
53            max_questions: 4,
54            max_records: 2_048,
55            max_rdata_len: u16::MAX as usize,
56            max_labels_per_name: 127,
57            max_compression_jumps: 32,
58        }
59    }
60
61    /// Stricter limits for a single-question requester.
62    #[must_use]
63    pub const fn requester() -> Self {
64        Self {
65            max_message_len: u16::MAX as usize,
66            max_questions: 1,
67            max_records: 1_024,
68            max_rdata_len: 16_384,
69            max_labels_per_name: 127,
70            max_compression_jumps: 16,
71        }
72    }
73}
74
75impl Default for ParseLimits {
76    fn default() -> Self {
77        Self::browser()
78    }
79}
80
81/// DNS wire parse or validation failure.
82#[derive(Clone, Debug, Eq, PartialEq)]
83#[non_exhaustive]
84pub enum Error {
85    /// A read extended beyond the supplied message or RDATA.
86    UnexpectedEof,
87    /// The complete message exceeds its configured bound.
88    MessageTooLong,
89    /// A declared section count exceeds its configured bound.
90    CountLimit,
91    /// A label exceeds 63 octets or uses reserved length bits.
92    InvalidLabel,
93    /// An expanded name exceeds configured label or RFC wire limits.
94    NameLimit,
95    /// A compression pointer points outside the packet.
96    PointerOutOfBounds,
97    /// A compression pointer points to itself or forward.
98    ForwardPointer,
99    /// A compression pointer cycle was detected.
100    CompressionLoop,
101    /// A name followed too many compression pointers.
102    CompressionJumpLimit,
103    /// A record RDATA length exceeds the configured bound.
104    RdataLimit,
105    /// A known resource record has malformed RDATA.
106    InvalidRdata,
107    /// EDNS options are malformed.
108    InvalidEdns,
109    /// Bytes remain after all declared sections.
110    TrailingBytes,
111    /// An arithmetic operation overflowed.
112    LengthOverflow,
113    /// A strict query has invalid flags or section structure.
114    InvalidQuery,
115    /// Reserved DNS header bits are nonzero.
116    ReservedHeaderBits,
117    /// A packet expected to be a response is not one.
118    NotResponse,
119    /// Response ID does not match the query.
120    IdMismatch,
121    /// Response opcode is unsupported or does not match.
122    OpcodeMismatch,
123    /// Response question does not exactly match the query.
124    QuestionMismatch,
125    /// Response is truncated and requires a bounded TCP retry.
126    Truncated,
127    /// Encoding would exceed a caller-provided bound.
128    EncodeLimit,
129    /// A typed RDATA variant does not match its RR type.
130    TypeMismatch,
131}
132
133impl fmt::Display for Error {
134    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
135        formatter.write_str(match self {
136            Self::UnexpectedEof => "unexpected end of DNS message",
137            Self::MessageTooLong => "DNS message exceeds configured limit",
138            Self::CountLimit => "DNS section count exceeds configured limit",
139            Self::InvalidLabel => "invalid DNS label",
140            Self::NameLimit => "expanded DNS name exceeds configured limit",
141            Self::PointerOutOfBounds => "DNS compression pointer is out of bounds",
142            Self::ForwardPointer => "DNS compression pointer is self-referential or forward",
143            Self::CompressionLoop => "DNS compression pointer loop",
144            Self::CompressionJumpLimit => "DNS compression jump limit exceeded",
145            Self::RdataLimit => "DNS RDATA exceeds configured limit",
146            Self::InvalidRdata => "malformed known DNS RDATA",
147            Self::InvalidEdns => "malformed EDNS option list",
148            Self::TrailingBytes => "trailing bytes after declared DNS sections",
149            Self::LengthOverflow => "DNS length arithmetic overflow",
150            Self::InvalidQuery => "invalid strict DNS query",
151            Self::ReservedHeaderBits => "reserved DNS header bits are nonzero",
152            Self::NotResponse => "DNS packet is not a response",
153            Self::IdMismatch => "DNS response ID mismatch",
154            Self::OpcodeMismatch => "DNS response opcode mismatch",
155            Self::QuestionMismatch => "DNS response question mismatch",
156            Self::Truncated => "DNS response is truncated",
157            Self::EncodeLimit => "encoded DNS message exceeds configured limit",
158            Self::TypeMismatch => "resource record type and typed RDATA do not match",
159        })
160    }
161}
162
163impl std::error::Error for Error {}
164
165/// A canonical, absolute DNS name.
166///
167/// ASCII letters are normalized to lowercase when parsed. Other label octets
168/// remain opaque and are escaped by [`Display`](fmt::Display).
169#[derive(Clone, Debug, Eq, Hash, PartialEq)]
170pub struct Name {
171    labels: Vec<Vec<u8>>,
172}
173
174impl Name {
175    /// The DNS root name.
176    #[must_use]
177    pub const fn root() -> Self {
178        Self { labels: Vec::new() }
179    }
180
181    /// Construct from opaque labels, validating and canonicalizing ASCII case.
182    pub fn from_labels(labels: Vec<Vec<u8>>) -> Result<Self, Error> {
183        let mut canonical = Vec::with_capacity(labels.len());
184        let mut wire_len = 1usize;
185        for label in labels {
186            if label.is_empty() || label.len() > MAX_LABEL_LEN {
187                return Err(Error::InvalidLabel);
188            }
189            wire_len = wire_len
190                .checked_add(label.len() + 1)
191                .ok_or(Error::LengthOverflow)?;
192            if wire_len > MAX_WIRE_NAME_LEN {
193                return Err(Error::NameLimit);
194            }
195            canonical.push(canonical_label(&label));
196        }
197        Ok(Self { labels: canonical })
198    }
199
200    /// Parse an ASCII presentation name. A final dot is optional.
201    pub fn from_ascii(input: &str) -> Result<Self, Error> {
202        let input = input.strip_suffix('.').unwrap_or(input);
203        if input.is_empty() {
204            return Ok(Self::root());
205        }
206
207        Self::from_labels(
208            input
209                .as_bytes()
210                .split(|byte| *byte == b'.')
211                .map(<[u8]>::to_vec)
212                .collect(),
213        )
214    }
215
216    /// Return the opaque labels in canonical lowercase form.
217    #[must_use]
218    pub fn labels(&self) -> &[Vec<u8>] {
219        &self.labels
220    }
221
222    /// Whether this is the root name.
223    #[must_use]
224    pub fn is_root(&self) -> bool {
225        self.labels.is_empty()
226    }
227
228    /// Expanded wire length, including the terminating root.
229    #[must_use]
230    pub fn wire_len(&self) -> usize {
231        self.labels
232            .iter()
233            .fold(1usize, |length, label| length + label.len() + 1)
234    }
235
236    /// Encode without compression.
237    pub fn encode(&self, output: &mut Vec<u8>) -> Result<(), Error> {
238        if self.wire_len() > MAX_WIRE_NAME_LEN {
239            return Err(Error::NameLimit);
240        }
241        for label in &self.labels {
242            let length = u8::try_from(label.len()).map_err(|_| Error::InvalidLabel)?;
243            if usize::from(length) > MAX_LABEL_LEN {
244                return Err(Error::InvalidLabel);
245            }
246            output.push(length);
247            output.extend_from_slice(label);
248        }
249        output.push(0);
250        Ok(())
251    }
252}
253
254impl fmt::Display for Name {
255    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
256        if self.labels.is_empty() {
257            return formatter.write_str(".");
258        }
259        for (label_index, label) in self.labels.iter().enumerate() {
260            if label_index != 0 {
261                formatter.write_str(".")?;
262            }
263            for byte in label {
264                if byte.is_ascii_alphanumeric() || matches!(*byte, b'-' | b'_') {
265                    formatter.write_str(&char::from(*byte).to_string())?;
266                } else {
267                    write!(formatter, "\\{byte:03}")?;
268                }
269            }
270        }
271        formatter.write_str(".")
272    }
273}
274
275/// DNS header flags.
276#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
277pub struct Flags(u16);
278
279impl Flags {
280    /// Construct flags from raw network bits.
281    #[must_use]
282    pub const fn from_bits(bits: u16) -> Self {
283        Self(bits)
284    }
285
286    /// Return raw network bits.
287    #[must_use]
288    pub const fn bits(self) -> u16 {
289        self.0
290    }
291
292    /// Query/response flag.
293    #[must_use]
294    pub const fn is_response(self) -> bool {
295        self.0 & 0x8000 != 0
296    }
297
298    /// Four-bit opcode.
299    #[must_use]
300    pub const fn opcode(self) -> u8 {
301        ((self.0 >> 11) & 0x0f) as u8
302    }
303
304    /// Authoritative answer flag.
305    #[must_use]
306    pub const fn authoritative(self) -> bool {
307        self.0 & 0x0400 != 0
308    }
309
310    /// Truncation flag.
311    #[must_use]
312    pub const fn truncated(self) -> bool {
313        self.0 & 0x0200 != 0
314    }
315
316    /// Recursion-desired flag.
317    #[must_use]
318    pub const fn recursion_desired(self) -> bool {
319        self.0 & 0x0100 != 0
320    }
321
322    /// Recursion-available flag.
323    #[must_use]
324    pub const fn recursion_available(self) -> bool {
325        self.0 & 0x0080 != 0
326    }
327
328    /// Authenticated-data flag. This is an untrusted peer claim.
329    #[must_use]
330    pub const fn authenticated_data_claim(self) -> bool {
331        self.0 & 0x0020 != 0
332    }
333
334    /// Four-bit response code.
335    #[must_use]
336    pub const fn rcode(self) -> u8 {
337        (self.0 & 0x000f) as u8
338    }
339}
340
341/// Parsed DNS header.
342#[derive(Clone, Copy, Debug, Eq, PartialEq)]
343pub struct Header {
344    /// Transaction identifier.
345    pub id: u16,
346    /// Header flags.
347    pub flags: Flags,
348    /// Declared question count.
349    pub question_count: u16,
350    /// Declared answer count.
351    pub answer_count: u16,
352    /// Declared authority count.
353    pub authority_count: u16,
354    /// Declared additional count.
355    pub additional_count: u16,
356}
357
358impl Header {
359    fn parse(message: &[u8]) -> Result<Self, Error> {
360        let bytes = message.get(..12).ok_or(Error::UnexpectedEof)?;
361        Ok(Self {
362            id: be_u16(bytes, 0)?,
363            flags: Flags::from_bits(be_u16(bytes, 2)?),
364            question_count: be_u16(bytes, 4)?,
365            answer_count: be_u16(bytes, 6)?,
366            authority_count: be_u16(bytes, 8)?,
367            additional_count: be_u16(bytes, 10)?,
368        })
369    }
370}
371
372/// DNS resource-record type.
373#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
374#[non_exhaustive]
375pub enum RecordType {
376    /// IPv4 address.
377    A,
378    /// Authoritative name server.
379    Ns,
380    /// Canonical name.
381    Cname,
382    /// Start of authority.
383    Soa,
384    /// Mail exchange.
385    Mx,
386    /// Text strings.
387    Txt,
388    /// IPv6 address.
389    Aaaa,
390    /// Service location.
391    Srv,
392    /// Delegation signer.
393    Ds,
394    /// EDNS pseudo-record.
395    Opt,
396    /// DNSSEC signature.
397    Rrsig,
398    /// Authenticated denial.
399    Nsec,
400    /// DNSSEC public key.
401    Dnskey,
402    /// Hashed authenticated denial.
403    Nsec3,
404    /// DANE TLS association.
405    Tlsa,
406    /// Service binding.
407    Svcb,
408    /// HTTPS service binding.
409    Https,
410    /// Unrecognized numeric type.
411    Unknown(u16),
412}
413
414impl RecordType {
415    /// Convert a wire code.
416    #[must_use]
417    pub const fn from_code(code: u16) -> Self {
418        match code {
419            1 => Self::A,
420            2 => Self::Ns,
421            5 => Self::Cname,
422            6 => Self::Soa,
423            15 => Self::Mx,
424            16 => Self::Txt,
425            28 => Self::Aaaa,
426            33 => Self::Srv,
427            41 => Self::Opt,
428            43 => Self::Ds,
429            46 => Self::Rrsig,
430            47 => Self::Nsec,
431            48 => Self::Dnskey,
432            50 => Self::Nsec3,
433            52 => Self::Tlsa,
434            64 => Self::Svcb,
435            65 => Self::Https,
436            value => Self::Unknown(value),
437        }
438    }
439
440    /// Convert to a wire code.
441    #[must_use]
442    pub const fn code(self) -> u16 {
443        match self {
444            Self::A => 1,
445            Self::Ns => 2,
446            Self::Cname => 5,
447            Self::Soa => 6,
448            Self::Mx => 15,
449            Self::Txt => 16,
450            Self::Aaaa => 28,
451            Self::Srv => 33,
452            Self::Opt => 41,
453            Self::Ds => 43,
454            Self::Rrsig => 46,
455            Self::Nsec => 47,
456            Self::Dnskey => 48,
457            Self::Nsec3 => 50,
458            Self::Tlsa => 52,
459            Self::Svcb => 64,
460            Self::Https => 65,
461            Self::Unknown(value) => value,
462        }
463    }
464}
465
466/// One DNS question.
467#[derive(Clone, Debug, Eq, PartialEq)]
468pub struct Question {
469    /// Canonical question name.
470    pub name: Name,
471    /// Requested RR type.
472    pub record_type: RecordType,
473    /// Requested class.
474    pub class: u16,
475}
476
477/// SOA RDATA.
478#[derive(Clone, Debug, Eq, PartialEq)]
479pub struct Soa {
480    /// Primary name server.
481    pub mname: Name,
482    /// Responsible mailbox name.
483    pub rname: Name,
484    /// Zone serial.
485    pub serial: u32,
486    /// Refresh interval.
487    pub refresh: u32,
488    /// Retry interval.
489    pub retry: u32,
490    /// Expire interval.
491    pub expire: u32,
492    /// Negative-cache minimum TTL.
493    pub minimum: u32,
494}
495
496/// MX RDATA.
497#[derive(Clone, Debug, Eq, PartialEq)]
498pub struct Mx {
499    /// Preference value.
500    pub preference: u16,
501    /// Mail-exchanger name.
502    pub exchange: Name,
503}
504
505/// SRV RDATA.
506#[derive(Clone, Debug, Eq, PartialEq)]
507pub struct Srv {
508    /// Selection priority.
509    pub priority: u16,
510    /// Relative weight.
511    pub weight: u16,
512    /// Service port.
513    pub port: u16,
514    /// Target host.
515    pub target: Name,
516}
517
518/// DS RDATA.
519#[derive(Clone, Debug, Eq, PartialEq)]
520pub struct Ds {
521    /// DNSKEY key tag.
522    pub key_tag: u16,
523    /// DNSSEC algorithm.
524    pub algorithm: u8,
525    /// Digest algorithm.
526    pub digest_type: u8,
527    /// Key digest.
528    pub digest: Vec<u8>,
529}
530
531/// DNSKEY RDATA.
532#[derive(Clone, Debug, Eq, PartialEq)]
533pub struct Dnskey {
534    /// DNSKEY flags.
535    pub flags: u16,
536    /// Must be 3 for DNSSEC.
537    pub protocol: u8,
538    /// DNSSEC algorithm.
539    pub algorithm: u8,
540    /// Encoded public key.
541    pub public_key: Vec<u8>,
542}
543
544/// RRSIG RDATA.
545#[derive(Clone, Debug, Eq, PartialEq)]
546pub struct Rrsig {
547    /// Covered RR type.
548    pub type_covered: RecordType,
549    /// DNSSEC algorithm.
550    pub algorithm: u8,
551    /// Original owner label count.
552    pub labels: u8,
553    /// Original RRset TTL.
554    pub original_ttl: u32,
555    /// Signature expiration time.
556    pub expiration: u32,
557    /// Signature inception time.
558    pub inception: u32,
559    /// Signing key tag.
560    pub key_tag: u16,
561    /// Signer name.
562    pub signer: Name,
563    /// Signature bytes.
564    pub signature: Vec<u8>,
565}
566
567/// NSEC RDATA.
568#[derive(Clone, Debug, Eq, PartialEq)]
569pub struct Nsec {
570    /// Next canonical owner.
571    pub next_domain: Name,
572    /// Validated RFC 4034 type bitmap bytes.
573    pub type_bitmaps: Vec<u8>,
574}
575
576/// NSEC3 RDATA.
577#[derive(Clone, Debug, Eq, PartialEq)]
578pub struct Nsec3 {
579    /// Hash algorithm.
580    pub hash_algorithm: u8,
581    /// NSEC3 flags.
582    pub flags: u8,
583    /// Additional hash iterations.
584    pub iterations: u16,
585    /// Salt.
586    pub salt: Vec<u8>,
587    /// Next hashed owner.
588    pub next_hashed_owner: Vec<u8>,
589    /// Validated RFC 4034 type bitmap bytes.
590    pub type_bitmaps: Vec<u8>,
591}
592
593/// TLSA RDATA.
594#[derive(Clone, Debug, Eq, PartialEq)]
595pub struct Tlsa {
596    /// Certificate usage.
597    pub usage: u8,
598    /// Selector.
599    pub selector: u8,
600    /// Matching type.
601    pub matching_type: u8,
602    /// Certificate association data.
603    pub association_data: Vec<u8>,
604}
605
606/// One EDNS option.
607#[derive(Clone, Debug, Eq, PartialEq)]
608pub struct EdnsOption {
609    /// EDNS option code.
610    pub code: u16,
611    /// Opaque option value.
612    pub data: Vec<u8>,
613}
614
615/// Parsed or preserved resource-record data.
616#[derive(Clone, Debug, Eq, PartialEq)]
617#[non_exhaustive]
618pub enum Rdata {
619    /// A address.
620    A(Ipv4Addr),
621    /// AAAA address.
622    Aaaa(Ipv6Addr),
623    /// NS name.
624    Ns(Name),
625    /// CNAME name.
626    Cname(Name),
627    /// SOA fields.
628    Soa(Soa),
629    /// MX fields.
630    Mx(Mx),
631    /// TXT character strings.
632    Txt(Vec<Vec<u8>>),
633    /// SRV fields.
634    Srv(Srv),
635    /// DS fields.
636    Ds(Ds),
637    /// DNSKEY fields.
638    Dnskey(Dnskey),
639    /// RRSIG fields.
640    Rrsig(Rrsig),
641    /// NSEC fields.
642    Nsec(Nsec),
643    /// NSEC3 fields.
644    Nsec3(Nsec3),
645    /// TLSA fields.
646    Tlsa(Tlsa),
647    /// Validated EDNS options.
648    Opt(Vec<EdnsOption>),
649    /// Opaque data for an unrecognized or intentionally uninterpreted type.
650    Opaque(Vec<u8>),
651}
652
653/// One DNS resource record.
654#[derive(Clone, Debug, Eq, PartialEq)]
655pub struct ResourceRecord {
656    /// Canonical owner name.
657    pub name: Name,
658    /// RR type.
659    pub record_type: RecordType,
660    /// RR class, or advertised UDP payload for OPT.
661    pub class: u16,
662    /// TTL, or EDNS extended fields for OPT.
663    pub ttl: u32,
664    /// Parsed RDATA.
665    pub rdata: Rdata,
666}
667
668/// Complete parsed DNS message.
669#[derive(Clone, Debug, Eq, PartialEq)]
670pub struct Message {
671    /// Header.
672    pub header: Header,
673    /// Questions.
674    pub questions: Vec<Question>,
675    /// Answer records.
676    pub answers: Vec<ResourceRecord>,
677    /// Authority records.
678    pub authorities: Vec<ResourceRecord>,
679    /// Additional records.
680    pub additionals: Vec<ResourceRecord>,
681}
682
683impl Message {
684    /// Parse with browser production limits.
685    pub fn parse(message: &[u8]) -> Result<Self, Error> {
686        Self::parse_with_limits(message, ParseLimits::browser())
687    }
688
689    /// Parse with explicit limits.
690    pub fn parse_with_limits(message: &[u8], limits: ParseLimits) -> Result<Self, Error> {
691        if message.len() > limits.max_message_len || message.len() > usize::from(u16::MAX) {
692            return Err(Error::MessageTooLong);
693        }
694        let header = Header::parse(message)?;
695        if header.flags.bits() & 0x0040 != 0 {
696            return Err(Error::ReservedHeaderBits);
697        }
698        if usize::from(header.question_count) > limits.max_questions {
699            return Err(Error::CountLimit);
700        }
701        let total_records = usize::from(header.answer_count)
702            .checked_add(usize::from(header.authority_count))
703            .and_then(|count| count.checked_add(usize::from(header.additional_count)))
704            .ok_or(Error::LengthOverflow)?;
705        if total_records > limits.max_records {
706            return Err(Error::CountLimit);
707        }
708
709        let mut cursor = 12usize;
710        let mut questions = Vec::with_capacity(usize::from(header.question_count));
711        for _ in 0..header.question_count {
712            let (question, next) = parse_question(message, cursor, limits)?;
713            questions.push(question);
714            cursor = next;
715        }
716        let (answers, next) = parse_records(message, cursor, header.answer_count, limits)?;
717        let (authorities, next) = parse_records(message, next, header.authority_count, limits)?;
718        let (additionals, next) = parse_records(message, next, header.additional_count, limits)?;
719        if next != message.len() {
720            return Err(Error::TrailingBytes);
721        }
722        let parsed = Self {
723            header,
724            questions,
725            answers,
726            authorities,
727            additionals,
728        };
729        validate_pseudo_records(&parsed)?;
730        Ok(parsed)
731    }
732
733    /// Encode all names without compression, enforcing a complete-message bound.
734    pub fn encode(&self, max_message_len: usize) -> Result<Vec<u8>, Error> {
735        let mut output = Vec::new();
736        write_u16(&mut output, self.header.id);
737        write_u16(&mut output, self.header.flags.bits());
738        write_count(&mut output, self.questions.len())?;
739        write_count(&mut output, self.answers.len())?;
740        write_count(&mut output, self.authorities.len())?;
741        write_count(&mut output, self.additionals.len())?;
742        for question in &self.questions {
743            encode_question(question, &mut output)?;
744        }
745        for record in self
746            .answers
747            .iter()
748            .chain(&self.authorities)
749            .chain(&self.additionals)
750        {
751            encode_record(record, &mut output)?;
752        }
753        if output.len() > max_message_len {
754            return Err(Error::EncodeLimit);
755        }
756        Ok(output)
757    }
758}
759
760/// A validated single-question standard query.
761#[derive(Clone, Debug, Eq, PartialEq)]
762pub struct Query {
763    /// Transaction identifier.
764    pub id: u16,
765    /// Exact question.
766    pub question: Question,
767}
768
769impl Query {
770    /// Construct a class-IN query.
771    pub fn new(id: u16, name: Name, record_type: RecordType) -> Result<Self, Error> {
772        if name.is_root() || matches!(record_type, RecordType::Opt) {
773            return Err(Error::InvalidQuery);
774        }
775        Ok(Self {
776            id,
777            question: Question {
778                name,
779                record_type,
780                class: CLASS_IN,
781            },
782        })
783    }
784
785    /// Parse and validate a single-question standard query.
786    pub fn parse(message: &[u8], limits: ParseLimits) -> Result<Self, Error> {
787        let parsed = Message::parse_with_limits(message, limits)?;
788        if parsed.header.flags.is_response()
789            || parsed.header.flags.opcode() != 0
790            || parsed.header.flags.truncated()
791            || parsed.header.flags.bits() & !0x0130 != 0
792            || parsed.questions.len() != 1
793            || !parsed.answers.is_empty()
794            || !parsed.authorities.is_empty()
795            || parsed.additionals.len() > 1
796        {
797            return Err(Error::InvalidQuery);
798        }
799        let question = parsed.questions.first().ok_or(Error::InvalidQuery)?.clone();
800        if question.class != CLASS_IN
801            || question.name.is_root()
802            || matches!(question.record_type, RecordType::Opt)
803        {
804            return Err(Error::InvalidQuery);
805        }
806        if let Some(opt) = parsed.additionals.first()
807            && (!opt.name.is_root() || opt.record_type != RecordType::Opt)
808        {
809            return Err(Error::InvalidQuery);
810        }
811        if parsed.additionals.iter().any(|record| {
812            matches!(
813                &record.rdata,
814                Rdata::Opt(options) if options.iter().any(|option| option.code == 8)
815            )
816        }) {
817            return Err(Error::InvalidQuery);
818        }
819        Ok(Self {
820            id: parsed.header.id,
821            question,
822        })
823    }
824
825    /// Encode an authoritative-oriented query with DNSSEC OK and no RD bit.
826    pub fn encode(&self, max_message_len: usize) -> Result<Vec<u8>, Error> {
827        let message = Message {
828            header: Header {
829                id: self.id,
830                flags: Flags::from_bits(0),
831                question_count: 1,
832                answer_count: 0,
833                authority_count: 0,
834                additional_count: 1,
835            },
836            questions: vec![self.question.clone()],
837            answers: Vec::new(),
838            authorities: Vec::new(),
839            additionals: vec![ResourceRecord {
840                name: Name::root(),
841                record_type: RecordType::Opt,
842                class: DEFAULT_UDP_PAYLOAD,
843                ttl: u32::from(EDNS_DO),
844                rdata: Rdata::Opt(Vec::new()),
845            }],
846        };
847        message.encode(max_message_len)
848    }
849
850    /// Correlate a parsed response to this exact query.
851    ///
852    /// The returned AD value is an untrusted transport claim only.
853    pub fn correlate<'a>(&self, response: &'a Message) -> Result<CorrelatedResponse<'a>, Error> {
854        if !response.header.flags.is_response() {
855            return Err(Error::NotResponse);
856        }
857        if response.header.id != self.id {
858            return Err(Error::IdMismatch);
859        }
860        if response.header.flags.opcode() != 0 {
861            return Err(Error::OpcodeMismatch);
862        }
863        if response.header.flags.truncated() {
864            return Err(Error::Truncated);
865        }
866        if response.questions.as_slice() != [self.question.clone()] {
867            return Err(Error::QuestionMismatch);
868        }
869        Ok(CorrelatedResponse {
870            message: response,
871            untrusted_ad_claim: response.header.flags.authenticated_data_claim(),
872        })
873    }
874}
875
876/// A structurally correlated response.
877#[derive(Clone, Copy, Debug)]
878pub struct CorrelatedResponse<'a> {
879    message: &'a Message,
880    untrusted_ad_claim: bool,
881}
882
883impl<'a> CorrelatedResponse<'a> {
884    /// The correlated response.
885    #[must_use]
886    pub const fn response(&self) -> &'a Message {
887        self.message
888    }
889
890    /// Whether the sender asserted AD. Never treat this as local validation.
891    #[must_use]
892    pub const fn untrusted_ad_claim(&self) -> bool {
893        self.untrusted_ad_claim
894    }
895}
896
897fn parse_question(
898    message: &[u8],
899    offset: usize,
900    limits: ParseLimits,
901) -> Result<(Question, usize), Error> {
902    let (name, cursor) = decode_name(message, offset, message.len(), limits)?;
903    let end = cursor.checked_add(4).ok_or(Error::LengthOverflow)?;
904    let fixed = message.get(cursor..end).ok_or(Error::UnexpectedEof)?;
905    Ok((
906        Question {
907            name,
908            record_type: RecordType::from_code(be_u16(fixed, 0)?),
909            class: be_u16(fixed, 2)?,
910        },
911        end,
912    ))
913}
914
915fn validate_pseudo_records(message: &Message) -> Result<(), Error> {
916    if message
917        .answers
918        .iter()
919        .chain(&message.authorities)
920        .any(|record| record.record_type == RecordType::Opt)
921    {
922        return Err(Error::InvalidEdns);
923    }
924    let mut opt_count = 0usize;
925    for record in &message.additionals {
926        if record.record_type == RecordType::Opt {
927            opt_count = opt_count.checked_add(1).ok_or(Error::LengthOverflow)?;
928            if opt_count > 1 || !record.name.is_root() {
929                return Err(Error::InvalidEdns);
930            }
931        }
932    }
933    Ok(())
934}
935
936fn parse_records(
937    message: &[u8],
938    mut cursor: usize,
939    count: u16,
940    limits: ParseLimits,
941) -> Result<(Vec<ResourceRecord>, usize), Error> {
942    let mut records = Vec::with_capacity(usize::from(count));
943    for _ in 0..count {
944        let (record, next) = parse_record(message, cursor, limits)?;
945        records.push(record);
946        cursor = next;
947    }
948    Ok((records, cursor))
949}
950
951fn parse_record(
952    message: &[u8],
953    offset: usize,
954    limits: ParseLimits,
955) -> Result<(ResourceRecord, usize), Error> {
956    let (name, cursor) = decode_name(message, offset, message.len(), limits)?;
957    let fixed_end = cursor.checked_add(10).ok_or(Error::LengthOverflow)?;
958    let fixed = message.get(cursor..fixed_end).ok_or(Error::UnexpectedEof)?;
959    let record_type = RecordType::from_code(be_u16(fixed, 0)?);
960    let class = be_u16(fixed, 2)?;
961    let ttl = be_u32(fixed, 4)?;
962    let rdata_len = usize::from(be_u16(fixed, 8)?);
963    if rdata_len > limits.max_rdata_len {
964        return Err(Error::RdataLimit);
965    }
966    let rdata_start = fixed_end;
967    let rdata_end = rdata_start
968        .checked_add(rdata_len)
969        .ok_or(Error::LengthOverflow)?;
970    message
971        .get(rdata_start..rdata_end)
972        .ok_or(Error::UnexpectedEof)?;
973    let rdata = parse_rdata(message, rdata_start, rdata_end, record_type, limits)?;
974    Ok((
975        ResourceRecord {
976            name,
977            record_type,
978            class,
979            ttl,
980            rdata,
981        },
982        rdata_end,
983    ))
984}
985
986fn parse_rdata(
987    message: &[u8],
988    start: usize,
989    end: usize,
990    record_type: RecordType,
991    limits: ParseLimits,
992) -> Result<Rdata, Error> {
993    let raw = message.get(start..end).ok_or(Error::UnexpectedEof)?;
994    match record_type {
995        RecordType::A => {
996            let bytes: [u8; 4] = raw.try_into().map_err(|_| Error::InvalidRdata)?;
997            Ok(Rdata::A(Ipv4Addr::from(bytes)))
998        }
999        RecordType::Aaaa => {
1000            let bytes: [u8; 16] = raw.try_into().map_err(|_| Error::InvalidRdata)?;
1001            Ok(Rdata::Aaaa(Ipv6Addr::from(bytes)))
1002        }
1003        RecordType::Ns | RecordType::Cname => {
1004            let (name, next) = decode_name(message, start, end, limits)?;
1005            if next != end {
1006                return Err(Error::InvalidRdata);
1007            }
1008            Ok(if record_type == RecordType::Ns {
1009                Rdata::Ns(name)
1010            } else {
1011                Rdata::Cname(name)
1012            })
1013        }
1014        RecordType::Soa => parse_soa(message, start, end, limits).map(Rdata::Soa),
1015        RecordType::Mx => parse_mx(message, start, end, limits).map(Rdata::Mx),
1016        RecordType::Txt => parse_txt(raw).map(Rdata::Txt),
1017        RecordType::Srv => parse_srv(message, start, end, limits).map(Rdata::Srv),
1018        RecordType::Ds => parse_ds(raw).map(Rdata::Ds),
1019        RecordType::Dnskey => parse_dnskey(raw).map(Rdata::Dnskey),
1020        RecordType::Rrsig => parse_rrsig(message, start, end, limits).map(Rdata::Rrsig),
1021        RecordType::Nsec => parse_nsec(message, start, end, limits).map(Rdata::Nsec),
1022        RecordType::Nsec3 => parse_nsec3(raw).map(Rdata::Nsec3),
1023        RecordType::Tlsa => parse_tlsa(raw).map(Rdata::Tlsa),
1024        RecordType::Opt => parse_edns(raw).map(Rdata::Opt),
1025        RecordType::Svcb | RecordType::Https | RecordType::Unknown(_) => {
1026            Ok(Rdata::Opaque(raw.to_vec()))
1027        }
1028    }
1029}
1030
1031fn parse_soa(message: &[u8], start: usize, end: usize, limits: ParseLimits) -> Result<Soa, Error> {
1032    let (mname, next) = decode_name(message, start, end, limits)?;
1033    let (rname, next) = decode_name(message, next, end, limits)?;
1034    let fixed_end = next.checked_add(20).ok_or(Error::LengthOverflow)?;
1035    let fixed = message.get(next..fixed_end).ok_or(Error::InvalidRdata)?;
1036    if fixed_end != end {
1037        return Err(Error::InvalidRdata);
1038    }
1039    Ok(Soa {
1040        mname,
1041        rname,
1042        serial: be_u32(fixed, 0)?,
1043        refresh: be_u32(fixed, 4)?,
1044        retry: be_u32(fixed, 8)?,
1045        expire: be_u32(fixed, 12)?,
1046        minimum: be_u32(fixed, 16)?,
1047    })
1048}
1049
1050fn parse_mx(message: &[u8], start: usize, end: usize, limits: ParseLimits) -> Result<Mx, Error> {
1051    let preference = be_u16(message.get(start..end).ok_or(Error::InvalidRdata)?, 0)?;
1052    let name_start = start.checked_add(2).ok_or(Error::LengthOverflow)?;
1053    let (exchange, next) = decode_name(message, name_start, end, limits)?;
1054    if next != end {
1055        return Err(Error::InvalidRdata);
1056    }
1057    Ok(Mx {
1058        preference,
1059        exchange,
1060    })
1061}
1062
1063fn parse_txt(raw: &[u8]) -> Result<Vec<Vec<u8>>, Error> {
1064    let mut cursor = 0usize;
1065    let mut strings = Vec::new();
1066    while cursor < raw.len() {
1067        let length = usize::from(*raw.get(cursor).ok_or(Error::InvalidRdata)?);
1068        cursor = cursor.checked_add(1).ok_or(Error::LengthOverflow)?;
1069        let end = cursor.checked_add(length).ok_or(Error::LengthOverflow)?;
1070        strings.push(raw.get(cursor..end).ok_or(Error::InvalidRdata)?.to_vec());
1071        cursor = end;
1072    }
1073    if strings.is_empty() {
1074        return Err(Error::InvalidRdata);
1075    }
1076    Ok(strings)
1077}
1078
1079fn parse_srv(message: &[u8], start: usize, end: usize, limits: ParseLimits) -> Result<Srv, Error> {
1080    let raw = message.get(start..end).ok_or(Error::InvalidRdata)?;
1081    let target_start = start.checked_add(6).ok_or(Error::LengthOverflow)?;
1082    let (target, next) = decode_name(message, target_start, end, limits)?;
1083    if next != end {
1084        return Err(Error::InvalidRdata);
1085    }
1086    Ok(Srv {
1087        priority: be_u16(raw, 0)?,
1088        weight: be_u16(raw, 2)?,
1089        port: be_u16(raw, 4)?,
1090        target,
1091    })
1092}
1093
1094fn parse_ds(raw: &[u8]) -> Result<Ds, Error> {
1095    if raw.len() < 5 {
1096        return Err(Error::InvalidRdata);
1097    }
1098    Ok(Ds {
1099        key_tag: be_u16(raw, 0)?,
1100        algorithm: *raw.get(2).ok_or(Error::InvalidRdata)?,
1101        digest_type: *raw.get(3).ok_or(Error::InvalidRdata)?,
1102        digest: raw.get(4..).ok_or(Error::InvalidRdata)?.to_vec(),
1103    })
1104}
1105
1106fn parse_dnskey(raw: &[u8]) -> Result<Dnskey, Error> {
1107    if raw.len() < 5 {
1108        return Err(Error::InvalidRdata);
1109    }
1110    Ok(Dnskey {
1111        flags: be_u16(raw, 0)?,
1112        protocol: *raw.get(2).ok_or(Error::InvalidRdata)?,
1113        algorithm: *raw.get(3).ok_or(Error::InvalidRdata)?,
1114        public_key: raw.get(4..).ok_or(Error::InvalidRdata)?.to_vec(),
1115    })
1116}
1117
1118fn parse_rrsig(
1119    message: &[u8],
1120    start: usize,
1121    end: usize,
1122    limits: ParseLimits,
1123) -> Result<Rrsig, Error> {
1124    let fixed_end = start.checked_add(18).ok_or(Error::LengthOverflow)?;
1125    let fixed = message.get(start..fixed_end).ok_or(Error::InvalidRdata)?;
1126    let (signer, next) = decode_name(message, fixed_end, end, limits)?;
1127    let signature = message.get(next..end).ok_or(Error::InvalidRdata)?;
1128    if signature.is_empty() {
1129        return Err(Error::InvalidRdata);
1130    }
1131    Ok(Rrsig {
1132        type_covered: RecordType::from_code(be_u16(fixed, 0)?),
1133        algorithm: *fixed.get(2).ok_or(Error::InvalidRdata)?,
1134        labels: *fixed.get(3).ok_or(Error::InvalidRdata)?,
1135        original_ttl: be_u32(fixed, 4)?,
1136        expiration: be_u32(fixed, 8)?,
1137        inception: be_u32(fixed, 12)?,
1138        key_tag: be_u16(fixed, 16)?,
1139        signer,
1140        signature: signature.to_vec(),
1141    })
1142}
1143
1144fn parse_nsec(
1145    message: &[u8],
1146    start: usize,
1147    end: usize,
1148    limits: ParseLimits,
1149) -> Result<Nsec, Error> {
1150    let (next_domain, next) = decode_name(message, start, end, limits)?;
1151    let bitmap = message.get(next..end).ok_or(Error::InvalidRdata)?;
1152    validate_type_bitmaps(bitmap)?;
1153    Ok(Nsec {
1154        next_domain,
1155        type_bitmaps: bitmap.to_vec(),
1156    })
1157}
1158
1159fn parse_nsec3(raw: &[u8]) -> Result<Nsec3, Error> {
1160    if raw.len() < 6 {
1161        return Err(Error::InvalidRdata);
1162    }
1163    let salt_len = usize::from(*raw.get(4).ok_or(Error::InvalidRdata)?);
1164    let salt_start = 5usize;
1165    let salt_end = salt_start
1166        .checked_add(salt_len)
1167        .ok_or(Error::LengthOverflow)?;
1168    let hash_len = usize::from(*raw.get(salt_end).ok_or(Error::InvalidRdata)?);
1169    if hash_len == 0 {
1170        return Err(Error::InvalidRdata);
1171    }
1172    let hash_start = salt_end.checked_add(1).ok_or(Error::LengthOverflow)?;
1173    let hash_end = hash_start
1174        .checked_add(hash_len)
1175        .ok_or(Error::LengthOverflow)?;
1176    let bitmap = raw.get(hash_end..).ok_or(Error::InvalidRdata)?;
1177    validate_type_bitmaps(bitmap)?;
1178    Ok(Nsec3 {
1179        hash_algorithm: *raw.first().ok_or(Error::InvalidRdata)?,
1180        flags: *raw.get(1).ok_or(Error::InvalidRdata)?,
1181        iterations: be_u16(raw, 2)?,
1182        salt: raw
1183            .get(salt_start..salt_end)
1184            .ok_or(Error::InvalidRdata)?
1185            .to_vec(),
1186        next_hashed_owner: raw
1187            .get(hash_start..hash_end)
1188            .ok_or(Error::InvalidRdata)?
1189            .to_vec(),
1190        type_bitmaps: bitmap.to_vec(),
1191    })
1192}
1193
1194fn parse_tlsa(raw: &[u8]) -> Result<Tlsa, Error> {
1195    if raw.len() < 4 {
1196        return Err(Error::InvalidRdata);
1197    }
1198    Ok(Tlsa {
1199        usage: *raw.first().ok_or(Error::InvalidRdata)?,
1200        selector: *raw.get(1).ok_or(Error::InvalidRdata)?,
1201        matching_type: *raw.get(2).ok_or(Error::InvalidRdata)?,
1202        association_data: raw.get(3..).ok_or(Error::InvalidRdata)?.to_vec(),
1203    })
1204}
1205
1206fn parse_edns(raw: &[u8]) -> Result<Vec<EdnsOption>, Error> {
1207    let mut cursor = 0usize;
1208    let mut options = Vec::new();
1209    while cursor < raw.len() {
1210        let header_end = cursor.checked_add(4).ok_or(Error::LengthOverflow)?;
1211        let header = raw.get(cursor..header_end).ok_or(Error::InvalidEdns)?;
1212        let code = be_u16(header, 0).map_err(|_| Error::InvalidEdns)?;
1213        let length = usize::from(be_u16(header, 2).map_err(|_| Error::InvalidEdns)?);
1214        let data_end = header_end
1215            .checked_add(length)
1216            .ok_or(Error::LengthOverflow)?;
1217        options.push(EdnsOption {
1218            code,
1219            data: raw
1220                .get(header_end..data_end)
1221                .ok_or(Error::InvalidEdns)?
1222                .to_vec(),
1223        });
1224        cursor = data_end;
1225    }
1226    Ok(options)
1227}
1228
1229fn validate_type_bitmaps(raw: &[u8]) -> Result<(), Error> {
1230    let mut cursor = 0usize;
1231    let mut previous_window = None;
1232    let mut block_count = 0usize;
1233    while cursor < raw.len() {
1234        let window = *raw.get(cursor).ok_or(Error::InvalidRdata)?;
1235        let bitmap_len = usize::from(*raw.get(cursor + 1).ok_or(Error::InvalidRdata)?);
1236        if !(1..=32).contains(&bitmap_len)
1237            || previous_window.is_some_and(|previous| window <= previous)
1238        {
1239            return Err(Error::InvalidRdata);
1240        }
1241        previous_window = Some(window);
1242        cursor = cursor
1243            .checked_add(2)
1244            .and_then(|value| value.checked_add(bitmap_len))
1245            .ok_or(Error::LengthOverflow)?;
1246        if cursor > raw.len() {
1247            return Err(Error::InvalidRdata);
1248        }
1249        block_count = block_count.checked_add(1).ok_or(Error::LengthOverflow)?;
1250        if block_count > 256 {
1251            return Err(Error::InvalidRdata);
1252        }
1253    }
1254    if block_count == 0 {
1255        return Err(Error::InvalidRdata);
1256    }
1257    Ok(())
1258}
1259
1260fn decode_name(
1261    message: &[u8],
1262    offset: usize,
1263    contiguous_end: usize,
1264    limits: ParseLimits,
1265) -> Result<(Name, usize), Error> {
1266    if contiguous_end > message.len() || offset >= contiguous_end {
1267        return Err(Error::UnexpectedEof);
1268    }
1269    let mut labels = Vec::new();
1270    let mut cursor = offset;
1271    let mut consumed_end = None;
1272    let mut jumps = 0usize;
1273    let mut expanded_len = 1usize;
1274    let mut visited = vec![false; message.len()];
1275
1276    loop {
1277        let was_visited = *visited.get(cursor).ok_or(Error::PointerOutOfBounds)?;
1278        if was_visited {
1279            return Err(Error::CompressionLoop);
1280        }
1281        let slot = visited.get_mut(cursor).ok_or(Error::PointerOutOfBounds)?;
1282        *slot = true;
1283
1284        let length = *message.get(cursor).ok_or(Error::UnexpectedEof)?;
1285        match length & 0xc0 {
1286            0xc0 => {
1287                let pointer_end = cursor.checked_add(2).ok_or(Error::LengthOverflow)?;
1288                if consumed_end.is_none() && pointer_end > contiguous_end {
1289                    return Err(Error::UnexpectedEof);
1290                }
1291                let second = *message.get(cursor + 1).ok_or(Error::UnexpectedEof)?;
1292                let pointer = (usize::from(length & 0x3f) << 8) | usize::from(second);
1293                if pointer >= message.len() {
1294                    return Err(Error::PointerOutOfBounds);
1295                }
1296                if pointer >= cursor {
1297                    return Err(Error::ForwardPointer);
1298                }
1299                if consumed_end.is_none() {
1300                    consumed_end = Some(pointer_end);
1301                }
1302                jumps = jumps.checked_add(1).ok_or(Error::LengthOverflow)?;
1303                if jumps > limits.max_compression_jumps {
1304                    return Err(Error::CompressionJumpLimit);
1305                }
1306                cursor = pointer;
1307            }
1308            0x00 => {
1309                cursor = cursor.checked_add(1).ok_or(Error::LengthOverflow)?;
1310                if length == 0 {
1311                    let next = consumed_end.unwrap_or(cursor);
1312                    return Ok((Name { labels }, next));
1313                }
1314                let label_len = usize::from(length);
1315                if label_len > MAX_LABEL_LEN {
1316                    return Err(Error::InvalidLabel);
1317                }
1318                let label_end = cursor.checked_add(label_len).ok_or(Error::LengthOverflow)?;
1319                if consumed_end.is_none() && label_end > contiguous_end {
1320                    return Err(Error::UnexpectedEof);
1321                }
1322                let label = message.get(cursor..label_end).ok_or(Error::UnexpectedEof)?;
1323                expanded_len = expanded_len
1324                    .checked_add(label_len + 1)
1325                    .ok_or(Error::LengthOverflow)?;
1326                if expanded_len > MAX_WIRE_NAME_LEN || labels.len() >= limits.max_labels_per_name {
1327                    return Err(Error::NameLimit);
1328                }
1329                labels.push(canonical_label(label));
1330                cursor = label_end;
1331            }
1332            _ => return Err(Error::InvalidLabel),
1333        }
1334    }
1335}
1336
1337fn canonical_label(label: &[u8]) -> Vec<u8> {
1338    label.iter().map(u8::to_ascii_lowercase).collect()
1339}
1340
1341fn encode_question(question: &Question, output: &mut Vec<u8>) -> Result<(), Error> {
1342    question.name.encode(output)?;
1343    write_u16(output, question.record_type.code());
1344    write_u16(output, question.class);
1345    Ok(())
1346}
1347
1348fn encode_record(record: &ResourceRecord, output: &mut Vec<u8>) -> Result<(), Error> {
1349    record.name.encode(output)?;
1350    write_u16(output, record.record_type.code());
1351    write_u16(output, record.class);
1352    output.extend_from_slice(&record.ttl.to_be_bytes());
1353    let mut rdata = Vec::new();
1354    encode_rdata(record.record_type, &record.rdata, &mut rdata)?;
1355    let length = u16::try_from(rdata.len()).map_err(|_| Error::EncodeLimit)?;
1356    write_u16(output, length);
1357    output.extend_from_slice(&rdata);
1358    Ok(())
1359}
1360
1361#[allow(
1362    clippy::too_many_lines,
1363    reason = "keeping the RR-type mapping in one exhaustive function makes type checks auditable"
1364)]
1365fn encode_rdata(record_type: RecordType, rdata: &Rdata, output: &mut Vec<u8>) -> Result<(), Error> {
1366    match (record_type, rdata) {
1367        (RecordType::A, Rdata::A(address)) => output.extend_from_slice(&address.octets()),
1368        (RecordType::Aaaa, Rdata::Aaaa(address)) => {
1369            output.extend_from_slice(&address.octets());
1370        }
1371        (RecordType::Ns, Rdata::Ns(name)) | (RecordType::Cname, Rdata::Cname(name)) => {
1372            name.encode(output)?;
1373        }
1374        (RecordType::Soa, Rdata::Soa(soa)) => {
1375            soa.mname.encode(output)?;
1376            soa.rname.encode(output)?;
1377            for value in [soa.serial, soa.refresh, soa.retry, soa.expire, soa.minimum] {
1378                output.extend_from_slice(&value.to_be_bytes());
1379            }
1380        }
1381        (RecordType::Mx, Rdata::Mx(mx)) => {
1382            write_u16(output, mx.preference);
1383            mx.exchange.encode(output)?;
1384        }
1385        (RecordType::Txt, Rdata::Txt(strings)) => {
1386            if strings.is_empty() {
1387                return Err(Error::InvalidRdata);
1388            }
1389            for string in strings {
1390                let length = u8::try_from(string.len()).map_err(|_| Error::InvalidRdata)?;
1391                output.push(length);
1392                output.extend_from_slice(string);
1393            }
1394        }
1395        (RecordType::Srv, Rdata::Srv(srv)) => {
1396            write_u16(output, srv.priority);
1397            write_u16(output, srv.weight);
1398            write_u16(output, srv.port);
1399            srv.target.encode(output)?;
1400        }
1401        (RecordType::Ds, Rdata::Ds(ds)) => {
1402            write_u16(output, ds.key_tag);
1403            output.extend_from_slice(&[ds.algorithm, ds.digest_type]);
1404            output.extend_from_slice(&ds.digest);
1405        }
1406        (RecordType::Dnskey, Rdata::Dnskey(key)) => {
1407            write_u16(output, key.flags);
1408            output.extend_from_slice(&[key.protocol, key.algorithm]);
1409            output.extend_from_slice(&key.public_key);
1410        }
1411        (RecordType::Rrsig, Rdata::Rrsig(signature)) => {
1412            write_u16(output, signature.type_covered.code());
1413            output.extend_from_slice(&[signature.algorithm, signature.labels]);
1414            for value in [
1415                signature.original_ttl,
1416                signature.expiration,
1417                signature.inception,
1418            ] {
1419                output.extend_from_slice(&value.to_be_bytes());
1420            }
1421            write_u16(output, signature.key_tag);
1422            signature.signer.encode(output)?;
1423            output.extend_from_slice(&signature.signature);
1424        }
1425        (RecordType::Nsec, Rdata::Nsec(nsec)) => {
1426            nsec.next_domain.encode(output)?;
1427            validate_type_bitmaps(&nsec.type_bitmaps)?;
1428            output.extend_from_slice(&nsec.type_bitmaps);
1429        }
1430        (RecordType::Nsec3, Rdata::Nsec3(nsec3)) => {
1431            let salt_len = u8::try_from(nsec3.salt.len()).map_err(|_| Error::InvalidRdata)?;
1432            let hash_len =
1433                u8::try_from(nsec3.next_hashed_owner.len()).map_err(|_| Error::InvalidRdata)?;
1434            if hash_len == 0 {
1435                return Err(Error::InvalidRdata);
1436            }
1437            output.extend_from_slice(&[nsec3.hash_algorithm, nsec3.flags]);
1438            write_u16(output, nsec3.iterations);
1439            output.push(salt_len);
1440            output.extend_from_slice(&nsec3.salt);
1441            output.push(hash_len);
1442            output.extend_from_slice(&nsec3.next_hashed_owner);
1443            validate_type_bitmaps(&nsec3.type_bitmaps)?;
1444            output.extend_from_slice(&nsec3.type_bitmaps);
1445        }
1446        (RecordType::Tlsa, Rdata::Tlsa(tlsa)) => {
1447            if tlsa.association_data.is_empty() {
1448                return Err(Error::InvalidRdata);
1449            }
1450            output.extend_from_slice(&[tlsa.usage, tlsa.selector, tlsa.matching_type]);
1451            output.extend_from_slice(&tlsa.association_data);
1452        }
1453        (RecordType::Opt, Rdata::Opt(options)) => {
1454            for option in options {
1455                write_u16(output, option.code);
1456                let length = u16::try_from(option.data.len()).map_err(|_| Error::InvalidEdns)?;
1457                write_u16(output, length);
1458                output.extend_from_slice(&option.data);
1459            }
1460        }
1461        (RecordType::Svcb | RecordType::Https | RecordType::Unknown(_), Rdata::Opaque(bytes)) => {
1462            output.extend_from_slice(bytes);
1463        }
1464        _ => return Err(Error::TypeMismatch),
1465    }
1466    Ok(())
1467}
1468
1469fn write_count(output: &mut Vec<u8>, count: usize) -> Result<(), Error> {
1470    write_u16(output, u16::try_from(count).map_err(|_| Error::CountLimit)?);
1471    Ok(())
1472}
1473
1474fn write_u16(output: &mut Vec<u8>, value: u16) {
1475    output.extend_from_slice(&value.to_be_bytes());
1476}
1477
1478fn be_u16(bytes: &[u8], offset: usize) -> Result<u16, Error> {
1479    let end = offset.checked_add(2).ok_or(Error::LengthOverflow)?;
1480    let value: [u8; 2] = bytes
1481        .get(offset..end)
1482        .ok_or(Error::UnexpectedEof)?
1483        .try_into()
1484        .map_err(|_| Error::UnexpectedEof)?;
1485    Ok(u16::from_be_bytes(value))
1486}
1487
1488fn be_u32(bytes: &[u8], offset: usize) -> Result<u32, Error> {
1489    let end = offset.checked_add(4).ok_or(Error::LengthOverflow)?;
1490    let value: [u8; 4] = bytes
1491        .get(offset..end)
1492        .ok_or(Error::UnexpectedEof)?
1493        .try_into()
1494        .map_err(|_| Error::UnexpectedEof)?;
1495    Ok(u32::from_be_bytes(value))
1496}
1497
1498#[cfg(test)]
1499#[allow(
1500    clippy::unwrap_used,
1501    clippy::indexing_slicing,
1502    reason = "tests intentionally fail immediately on malformed fixtures"
1503)]
1504mod tests {
1505    use super::*;
1506
1507    const BASIC_QUERY: &[u8] =
1508        b"\x12\x34\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x07example\x03com\x00\x00\x01\x00\x01";
1509    const COMPRESSED_RESPONSE: &[u8] =
1510        b"\x12\x34\x84\x20\x00\x01\x00\x01\x00\x00\x00\x00\x07example\x03com\x00\x00\x01\x00\x01\xc0\x0c\x00\x01\x00\x01\x00\x00\x00\x3c\x00\x04\x7f\x00\x00\x01";
1511
1512    fn decode_hex(input: &str) -> Vec<u8> {
1513        let compact: Vec<u8> = input
1514            .bytes()
1515            .filter(|byte| !byte.is_ascii_whitespace())
1516            .collect();
1517        assert!(compact.len().is_multiple_of(2));
1518        compact
1519            .chunks_exact(2)
1520            .map(|pair| {
1521                let high = (pair[0] as char).to_digit(16).unwrap();
1522                let low = (pair[1] as char).to_digit(16).unwrap();
1523                u8::try_from((high << 4) | low).unwrap()
1524            })
1525            .collect()
1526    }
1527
1528    #[test]
1529    fn pinned_fixture_corpus_matches_parser_contract() {
1530        let query_wire = decode_hex(include_str!("../fixtures/dns/basic-query.hex"));
1531        let response_wire =
1532            decode_hex(include_str!("../fixtures/dns/compressed-a-response-ad.hex"));
1533        let tlsa_wire = decode_hex(include_str!("../fixtures/dns/tlsa-response.hex"));
1534        let query = Query::parse(&query_wire, ParseLimits::requester()).unwrap();
1535        let response = Message::parse(&response_wire).unwrap();
1536        assert!(query.correlate(&response).unwrap().untrusted_ad_claim());
1537
1538        let tlsa = Message::parse(&tlsa_wire).unwrap();
1539        assert!(matches!(tlsa.answers[0].rdata, Rdata::Tlsa(_)));
1540
1541        let self_loop = decode_hex(include_str!(
1542            "../fixtures/dns/mutation-compression-self-loop.hex"
1543        ));
1544        assert_eq!(Message::parse(&self_loop), Err(Error::ForwardPointer));
1545
1546        let out_of_bounds = decode_hex(include_str!(
1547            "../fixtures/dns/mutation-pointer-out-of-bounds.hex"
1548        ));
1549        assert_eq!(
1550            Message::parse(&out_of_bounds),
1551            Err(Error::PointerOutOfBounds)
1552        );
1553
1554        let count_bomb = decode_hex(include_str!("../fixtures/dns/mutation-count-bomb.hex"));
1555        assert_eq!(
1556            Message::parse_with_limits(&count_bomb, ParseLimits::requester()),
1557            Err(Error::CountLimit)
1558        );
1559    }
1560
1561    #[test]
1562    fn parses_and_correlates_compressed_response_without_trusting_ad() {
1563        let query = Query::parse(BASIC_QUERY, ParseLimits::requester()).unwrap();
1564        let response = Message::parse(COMPRESSED_RESPONSE).unwrap();
1565        let correlated = query.correlate(&response).unwrap();
1566
1567        assert!(correlated.untrusted_ad_claim());
1568        assert_eq!(correlated.response().answers.len(), 1);
1569        assert_eq!(
1570            correlated.response().answers[0].rdata,
1571            Rdata::A(Ipv4Addr::LOCALHOST)
1572        );
1573    }
1574
1575    #[test]
1576    fn outgoing_query_sets_do_but_not_rd() {
1577        let query = Query::new(
1578            7,
1579            Name::from_ascii("_443._tcp.example").unwrap(),
1580            RecordType::Tlsa,
1581        )
1582        .unwrap();
1583        let encoded = query.encode(1_232).unwrap();
1584        let parsed = Message::parse(&encoded).unwrap();
1585
1586        assert!(!parsed.header.flags.recursion_desired());
1587        assert_eq!(parsed.additionals.len(), 1);
1588        assert_eq!(parsed.additionals[0].record_type, RecordType::Opt);
1589        assert_eq!(
1590            u16::try_from(parsed.additionals[0].ttl).unwrap() & EDNS_DO,
1591            EDNS_DO
1592        );
1593    }
1594
1595    #[test]
1596    fn parses_tlsa_dnskey_ds_rrsig_nsec_and_nsec3() {
1597        let name = Name::from_ascii("example").unwrap();
1598        let records = vec![
1599            ResourceRecord {
1600                name: name.clone(),
1601                record_type: RecordType::Tlsa,
1602                class: CLASS_IN,
1603                ttl: 60,
1604                rdata: Rdata::Tlsa(Tlsa {
1605                    usage: 3,
1606                    selector: 1,
1607                    matching_type: 1,
1608                    association_data: vec![0x42; 32],
1609                }),
1610            },
1611            ResourceRecord {
1612                name: name.clone(),
1613                record_type: RecordType::Dnskey,
1614                class: CLASS_IN,
1615                ttl: 60,
1616                rdata: Rdata::Dnskey(Dnskey {
1617                    flags: 257,
1618                    protocol: 3,
1619                    algorithm: 13,
1620                    public_key: vec![0x11; 64],
1621                }),
1622            },
1623            ResourceRecord {
1624                name: name.clone(),
1625                record_type: RecordType::Ds,
1626                class: CLASS_IN,
1627                ttl: 60,
1628                rdata: Rdata::Ds(Ds {
1629                    key_tag: 42,
1630                    algorithm: 13,
1631                    digest_type: 2,
1632                    digest: vec![0x22; 32],
1633                }),
1634            },
1635            ResourceRecord {
1636                name: name.clone(),
1637                record_type: RecordType::Rrsig,
1638                class: CLASS_IN,
1639                ttl: 60,
1640                rdata: Rdata::Rrsig(Rrsig {
1641                    type_covered: RecordType::Tlsa,
1642                    algorithm: 13,
1643                    labels: 1,
1644                    original_ttl: 60,
1645                    expiration: 2_000_000_000,
1646                    inception: 1_900_000_000,
1647                    key_tag: 42,
1648                    signer: name.clone(),
1649                    signature: vec![0x33; 64],
1650                }),
1651            },
1652            ResourceRecord {
1653                name: name.clone(),
1654                record_type: RecordType::Nsec,
1655                class: CLASS_IN,
1656                ttl: 60,
1657                rdata: Rdata::Nsec(Nsec {
1658                    next_domain: Name::from_ascii("next").unwrap(),
1659                    type_bitmaps: vec![0, 1, 0x40],
1660                }),
1661            },
1662            ResourceRecord {
1663                name,
1664                record_type: RecordType::Nsec3,
1665                class: CLASS_IN,
1666                ttl: 60,
1667                rdata: Rdata::Nsec3(Nsec3 {
1668                    hash_algorithm: 1,
1669                    flags: 0,
1670                    iterations: 10,
1671                    salt: vec![1, 2],
1672                    next_hashed_owner: vec![0x44; 20],
1673                    type_bitmaps: vec![0, 1, 0x40],
1674                }),
1675            },
1676        ];
1677        let message = Message {
1678            header: Header {
1679                id: 3,
1680                flags: Flags::from_bits(0x8400),
1681                question_count: 0,
1682                answer_count: u16::try_from(records.len()).unwrap(),
1683                authority_count: 0,
1684                additional_count: 0,
1685            },
1686            questions: Vec::new(),
1687            answers: records.clone(),
1688            authorities: Vec::new(),
1689            additionals: Vec::new(),
1690        };
1691        let encoded = message.encode(u16::MAX as usize).unwrap();
1692        let parsed = Message::parse(&encoded).unwrap();
1693
1694        assert_eq!(parsed.answers, records);
1695    }
1696
1697    #[test]
1698    fn canonicalizes_ascii_case_and_escapes_opaque_octets() {
1699        let wire = b"\x03WwW\x02\xffx\x00";
1700        let (name, next) = decode_name(wire, 0, wire.len(), ParseLimits::browser()).unwrap();
1701
1702        assert_eq!(next, wire.len());
1703        assert_eq!(name.labels()[0], b"www");
1704        assert_eq!(name.to_string(), "www.\\255x.");
1705    }
1706
1707    #[test]
1708    fn accepts_maximum_wire_name_and_rejects_one_octet_more() {
1709        let valid = format!(
1710            "{}.{}.{}.{}",
1711            "a".repeat(63),
1712            "b".repeat(63),
1713            "c".repeat(63),
1714            "d".repeat(61)
1715        );
1716        assert_eq!(Name::from_ascii(&valid).unwrap().wire_len(), 255);
1717
1718        let invalid = format!("{valid}e");
1719        assert_eq!(Name::from_ascii(&invalid), Err(Error::NameLimit));
1720    }
1721
1722    #[test]
1723    fn rejects_self_pointer_loop() {
1724        assert_eq!(
1725            decode_name(b"\xc0\x00", 0, 2, ParseLimits::browser()),
1726            Err(Error::ForwardPointer)
1727        );
1728    }
1729
1730    #[test]
1731    fn rejects_two_pointer_cycle() {
1732        let message = b"\x00\x00\xc0\x04\xc0\x02";
1733        assert_eq!(
1734            decode_name(message, 4, message.len(), ParseLimits::browser()),
1735            Err(Error::ForwardPointer)
1736        );
1737    }
1738
1739    #[test]
1740    fn rejects_out_of_bounds_pointer() {
1741        assert_eq!(
1742            decode_name(b"\x00\xc0\xff", 1, 3, ParseLimits::browser()),
1743            Err(Error::PointerOutOfBounds)
1744        );
1745    }
1746
1747    #[test]
1748    fn rejects_reserved_label_bits() {
1749        assert_eq!(
1750            decode_name(b"\x40\x00", 0, 2, ParseLimits::browser()),
1751            Err(Error::InvalidLabel)
1752        );
1753    }
1754
1755    #[test]
1756    fn rejects_count_bomb_before_section_allocation() {
1757        let message = b"\x00\x01\x80\x00\xff\xff\xff\xff\xff\xff\xff\xff";
1758        assert_eq!(
1759            Message::parse_with_limits(message, ParseLimits::requester()),
1760            Err(Error::CountLimit)
1761        );
1762    }
1763
1764    #[test]
1765    fn rejects_reserved_header_bits_and_oversized_tcp_message() {
1766        let mut reserved = BASIC_QUERY.to_vec();
1767        reserved[3] |= 0x40;
1768        assert_eq!(Message::parse(&reserved), Err(Error::ReservedHeaderBits));
1769
1770        assert_eq!(
1771            Message::parse(&vec![0; usize::from(u16::MAX) + 1]),
1772            Err(Error::MessageTooLong)
1773        );
1774    }
1775
1776    #[test]
1777    fn strict_query_rejects_ecs_and_misplaced_opt() {
1778        let query = Query::new(9, Name::from_ascii("example").unwrap(), RecordType::A).unwrap();
1779        let mut encoded = query.encode(1_232).unwrap();
1780        // Replace empty OPT RDATA with one empty ECS option.
1781        encoded.truncate(encoded.len() - 2);
1782        encoded.extend_from_slice(&[0, 4, 0, 8, 0, 0]);
1783        assert_eq!(
1784            Query::parse(&encoded, ParseLimits::requester()),
1785            Err(Error::InvalidQuery)
1786        );
1787
1788        let misplaced = Message {
1789            header: Header {
1790                id: 1,
1791                flags: Flags::from_bits(0x8000),
1792                question_count: 0,
1793                answer_count: 1,
1794                authority_count: 0,
1795                additional_count: 0,
1796            },
1797            questions: Vec::new(),
1798            answers: vec![ResourceRecord {
1799                name: Name::root(),
1800                record_type: RecordType::Opt,
1801                class: DEFAULT_UDP_PAYLOAD,
1802                ttl: 0,
1803                rdata: Rdata::Opt(Vec::new()),
1804            }],
1805            authorities: Vec::new(),
1806            additionals: Vec::new(),
1807        }
1808        .encode(1_232)
1809        .unwrap();
1810        assert_eq!(Message::parse(&misplaced), Err(Error::InvalidEdns));
1811    }
1812
1813    #[test]
1814    fn rejects_truncated_and_oversized_rdata() {
1815        let truncated =
1816            b"\x00\x01\x80\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x01\x00\x01\x00\x00\x00\x00\x00\x04\x7f";
1817        assert_eq!(
1818            Message::parse_with_limits(truncated, ParseLimits::browser()),
1819            Err(Error::UnexpectedEof)
1820        );
1821
1822        let mut limits = ParseLimits::browser();
1823        limits.max_rdata_len = 2;
1824        assert_eq!(
1825            Message::parse_with_limits(COMPRESSED_RESPONSE, limits),
1826            Err(Error::RdataLimit)
1827        );
1828    }
1829
1830    #[test]
1831    fn mutation_negatives_reject_response_mismatches() {
1832        let query = Query::parse(BASIC_QUERY, ParseLimits::requester()).unwrap();
1833
1834        let mut bad_id = COMPRESSED_RESPONSE.to_vec();
1835        bad_id[1] ^= 1;
1836        assert_eq!(
1837            query
1838                .correlate(&Message::parse(&bad_id).unwrap())
1839                .unwrap_err(),
1840            Error::IdMismatch
1841        );
1842
1843        let mut bad_name = COMPRESSED_RESPONSE.to_vec();
1844        bad_name[13] = b'f';
1845        assert_eq!(
1846            query
1847                .correlate(&Message::parse(&bad_name).unwrap())
1848                .unwrap_err(),
1849            Error::QuestionMismatch
1850        );
1851
1852        let mut truncated = COMPRESSED_RESPONSE.to_vec();
1853        truncated[2] |= 0x02;
1854        assert_eq!(
1855            query
1856                .correlate(&Message::parse(&truncated).unwrap())
1857                .unwrap_err(),
1858            Error::Truncated
1859        );
1860    }
1861
1862    #[test]
1863    fn rejects_malformed_dnssec_rdata() {
1864        let message =
1865            b"\x00\x01\x80\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x2b\x00\x01\x00\x00\x00\x00\x00\x04\x00\x01\x08\x02";
1866        assert_eq!(Message::parse(message), Err(Error::InvalidRdata));
1867    }
1868
1869    #[test]
1870    fn rejects_invalid_nsec_bitmap_window_order() {
1871        let nsec = ResourceRecord {
1872            name: Name::from_ascii("example").unwrap(),
1873            record_type: RecordType::Nsec,
1874            class: CLASS_IN,
1875            ttl: 60,
1876            rdata: Rdata::Nsec(Nsec {
1877                next_domain: Name::from_ascii("next").unwrap(),
1878                type_bitmaps: vec![1, 1, 1, 0, 1, 1],
1879            }),
1880        };
1881        let message = Message {
1882            header: Header {
1883                id: 1,
1884                flags: Flags::from_bits(0x8000),
1885                question_count: 0,
1886                answer_count: 1,
1887                authority_count: 0,
1888                additional_count: 0,
1889            },
1890            questions: Vec::new(),
1891            answers: vec![nsec],
1892            authorities: Vec::new(),
1893            additionals: Vec::new(),
1894        };
1895        assert_eq!(message.encode(1_232), Err(Error::InvalidRdata));
1896    }
1897}